summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.clang-format39
-rw-r--r--.scons2ninja.conf2
-rw-r--r--3rdParty/Boost/SConscript306
-rw-r--r--3rdParty/Boost/src/boost/cstdlib.hpp41
-rw-r--r--3rdParty/Boost/src/boost/detail/binary_search.hpp216
-rw-r--r--3rdParty/Boost/src/boost/detail/is_xxx.hpp27
-rw-r--r--3rdParty/Boost/src/boost/function/function_typeof.hpp45
-rw-r--r--3rdParty/Boost/src/boost/function/gen_function_N.pl26
-rw-r--r--3rdParty/Boost/src/boost/function_output_iterator.hpp56
-rw-r--r--3rdParty/Boost/src/boost/last_value.hpp54
-rw-r--r--3rdParty/Boost/src/boost/make_shared.hpp17
-rw-r--r--3rdParty/Boost/src/boost/mpl/aux_/unwrap.hpp51
-rw-r--r--3rdParty/Boost/src/boost/mpl/for_each.hpp123
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/at_impl.hpp40
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/begin_end_impl.hpp43
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/clear_impl.hpp35
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/empty_impl.hpp34
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/erase_impl.hpp41
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/erase_key_impl.hpp53
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/has_key_impl.hpp60
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/insert_impl.hpp65
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/item.hpp80
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/iterator.hpp98
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/key_type_impl.hpp34
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/set0.hpp69
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/size_impl.hpp33
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/tag.hpp24
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/aux_/value_type_impl.hpp34
-rw-r--r--3rdParty/Boost/src/boost/mpl/set/set0.hpp35
-rw-r--r--3rdParty/Boost/src/boost/multi_index/detail/scope_guard.hpp453
-rwxr-xr-x3rdParty/Boost/src/boost/parameter.hpp21
-rw-r--r--3rdParty/Boost/src/boost/parameter/aux_/arg_list.hpp459
-rw-r--r--3rdParty/Boost/src/boost/parameter/aux_/cast.hpp143
-rw-r--r--3rdParty/Boost/src/boost/parameter/aux_/default.hpp69
-rw-r--r--3rdParty/Boost/src/boost/parameter/aux_/is_maybe.hpp26
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/aux_/overloads.hpp88
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/aux_/parameter_requirements.hpp25
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/aux_/parenthesized_type.hpp119
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/aux_/preprocessor/flatten.hpp115
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/aux_/preprocessor/for_each.hpp103
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/aux_/result_of0.hpp36
-rw-r--r--3rdParty/Boost/src/boost/parameter/aux_/set.hpp67
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/aux_/tag.hpp38
-rw-r--r--3rdParty/Boost/src/boost/parameter/aux_/tagged_argument.hpp188
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/aux_/template_keyword.hpp47
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/aux_/unwrap_cv_reference.hpp97
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/aux_/void.hpp29
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/aux_/yesno.hpp26
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/binding.hpp106
-rw-r--r--3rdParty/Boost/src/boost/parameter/config.hpp14
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/keyword.hpp152
-rw-r--r--3rdParty/Boost/src/boost/parameter/macros.hpp99
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/match.hpp55
-rw-r--r--3rdParty/Boost/src/boost/parameter/name.hpp156
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/parameters.hpp931
-rw-r--r--3rdParty/Boost/src/boost/parameter/preprocessor.hpp1178
-rwxr-xr-x3rdParty/Boost/src/boost/parameter/value_type.hpp108
-rw-r--r--3rdParty/Boost/src/boost/preprocessor/arithmetic.hpp25
-rw-r--r--3rdParty/Boost/src/boost/preprocessor/arithmetic/div.hpp39
-rw-r--r--3rdParty/Boost/src/boost/preprocessor/arithmetic/mul.hpp53
-rw-r--r--3rdParty/Boost/src/boost/preprocessor/detail/is_nullary.hpp30
-rw-r--r--3rdParty/Boost/src/boost/preprocessor/for.hpp17
-rw-r--r--3rdParty/Boost/src/boost/preprocessor/iteration.hpp19
-rw-r--r--3rdParty/Boost/src/boost/preprocessor/repetition.hpp32
-rw-r--r--3rdParty/Boost/src/boost/preprocessor/repetition/deduce_r.hpp22
-rw-r--r--3rdParty/Boost/src/boost/preprocessor/repetition/deduce_z.hpp22
-rw-r--r--3rdParty/Boost/src/boost/preprocessor/repetition/enum_shifted_binary_params.hpp51
-rw-r--r--3rdParty/Boost/src/boost/progress.hpp143
-rw-r--r--3rdParty/Boost/src/boost/range/adaptor/reversed.hpp103
-rw-r--r--3rdParty/Boost/src/boost/signal.hpp366
-rw-r--r--3rdParty/Boost/src/boost/signals.hpp10
-rw-r--r--3rdParty/Boost/src/boost/signals/connection.hpp213
-rw-r--r--3rdParty/Boost/src/boost/signals/detail/config.hpp54
-rw-r--r--3rdParty/Boost/src/boost/signals/detail/named_slot_map.hpp192
-rw-r--r--3rdParty/Boost/src/boost/signals/detail/signal_base.hpp159
-rw-r--r--3rdParty/Boost/src/boost/signals/detail/signals_common.hpp144
-rw-r--r--3rdParty/Boost/src/boost/signals/detail/slot_call_iterator.hpp95
-rw-r--r--3rdParty/Boost/src/boost/signals/signal0.hpp37
-rw-r--r--3rdParty/Boost/src/boost/signals/signal1.hpp37
-rw-r--r--3rdParty/Boost/src/boost/signals/signal10.hpp37
-rw-r--r--3rdParty/Boost/src/boost/signals/signal2.hpp37
-rw-r--r--3rdParty/Boost/src/boost/signals/signal3.hpp37
-rw-r--r--3rdParty/Boost/src/boost/signals/signal4.hpp37
-rw-r--r--3rdParty/Boost/src/boost/signals/signal5.hpp37
-rw-r--r--3rdParty/Boost/src/boost/signals/signal6.hpp37
-rw-r--r--3rdParty/Boost/src/boost/signals/signal7.hpp37
-rw-r--r--3rdParty/Boost/src/boost/signals/signal8.hpp37
-rw-r--r--3rdParty/Boost/src/boost/signals/signal9.hpp37
-rw-r--r--3rdParty/Boost/src/boost/signals/signal_template.hpp401
-rw-r--r--3rdParty/Boost/src/boost/signals/slot.hpp157
-rw-r--r--3rdParty/Boost/src/boost/signals/trackable.hpp173
-rw-r--r--3rdParty/Boost/src/boost/signals2.hpp23
-rw-r--r--3rdParty/Boost/src/boost/signals2/connection.hpp297
-rw-r--r--3rdParty/Boost/src/boost/signals2/deconstruct.hpp547
-rw-r--r--3rdParty/Boost/src/boost/signals2/deconstruct_ptr.hpp84
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/auto_buffer.hpp1138
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/foreign_ptr.hpp185
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/lwm_nop.hpp38
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/lwm_pthreads.hpp78
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/lwm_win32_cs.hpp120
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/null_output_iterator.hpp34
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/preprocessed_arg_type.hpp34
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/preprocessed_arg_type_template.hpp39
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/replace_slot_function.hpp32
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/result_type_wrapper.hpp72
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/signal_template.hpp859
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/signals_common.hpp77
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/signals_common_macros.hpp212
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/slot_call_iterator.hpp147
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/slot_groups.hpp235
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/slot_template.hpp187
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/tracked_objects_visitor.hpp98
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/unique_lock.hpp42
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/variadic_arg_type.hpp49
-rw-r--r--3rdParty/Boost/src/boost/signals2/detail/variadic_slot_invoker.hpp139
-rw-r--r--3rdParty/Boost/src/boost/signals2/dummy_mutex.hpp28
-rw-r--r--3rdParty/Boost/src/boost/signals2/expired_slot.hpp31
-rw-r--r--3rdParty/Boost/src/boost/signals2/last_value.hpp78
-rw-r--r--3rdParty/Boost/src/boost/signals2/mutex.hpp38
-rw-r--r--3rdParty/Boost/src/boost/signals2/optional_last_value.hpp65
-rw-r--r--3rdParty/Boost/src/boost/signals2/postconstructible.hpp55
-rw-r--r--3rdParty/Boost/src/boost/signals2/predestructible.hpp46
-rw-r--r--3rdParty/Boost/src/boost/signals2/preprocessed_signal.hpp59
-rw-r--r--3rdParty/Boost/src/boost/signals2/preprocessed_slot.hpp72
-rw-r--r--3rdParty/Boost/src/boost/signals2/shared_connection_block.hpp64
-rw-r--r--3rdParty/Boost/src/boost/signals2/signal.hpp62
-rw-r--r--3rdParty/Boost/src/boost/signals2/signal_base.hpp33
-rw-r--r--3rdParty/Boost/src/boost/signals2/signal_type.hpp144
-rw-r--r--3rdParty/Boost/src/boost/signals2/slot.hpp33
-rw-r--r--3rdParty/Boost/src/boost/signals2/slot_base.hpp100
-rw-r--r--3rdParty/Boost/src/boost/signals2/trackable.hpp49
-rw-r--r--3rdParty/Boost/src/boost/signals2/variadic_signal.hpp44
-rw-r--r--3rdParty/Boost/src/boost/signals2/variadic_slot.hpp25
-rw-r--r--3rdParty/Boost/src/boost/smart_ptr.hpp31
-rw-r--r--3rdParty/Boost/src/boost/timer.hpp72
-rw-r--r--3rdParty/Boost/src/libs/atomic/README.md19
-rw-r--r--3rdParty/Boost/src/libs/atomic/doc/Jamfile.v226
-rw-r--r--3rdParty/Boost/src/libs/atomic/doc/atomic.hpp547
-rw-r--r--3rdParty/Boost/src/libs/atomic/doc/atomic.qbk828
-rw-r--r--3rdParty/Boost/src/libs/atomic/doc/examples.qbk398
-rw-r--r--3rdParty/Boost/src/libs/atomic/doc/logo.pngbin0 -> 11094 bytes
-rw-r--r--3rdParty/Boost/src/libs/atomic/doc/logo.svg1053
-rw-r--r--3rdParty/Boost/src/libs/atomic/doc/platform.qbk312
-rw-r--r--3rdParty/Boost/src/libs/atomic/index.html13
-rw-r--r--3rdParty/Boost/src/libs/signals/src/connection.cpp155
-rw-r--r--3rdParty/Boost/src/libs/signals/src/named_slot_map.cpp134
-rw-r--r--3rdParty/Boost/src/libs/signals/src/signal_base.cpp189
-rw-r--r--3rdParty/Boost/src/libs/signals/src/slot.cpp71
-rw-r--r--3rdParty/Boost/src/libs/signals/src/trackable.cpp59
-rwxr-xr-x3rdParty/Boost/update.sh12
-rw-r--r--3rdParty/Breakpad/01_breakpad_filename_prefix.diff66
-rw-r--r--3rdParty/Breakpad/SConscript148
-rw-r--r--3rdParty/Breakpad/src/client/windows/handler/exception_handler.cc6
-rw-r--r--3rdParty/Breakpad/src/client/windows/handler/exception_handler.h10
-rw-r--r--3rdParty/CppUnit/SConscript104
-rw-r--r--3rdParty/Expat/SConscript46
-rwxr-xr-x3rdParty/LCov/gendesc11
-rwxr-xr-x3rdParty/LCov/genhtml672
-rwxr-xr-x3rdParty/LCov/geninfo1200
-rwxr-xr-x3rdParty/LCov/genpng20
-rwxr-xr-x3rdParty/LCov/lcov489
-rw-r--r--3rdParty/Ldns/SConscript111
-rw-r--r--3rdParty/LibIDN/SConscript108
-rw-r--r--3rdParty/LibMiniUPnPc/SConscript106
-rw-r--r--3rdParty/LibNATPMP/SConscript82
-rw-r--r--3rdParty/Lua/SConscript128
-rw-r--r--3rdParty/OpenSSL/SConscript1304
-rw-r--r--3rdParty/SQLite/SConscript20
-rw-r--r--3rdParty/Snarl/SConscript18
-rw-r--r--3rdParty/Snarl/SnarlInterface.cpp517
-rw-r--r--3rdParty/Snarl/SnarlInterface.h276
-rw-r--r--3rdParty/Unbound/SConscript190
-rw-r--r--3rdParty/ZLib/SConscript40
-rwxr-xr-xBuildTools/CheckHeaders.py46
-rwxr-xr-xBuildTools/CheckTabs.py36
-rwxr-xr-xBuildTools/CheckTests.py48
-rwxr-xr-xBuildTools/CheckTranslations.py70
-rwxr-xr-xBuildTools/Copyright/find-contribs.py80
-rwxr-xr-xBuildTools/Copyrighter.py276
-rwxr-xr-xBuildTools/Coverage/FilterLCovData.py24
-rwxr-xr-xBuildTools/Coverage/GenerateSummary.py32
-rwxr-xr-xBuildTools/Cppcheck.sh36
-rw-r--r--BuildTools/CrashReportAnalysis/WindowsMinidumpAnalyse.py134
-rw-r--r--BuildTools/DocBook/SCons/DocBook.py162
-rw-r--r--BuildTools/DocBook/SCons/FO.py64
-rw-r--r--BuildTools/DocBook/SCons/XSLT.py106
-rwxr-xr-xBuildTools/FilterScanBuildResults.py38
-rwxr-xr-xBuildTools/FixIncludes.py198
-rwxr-xr-xBuildTools/GenerateAppCastFeeds.py153
-rwxr-xr-xBuildTools/GetBuildVersion.py16
-rwxr-xr-xBuildTools/Gource/GetGravatars.py56
-rwxr-xr-xBuildTools/InstallSwiftDependencies.sh48
-rw-r--r--BuildTools/SCons/SConscript.boot511
-rw-r--r--BuildTools/SCons/SConstruct920
-rw-r--r--BuildTools/SCons/Tools/AppBundle.py108
-rw-r--r--BuildTools/SCons/Tools/BuildVersion.py10
-rw-r--r--BuildTools/SCons/Tools/DoxyGen.py38
-rw-r--r--BuildTools/SCons/Tools/Flags.py16
-rw-r--r--BuildTools/SCons/Tools/InstallWithSymLinks.py114
-rw-r--r--BuildTools/SCons/Tools/Nib.py14
-rw-r--r--BuildTools/SCons/Tools/ReplacePragmaOnce.py36
-rw-r--r--BuildTools/SCons/Tools/SLOCCount.py22
-rw-r--r--BuildTools/SCons/Tools/Test.py96
-rw-r--r--BuildTools/SCons/Tools/WindowsBundle.py222
-rw-r--r--BuildTools/SCons/Tools/WriteVal.py16
-rw-r--r--BuildTools/SCons/Tools/nsis.py48
-rw-r--r--BuildTools/SCons/Tools/qt4.py1015
-rw-r--r--BuildTools/SCons/Tools/textfile.py218
-rw-r--r--BuildTools/SCons/Tools/wix.py86
-rw-r--r--BuildTools/SCons/Version.py110
-rwxr-xr-xBuildTools/UpdateDebianChangelog.py32
-rwxr-xr-xBuildTools/scons2ninja.py918
-rw-r--r--COPYING.thirdparty102
-rw-r--r--DEVELOPMENT.md229
-rw-r--r--Documentation/API/SConscript6
-rw-r--r--Documentation/BuildingGenerics.txt6
-rw-r--r--Documentation/BuildingOnAndroid.txt97
-rw-r--r--Documentation/BuildingOnIOS.txt44
-rw-r--r--Documentation/BuildingOnUnix.txt35
-rw-r--r--Documentation/BuildingOnWindows.txt66
-rw-r--r--Documentation/SConscript2
-rw-r--r--Documentation/SwiftAPI/SConscript6
-rw-r--r--Documentation/SwiftUserGuide/SConscript2
-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.cpp33
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot3.cpp75
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot4.cpp133
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot5.cpp149
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot6.cpp179
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoComponent.cpp89
-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.h17
-rw-r--r--Documentation/SwiftenDevelopersGuide/Examples/EchoBot/SConscript29
-rw-r--r--Documentation/SwiftenDevelopersGuide/SConscript138
-rw-r--r--Limber/SConscript46
-rw-r--r--Limber/Server/ServerFromClientSession.cpp184
-rw-r--r--Limber/Server/ServerFromClientSession.h96
-rw-r--r--Limber/Server/ServerSession.cpp4
-rw-r--r--Limber/Server/ServerSession.h18
-rw-r--r--Limber/Server/ServerStanzaRouter.cpp90
-rw-r--r--Limber/Server/ServerStanzaRouter.h26
-rw-r--r--Limber/Server/SimpleUserRegistry.cpp10
-rw-r--r--Limber/Server/SimpleUserRegistry.h25
-rw-r--r--Limber/Server/UnitTest/ServerStanzaRouterTest.cpp271
-rw-r--r--Limber/Server/UserRegistry.cpp4
-rw-r--r--Limber/Server/UserRegistry.h15
-rw-r--r--Limber/main.cpp170
-rw-r--r--QA/Checker/IO.cpp82
-rw-r--r--QA/Checker/SConscript32
-rw-r--r--QA/Checker/checker.cpp131
-rwxr-xr-xQA/CrossDistributionTest/VagrantCrossDistributionTest.py90
-rw-r--r--QA/CrossDistributionTest/playbook.yml33
-rw-r--r--QA/SConscript6
-rw-r--r--QA/UnitTest/SConscript48
-rw-r--r--QA/UnitTest/template/FooTest.cpp20
-rw-r--r--README.md86
-rw-r--r--README.txt1
-rw-r--r--SConstruct4
-rw-r--r--Slimber/CLI/DummyMenulet.cpp5
-rw-r--r--Slimber/CLI/DummyMenulet.h38
-rw-r--r--Slimber/CLI/SConscript6
-rw-r--r--Slimber/CLI/main.cpp19
-rw-r--r--Slimber/Cocoa/CocoaController.mm18
-rw-r--r--Slimber/Cocoa/CocoaMenulet.h37
-rw-r--r--Slimber/Cocoa/CocoaMenulet.mm97
-rw-r--r--Slimber/Cocoa/SConscript30
-rw-r--r--Slimber/Cocoa/main.mm17
-rw-r--r--Slimber/FileVCardCollection.cpp43
-rw-r--r--Slimber/FileVCardCollection.h23
-rw-r--r--Slimber/LinkLocalPresenceManager.cpp137
-rw-r--r--Slimber/LinkLocalPresenceManager.h53
-rw-r--r--Slimber/MainController.cpp164
-rw-r--r--Slimber/MainController.h55
-rw-r--r--Slimber/Menulet.cpp4
-rw-r--r--Slimber/Menulet.h25
-rw-r--r--Slimber/MenuletController.cpp64
-rw-r--r--Slimber/MenuletController.h50
-rw-r--r--Slimber/Qt/QtAboutDialog.cpp50
-rw-r--r--Slimber/Qt/QtAboutDialog.h4
-rw-r--r--Slimber/Qt/QtMenulet.cpp5
-rw-r--r--Slimber/Qt/QtMenulet.h110
-rw-r--r--Slimber/Qt/SConscript52
-rw-r--r--Slimber/Qt/main.cpp31
-rw-r--r--Slimber/SConscript74
-rw-r--r--Slimber/Server.cpp735
-rw-r--r--Slimber/Server.h225
-rw-r--r--Slimber/ServerError.h42
-rw-r--r--Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp487
-rw-r--r--Slimber/UnitTest/MenuletControllerTest.cpp284
-rw-r--r--Slimber/VCardCollection.cpp4
-rw-r--r--Slimber/VCardCollection.h16
-rw-r--r--Sluift/Completer.h10
-rw-r--r--Sluift/Console.cpp436
-rw-r--r--Sluift/Console.h43
-rw-r--r--Sluift/EditlineTerminal.cpp85
-rw-r--r--Sluift/EditlineTerminal.h23
-rw-r--r--Sluift/ElementConvertors/BodyConvertor.cpp30
-rw-r--r--Sluift/ElementConvertors/BodyConvertor.h20
-rw-r--r--Sluift/ElementConvertors/CarbonsReceivedConvertor.cpp53
-rw-r--r--Sluift/ElementConvertors/CarbonsReceivedConvertor.h30
-rw-r--r--Sluift/ElementConvertors/CarbonsSentConvertor.cpp52
-rw-r--r--Sluift/ElementConvertors/CarbonsSentConvertor.h30
-rw-r--r--Sluift/ElementConvertors/CommandConvertor.cpp333
-rw-r--r--Sluift/ElementConvertors/CommandConvertor.h24
-rw-r--r--Sluift/ElementConvertors/DOMElementConvertor.cpp342
-rw-r--r--Sluift/ElementConvertors/DOMElementConvertor.h26
-rw-r--r--Sluift/ElementConvertors/DefaultElementConvertor.cpp21
-rw-r--r--Sluift/ElementConvertors/DefaultElementConvertor.h16
-rw-r--r--Sluift/ElementConvertors/DelayConvertor.cpp56
-rw-r--r--Sluift/ElementConvertors/DelayConvertor.h18
-rw-r--r--Sluift/ElementConvertors/DiscoInfoConvertor.cpp187
-rw-r--r--Sluift/ElementConvertors/DiscoInfoConvertor.h20
-rw-r--r--Sluift/ElementConvertors/DiscoItemsConvertor.cpp97
-rw-r--r--Sluift/ElementConvertors/DiscoItemsConvertor.h18
-rw-r--r--Sluift/ElementConvertors/ElementConvertors.ipp136
-rw-r--r--Sluift/ElementConvertors/FormConvertor.cpp666
-rw-r--r--Sluift/ElementConvertors/FormConvertor.h18
-rw-r--r--Sluift/ElementConvertors/ForwardedConvertor.cpp96
-rw-r--r--Sluift/ElementConvertors/ForwardedConvertor.h29
-rw-r--r--Sluift/ElementConvertors/IQConvertor.cpp95
-rw-r--r--Sluift/ElementConvertors/IQConvertor.h31
-rw-r--r--Sluift/ElementConvertors/IsodeIQDelegationConvertor.cpp54
-rw-r--r--Sluift/ElementConvertors/IsodeIQDelegationConvertor.h26
-rw-r--r--Sluift/ElementConvertors/MAMFinConvertor.cpp113
-rw-r--r--Sluift/ElementConvertors/MAMFinConvertor.h27
-rw-r--r--Sluift/ElementConvertors/MAMQueryConvertor.cpp125
-rw-r--r--Sluift/ElementConvertors/MAMQueryConvertor.h27
-rw-r--r--Sluift/ElementConvertors/MAMResultConvertor.cpp98
-rw-r--r--Sluift/ElementConvertors/MAMResultConvertor.h27
-rw-r--r--Sluift/ElementConvertors/MessageConvertor.cpp115
-rw-r--r--Sluift/ElementConvertors/MessageConvertor.h31
-rw-r--r--Sluift/ElementConvertors/PresenceConvertor.cpp139
-rw-r--r--Sluift/ElementConvertors/PresenceConvertor.h31
-rw-r--r--Sluift/ElementConvertors/PubSubAffiliationConvertor.cpp137
-rw-r--r--Sluift/ElementConvertors/PubSubAffiliationConvertor.h25
-rw-r--r--Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp107
-rw-r--r--Sluift/ElementConvertors/PubSubAffiliationsConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubConfigureConvertor.cpp54
-rw-r--r--Sluift/ElementConvertors/PubSubConfigureConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubCreateConvertor.cpp70
-rw-r--r--Sluift/ElementConvertors/PubSubCreateConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubDefaultConvertor.cpp105
-rw-r--r--Sluift/ElementConvertors/PubSubDefaultConvertor.h25
-rw-r--r--Sluift/ElementConvertors/PubSubEventAssociateConvertor.cpp49
-rw-r--r--Sluift/ElementConvertors/PubSubEventAssociateConvertor.h25
-rw-r--r--Sluift/ElementConvertors/PubSubEventCollectionConvertor.cpp96
-rw-r--r--Sluift/ElementConvertors/PubSubEventCollectionConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubEventConfigurationConvertor.cpp70
-rw-r--r--Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubEventConvertor.cpp30
-rw-r--r--Sluift/ElementConvertors/PubSubEventConvertor.h24
-rw-r--r--Sluift/ElementConvertors/PubSubEventDeleteConvertor.cpp70
-rw-r--r--Sluift/ElementConvertors/PubSubEventDeleteConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubEventDisassociateConvertor.cpp49
-rw-r--r--Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h25
-rw-r--r--Sluift/ElementConvertors/PubSubEventItemConvertor.cpp155
-rw-r--r--Sluift/ElementConvertors/PubSubEventItemConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp171
-rw-r--r--Sluift/ElementConvertors/PubSubEventItemsConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubEventPurgeConvertor.cpp49
-rw-r--r--Sluift/ElementConvertors/PubSubEventPurgeConvertor.h25
-rw-r--r--Sluift/ElementConvertors/PubSubEventRedirectConvertor.cpp49
-rw-r--r--Sluift/ElementConvertors/PubSubEventRedirectConvertor.h25
-rw-r--r--Sluift/ElementConvertors/PubSubEventRetractConvertor.cpp49
-rw-r--r--Sluift/ElementConvertors/PubSubEventRetractConvertor.h25
-rw-r--r--Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.cpp163
-rw-r--r--Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h25
-rw-r--r--Sluift/ElementConvertors/PubSubItemConvertor.cpp111
-rw-r--r--Sluift/ElementConvertors/PubSubItemConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubItemsConvertor.cpp143
-rw-r--r--Sluift/ElementConvertors/PubSubItemsConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubOptionsConvertor.cpp106
-rw-r--r--Sluift/ElementConvertors/PubSubOptionsConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.cpp137
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.h25
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp103
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.cpp74
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.cpp54
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.cpp70
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.cpp49
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h25
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.cpp49
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h25
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.cpp113
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h25
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp103
-rw-r--r--Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubPublishConvertor.cpp111
-rw-r--r--Sluift/ElementConvertors/PubSubPublishConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubRetractConvertor.cpp129
-rw-r--r--Sluift/ElementConvertors/PubSubRetractConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubSubscribeConvertor.cpp90
-rw-r--r--Sluift/ElementConvertors/PubSubSubscribeConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.cpp49
-rw-r--r--Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h25
-rw-r--r--Sluift/ElementConvertors/PubSubSubscriptionConvertor.cpp174
-rw-r--r--Sluift/ElementConvertors/PubSubSubscriptionConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp107
-rw-r--r--Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h26
-rw-r--r--Sluift/ElementConvertors/PubSubUnsubscribeConvertor.cpp89
-rw-r--r--Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h25
-rw-r--r--Sluift/ElementConvertors/RawXMLElementConvertor.cpp35
-rw-r--r--Sluift/ElementConvertors/RawXMLElementConvertor.h22
-rw-r--r--Sluift/ElementConvertors/ResultSetConvertor.cpp190
-rw-r--r--Sluift/ElementConvertors/ResultSetConvertor.h26
-rw-r--r--Sluift/ElementConvertors/SConscript98
-rw-r--r--Sluift/ElementConvertors/SecurityLabelConvertor.cpp151
-rw-r--r--Sluift/ElementConvertors/SecurityLabelConvertor.h25
-rw-r--r--Sluift/ElementConvertors/SoftwareVersionConvertor.cpp61
-rw-r--r--Sluift/ElementConvertors/SoftwareVersionConvertor.h18
-rw-r--r--Sluift/ElementConvertors/StanzaConvertor.h142
-rw-r--r--Sluift/ElementConvertors/StatusConvertor.cpp33
-rw-r--r--Sluift/ElementConvertors/StatusConvertor.h18
-rw-r--r--Sluift/ElementConvertors/StatusShowConvertor.cpp95
-rw-r--r--Sluift/ElementConvertors/StatusShowConvertor.h22
-rw-r--r--Sluift/ElementConvertors/SubjectConvertor.cpp30
-rw-r--r--Sluift/ElementConvertors/SubjectConvertor.h20
-rw-r--r--Sluift/ElementConvertors/UserLocationConvertor.cpp471
-rw-r--r--Sluift/ElementConvertors/UserLocationConvertor.h25
-rw-r--r--Sluift/ElementConvertors/UserTuneConvertor.cpp173
-rw-r--r--Sluift/ElementConvertors/UserTuneConvertor.h25
-rw-r--r--Sluift/ElementConvertors/VCardConvertor.cpp1218
-rw-r--r--Sluift/ElementConvertors/VCardConvertor.h18
-rw-r--r--Sluift/ElementConvertors/VCardUpdateConvertor.cpp33
-rw-r--r--Sluift/ElementConvertors/VCardUpdateConvertor.h18
-rw-r--r--Sluift/GenericLuaElementConvertor.h80
-rw-r--r--Sluift/Helpers.cpp92
-rw-r--r--Sluift/Helpers.h16
-rw-r--r--Sluift/ITunesInterface.h54
-rw-r--r--Sluift/ITunesInterface.mm50
-rw-r--r--Sluift/Lua/Check.cpp70
-rw-r--r--Sluift/Lua/Check.h22
-rw-r--r--Sluift/Lua/Debug.h35
-rw-r--r--Sluift/Lua/Exception.h19
-rw-r--r--Sluift/Lua/FunctionRegistration.cpp2
-rw-r--r--Sluift/Lua/FunctionRegistration.h55
-rw-r--r--Sluift/Lua/FunctionRegistry.cpp57
-rw-r--r--Sluift/Lua/FunctionRegistry.h72
-rw-r--r--Sluift/Lua/LuaUtils.cpp309
-rw-r--r--Sluift/Lua/LuaUtils.h48
-rw-r--r--Sluift/Lua/Value.cpp76
-rw-r--r--Sluift/Lua/Value.h88
-rw-r--r--Sluift/LuaElementConvertor.h43
-rw-r--r--Sluift/LuaElementConvertors.cpp197
-rw-r--r--Sluift/LuaElementConvertors.h75
-rw-r--r--Sluift/Response.cpp113
-rw-r--r--Sluift/Response.h46
-rw-r--r--Sluift/SConscript148
-rw-r--r--Sluift/SConscript.variant56
-rw-r--r--Sluift/SluiftClient.cpp241
-rw-r--r--Sluift/SluiftClient.h220
-rw-r--r--Sluift/SluiftComponent.cpp185
-rw-r--r--Sluift/SluiftComponent.h174
-rw-r--r--Sluift/SluiftGlobals.h30
-rw-r--r--Sluift/StandardTerminal.cpp25
-rw-r--r--Sluift/StandardTerminal.h19
-rw-r--r--Sluift/Terminal.cpp4
-rw-r--r--Sluift/Terminal.h37
-rw-r--r--Sluift/Tests/FormTest.lua14
-rw-r--r--Sluift/UnitTest/TokenizeTest.cpp76
-rw-r--r--Sluift/Watchdog.cpp56
-rw-r--r--Sluift/Watchdog.h30
-rw-r--r--Sluift/client.cpp1240
-rw-r--r--Sluift/component.cpp717
-rw-r--r--Sluift/globals.h6
-rw-r--r--Sluift/main.cpp268
-rw-r--r--Sluift/sluift.cpp671
-rw-r--r--Sluift/tokenize.cpp131
-rw-r--r--Sluift/tokenize.h10
-rw-r--r--SwifTools/Application/ApplicationPathProvider.cpp42
-rw-r--r--SwifTools/Application/ApplicationPathProvider.h34
-rw-r--r--SwifTools/Application/CocoaApplication.h20
-rw-r--r--SwifTools/Application/CocoaApplication.mm20
-rw-r--r--SwifTools/Application/MacOSXApplicationPathProvider.cpp27
-rw-r--r--SwifTools/Application/MacOSXApplicationPathProvider.h22
-rw-r--r--SwifTools/Application/PlatformApplicationPathProvider.h6
-rw-r--r--SwifTools/Application/SConscript30
-rw-r--r--SwifTools/Application/UnitTest/ApplicationPathProviderTest.cpp71
-rw-r--r--SwifTools/Application/UnixApplicationPathProvider.cpp75
-rw-r--r--SwifTools/Application/UnixApplicationPathProvider.h22
-rw-r--r--SwifTools/Application/WindowsApplicationPathProvider.cpp30
-rw-r--r--SwifTools/Application/WindowsApplicationPathProvider.h22
-rw-r--r--SwifTools/AutoUpdater/AutoUpdater.h26
-rw-r--r--SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.cpp12
-rw-r--r--SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.h12
-rw-r--r--SwifTools/AutoUpdater/SparkleAutoUpdater.h32
-rw-r--r--SwifTools/AutoUpdater/SparkleAutoUpdater.mm54
-rw-r--r--SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.h35
-rw-r--r--SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.mm57
-rw-r--r--SwifTools/Cocoa/CocoaAction.h5
-rw-r--r--SwifTools/Cocoa/CocoaAction.mm18
-rw-r--r--SwifTools/Cocoa/CocoaUtil.h44
-rw-r--r--SwifTools/Cocoa/SConscript2
-rw-r--r--SwifTools/CrashReporter.cpp60
-rw-r--r--SwifTools/CrashReporter.h21
-rw-r--r--SwifTools/Dock/Dock.h12
-rw-r--r--SwifTools/Dock/MacOSXDock.h14
-rw-r--r--SwifTools/Dock/MacOSXDock.mm15
-rw-r--r--SwifTools/Dock/NullDock.h12
-rw-r--r--SwifTools/Dock/SConscript10
-rw-r--r--SwifTools/Dock/WindowsDock.h57
-rw-r--r--SwifTools/HunspellChecker.cpp167
-rw-r--r--SwifTools/HunspellChecker.h56
-rw-r--r--SwifTools/Idle/ActualIdleDetector.cpp17
-rw-r--r--SwifTools/Idle/ActualIdleDetector.h30
-rw-r--r--SwifTools/Idle/DummyIdleQuerier.h14
-rw-r--r--SwifTools/Idle/IdleDetector.h67
-rw-r--r--SwifTools/Idle/IdleQuerier.h10
-rw-r--r--SwifTools/Idle/IdleQuerierTest/IdleQuerierTest.cpp21
-rw-r--r--SwifTools/Idle/IdleQuerierTest/SConscript18
-rw-r--r--SwifTools/Idle/MacOSXIdleQuerier.cpp22
-rw-r--r--SwifTools/Idle/MacOSXIdleQuerier.h14
-rw-r--r--SwifTools/Idle/PlatformIdleQuerier.cpp16
-rw-r--r--SwifTools/Idle/PlatformIdleQuerier.h20
-rw-r--r--SwifTools/Idle/UnitTest/ActualIdleDetectorTest.cpp304
-rw-r--r--SwifTools/Idle/UnitTest/SConscript4
-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.cpp32
-rw-r--r--SwifTools/LastLineTracker.h18
-rw-r--r--SwifTools/Linkify.cpp167
-rw-r--r--SwifTools/Linkify.h32
-rw-r--r--SwifTools/MacOSXChecker.h31
-rw-r--r--SwifTools/MacOSXChecker.mm69
-rw-r--r--SwifTools/Notifier/GNTPNotifier.cpp94
-rw-r--r--SwifTools/Notifier/GNTPNotifier.h51
-rw-r--r--SwifTools/Notifier/GrowlNotifier.h58
-rw-r--r--SwifTools/Notifier/GrowlNotifier.mm135
-rw-r--r--SwifTools/Notifier/GrowlNotifierDelegate.h8
-rw-r--r--SwifTools/Notifier/GrowlNotifierDelegate.mm8
-rw-r--r--SwifTools/Notifier/LoggingNotifier.h37
-rw-r--r--SwifTools/Notifier/NotificationCenterNotifier.h25
-rw-r--r--SwifTools/Notifier/NotificationCenterNotifier.mm101
-rw-r--r--SwifTools/Notifier/NotificationCenterNotifierDelegate.h2
-rw-r--r--SwifTools/Notifier/NotificationCenterNotifierDelegate.mm8
-rw-r--r--SwifTools/Notifier/Notifier.cpp40
-rw-r--r--SwifTools/Notifier/Notifier.h77
-rw-r--r--SwifTools/Notifier/NullNotifier.h14
-rw-r--r--SwifTools/Notifier/SConscript28
-rw-r--r--SwifTools/Notifier/SnarlNotifier.cpp73
-rw-r--r--SwifTools/Notifier/SnarlNotifier.h39
-rw-r--r--SwifTools/Notifier/TogglableNotifier.h100
-rw-r--r--SwifTools/Notifier/Win32NotifierWindow.h16
-rw-r--r--SwifTools/SConscript128
-rw-r--r--SwifTools/SpellChecker.h47
-rw-r--r--SwifTools/SpellCheckerFactory.cpp20
-rw-r--r--SwifTools/SpellCheckerFactory.h21
-rw-r--r--SwifTools/SpellParser.cpp90
-rw-r--r--SwifTools/SpellParser.h37
-rw-r--r--SwifTools/TabComplete.cpp65
-rw-r--r--SwifTools/TabComplete.h27
-rw-r--r--SwifTools/URIHandler/MacOSXURIHandler.h24
-rw-r--r--SwifTools/URIHandler/MacOSXURIHandler.mm59
-rw-r--r--SwifTools/URIHandler/NullURIHandler.h14
-rw-r--r--SwifTools/URIHandler/SConscript20
-rw-r--r--SwifTools/URIHandler/URIHandler.h17
-rw-r--r--SwifTools/URIHandler/UnitTest/XMPPURITest.cpp312
-rw-r--r--SwifTools/URIHandler/XMPPURI.cpp156
-rw-r--r--SwifTools/URIHandler/XMPPURI.h120
-rw-r--r--SwifTools/UnitTest/LastLineTrackerTest.cpp92
-rw-r--r--SwifTools/UnitTest/LinkifyTest.cpp448
-rw-r--r--SwifTools/UnitTest/SConscript14
-rw-r--r--SwifTools/UnitTest/SpellParserTest.cpp75
-rw-r--r--SwifTools/UnitTest/TabCompleteTest.cpp486
-rw-r--r--Swift/ChangeLog.md65
-rw-r--r--Swift/Controllers/AdHocController.cpp20
-rw-r--r--Swift/Controllers/AdHocController.h17
-rw-r--r--Swift/Controllers/AdHocManager.cpp120
-rw-r--r--Swift/Controllers/AdHocManager.h49
-rw-r--r--Swift/Controllers/BlockListController.cpp273
-rw-r--r--Swift/Controllers/BlockListController.h39
-rw-r--r--Swift/Controllers/CertificateMemoryStorageFactory.h28
-rw-r--r--Swift/Controllers/Chat/AutoAcceptMUCInviteDecider.h71
-rw-r--r--Swift/Controllers/Chat/ChatController.cpp782
-rw-r--r--Swift/Controllers/Chat/ChatController.h194
-rw-r--r--Swift/Controllers/Chat/ChatControllerBase.cpp577
-rw-r--r--Swift/Controllers/Chat/ChatControllerBase.h202
-rw-r--r--Swift/Controllers/Chat/ChatMessageParser.cpp358
-rw-r--r--Swift/Controllers/Chat/ChatMessageParser.h22
-rw-r--r--Swift/Controllers/Chat/ChatsManager.cpp1672
-rw-r--r--Swift/Controllers/Chat/ChatsManager.h316
-rw-r--r--Swift/Controllers/Chat/MUCController.cpp1824
-rw-r--r--Swift/Controllers/Chat/MUCController.h315
-rw-r--r--Swift/Controllers/Chat/MUCSearchController.cpp248
-rw-r--r--Swift/Controllers/Chat/MUCSearchController.h220
-rw-r--r--Swift/Controllers/Chat/UnitTest/ChatMessageParserTest.cpp519
-rw-r--r--Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp1831
-rw-r--r--Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp998
-rw-r--r--Swift/Controllers/Chat/UnitTest/MockChatListWindow.h32
-rw-r--r--Swift/Controllers/Chat/UserSearchController.cpp583
-rw-r--r--Swift/Controllers/Chat/UserSearchController.h138
-rw-r--r--Swift/Controllers/ChatMessageSummarizer.cpp56
-rw-r--r--Swift/Controllers/ChatMessageSummarizer.h14
-rw-r--r--Swift/Controllers/ConnectionSettings.h54
-rw-r--r--Swift/Controllers/Contact.cpp83
-rw-r--r--Swift/Controllers/Contact.h31
-rw-r--r--Swift/Controllers/ContactEditController.cpp139
-rw-r--r--Swift/Controllers/ContactEditController.h78
-rw-r--r--Swift/Controllers/ContactProvider.h6
-rw-r--r--Swift/Controllers/ContactSuggester.cpp75
-rw-r--r--Swift/Controllers/ContactSuggester.h40
-rw-r--r--Swift/Controllers/ContactsFromXMPPRoster.cpp21
-rw-r--r--Swift/Controllers/ContactsFromXMPPRoster.h18
-rw-r--r--Swift/Controllers/DummySoundPlayer.h8
-rw-r--r--Swift/Controllers/DummySystemTray.h16
-rw-r--r--Swift/Controllers/EventNotifier.cpp82
-rw-r--r--Swift/Controllers/EventNotifier.h65
-rw-r--r--Swift/Controllers/EventWindowController.cpp61
-rw-r--r--Swift/Controllers/EventWindowController.h33
-rw-r--r--Swift/Controllers/FileTransfer/FileTransferController.cpp179
-rw-r--r--Swift/Controllers/FileTransfer/FileTransferController.h72
-rw-r--r--Swift/Controllers/FileTransfer/FileTransferOverview.cpp89
-rw-r--r--Swift/Controllers/FileTransfer/FileTransferOverview.h32
-rw-r--r--Swift/Controllers/FileTransfer/FileTransferProgressInfo.cpp26
-rw-r--r--Swift/Controllers/FileTransfer/FileTransferProgressInfo.h22
-rw-r--r--Swift/Controllers/FileTransferListController.cpp50
-rw-r--r--Swift/Controllers/FileTransferListController.h24
-rw-r--r--Swift/Controllers/HighlightAction.cpp52
-rw-r--r--Swift/Controllers/HighlightAction.h118
-rw-r--r--Swift/Controllers/HighlightEditorController.cpp43
-rw-r--r--Swift/Controllers/HighlightEditorController.h45
-rw-r--r--Swift/Controllers/HighlightManager.cpp150
-rw-r--r--Swift/Controllers/HighlightManager.h93
-rw-r--r--Swift/Controllers/HighlightRule.cpp215
-rw-r--r--Swift/Controllers/HighlightRule.h120
-rw-r--r--Swift/Controllers/Highlighter.cpp36
-rw-r--r--Swift/Controllers/Highlighter.h39
-rw-r--r--Swift/Controllers/HistoryController.cpp26
-rw-r--r--Swift/Controllers/HistoryController.h36
-rw-r--r--Swift/Controllers/HistoryViewController.cpp537
-rw-r--r--Swift/Controllers/HistoryViewController.h102
-rw-r--r--Swift/Controllers/Intl.h5
-rw-r--r--Swift/Controllers/MainController.cpp1431
-rw-r--r--Swift/Controllers/MainController.h351
-rw-r--r--Swift/Controllers/PresenceNotifier.cpp189
-rw-r--r--Swift/Controllers/PresenceNotifier.h96
-rw-r--r--Swift/Controllers/PreviousStatusStore.cpp52
-rw-r--r--Swift/Controllers/PreviousStatusStore.h29
-rw-r--r--Swift/Controllers/ProfileController.cpp125
-rw-r--r--Swift/Controllers/ProfileController.h63
-rw-r--r--Swift/Controllers/ProfileSettingsProvider.cpp68
-rw-r--r--Swift/Controllers/ProfileSettingsProvider.h38
-rw-r--r--Swift/Controllers/Roster/ContactRosterItem.cpp147
-rw-r--r--Swift/Controllers/Roster/ContactRosterItem.h136
-rw-r--r--Swift/Controllers/Roster/FuzzyRosterFilter.h38
-rw-r--r--Swift/Controllers/Roster/GroupRosterItem.cpp309
-rw-r--r--Swift/Controllers/Roster/GroupRosterItem.h66
-rw-r--r--Swift/Controllers/Roster/ItemOperations/AppearOffline.h24
-rw-r--r--Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h34
-rw-r--r--Swift/Controllers/Roster/ItemOperations/SetAvailableFeatures.h38
-rw-r--r--Swift/Controllers/Roster/ItemOperations/SetAvatar.h34
-rw-r--r--Swift/Controllers/Roster/ItemOperations/SetBlockingState.h56
-rw-r--r--Swift/Controllers/Roster/ItemOperations/SetMUC.h38
-rw-r--r--Swift/Controllers/Roster/ItemOperations/SetName.h34
-rw-r--r--Swift/Controllers/Roster/ItemOperations/SetPresence.h28
-rw-r--r--Swift/Controllers/Roster/ItemOperations/SetVCard.h38
-rw-r--r--Swift/Controllers/Roster/LeastCommonSubsequence.h173
-rw-r--r--Swift/Controllers/Roster/OfflineRosterFilter.h23
-rw-r--r--Swift/Controllers/Roster/Roster.cpp367
-rw-r--r--Swift/Controllers/Roster/Roster.h82
-rw-r--r--Swift/Controllers/Roster/RosterController.cpp525
-rw-r--r--Swift/Controllers/Roster/RosterController.h192
-rw-r--r--Swift/Controllers/Roster/RosterFilter.h10
-rw-r--r--Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp61
-rw-r--r--Swift/Controllers/Roster/RosterGroupExpandinessPersister.h31
-rw-r--r--Swift/Controllers/Roster/RosterItem.cpp26
-rw-r--r--Swift/Controllers/Roster/RosterItem.h32
-rw-r--r--Swift/Controllers/Roster/RosterVCardProvider.cpp22
-rw-r--r--Swift/Controllers/Roster/RosterVCardProvider.h38
-rw-r--r--Swift/Controllers/Roster/TableRoster.cpp291
-rw-r--r--Swift/Controllers/Roster/TableRoster.h141
-rw-r--r--Swift/Controllers/Roster/UnitTest/LeastCommonSubsequenceTest.cpp565
-rw-r--r--Swift/Controllers/Roster/UnitTest/RosterControllerTest.cpp781
-rw-r--r--Swift/Controllers/Roster/UnitTest/RosterTest.cpp252
-rw-r--r--Swift/Controllers/Roster/UnitTest/TableRosterTest.cpp126
-rw-r--r--Swift/Controllers/SConscript190
-rw-r--r--Swift/Controllers/SettingConstants.cpp9
-rw-r--r--Swift/Controllers/SettingConstants.h176
-rw-r--r--Swift/Controllers/Settings/DummySettingsProvider.h84
-rw-r--r--Swift/Controllers/Settings/SettingsProvider.h108
-rw-r--r--Swift/Controllers/Settings/SettingsProviderHierachy.cpp124
-rw-r--r--Swift/Controllers/Settings/SettingsProviderHierachy.h56
-rw-r--r--Swift/Controllers/Settings/UnitTest/SettingsProviderHierachyTest.cpp120
-rw-r--r--Swift/Controllers/Settings/XMLSettingsProvider.cpp120
-rw-r--r--Swift/Controllers/Settings/XMLSettingsProvider.h77
-rw-r--r--Swift/Controllers/ShowProfileController.cpp76
-rw-r--r--Swift/Controllers/ShowProfileController.h50
-rw-r--r--Swift/Controllers/SoundEventController.cpp42
-rw-r--r--Swift/Controllers/SoundEventController.h44
-rw-r--r--Swift/Controllers/SoundPlayer.h12
-rw-r--r--Swift/Controllers/StatusCache.cpp136
-rw-r--r--Swift/Controllers/StatusCache.h45
-rw-r--r--Swift/Controllers/StatusTracker.cpp66
-rw-r--r--Swift/Controllers/StatusTracker.h32
-rw-r--r--Swift/Controllers/StatusUtil.cpp23
-rw-r--r--Swift/Controllers/StatusUtil.h2
-rw-r--r--Swift/Controllers/Storages/AvatarFileStorage.cpp130
-rw-r--r--Swift/Controllers/Storages/AvatarFileStorage.h45
-rw-r--r--Swift/Controllers/Storages/CapsFileStorage.cpp22
-rw-r--r--Swift/Controllers/Storages/CapsFileStorage.h27
-rw-r--r--Swift/Controllers/Storages/CertificateFileStorage.cpp67
-rw-r--r--Swift/Controllers/Storages/CertificateFileStorage.h32
-rw-r--r--Swift/Controllers/Storages/CertificateFileStorageFactory.h34
-rw-r--r--Swift/Controllers/Storages/CertificateMemoryStorage.cpp18
-rw-r--r--Swift/Controllers/Storages/CertificateMemoryStorage.h16
-rw-r--r--Swift/Controllers/Storages/CertificateStorage.cpp4
-rw-r--r--Swift/Controllers/Storages/CertificateStorage.h12
-rw-r--r--Swift/Controllers/Storages/CertificateStorageFactory.h14
-rw-r--r--Swift/Controllers/Storages/CertificateStorageTrustChecker.h39
-rw-r--r--Swift/Controllers/Storages/FileStorages.cpp52
-rw-r--r--Swift/Controllers/Storages/FileStorages.h80
-rw-r--r--Swift/Controllers/Storages/FileStoragesFactory.h28
-rw-r--r--Swift/Controllers/Storages/MemoryStoragesFactory.h29
-rw-r--r--Swift/Controllers/Storages/RosterFileStorage.cpp12
-rw-r--r--Swift/Controllers/Storages/RosterFileStorage.h18
-rw-r--r--Swift/Controllers/Storages/StoragesFactory.h14
-rw-r--r--Swift/Controllers/Storages/VCardFileStorage.cpp178
-rw-r--r--Swift/Controllers/Storages/VCardFileStorage.h51
-rw-r--r--Swift/Controllers/SystemTray.h18
-rw-r--r--Swift/Controllers/SystemTrayController.cpp36
-rw-r--r--Swift/Controllers/SystemTrayController.h30
-rw-r--r--Swift/Controllers/Translator.cpp16
-rw-r--r--Swift/Controllers/Translator.h28
-rw-r--r--Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h24
-rw-r--r--Swift/Controllers/UIEvents/AddContactUIEvent.h50
-rw-r--r--Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h23
-rw-r--r--Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h24
-rw-r--r--Swift/Controllers/UIEvents/CreateImpromptuMUCUIEvent.h41
-rw-r--r--Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h27
-rw-r--r--Swift/Controllers/UIEvents/InviteToMUCUIEvent.h59
-rw-r--r--Swift/Controllers/UIEvents/JoinMUCUIEvent.h47
-rw-r--r--Swift/Controllers/UIEvents/RemoveMUCBookmarkUIEvent.h23
-rw-r--r--Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h19
-rw-r--r--Swift/Controllers/UIEvents/RenameGroupUIEvent.h33
-rw-r--r--Swift/Controllers/UIEvents/RenameRosterItemUIEvent.h27
-rw-r--r--Swift/Controllers/UIEvents/RequestAdHocUIEvent.h19
-rw-r--r--Swift/Controllers/UIEvents/RequestAdHocWithJIDUIEvent.h26
-rw-r--r--Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h25
-rw-r--r--Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h48
-rw-r--r--Swift/Controllers/UIEvents/RequestChatUIEvent.h20
-rw-r--r--Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h8
-rw-r--r--Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h25
-rw-r--r--Swift/Controllers/UIEvents/RequestHighlightEditorUIEvent.h4
-rw-r--r--Swift/Controllers/UIEvents/RequestHistoryUIEvent.h4
-rw-r--r--Swift/Controllers/UIEvents/RequestInviteToMUCUIEvent.h77
-rw-r--r--Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h29
-rw-r--r--Swift/Controllers/UIEvents/RequestProfileEditorUIEvent.h12
-rw-r--r--Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h24
-rw-r--r--Swift/Controllers/UIEvents/RequestXMLConsoleUIEvent.h8
-rw-r--r--Swift/Controllers/UIEvents/SendFileUIEvent.h45
-rw-r--r--Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h23
-rw-r--r--Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h24
-rw-r--r--Swift/Controllers/UIEvents/UIEvent.cpp4
-rw-r--r--Swift/Controllers/UIEvents/UIEvent.h14
-rw-r--r--Swift/Controllers/UIEvents/UIEventStream.h23
-rw-r--r--Swift/Controllers/UIInterfaces/AdHocCommandWindow.h16
-rw-r--r--Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h15
-rw-r--r--Swift/Controllers/UIInterfaces/BlockListEditorWidget.h29
-rw-r--r--Swift/Controllers/UIInterfaces/BlockListEditorWidgetFactory.h12
-rw-r--r--Swift/Controllers/UIInterfaces/ChatListWindow.cpp4
-rw-r--r--Swift/Controllers/UIInterfaces/ChatListWindow.h168
-rw-r--r--Swift/Controllers/UIInterfaces/ChatListWindowFactory.h16
-rw-r--r--Swift/Controllers/UIInterfaces/ChatWindow.h443
-rw-r--r--Swift/Controllers/UIInterfaces/ChatWindowFactory.h20
-rw-r--r--Swift/Controllers/UIInterfaces/ContactEditWindow.h34
-rw-r--r--Swift/Controllers/UIInterfaces/ContactEditWindowFactory.h10
-rw-r--r--Swift/Controllers/UIInterfaces/EventWindow.h30
-rw-r--r--Swift/Controllers/UIInterfaces/EventWindowFactory.h18
-rw-r--r--Swift/Controllers/UIInterfaces/FileTransferListWidget.h8
-rw-r--r--Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h12
-rw-r--r--Swift/Controllers/UIInterfaces/HighlightEditorWidget.h14
-rw-r--r--Swift/Controllers/UIInterfaces/HighlightEditorWidgetFactory.h12
-rw-r--r--Swift/Controllers/UIInterfaces/HighlightEditorWindow.h20
-rw-r--r--Swift/Controllers/UIInterfaces/HighlightEditorWindowFactory.h12
-rw-r--r--Swift/Controllers/UIInterfaces/HistoryWindow.h44
-rw-r--r--Swift/Controllers/UIInterfaces/HistoryWindowFactory.h12
-rw-r--r--Swift/Controllers/UIInterfaces/JoinMUCWindow.h23
-rw-r--r--Swift/Controllers/UIInterfaces/JoinMUCWindowFactory.h12
-rw-r--r--Swift/Controllers/UIInterfaces/LoginWindow.h55
-rw-r--r--Swift/Controllers/UIInterfaces/LoginWindowFactory.h28
-rw-r--r--Swift/Controllers/UIInterfaces/MUCSearchWindow.h33
-rw-r--r--Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h16
-rw-r--r--Swift/Controllers/UIInterfaces/MainWindow.h75
-rw-r--r--Swift/Controllers/UIInterfaces/MainWindowFactory.h18
-rw-r--r--Swift/Controllers/UIInterfaces/ProfileWindow.h37
-rw-r--r--Swift/Controllers/UIInterfaces/ProfileWindowFactory.h10
-rw-r--r--Swift/Controllers/UIInterfaces/UIFactory.h64
-rw-r--r--Swift/Controllers/UIInterfaces/UserSearchWindow.h82
-rw-r--r--Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h16
-rw-r--r--Swift/Controllers/UIInterfaces/WhiteboardWindow.h30
-rw-r--r--Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h22
-rw-r--r--Swift/Controllers/UIInterfaces/XMLConsoleWidget.cpp4
-rw-r--r--Swift/Controllers/UIInterfaces/XMLConsoleWidget.h16
-rw-r--r--Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h16
-rw-r--r--Swift/Controllers/UnitTest/ChatMessageSummarizerTest.cpp206
-rw-r--r--Swift/Controllers/UnitTest/ContactSuggesterTest.cpp216
-rw-r--r--Swift/Controllers/UnitTest/HighlightRuleTest.cpp488
-rw-r--r--Swift/Controllers/UnitTest/MockChatWindow.cpp4
-rw-r--r--Swift/Controllers/UnitTest/MockChatWindow.h241
-rw-r--r--Swift/Controllers/UnitTest/MockMainWindow.h40
-rw-r--r--Swift/Controllers/UnitTest/MockMainWindowFactory.h26
-rw-r--r--Swift/Controllers/UnitTest/PresenceNotifierTest.cpp522
-rw-r--r--Swift/Controllers/UnitTest/PreviousStatusStoreTest.cpp44
-rw-r--r--Swift/Controllers/WhiteboardManager.cpp240
-rw-r--r--Swift/Controllers/WhiteboardManager.h87
-rw-r--r--Swift/Controllers/XMLConsoleController.cpp44
-rw-r--r--Swift/Controllers/XMLConsoleController.h50
-rw-r--r--Swift/Controllers/XMPPEvents/ErrorEvent.h35
-rw-r--r--Swift/Controllers/XMPPEvents/EventController.cpp80
-rw-r--r--Swift/Controllers/XMPPEvents/EventController.h41
-rw-r--r--Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h24
-rw-r--r--Swift/Controllers/XMPPEvents/MUCInviteEvent.h49
-rw-r--r--Swift/Controllers/XMPPEvents/MessageEvent.h49
-rw-r--r--Swift/Controllers/XMPPEvents/StanzaEvent.h36
-rw-r--r--Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h65
-rw-r--r--Swift/Controllers/XMPPURIController.cpp34
-rw-r--r--Swift/Controllers/XMPPURIController.h35
-rw-r--r--Swift/Packaging/Debian/debian/control.in2
-rwxr-xr-xSwift/Packaging/Debian/package_all_platforms.sh2
-rw-r--r--Swift/Packaging/MacOSX/Swift.dmg.gzbin517911 -> 539857 bytes
-rwxr-xr-xSwift/Packaging/MacOSX/package.sh6
-rwxr-xr-xSwift/Packaging/Source/package.sh21
-rw-r--r--Swift/QtUI/ApplicationTest/main.cpp59
-rw-r--r--Swift/QtUI/CAPICertificateSelector.cpp114
-rw-r--r--Swift/QtUI/CAPICertificateSelector.h4
-rw-r--r--Swift/QtUI/ChatList/ChatListDelegate.cpp191
-rw-r--r--Swift/QtUI/ChatList/ChatListDelegate.h46
-rw-r--r--Swift/QtUI/ChatList/ChatListGroupItem.h63
-rw-r--r--Swift/QtUI/ChatList/ChatListItem.h23
-rw-r--r--Swift/QtUI/ChatList/ChatListMUCItem.cpp32
-rw-r--r--Swift/QtUI/ChatList/ChatListMUCItem.h40
-rw-r--r--Swift/QtUI/ChatList/ChatListModel.cpp231
-rw-r--r--Swift/QtUI/ChatList/ChatListModel.h66
-rw-r--r--Swift/QtUI/ChatList/ChatListRecentItem.cpp31
-rw-r--r--Swift/QtUI/ChatList/ChatListRecentItem.h41
-rw-r--r--Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp60
-rw-r--r--Swift/QtUI/ChatList/ChatListWhiteboardItem.h39
-rw-r--r--Swift/QtUI/ChatList/QtChatListWindow.cpp250
-rw-r--r--Swift/QtUI/ChatList/QtChatListWindow.h86
-rw-r--r--Swift/QtUI/ChatSnippet.cpp118
-rw-r--r--Swift/QtUI/ChatSnippet.h108
-rw-r--r--Swift/QtUI/ChatView/main.cpp286
-rw-r--r--Swift/QtUI/CocoaApplicationActivateHelper.h32
-rw-r--r--Swift/QtUI/CocoaApplicationActivateHelper.mm42
-rw-r--r--Swift/QtUI/CocoaUIHelpers.h12
-rw-r--r--Swift/QtUI/CocoaUIHelpers.mm48
-rw-r--r--Swift/QtUI/EventViewer/EventDelegate.cpp110
-rw-r--r--Swift/QtUI/EventViewer/EventDelegate.h34
-rw-r--r--Swift/QtUI/EventViewer/EventModel.cpp132
-rw-r--r--Swift/QtUI/EventViewer/EventModel.h38
-rw-r--r--Swift/QtUI/EventViewer/EventView.cpp6
-rw-r--r--Swift/QtUI/EventViewer/EventView.h10
-rw-r--r--Swift/QtUI/EventViewer/QtEvent.cpp132
-rw-r--r--Swift/QtUI/EventViewer/QtEvent.h34
-rw-r--r--Swift/QtUI/EventViewer/QtEventWindow.cpp149
-rw-r--r--Swift/QtUI/EventViewer/QtEventWindow.h62
-rw-r--r--Swift/QtUI/EventViewer/TwoLineDelegate.cpp83
-rw-r--r--Swift/QtUI/EventViewer/TwoLineDelegate.h30
-rw-r--r--Swift/QtUI/EventViewer/main.cpp42
-rw-r--r--Swift/QtUI/FreeDesktopNotifier.cpp62
-rw-r--r--Swift/QtUI/FreeDesktopNotifier.h25
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp111
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchDelegate.h26
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp46
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h23
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchItem.h18
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchModel.cpp130
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchModel.h44
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp30
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchRoomItem.h30
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchServiceItem.cpp78
-rw-r--r--Swift/QtUI/MUCSearch/MUCSearchServiceItem.h47
-rw-r--r--Swift/QtUI/MUCSearch/QtLeafSortFilterProxyModel.cpp28
-rw-r--r--Swift/QtUI/MUCSearch/QtLeafSortFilterProxyModel.h29
-rw-r--r--Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp277
-rw-r--r--Swift/QtUI/MUCSearch/QtMUCSearchWindow.h84
-rw-r--r--Swift/QtUI/MUCSearch/QtMUCSearchWindow.ui62
-rw-r--r--Swift/QtUI/MessageSnippet.cpp60
-rw-r--r--Swift/QtUI/MessageSnippet.h30
-rw-r--r--Swift/QtUI/NotifierTest/NotifierTest.cpp20
-rw-r--r--Swift/QtUI/QtAboutWidget.cpp179
-rw-r--r--Swift/QtUI/QtAboutWidget.h33
-rw-r--r--Swift/QtUI/QtAdHocCommandWindow.cpp226
-rw-r--r--Swift/QtUI/QtAdHocCommandWindow.h76
-rw-r--r--Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp48
-rw-r--r--Swift/QtUI/QtAdHocCommandWithJIDWindow.h30
-rw-r--r--Swift/QtUI/QtAddBookmarkWindow.cpp26
-rw-r--r--Swift/QtUI/QtAddBookmarkWindow.h26
-rw-r--r--Swift/QtUI/QtAffiliationEditor.cpp87
-rw-r--r--Swift/QtUI/QtAffiliationEditor.h45
-rw-r--r--Swift/QtUI/QtAvatarWidget.cpp165
-rw-r--r--Swift/QtUI/QtAvatarWidget.h69
-rw-r--r--Swift/QtUI/QtBlockListEditorWindow.cpp304
-rw-r--r--Swift/QtUI/QtBlockListEditorWindow.h57
-rw-r--r--Swift/QtUI/QtBookmarkDetailWindow.cpp102
-rw-r--r--Swift/QtUI/QtBookmarkDetailWindow.h34
-rw-r--r--Swift/QtUI/QtCachedImageScaler.cpp47
-rw-r--r--Swift/QtUI/QtCachedImageScaler.h10
-rw-r--r--Swift/QtUI/QtCertificateViewerDialog.cpp187
-rw-r--r--Swift/QtUI/QtCertificateViewerDialog.h28
-rw-r--r--Swift/QtUI/QtChatTabs.cpp644
-rw-r--r--Swift/QtUI/QtChatTabs.h118
-rw-r--r--Swift/QtUI/QtChatTabsBase.h8
-rw-r--r--Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp101
-rw-r--r--Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h32
-rw-r--r--Swift/QtUI/QtChatTheme.cpp96
-rw-r--r--Swift/QtUI/QtChatTheme.h57
-rw-r--r--Swift/QtUI/QtChatView.cpp5
-rw-r--r--Swift/QtUI/QtChatView.h80
-rw-r--r--Swift/QtUI/QtChatWindow.cpp1284
-rw-r--r--Swift/QtUI/QtChatWindow.h401
-rw-r--r--Swift/QtUI/QtChatWindowFactory.cpp96
-rw-r--r--Swift/QtUI/QtChatWindowFactory.h48
-rw-r--r--Swift/QtUI/QtChatWindowJSBridge.cpp12
-rw-r--r--Swift/QtUI/QtChatWindowJSBridge.h19
-rw-r--r--Swift/QtUI/QtClickableLabel.cpp6
-rw-r--r--Swift/QtUI/QtClickableLabel.h16
-rw-r--r--Swift/QtUI/QtClosableLineEdit.cpp48
-rw-r--r--Swift/QtUI/QtClosableLineEdit.h24
-rw-r--r--Swift/QtUI/QtColorToolButton.cpp40
-rw-r--r--Swift/QtUI/QtColorToolButton.h36
-rw-r--r--Swift/QtUI/QtConnectionSettingsWindow.cpp272
-rw-r--r--Swift/QtUI/QtConnectionSettingsWindow.h48
-rw-r--r--Swift/QtUI/QtContactEditWidget.cpp258
-rw-r--r--Swift/QtUI/QtContactEditWidget.h73
-rw-r--r--Swift/QtUI/QtContactEditWindow.cpp116
-rw-r--r--Swift/QtUI/QtContactEditWindow.h52
-rw-r--r--Swift/QtUI/QtDBUSURIHandler.cpp44
-rw-r--r--Swift/QtUI/QtDBUSURIHandler.h11
-rw-r--r--Swift/QtUI/QtEditBookmarkWindow.cpp28
-rw-r--r--Swift/QtUI/QtEditBookmarkWindow.h29
-rw-r--r--Swift/QtUI/QtElidingLabel.cpp56
-rw-r--r--Swift/QtUI/QtElidingLabel.h36
-rw-r--r--Swift/QtUI/QtEmoticonCell.cpp22
-rw-r--r--Swift/QtUI/QtEmoticonCell.h28
-rw-r--r--Swift/QtUI/QtEmoticonsGrid.cpp64
-rw-r--r--Swift/QtUI/QtEmoticonsGrid.h32
-rw-r--r--Swift/QtUI/QtFileTransferListItemModel.cpp158
-rw-r--r--Swift/QtUI/QtFileTransferListItemModel.h48
-rw-r--r--Swift/QtUI/QtFileTransferListWidget.cpp98
-rw-r--r--Swift/QtUI/QtFileTransferListWidget.h30
-rw-r--r--Swift/QtUI/QtFormResultItemModel.cpp85
-rw-r--r--Swift/QtUI/QtFormResultItemModel.h28
-rw-r--r--Swift/QtUI/QtFormWidget.cpp390
-rw-r--r--Swift/QtUI/QtFormWidget.h31
-rw-r--r--Swift/QtUI/QtHighlightEditor.cpp786
-rw-r--r--Swift/QtUI/QtHighlightEditor.h98
-rw-r--r--Swift/QtUI/QtHighlightEditorWidget.cpp149
-rw-r--r--Swift/QtUI/QtHighlightEditorWidget.h44
-rw-r--r--Swift/QtUI/QtHighlightEditorWidget.ui124
-rw-r--r--Swift/QtUI/QtHighlightRulesItemModel.cpp284
-rw-r--r--Swift/QtUI/QtHighlightRulesItemModel.h64
-rw-r--r--Swift/QtUI/QtHistoryWindow.cpp333
-rw-r--r--Swift/QtUI/QtHistoryWindow.h117
-rw-r--r--Swift/QtUI/QtJoinMUCWindow.cpp71
-rw-r--r--Swift/QtUI/QtJoinMUCWindow.h117
-rw-r--r--Swift/QtUI/QtLineEdit.cpp12
-rw-r--r--Swift/QtUI/QtLineEdit.h20
-rw-r--r--Swift/QtUI/QtLoginWindow.cpp753
-rw-r--r--Swift/QtUI/QtLoginWindow.h169
-rw-r--r--Swift/QtUI/QtMUCConfigurationWindow.cpp66
-rw-r--r--Swift/QtUI/QtMUCConfigurationWindow.h47
-rw-r--r--Swift/QtUI/QtMainWindow.cpp504
-rw-r--r--Swift/QtUI/QtMainWindow.h164
-rw-r--r--Swift/QtUI/QtNameWidget.cpp118
-rw-r--r--Swift/QtUI/QtNameWidget.h66
-rw-r--r--Swift/QtUI/QtPlainChatView.cpp611
-rw-r--r--Swift/QtUI/QtPlainChatView.h220
-rw-r--r--Swift/QtUI/QtProfileWindow.cpp178
-rw-r--r--Swift/QtUI/QtProfileWindow.h50
-rw-r--r--Swift/QtUI/QtResourceHelper.cpp20
-rw-r--r--Swift/QtUI/QtRosterHeader.cpp169
-rw-r--r--Swift/QtUI/QtRosterHeader.h82
-rw-r--r--Swift/QtUI/QtScaledAvatarCache.cpp103
-rw-r--r--Swift/QtUI/QtScaledAvatarCache.h17
-rw-r--r--Swift/QtUI/QtSettingsProvider.cpp126
-rw-r--r--Swift/QtUI/QtSettingsProvider.h50
-rw-r--r--Swift/QtUI/QtSingleWindow.cpp70
-rw-r--r--Swift/QtUI/QtSingleWindow.h46
-rw-r--r--Swift/QtUI/QtSoundPlayer.cpp45
-rw-r--r--Swift/QtUI/QtSoundPlayer.h30
-rw-r--r--Swift/QtUI/QtSpellCheckHighlighter.cpp22
-rw-r--r--Swift/QtUI/QtSpellCheckHighlighter.h20
-rw-r--r--Swift/QtUI/QtSpellCheckerWindow.cpp129
-rw-r--r--Swift/QtUI/QtSpellCheckerWindow.h60
-rw-r--r--Swift/QtUI/QtSpellCheckerWindow.ui45
-rw-r--r--Swift/QtUI/QtStatusWidget.cpp453
-rw-r--r--Swift/QtUI/QtStatusWidget.h108
-rw-r--r--Swift/QtUI/QtStrings.h2
-rw-r--r--Swift/QtUI/QtSubscriptionRequestWindow.cpp112
-rw-r--r--Swift/QtUI/QtSubscriptionRequestWindow.h44
-rw-r--r--Swift/QtUI/QtSwift.cpp444
-rw-r--r--Swift/QtUI/QtSwift.h127
-rw-r--r--Swift/QtUI/QtSystemTray.cpp92
-rw-r--r--Swift/QtUI/QtSystemTray.h68
-rw-r--r--Swift/QtUI/QtTabWidget.cpp48
-rw-r--r--Swift/QtUI/QtTabWidget.h23
-rw-r--r--Swift/QtUI/QtTabbable.cpp66
-rw-r--r--Swift/QtUI/QtTabbable.h51
-rw-r--r--Swift/QtUI/QtTextEdit.cpp332
-rw-r--r--Swift/QtUI/QtTextEdit.h95
-rw-r--r--Swift/QtUI/QtTranslator.h28
-rw-r--r--Swift/QtUI/QtUIFactory.cpp198
-rw-r--r--Swift/QtUI/QtUIFactory.h125
-rw-r--r--Swift/QtUI/QtUISettingConstants.cpp11
-rw-r--r--Swift/QtUI/QtUISettingConstants.h55
-rw-r--r--Swift/QtUI/QtURIHandler.cpp24
-rw-r--r--Swift/QtUI/QtURIHandler.h15
-rw-r--r--Swift/QtUI/QtURLValidator.cpp11
-rw-r--r--Swift/QtUI/QtURLValidator.h12
-rw-r--r--Swift/QtUI/QtUpdateFeedSelectionDialog.cpp83
-rw-r--r--Swift/QtUI/QtUpdateFeedSelectionDialog.h30
-rw-r--r--Swift/QtUI/QtUpdateFeedSelectionDialog.ui146
-rw-r--r--Swift/QtUI/QtUtilities.cpp20
-rw-r--r--Swift/QtUI/QtUtilities.h14
-rw-r--r--Swift/QtUI/QtVCardWidget/QtCloseButton.cpp40
-rw-r--r--Swift/QtUI/QtVCardWidget/QtCloseButton.h24
-rw-r--r--Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp58
-rw-r--r--Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h18
-rw-r--r--Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp42
-rw-r--r--Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h34
-rw-r--r--Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp108
-rw-r--r--Swift/QtUI/QtVCardWidget/QtTagComboBox.h46
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp236
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardAddressField.h74
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp108
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h38
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp51
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h43
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp59
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h42
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h74
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp172
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h124
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp24
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h28
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp87
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h44
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp71
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardJIDField.h42
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp178
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h50
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp126
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h66
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp35
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardRoleField.h40
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp130
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h42
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp37
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardTitleField.h40
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp72
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardURLField.h42
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp674
-rw-r--r--Swift/QtUI/QtVCardWidget/QtVCardWidget.h87
-rw-r--r--Swift/QtUI/QtWebKitChatView.cpp1489
-rw-r--r--Swift/QtUI/QtWebKitChatView.h336
-rw-r--r--Swift/QtUI/QtWebView.cpp123
-rw-r--r--Swift/QtUI/QtWebView.h49
-rw-r--r--Swift/QtUI/QtWin32NotifierWindow.h30
-rw-r--r--Swift/QtUI/QtXMLConsoleWidget.cpp126
-rw-r--r--Swift/QtUI/QtXMLConsoleWidget.h43
-rw-r--r--Swift/QtUI/Roster/DelegateCommons.cpp179
-rw-r--r--Swift/QtUI/Roster/DelegateCommons.h48
-rw-r--r--Swift/QtUI/Roster/GroupItemDelegate.cpp168
-rw-r--r--Swift/QtUI/Roster/GroupItemDelegate.h32
-rw-r--r--Swift/QtUI/Roster/QtFilterWidget.cpp218
-rw-r--r--Swift/QtUI/Roster/QtFilterWidget.h60
-rw-r--r--Swift/QtUI/Roster/QtOccupantListWidget.cpp80
-rw-r--r--Swift/QtUI/Roster/QtOccupantListWidget.h28
-rw-r--r--Swift/QtUI/Roster/QtRosterWidget.cpp227
-rw-r--r--Swift/QtUI/Roster/QtRosterWidget.h24
-rw-r--r--Swift/QtUI/Roster/QtTreeWidget.cpp322
-rw-r--r--Swift/QtUI/Roster/QtTreeWidget.h102
-rw-r--r--Swift/QtUI/Roster/RosterDelegate.cpp86
-rw-r--r--Swift/QtUI/Roster/RosterDelegate.h44
-rw-r--r--Swift/QtUI/Roster/RosterModel.cpp343
-rw-r--r--Swift/QtUI/Roster/RosterModel.h102
-rw-r--r--Swift/QtUI/Roster/RosterTooltip.cpp275
-rw-r--r--Swift/QtUI/Roster/RosterTooltip.h10
-rw-r--r--Swift/QtUI/Roster/main.cpp97
-rw-r--r--Swift/QtUI/SConscript682
-rw-r--r--Swift/QtUI/Swift.qrc8
-rw-r--r--Swift/QtUI/SwiftUpdateFeeds.h29
-rw-r--r--Swift/QtUI/SystemMessageSnippet.cpp24
-rw-r--r--Swift/QtUI/SystemMessageSnippet.h24
-rw-r--r--Swift/QtUI/Trellis/QtDNDTabBar.cpp220
-rw-r--r--Swift/QtUI/Trellis/QtDNDTabBar.h55
-rw-r--r--Swift/QtUI/Trellis/QtDynamicGridLayout.cpp786
-rw-r--r--Swift/QtUI/Trellis/QtDynamicGridLayout.h98
-rw-r--r--Swift/QtUI/Trellis/QtGridSelectionDialog.cpp222
-rw-r--r--Swift/QtUI/Trellis/QtGridSelectionDialog.h91
-rw-r--r--Swift/QtUI/UserSearch/ContactListDelegate.cpp40
-rw-r--r--Swift/QtUI/UserSearch/ContactListDelegate.h20
-rw-r--r--Swift/QtUI/UserSearch/ContactListModel.cpp145
-rw-r--r--Swift/QtUI/UserSearch/ContactListModel.h68
-rw-r--r--Swift/QtUI/UserSearch/QtContactListWidget.cpp93
-rw-r--r--Swift/QtUI/UserSearch/QtContactListWidget.h44
-rw-r--r--Swift/QtUI/UserSearch/QtSuggestingJIDInput.cpp298
-rw-r--r--Swift/QtUI/UserSearch/QtSuggestingJIDInput.h62
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchDetailsPage.cpp32
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h43
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFieldsPage.cpp38
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h27
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.cpp115
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h67
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFirstPage.cpp58
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchFirstPage.h34
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchResultsPage.cpp36
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchResultsPage.h24
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchWindow.cpp917
-rw-r--r--Swift/QtUI/UserSearch/QtUserSearchWindow.h172
-rw-r--r--Swift/QtUI/UserSearch/UserSearchDelegate.cpp72
-rw-r--r--Swift/QtUI/UserSearch/UserSearchDelegate.h26
-rw-r--r--Swift/QtUI/UserSearch/UserSearchModel.cpp92
-rw-r--r--Swift/QtUI/UserSearch/UserSearchModel.h52
-rw-r--r--Swift/QtUI/Whiteboard/ColorWidget.cpp57
-rw-r--r--Swift/QtUI/Whiteboard/ColorWidget.h36
-rw-r--r--Swift/QtUI/Whiteboard/FreehandLineItem.cpp157
-rw-r--r--Swift/QtUI/Whiteboard/FreehandLineItem.h45
-rw-r--r--Swift/QtUI/Whiteboard/GView.cpp981
-rw-r--r--Swift/QtUI/Whiteboard/GView.h118
-rw-r--r--Swift/QtUI/Whiteboard/QtWhiteboardWindow.cpp736
-rw-r--r--Swift/QtUI/Whiteboard/QtWhiteboardWindow.h138
-rw-r--r--Swift/QtUI/Whiteboard/TextDialog.cpp92
-rw-r--r--Swift/QtUI/Whiteboard/TextDialog.h60
-rw-r--r--Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h350
-rw-r--r--Swift/QtUI/WinUIHelpers.cpp88
-rw-r--r--Swift/QtUI/WinUIHelpers.h11
-rw-r--r--Swift/QtUI/WindowsNotifier.cpp46
-rw-r--r--Swift/QtUI/WindowsNotifier.h35
-rw-r--r--Swift/QtUI/main.cpp144
-rw-r--r--Swift/QtUI/swift-open-uri.cpp31
-rw-r--r--Swift/SConscript24
-rw-r--r--Swift/Translations/swift_ca.ts2
-rw-r--r--Swift/Translations/swift_cs.ts2
-rw-r--r--Swift/Translations/swift_de.ts2
-rw-r--r--Swift/Translations/swift_es.ts2
-rw-r--r--Swift/Translations/swift_fr.ts2
-rw-r--r--Swift/Translations/swift_gl.ts2
-rw-r--r--Swift/Translations/swift_he.ts4
-rw-r--r--Swift/Translations/swift_hu.ts2
-rw-r--r--Swift/Translations/swift_nl.ts2
-rw-r--r--Swift/Translations/swift_pl.ts2
-rw-r--r--Swift/Translations/swift_ru.ts2
-rw-r--r--Swift/Translations/swift_sk.ts2
-rw-r--r--Swift/Translations/swift_sv.ts2
-rw-r--r--Swift/resources/icons/avatar.pngbin2096 -> 0 bytes
-rw-r--r--Swift/resources/icons/avatar.svg4788
-rw-r--r--Swift/resources/icons/delivery-failure.svg14
-rw-r--r--Swift/resources/icons/delivery-success.svg11
-rw-r--r--Swift/resources/icons/delivery-warning.svg18
-rw-r--r--Swift/resources/logo/logo-shaded-text.256.pngbin18541 -> 0 bytes
-rw-r--r--Swift/resources/logo/logo-shaded-text.pngbin0 -> 11177 bytes
-rw-r--r--Swift/resources/logo/logo-shaded-text.svg65
-rwxr-xr-xSwift/resources/themes/Default/Demo.html91
-rwxr-xr-xSwift/resources/themes/Default/Header.html5
-rw-r--r--[-rwxr-xr-x]Swift/resources/themes/Default/Incoming/Content.html47
-rwxr-xr-xSwift/resources/themes/Default/Incoming/Context.html30
-rw-r--r--[-rwxr-xr-x]Swift/resources/themes/Default/Incoming/NextContent.html26
-rwxr-xr-xSwift/resources/themes/Default/Incoming/NextContext.html7
-rw-r--r--Swift/resources/themes/Default/Incoming/buddy_icon.pngbin12047 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/LICENSE.txt15
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-Black.ttfbin0 -> 614544 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-BlackItalic.ttfbin0 -> 672480 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-Bold.ttfbin0 -> 657188 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-BoldItalic.ttfbin0 -> 699008 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-Hairline.ttfbin0 -> 584784 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-HairlineItalic.ttfbin0 -> 609436 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-Heavy.ttfbin0 -> 665420 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-HeavyItalic.ttfbin0 -> 698924 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-Italic.ttfbin0 -> 723544 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-Light.ttfbin0 -> 644556 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-LightItalic.ttfbin0 -> 658212 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-Medium.ttfbin0 -> 637068 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-MediumItalic.ttfbin0 -> 695588 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-Regular.ttfbin0 -> 657212 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-Semibold.ttfbin0 -> 669228 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-SemiboldItalic.ttfbin0 -> 698028 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-Thin.ttfbin0 -> 627220 bytes
-rw-r--r--Swift/resources/themes/Default/Lato2OFL/Lato-ThinItalic.ttfbin0 -> 654216 bytes
-rwxr-xr-xSwift/resources/themes/Default/Lato2OFL/OFL.txt94
-rwxr-xr-xSwift/resources/themes/Default/Lato2OFL/README.txt72
-rw-r--r--[-rwxr-xr-x]Swift/resources/themes/Default/Outgoing/Content.html47
-rwxr-xr-xSwift/resources/themes/Default/Outgoing/Context.html31
-rw-r--r--[-rwxr-xr-x]Swift/resources/themes/Default/Outgoing/NextContent.html24
-rwxr-xr-xSwift/resources/themes/Default/Outgoing/NextContext.html6
-rw-r--r--Swift/resources/themes/Default/Outgoing/buddy_icon.pngbin12047 -> 0 bytes
-rw-r--r--[-rwxr-xr-x]Swift/resources/themes/Default/Status.html40
-rw-r--r--[-rwxr-xr-x]Swift/resources/themes/Default/Template.html359
-rw-r--r--Swift/resources/themes/Default/Unread.html1
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Green Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Green No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Green No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Green.css90
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Red Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Red No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Red No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Red.css89
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Steel Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Steel No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Steel No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Steel.css91
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Yellow Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Yellow No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Yellow No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Blue on Yellow.css91
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Blue Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Blue No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Blue No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Blue.css91
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Red Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Red No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Red No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Red.css91
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Steel Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Steel No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Steel No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Steel.css91
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Yellow Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Yellow No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Yellow No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Green on Yellow.css91
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Blue Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Blue No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Blue No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Blue.css90
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Green Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Green No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Green No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Green.css95
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Steel Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Steel No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Steel No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Steel.css93
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Yellow Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Yellow No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Yellow No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Red on Yellow.css91
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Blue Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Blue No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Blue No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Blue.css92
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Green Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Green No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Green No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Green.css97
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Red Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Red No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Red No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Red.css89
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Yellow Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Yellow No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Yellow No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Steel on Yellow.css92
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Blue Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Blue No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Blue No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Blue.css91
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Green Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Green No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Green No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Green.css96
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Red Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Red No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Red No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Red.css91
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Steel Alternating.css7
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Steel No Names Alt.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Steel No Names.css2
-rw-r--r--Swift/resources/themes/Default/Variants/Yellow on Steel.css91
-rw-r--r--Swift/resources/themes/Default/alternating.css16
-rwxr-xr-xSwift/resources/themes/Default/images/DummyContact.pngbin754 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/alert.pngbin5305 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/blueBackground.gifbin198 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/blueBackground.pngbin165 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/blueCurves.gifbin3320 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/blueCurves.pngbin1218 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/blueIndicator.gifbin536 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/blueIndicator.pngbin370 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/blueIndicator2.pngbin380 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/blueIndicatorAlt.gifbin526 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/greenBackground.gifbin117 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/greenBackground.pngbin166 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/greenCurves.gifbin3259 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/greenCurves.pngbin1234 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/greenIndicator.gifbin530 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/greenIndicator.pngbin334 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/greenIndicator2.pngbin345 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/greenIndicatorAlt.gifbin529 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/redBackground.gifbin117 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/redBackground.pngbin160 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/redCurves.gifbin2527 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/redCurves.pngbin1194 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/redIndicator.gifbin527 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/redIndicator.pngbin410 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/redIndicator2.pngbin402 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/redIndicatorAlt.gifbin527 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/silverBackground.gifbin117 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/silverCurves.gifbin2778 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/steelBackground.gifbin122 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/steelBackground.pngbin156 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/steelCurves.gifbin2169 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/steelCurves.pngbin1179 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/steelHeading.jpgbin321 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/steelIndicator.gifbin328 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/steelIndicator.pngbin375 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/steelIndicator2.pngbin392 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/steelIndicatorAlt.gifbin326 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/typing-left.pngbin1702 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/typing-right.pngbin1710 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/yellowBackground.gifbin117 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/yellowBackground.pngbin162 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/yellowCurves.gifbin3202 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/yellowCurves.pngbin1200 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/yellowHeading.jpgbin1447 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/images/yellowIndicator.gifbin532 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/yellowIndicator.pngbin380 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/yellowIndicator2.pngbin400 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/yellowIndicatorAlt.gifbin931 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/yellowTL.pngbin326 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/images/yellowTR.pngbin364 -> 0 bytes
-rwxr-xr-xSwift/resources/themes/Default/incoming_icon.pngbin23643 -> 0 bytes
-rw-r--r--Swift/resources/themes/Default/lato.css143
-rw-r--r--[-rwxr-xr-x]Swift/resources/themes/Default/main.css401
-rw-r--r--Swift/resources/themes/Default/noname.css3
-rwxr-xr-xSwift/resources/themes/Default/outgoing_icon.pngbin23643 -> 0 bytes
-rw-r--r--Swiften/AdHoc/OutgoingAdHocCommandSession.cpp109
-rw-r--r--Swiften/AdHoc/OutgoingAdHocCommandSession.h150
-rw-r--r--Swiften/AdHoc/SConscript4
-rw-r--r--Swiften/Avatars/AvatarManager.h20
-rw-r--r--Swiften/Avatars/AvatarManagerImpl.cpp62
-rw-r--r--Swiften/Avatars/AvatarManagerImpl.h58
-rw-r--r--Swiften/Avatars/AvatarMemoryStorage.h58
-rw-r--r--Swiften/Avatars/AvatarProvider.h19
-rw-r--r--Swiften/Avatars/AvatarStorage.h27
-rw-r--r--Swiften/Avatars/CombinedAvatarProvider.cpp63
-rw-r--r--Swiften/Avatars/CombinedAvatarProvider.h30
-rw-r--r--Swiften/Avatars/DummyAvatarManager.h36
-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/SConscript18
-rw-r--r--Swiften/Avatars/UnitTest/AvatarManagerImplTest.cpp238
-rw-r--r--Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp708
-rw-r--r--Swiften/Avatars/UnitTest/VCardAvatarManagerTest.cpp307
-rw-r--r--Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp381
-rw-r--r--Swiften/Avatars/VCardAvatarManager.cpp68
-rw-r--r--Swiften/Avatars/VCardAvatarManager.h38
-rw-r--r--Swiften/Avatars/VCardUpdateAvatarManager.cpp122
-rw-r--r--Swiften/Avatars/VCardUpdateAvatarManager.h62
-rw-r--r--Swiften/Base/API.h8
-rw-r--r--Swiften/Base/Algorithm.h276
-rw-r--r--Swiften/Base/Atomic.h55
-rw-r--r--Swiften/Base/BoostRandomGenerator.cpp13
-rw-r--r--Swiften/Base/BoostRandomGenerator.h24
-rw-r--r--Swiften/Base/ByteArray.cpp48
-rw-r--r--Swiften/Base/ByteArray.h53
-rw-r--r--Swiften/Base/Concat.h112
-rw-r--r--Swiften/Base/DateTime.cpp45
-rw-r--r--Swiften/Base/DateTime.h31
-rw-r--r--Swiften/Base/Debug.cpp289
-rw-r--r--Swiften/Base/Debug.h14
-rw-r--r--Swiften/Base/Error.h15
-rw-r--r--Swiften/Base/FileSize.cpp19
-rw-r--r--Swiften/Base/FileSize.h8
-rw-r--r--Swiften/Base/IDGenerator.cpp13
-rw-r--r--Swiften/Base/IDGenerator.h13
-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/LogSerializers.cpp68
-rw-r--r--Swiften/Base/LogSerializers.h47
-rw-r--r--Swiften/Base/Path.cpp8
-rw-r--r--Swiften/Base/Path.h30
-rw-r--r--Swiften/Base/Paths.cpp38
-rw-r--r--Swiften/Base/Paths.h8
-rw-r--r--Swiften/Base/RandomGenerator.h23
-rw-r--r--Swiften/Base/Regex.cpp30
-rw-r--r--Swiften/Base/Regex.h6
-rw-r--r--Swiften/Base/SConscript37
-rw-r--r--Swiften/Base/SafeAllocator.cpp10
-rw-r--r--Swiften/Base/SafeAllocator.h46
-rw-r--r--Swiften/Base/SafeByteArray.cpp12
-rw-r--r--Swiften/Base/SafeByteArray.h68
-rw-r--r--Swiften/Base/SafeString.h36
-rw-r--r--Swiften/Base/SimpleIDGenerator.cpp41
-rw-r--r--Swiften/Base/SimpleIDGenerator.h26
-rw-r--r--Swiften/Base/StartStopper.h24
-rw-r--r--Swiften/Base/String.cpp202
-rw-r--r--Swiften/Base/String.h63
-rw-r--r--Swiften/Base/URL.cpp307
-rw-r--r--Swiften/Base/URL.h128
-rw-r--r--Swiften/Base/UnitTest/ByteArrayTest.cpp61
-rw-r--r--Swiften/Base/UnitTest/DateTimeTest.cpp54
-rw-r--r--Swiften/Base/UnitTest/IDGeneratorTest.cpp47
-rw-r--r--Swiften/Base/UnitTest/PathTest.cpp24
-rw-r--r--Swiften/Base/UnitTest/SimpleIDGeneratorTest.cpp49
-rw-r--r--Swiften/Base/UnitTest/StringTest.cpp175
-rw-r--r--Swiften/Base/UnitTest/URLTest.cpp320
-rw-r--r--Swiften/Base/WindowsRegistry.h90
-rw-r--r--Swiften/Base/boost_bsignals.h26
-rw-r--r--Swiften/Base/foreach.h13
-rw-r--r--Swiften/Base/format.h29
-rw-r--r--Swiften/Base/sleep.cpp15
-rw-r--r--Swiften/Base/sleep.h2
-rw-r--r--Swiften/ChangeLog.md17
-rw-r--r--Swiften/Chat/ChatStateNotifier.cpp83
-rw-r--r--Swiften/Chat/ChatStateNotifier.h75
-rw-r--r--Swiften/Chat/ChatStateTracker.cpp36
-rw-r--r--Swiften/Chat/ChatStateTracker.h31
-rw-r--r--Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp298
-rw-r--r--Swiften/Client/BlockList.cpp8
-rw-r--r--Swiften/Client/BlockList.h49
-rw-r--r--Swiften/Client/BlockListImpl.cpp72
-rw-r--r--Swiften/Client/BlockListImpl.h50
-rw-r--r--Swiften/Client/Client.cpp216
-rw-r--r--Swiften/Client/Client.h394
-rw-r--r--Swiften/Client/ClientBlockListManager.cpp187
-rw-r--r--Swiften/Client/ClientBlockListManager.h83
-rw-r--r--Swiften/Client/ClientError.h95
-rw-r--r--Swiften/Client/ClientOptions.h289
-rw-r--r--Swiften/Client/ClientSession.cpp892
-rw-r--r--Swiften/Client/ClientSession.h388
-rw-r--r--Swiften/Client/ClientSessionStanzaChannel.cpp132
-rw-r--r--Swiften/Client/ClientSessionStanzaChannel.h66
-rw-r--r--Swiften/Client/ClientXMLTracer.cpp49
-rw-r--r--Swiften/Client/ClientXMLTracer.h30
-rw-r--r--Swiften/Client/CoreClient.cpp724
-rw-r--r--Swiften/Client/CoreClient.h442
-rw-r--r--Swiften/Client/DummyNickManager.h18
-rw-r--r--Swiften/Client/DummyStanzaChannel.h162
-rw-r--r--Swiften/Client/MemoryStorages.cpp36
-rw-r--r--Swiften/Client/MemoryStorages.h44
-rw-r--r--Swiften/Client/NickManager.h22
-rw-r--r--Swiften/Client/NickManagerImpl.cpp32
-rw-r--r--Swiften/Client/NickManagerImpl.h30
-rw-r--r--Swiften/Client/NickResolver.cpp87
-rw-r--r--Swiften/Client/NickResolver.h57
-rw-r--r--Swiften/Client/StanzaChannel.h33
-rw-r--r--Swiften/Client/Storages.h36
-rw-r--r--Swiften/Client/UnitTest/BlockListImplTest.cpp140
-rw-r--r--Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp344
-rw-r--r--Swiften/Client/UnitTest/ClientSessionTest.cpp1681
-rw-r--r--Swiften/Client/UnitTest/NickResolverTest.cpp266
-rw-r--r--Swiften/Client/XMLBeautifier.cpp140
-rw-r--r--Swiften/Client/XMLBeautifier.h51
-rw-r--r--Swiften/Component/Component.cpp10
-rw-r--r--Swiften/Component/Component.h43
-rw-r--r--Swiften/Component/ComponentConnector.cpp121
-rw-r--r--Swiften/Component/ComponentConnector.h81
-rw-r--r--Swiften/Component/ComponentError.h32
-rw-r--r--Swiften/Component/ComponentHandshakeGenerator.cpp19
-rw-r--r--Swiften/Component/ComponentHandshakeGenerator.h10
-rw-r--r--Swiften/Component/ComponentSession.cpp149
-rw-r--r--Swiften/Component/ComponentSession.h142
-rw-r--r--Swiften/Component/ComponentSessionStanzaChannel.cpp93
-rw-r--r--Swiften/Component/ComponentSessionStanzaChannel.h78
-rw-r--r--Swiften/Component/ComponentXMLTracer.cpp19
-rw-r--r--Swiften/Component/ComponentXMLTracer.h14
-rw-r--r--Swiften/Component/CoreComponent.cpp229
-rw-r--r--Swiften/Component/CoreComponent.h154
-rw-r--r--Swiften/Component/SConscript16
-rw-r--r--Swiften/Component/UnitTest/ComponentConnectorTest.cpp370
-rw-r--r--Swiften/Component/UnitTest/ComponentHandshakeGeneratorTest.cpp46
-rw-r--r--Swiften/Component/UnitTest/ComponentSessionTest.cpp404
-rw-r--r--Swiften/Compress/UnitTest/ZLibCompressorTest.cpp38
-rw-r--r--Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp118
-rw-r--r--Swiften/Compress/ZLibCodecompressor.cpp61
-rw-r--r--Swiften/Compress/ZLibCodecompressor.h24
-rw-r--r--Swiften/Compress/ZLibCodecompressor_Private.h12
-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.h11
-rw-r--r--Swiften/Config/SConscript54
-rw-r--r--Swiften/Config/swiften-config.cpp190
-rw-r--r--Swiften/Crypto/CommonCryptoCryptoProvider.cpp196
-rw-r--r--Swiften/Crypto/CommonCryptoCryptoProvider.h24
-rw-r--r--Swiften/Crypto/CryptoProvider.cpp4
-rw-r--r--Swiften/Crypto/CryptoProvider.h36
-rw-r--r--Swiften/Crypto/Hash.h14
-rw-r--r--Swiften/Crypto/OpenSSLCryptoProvider.cpp190
-rw-r--r--Swiften/Crypto/OpenSSLCryptoProvider.h24
-rw-r--r--Swiften/Crypto/PlatformCryptoProvider.cpp12
-rw-r--r--Swiften/Crypto/PlatformCryptoProvider.h8
-rw-r--r--Swiften/Crypto/SConscript24
-rw-r--r--Swiften/Crypto/UnitTest/CryptoProviderTest.cpp178
-rw-r--r--Swiften/Crypto/WindowsCryptoProvider.cpp331
-rw-r--r--Swiften/Crypto/WindowsCryptoProvider.h29
-rw-r--r--Swiften/Disco/CapsInfoGenerator.cpp77
-rw-r--r--Swiften/Disco/CapsInfoGenerator.h23
-rw-r--r--Swiften/Disco/CapsManager.cpp100
-rw-r--r--Swiften/Disco/CapsManager.h77
-rw-r--r--Swiften/Disco/CapsMemoryStorage.h44
-rw-r--r--Swiften/Disco/CapsProvider.h21
-rw-r--r--Swiften/Disco/CapsStorage.h18
-rw-r--r--Swiften/Disco/ClientDiscoManager.cpp30
-rw-r--r--Swiften/Disco/ClientDiscoManager.h115
-rw-r--r--Swiften/Disco/DiscoInfoResponder.cpp49
-rw-r--r--Swiften/Disco/DiscoInfoResponder.h30
-rw-r--r--Swiften/Disco/DiscoServiceWalker.cpp195
-rw-r--r--Swiften/Disco/DiscoServiceWalker.h103
-rw-r--r--Swiften/Disco/DummyEntityCapsProvider.cpp14
-rw-r--r--Swiften/Disco/DummyEntityCapsProvider.h14
-rw-r--r--Swiften/Disco/EntityCapsManager.cpp102
-rw-r--r--Swiften/Disco/EntityCapsManager.h63
-rw-r--r--Swiften/Disco/EntityCapsProvider.h41
-rw-r--r--Swiften/Disco/FeatureOracle.cpp224
-rw-r--r--Swiften/Disco/FeatureOracle.h50
-rw-r--r--Swiften/Disco/GetDiscoInfoRequest.h50
-rw-r--r--Swiften/Disco/GetDiscoItemsRequest.h50
-rw-r--r--Swiften/Disco/JIDDiscoInfoResponder.cpp63
-rw-r--r--Swiften/Disco/JIDDiscoInfoResponder.h46
-rw-r--r--Swiften/Disco/SConscript24
-rw-r--r--Swiften/Disco/UnitTest/CapsInfoGeneratorTest.cpp122
-rw-r--r--Swiften/Disco/UnitTest/CapsManagerTest.cpp543
-rw-r--r--Swiften/Disco/UnitTest/DiscoInfoResponderTest.cpp159
-rw-r--r--Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp348
-rw-r--r--Swiften/Disco/UnitTest/FeatureOracleTest.cpp151
-rw-r--r--Swiften/Disco/UnitTest/JIDDiscoInfoResponderTest.cpp203
-rw-r--r--Swiften/Elements/AuthChallenge.h35
-rw-r--r--Swiften/Elements/AuthFailure.h14
-rw-r--r--Swiften/Elements/AuthRequest.h73
-rw-r--r--Swiften/Elements/AuthResponse.h39
-rw-r--r--Swiften/Elements/AuthSuccess.h27
-rw-r--r--Swiften/Elements/BlockListPayload.h30
-rw-r--r--Swiften/Elements/BlockPayload.h30
-rw-r--r--Swiften/Elements/Body.h26
-rw-r--r--Swiften/Elements/Bytestreams.h75
-rw-r--r--Swiften/Elements/CapsInfo.h92
-rw-r--r--Swiften/Elements/CarbonsDisable.cpp4
-rw-r--r--Swiften/Elements/CarbonsDisable.h16
-rw-r--r--Swiften/Elements/CarbonsEnable.cpp4
-rw-r--r--Swiften/Elements/CarbonsEnable.h16
-rw-r--r--Swiften/Elements/CarbonsPrivate.cpp4
-rw-r--r--Swiften/Elements/CarbonsPrivate.h16
-rw-r--r--Swiften/Elements/CarbonsReceived.cpp18
-rw-r--r--Swiften/Elements/CarbonsReceived.h24
-rw-r--r--Swiften/Elements/CarbonsSent.cpp20
-rw-r--r--Swiften/Elements/CarbonsSent.h24
-rw-r--r--Swiften/Elements/ChatState.h28
-rw-r--r--Swiften/Elements/Command.h136
-rw-r--r--Swiften/Elements/ComponentHandshake.h32
-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.h39
-rw-r--r--Swiften/Elements/Delay.h24
-rw-r--r--Swiften/Elements/DeliveryReceipt.h28
-rw-r--r--Swiften/Elements/DeliveryReceiptRequest.h10
-rw-r--r--Swiften/Elements/DiscoInfo.cpp35
-rw-r--r--Swiften/Elements/DiscoInfo.h199
-rw-r--r--Swiften/Elements/DiscoItems.h92
-rw-r--r--Swiften/Elements/Element.h14
-rw-r--r--Swiften/Elements/EnableStreamManagement.h12
-rw-r--r--Swiften/Elements/ErrorPayload.h146
-rw-r--r--Swiften/Elements/Form.cpp67
-rw-r--r--Swiften/Elements/Form.h215
-rw-r--r--Swiften/Elements/FormField.cpp20
-rw-r--r--Swiften/Elements/FormField.h249
-rw-r--r--Swiften/Elements/FormPage.cpp48
-rw-r--r--Swiften/Elements/FormPage.h57
-rw-r--r--Swiften/Elements/FormReportedRef.h12
-rw-r--r--Swiften/Elements/FormSection.cpp42
-rw-r--r--Swiften/Elements/FormSection.h55
-rw-r--r--Swiften/Elements/FormText.cpp4
-rw-r--r--Swiften/Elements/FormText.h25
-rw-r--r--Swiften/Elements/Forwarded.h35
-rw-r--r--Swiften/Elements/HashElement.h60
-rw-r--r--Swiften/Elements/IBB.h185
-rw-r--r--Swiften/Elements/IQ.cpp94
-rw-r--r--Swiften/Elements/IQ.h90
-rw-r--r--Swiften/Elements/Idle.h37
-rw-r--r--Swiften/Elements/InBandRegistrationPayload.h355
-rw-r--r--Swiften/Elements/IsodeIQDelegation.h40
-rw-r--r--Swiften/Elements/JingleContentPayload.h171
-rw-r--r--Swiften/Elements/JingleDescription.h12
-rw-r--r--Swiften/Elements/JingleFileTransferDescription.h28
-rw-r--r--Swiften/Elements/JingleFileTransferFileInfo.h204
-rw-r--r--Swiften/Elements/JingleFileTransferHash.h22
-rw-r--r--Swiften/Elements/JingleIBBTransportPayload.h71
-rw-r--r--Swiften/Elements/JinglePayload.h303
-rw-r--r--Swiften/Elements/JingleS5BTransportPayload.h212
-rw-r--r--Swiften/Elements/JingleTransportPayload.h31
-rw-r--r--Swiften/Elements/Last.h16
-rw-r--r--Swiften/Elements/MAMFin.h92
-rw-r--r--Swiften/Elements/MAMQuery.h38
-rw-r--r--Swiften/Elements/MAMResult.h22
-rw-r--r--Swiften/Elements/MUCAdminPayload.h33
-rw-r--r--Swiften/Elements/MUCDestroyPayload.h44
-rw-r--r--Swiften/Elements/MUCInvitationPayload.h126
-rw-r--r--Swiften/Elements/MUCItem.h19
-rw-r--r--Swiften/Elements/MUCOccupant.cpp24
-rw-r--r--Swiften/Elements/MUCOccupant.h57
-rw-r--r--Swiften/Elements/MUCOwnerPayload.h38
-rw-r--r--Swiften/Elements/MUCPayload.h123
-rw-r--r--Swiften/Elements/MUCUserPayload.h125
-rw-r--r--Swiften/Elements/Message.h119
-rw-r--r--Swiften/Elements/Nickname.h31
-rw-r--r--Swiften/Elements/Payload.h22
-rw-r--r--Swiften/Elements/Presence.cpp26
-rw-r--r--Swiften/Elements/Presence.h89
-rw-r--r--Swiften/Elements/Priority.h26
-rw-r--r--Swiften/Elements/PrivateStorage.h30
-rw-r--r--Swiften/Elements/ProtocolHeader.h60
-rw-r--r--Swiften/Elements/PubSub.h15
-rw-r--r--Swiften/Elements/PubSubAffiliation.h81
-rw-r--r--Swiften/Elements/PubSubAffiliations.h77
-rw-r--r--Swiften/Elements/PubSubConfigure.h40
-rw-r--r--Swiften/Elements/PubSubCreate.h66
-rw-r--r--Swiften/Elements/PubSubDefault.h77
-rw-r--r--Swiften/Elements/PubSubError.h182
-rw-r--r--Swiften/Elements/PubSubEvent.h20
-rw-r--r--Swiften/Elements/PubSubEventAssociate.h37
-rw-r--r--Swiften/Elements/PubSubEventCollection.h87
-rw-r--r--Swiften/Elements/PubSubEventConfiguration.h66
-rw-r--r--Swiften/Elements/PubSubEventDelete.h66
-rw-r--r--Swiften/Elements/PubSubEventDisassociate.h37
-rw-r--r--Swiften/Elements/PubSubEventItem.h112
-rw-r--r--Swiften/Elements/PubSubEventItems.h100
-rw-r--r--Swiften/Elements/PubSubEventPayload.h8
-rw-r--r--Swiften/Elements/PubSubEventPurge.h38
-rw-r--r--Swiften/Elements/PubSubEventRedirect.h37
-rw-r--r--Swiften/Elements/PubSubEventRetract.h37
-rw-r--r--Swiften/Elements/PubSubEventSubscription.h133
-rw-r--r--Swiften/Elements/PubSubItem.h73
-rw-r--r--Swiften/Elements/PubSubItems.h113
-rw-r--r--Swiften/Elements/PubSubOptions.h105
-rw-r--r--Swiften/Elements/PubSubOwnerAffiliation.h78
-rw-r--r--Swiften/Elements/PubSubOwnerAffiliations.h74
-rw-r--r--Swiften/Elements/PubSubOwnerConfigure.h69
-rw-r--r--Swiften/Elements/PubSubOwnerDefault.h40
-rw-r--r--Swiften/Elements/PubSubOwnerDelete.h66
-rw-r--r--Swiften/Elements/PubSubOwnerPayload.h8
-rw-r--r--Swiften/Elements/PubSubOwnerPubSub.h15
-rw-r--r--Swiften/Elements/PubSubOwnerPurge.h38
-rw-r--r--Swiften/Elements/PubSubOwnerRedirect.h37
-rw-r--r--Swiften/Elements/PubSubOwnerSubscription.h74
-rw-r--r--Swiften/Elements/PubSubOwnerSubscriptions.h74
-rw-r--r--Swiften/Elements/PubSubPayload.h8
-rw-r--r--Swiften/Elements/PubSubPublish.h74
-rw-r--r--Swiften/Elements/PubSubRetract.cpp4
-rw-r--r--Swiften/Elements/PubSubRetract.h93
-rw-r--r--Swiften/Elements/PubSubSubscribe.h87
-rw-r--r--Swiften/Elements/PubSubSubscribeOptions.h35
-rw-r--r--Swiften/Elements/PubSubSubscription.h135
-rw-r--r--Swiften/Elements/PubSubSubscriptions.h77
-rw-r--r--Swiften/Elements/PubSubUnsubscribe.h85
-rw-r--r--Swiften/Elements/RawXMLPayload.h24
-rw-r--r--Swiften/Elements/Replace.h30
-rw-r--r--Swiften/Elements/ResourceBind.h50
-rw-r--r--Swiften/Elements/ResultSet.h63
-rw-r--r--Swiften/Elements/RosterItemExchangePayload.cpp7
-rw-r--r--Swiften/Elements/RosterItemExchangePayload.h114
-rw-r--r--Swiften/Elements/RosterItemPayload.h76
-rw-r--r--Swiften/Elements/RosterPayload.cpp19
-rw-r--r--Swiften/Elements/RosterPayload.h54
-rw-r--r--Swiften/Elements/S5BProxyRequest.h56
-rw-r--r--Swiften/Elements/SearchPayload.h163
-rw-r--r--Swiften/Elements/SecurityLabel.h127
-rw-r--r--Swiften/Elements/SecurityLabelsCatalog.h148
-rw-r--r--Swiften/Elements/SoftwareVersion.h82
-rw-r--r--Swiften/Elements/Stanza.cpp65
-rw-r--r--Swiften/Elements/Stanza.h157
-rw-r--r--Swiften/Elements/StanzaAck.cpp4
-rw-r--r--Swiften/Elements/StanzaAck.h38
-rw-r--r--Swiften/Elements/StanzaAckRequest.h4
-rw-r--r--Swiften/Elements/StartSession.h11
-rw-r--r--Swiften/Elements/StartTLSFailure.h8
-rw-r--r--Swiften/Elements/StartTLSRequest.h8
-rw-r--r--Swiften/Elements/Status.h31
-rw-r--r--Swiften/Elements/StatusShow.h73
-rw-r--r--Swiften/Elements/Storage.h102
-rw-r--r--Swiften/Elements/StreamError.h100
-rw-r--r--Swiften/Elements/StreamFeatures.cpp4
-rw-r--r--Swiften/Elements/StreamFeatures.h183
-rw-r--r--Swiften/Elements/StreamInitiation.h113
-rw-r--r--Swiften/Elements/StreamInitiationFileInfo.h167
-rw-r--r--Swiften/Elements/StreamManagementEnabled.h50
-rw-r--r--Swiften/Elements/StreamManagementFailed.h8
-rw-r--r--Swiften/Elements/StreamResume.h53
-rw-r--r--Swiften/Elements/StreamResumed.h53
-rw-r--r--Swiften/Elements/StreamType.h10
-rw-r--r--Swiften/Elements/Subject.h31
-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.h30
-rw-r--r--Swiften/Elements/UnitTest/FormTest.cpp60
-rw-r--r--Swiften/Elements/UnitTest/IQTest.cpp79
-rw-r--r--Swiften/Elements/UnitTest/StanzaTest.cpp430
-rw-r--r--Swiften/Elements/UnknownElement.h8
-rw-r--r--Swiften/Elements/UserLocation.h386
-rw-r--r--Swiften/Elements/UserTune.h156
-rw-r--r--Swiften/Elements/VCard.cpp22
-rw-r--r--Swiften/Elements/VCard.h557
-rw-r--r--Swiften/Elements/VCardUpdate.h16
-rw-r--r--Swiften/Elements/Version.h22
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardColor.cpp91
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardColor.h30
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h30
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardElement.h40
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h32
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h126
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h76
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h30
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardLineElement.h88
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardOperation.h86
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h82
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardRectElement.h126
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardTextElement.h86
-rw-r--r--Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h52
-rw-r--r--Swiften/Elements/WhiteboardPayload.h98
-rw-r--r--Swiften/Entity/Entity.cpp23
-rw-r--r--Swiften/Entity/Entity.h58
-rw-r--r--Swiften/Entity/GenericPayloadPersister.h40
-rw-r--r--Swiften/Entity/PayloadPersister.cpp62
-rw-r--r--Swiften/Entity/PayloadPersister.h31
-rw-r--r--Swiften/Entity/SConscript4
-rw-r--r--Swiften/EventLoop/BoostASIOEventLoop.cpp24
-rw-r--r--Swiften/EventLoop/BoostASIOEventLoop.h31
-rw-r--r--Swiften/EventLoop/Cocoa/CocoaEvent.h10
-rw-r--r--Swiften/EventLoop/Cocoa/CocoaEvent.mm17
-rw-r--r--Swiften/EventLoop/Cocoa/CocoaEventLoop.h28
-rw-r--r--Swiften/EventLoop/Cocoa/CocoaEventLoop.mm34
-rw-r--r--Swiften/EventLoop/DummyEventLoop.cpp26
-rw-r--r--Swiften/EventLoop/DummyEventLoop.h28
-rw-r--r--Swiften/EventLoop/Event.cpp22
-rw-r--r--Swiften/EventLoop/Event.h31
-rw-r--r--Swiften/EventLoop/EventLoop.cpp124
-rw-r--r--Swiften/EventLoop/EventLoop.h96
-rw-r--r--Swiften/EventLoop/EventOwner.h8
-rw-r--r--Swiften/EventLoop/Qt/QtEventLoop.h86
-rw-r--r--Swiften/EventLoop/SConscript30
-rw-r--r--Swiften/EventLoop/SimpleEventLoop.cpp48
-rw-r--r--Swiften/EventLoop/SimpleEventLoop.h54
-rw-r--r--Swiften/EventLoop/SingleThreadedEventLoop.cpp51
-rw-r--r--Swiften/EventLoop/SingleThreadedEventLoop.h68
-rw-r--r--Swiften/EventLoop/UnitTest/EventLoopTest.cpp148
-rw-r--r--Swiften/EventLoop/UnitTest/SimpleEventLoopTest.cpp104
-rw-r--r--Swiften/Examples/BenchTool/BenchTool.cpp73
-rw-r--r--Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp139
-rw-r--r--Swiften/Examples/LinkLocalTool/SConscript4
-rw-r--r--Swiften/Examples/LinkLocalTool/main.cpp64
-rw-r--r--Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp135
-rw-r--r--Swiften/Examples/NetworkTool/SConscript12
-rw-r--r--Swiften/Examples/NetworkTool/main.cpp113
-rw-r--r--Swiften/Examples/ParserTester/ParserTester.cpp83
-rw-r--r--Swiften/Examples/SConscript16
-rw-r--r--Swiften/Examples/SendFile/ReceiveFile.cpp203
-rw-r--r--Swiften/Examples/SendFile/SendFile.cpp206
-rw-r--r--Swiften/Examples/SendMessage/SendMessage.cpp121
-rw-r--r--Swiften/FileTransfer/ByteArrayReadBytestream.cpp33
-rw-r--r--Swiften/FileTransfer/ByteArrayReadBytestream.h38
-rw-r--r--Swiften/FileTransfer/ByteArrayWriteBytestream.h30
-rw-r--r--Swiften/FileTransfer/BytestreamException.h10
-rw-r--r--Swiften/FileTransfer/BytestreamsRequest.h36
-rw-r--r--Swiften/FileTransfer/DefaultFileTransferTransporter.cpp394
-rw-r--r--Swiften/FileTransfer/DefaultFileTransferTransporter.h178
-rw-r--r--Swiften/FileTransfer/DefaultFileTransferTransporterFactory.cpp96
-rw-r--r--Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h72
-rw-r--r--Swiften/FileTransfer/FailingTransportSession.cpp24
-rw-r--r--Swiften/FileTransfer/FailingTransportSession.h16
-rw-r--r--Swiften/FileTransfer/FileReadBytestream.cpp40
-rw-r--r--Swiften/FileTransfer/FileReadBytestream.h20
-rw-r--r--Swiften/FileTransfer/FileTransfer.cpp10
-rw-r--r--Swiften/FileTransfer/FileTransfer.h135
-rw-r--r--Swiften/FileTransfer/FileTransferError.h32
-rw-r--r--Swiften/FileTransfer/FileTransferManager.cpp15
-rw-r--r--Swiften/FileTransfer/FileTransferManager.h59
-rw-r--r--Swiften/FileTransfer/FileTransferManagerImpl.cpp229
-rw-r--r--Swiften/FileTransfer/FileTransferManagerImpl.h140
-rw-r--r--Swiften/FileTransfer/FileTransferOptions.h86
-rw-r--r--Swiften/FileTransfer/FileTransferTransporter.h90
-rw-r--r--Swiften/FileTransfer/FileTransferTransporterFactory.h32
-rw-r--r--Swiften/FileTransfer/FileWriteBytestream.cpp50
-rw-r--r--Swiften/FileTransfer/FileWriteBytestream.h20
-rw-r--r--Swiften/FileTransfer/IBBReceiveSession.cpp162
-rw-r--r--Swiften/FileTransfer/IBBReceiveSession.h97
-rw-r--r--Swiften/FileTransfer/IBBReceiveTransportSession.cpp14
-rw-r--r--Swiften/FileTransfer/IBBReceiveTransportSession.h25
-rw-r--r--Swiften/FileTransfer/IBBRequest.h25
-rw-r--r--Swiften/FileTransfer/IBBSendSession.cpp130
-rw-r--r--Swiften/FileTransfer/IBBSendSession.h89
-rw-r--r--Swiften/FileTransfer/IBBSendTransportSession.cpp16
-rw-r--r--Swiften/FileTransfer/IBBSendTransportSession.h25
-rw-r--r--Swiften/FileTransfer/IncomingFileTransfer.h47
-rw-r--r--Swiften/FileTransfer/IncomingFileTransferManager.cpp70
-rw-r--r--Swiften/FileTransfer/IncomingFileTransferManager.h63
-rw-r--r--Swiften/FileTransfer/IncomingJingleFileTransfer.cpp573
-rw-r--r--Swiften/FileTransfer/IncomingJingleFileTransfer.h225
-rw-r--r--Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp64
-rw-r--r--Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h41
-rw-r--r--Swiften/FileTransfer/JingleFileTransfer.cpp341
-rw-r--r--Swiften/FileTransfer/JingleFileTransfer.h136
-rw-r--r--Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp269
-rw-r--r--Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h81
-rw-r--r--Swiften/FileTransfer/OutgoingFileTransfer.h18
-rw-r--r--Swiften/FileTransfer/OutgoingFileTransferManager.cpp74
-rw-r--r--Swiften/FileTransfer/OutgoingFileTransferManager.h78
-rw-r--r--Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp550
-rw-r--r--Swiften/FileTransfer/OutgoingJingleFileTransfer.h191
-rw-r--r--Swiften/FileTransfer/ReadBytestream.h39
-rw-r--r--Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp106
-rw-r--r--Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h81
-rw-r--r--Swiften/FileTransfer/S5BTransportSession.h82
-rw-r--r--Swiften/FileTransfer/SConscript91
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp400
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamClientSession.h103
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp288
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h86
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp83
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h38
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp21
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamRegistry.h32
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServer.cpp67
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServer.h50
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp352
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerManager.h156
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.cpp34
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h25
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.cpp22
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h25
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp268
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerSession.h133
-rw-r--r--Swiften/FileTransfer/StreamInitiationRequest.h35
-rw-r--r--Swiften/FileTransfer/TransportSession.h23
-rw-r--r--Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h73
-rw-r--r--Swiften/FileTransfer/UnitTest/DummyFileTransferTransporterFactory.h312
-rw-r--r--Swiften/FileTransfer/UnitTest/IBBReceiveSessionTest.cpp308
-rw-r--r--Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp426
-rw-r--r--Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp378
-rw-r--r--Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp436
-rw-r--r--Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp511
-rw-r--r--Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp386
-rw-r--r--Swiften/FileTransfer/WriteBytestream.h28
-rw-r--r--Swiften/History/HistoryMessage.h107
-rw-r--r--Swiften/History/HistoryStorage.h38
-rw-r--r--Swiften/History/SConscript10
-rw-r--r--Swiften/History/SQLiteHistoryStorage.cpp628
-rw-r--r--Swiften/History/SQLiteHistoryStorage.h55
-rw-r--r--Swiften/History/UnitTest/SQLiteHistoryManagerTest.cpp199
-rw-r--r--Swiften/IDN/ICUConverter.cpp246
-rw-r--r--Swiften/IDN/ICUConverter.h15
-rw-r--r--Swiften/IDN/IDNConverter.h40
-rw-r--r--Swiften/IDN/LibIDNConverter.cpp96
-rw-r--r--Swiften/IDN/LibIDNConverter.h15
-rw-r--r--Swiften/IDN/PlatformIDNConverter.cpp8
-rw-r--r--Swiften/IDN/PlatformIDNConverter.h8
-rw-r--r--Swiften/IDN/SConscript30
-rw-r--r--Swiften/IDN/UTF8Validator.h98
-rw-r--r--Swiften/IDN/UnitTest/IDNConverterTest.cpp93
-rw-r--r--Swiften/IDN/UnitTest/UTF8ValidatorTest.cpp64
-rw-r--r--Swiften/JID/JID.cpp419
-rw-r--r--Swiften/JID/JID.h370
-rw-r--r--Swiften/JID/SConscript4
-rw-r--r--Swiften/JID/UnitTest/JIDTest.cpp724
-rw-r--r--Swiften/Jingle/AbstractJingleSessionListener.cpp28
-rw-r--r--Swiften/Jingle/AbstractJingleSessionListener.h24
-rw-r--r--Swiften/Jingle/FakeJingleSession.cpp39
-rw-r--r--Swiften/Jingle/FakeJingleSession.h179
-rw-r--r--Swiften/Jingle/IncomingJingleSessionHandler.h10
-rw-r--r--Swiften/Jingle/Jingle.h24
-rw-r--r--Swiften/Jingle/JingleContentID.h32
-rw-r--r--Swiften/Jingle/JingleResponder.cpp81
-rw-r--r--Swiften/Jingle/JingleResponder.h28
-rw-r--r--Swiften/Jingle/JingleSession.cpp14
-rw-r--r--Swiften/Jingle/JingleSession.h73
-rw-r--r--Swiften/Jingle/JingleSessionImpl.cpp281
-rw-r--r--Swiften/Jingle/JingleSessionImpl.h72
-rw-r--r--Swiften/Jingle/JingleSessionListener.h50
-rw-r--r--Swiften/Jingle/JingleSessionManager.cpp44
-rw-r--r--Swiften/Jingle/JingleSessionManager.h75
-rw-r--r--Swiften/Jingle/SConscript18
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.cpp75
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h36
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp62
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h78
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.cpp5
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h31
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.cpp141
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h72
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp13
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h29
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.cpp81
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h38
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h101
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp181
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h85
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.cpp19
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h54
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h85
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h94
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h94
-rw-r--r--Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h22
-rw-r--r--Swiften/LinkLocal/DNSSD/DNSSDQuerier.h40
-rw-r--r--Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h22
-rw-r--r--Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h18
-rw-r--r--Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h36
-rw-r--r--Swiften/LinkLocal/DNSSD/DNSSDServiceID.h109
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDBrowseQuery.h28
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp166
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h135
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.cpp9
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h35
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h45
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveHostnameQuery.h33
-rw-r--r--Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h30
-rw-r--r--Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.cpp16
-rw-r--r--Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h24
-rw-r--r--Swiften/LinkLocal/IncomingLinkLocalSession.cpp77
-rw-r--r--Swiften/LinkLocal/IncomingLinkLocalSession.h63
-rw-r--r--Swiften/LinkLocal/LinkLocalConnector.cpp82
-rw-r--r--Swiften/LinkLocal/LinkLocalConnector.h88
-rw-r--r--Swiften/LinkLocal/LinkLocalService.cpp32
-rw-r--r--Swiften/LinkLocal/LinkLocalService.h77
-rw-r--r--Swiften/LinkLocal/LinkLocalServiceBrowser.cpp188
-rw-r--r--Swiften/LinkLocal/LinkLocalServiceBrowser.h99
-rw-r--r--Swiften/LinkLocal/LinkLocalServiceInfo.cpp184
-rw-r--r--Swiften/LinkLocal/LinkLocalServiceInfo.h75
-rw-r--r--Swiften/LinkLocal/OutgoingLinkLocalSession.cpp47
-rw-r--r--Swiften/LinkLocal/OutgoingLinkLocalSession.h62
-rw-r--r--Swiften/LinkLocal/SConscript60
-rw-r--r--Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp250
-rw-r--r--Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp790
-rw-r--r--Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp92
-rw-r--r--Swiften/LinkLocal/UnitTest/LinkLocalServiceTest.cpp102
-rw-r--r--Swiften/MUC/MUC.h156
-rw-r--r--Swiften/MUC/MUCBookmark.h149
-rw-r--r--Swiften/MUC/MUCBookmarkManager.cpp162
-rw-r--r--Swiften/MUC/MUCBookmarkManager.h72
-rw-r--r--Swiften/MUC/MUCImpl.cpp685
-rw-r--r--Swiften/MUC/MUCImpl.h232
-rw-r--r--Swiften/MUC/MUCManager.cpp5
-rw-r--r--Swiften/MUC/MUCManager.h28
-rw-r--r--Swiften/MUC/MUCRegistry.cpp6
-rw-r--r--Swiften/MUC/MUCRegistry.h22
-rw-r--r--Swiften/MUC/UnitTest/MUCTest.cpp518
-rw-r--r--Swiften/MUC/UnitTest/MockMUC.cpp32
-rw-r--r--Swiften/MUC/UnitTest/MockMUC.h154
-rw-r--r--Swiften/Network/BOSHConnection.cpp538
-rw-r--r--Swiften/Network/BOSHConnection.h188
-rw-r--r--Swiften/Network/BOSHConnectionPool.cpp429
-rw-r--r--Swiften/Network/BOSHConnectionPool.h126
-rw-r--r--Swiften/Network/BoostConnection.cpp201
-rw-r--r--Swiften/Network/BoostConnection.h116
-rw-r--r--Swiften/Network/BoostConnectionFactory.cpp9
-rw-r--r--Swiften/Network/BoostConnectionFactory.h22
-rw-r--r--Swiften/Network/BoostConnectionServer.cpp126
-rw-r--r--Swiften/Network/BoostConnectionServer.h66
-rw-r--r--Swiften/Network/BoostConnectionServerFactory.cpp17
-rw-r--r--Swiften/Network/BoostConnectionServerFactory.h24
-rw-r--r--Swiften/Network/BoostIOServiceThread.cpp36
-rw-r--r--Swiften/Network/BoostIOServiceThread.h55
-rw-r--r--Swiften/Network/BoostNetworkFactories.cpp56
-rw-r--r--Swiften/Network/BoostNetworkFactories.h160
-rw-r--r--Swiften/Network/BoostTimer.cpp64
-rw-r--r--Swiften/Network/BoostTimer.h49
-rw-r--r--Swiften/Network/BoostTimerFactory.cpp9
-rw-r--r--Swiften/Network/BoostTimerFactory.h24
-rw-r--r--Swiften/Network/CachingDomainNameResolver.cpp12
-rw-r--r--Swiften/Network/CachingDomainNameResolver.h24
-rw-r--r--Swiften/Network/ChainedConnector.cpp113
-rw-r--r--Swiften/Network/ChainedConnector.h74
-rw-r--r--Swiften/Network/Connection.h63
-rw-r--r--Swiften/Network/ConnectionFactory.h16
-rw-r--r--Swiften/Network/ConnectionServer.h35
-rw-r--r--Swiften/Network/ConnectionServerFactory.h21
-rw-r--r--Swiften/Network/Connector.cpp271
-rw-r--r--Swiften/Network/Connector.h110
-rw-r--r--Swiften/Network/DomainNameAddressQuery.h21
-rw-r--r--Swiften/Network/DomainNameResolveError.h12
-rw-r--r--Swiften/Network/DomainNameResolver.h22
-rw-r--r--Swiften/Network/DomainNameServiceQuery.cpp69
-rw-r--r--Swiften/Network/DomainNameServiceQuery.h43
-rw-r--r--Swiften/Network/DummyConnection.cpp13
-rw-r--r--Swiften/Network/DummyConnection.h52
-rw-r--r--Swiften/Network/DummyConnectionFactory.h20
-rw-r--r--Swiften/Network/DummyConnectionServer.h44
-rw-r--r--Swiften/Network/DummyConnectionServerFactory.h22
-rw-r--r--Swiften/Network/DummyTimerFactory.cpp67
-rw-r--r--Swiften/Network/DummyTimerFactory.h24
-rw-r--r--Swiften/Network/EnvironmentProxyProvider.cpp44
-rw-r--r--Swiften/Network/EnvironmentProxyProvider.h20
-rw-r--r--Swiften/Network/FakeConnection.cpp66
-rw-r--r--Swiften/Network/FakeConnection.h78
-rw-r--r--Swiften/Network/GConfProxyProvider.cpp58
-rw-r--r--Swiften/Network/GConfProxyProvider.h20
-rw-r--r--Swiften/Network/HTTPConnectProxiedConnection.cpp225
-rw-r--r--Swiften/Network/HTTPConnectProxiedConnection.h56
-rw-r--r--Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp14
-rw-r--r--Swiften/Network/HTTPConnectProxiedConnectionFactory.h42
-rw-r--r--Swiften/Network/HTTPTrafficFilter.h18
-rw-r--r--Swiften/Network/HostAddress.cpp71
-rw-r--r--Swiften/Network/HostAddress.h46
-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.h10
-rw-r--r--Swiften/Network/MacOSXProxyProvider.cpp119
-rw-r--r--Swiften/Network/MacOSXProxyProvider.h22
-rw-r--r--Swiften/Network/MiniUPnPInterface.cpp150
-rw-r--r--Swiften/Network/MiniUPnPInterface.h27
-rw-r--r--Swiften/Network/NATPMPInterface.cpp199
-rw-r--r--Swiften/Network/NATPMPInterface.h27
-rw-r--r--Swiften/Network/NATPortMapping.h68
-rw-r--r--Swiften/Network/NATTraversalForwardPortRequest.h22
-rw-r--r--Swiften/Network/NATTraversalGetPublicIPRequest.h19
-rw-r--r--Swiften/Network/NATTraversalInterface.cpp3
-rw-r--r--Swiften/Network/NATTraversalInterface.h16
-rw-r--r--Swiften/Network/NATTraversalRemovePortForwardingRequest.h49
-rw-r--r--Swiften/Network/NATTraverser.h24
-rw-r--r--Swiften/Network/NetworkEnvironment.cpp27
-rw-r--r--Swiften/Network/NetworkEnvironment.h21
-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.cpp81
-rw-r--r--Swiften/Network/NullNATTraverser.h22
-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.h44
-rw-r--r--Swiften/Network/PlatformDomainNameQuery.h32
-rw-r--r--Swiften/Network/PlatformDomainNameResolver.cpp87
-rw-r--r--Swiften/Network/PlatformDomainNameResolver.h61
-rw-r--r--Swiften/Network/PlatformDomainNameServiceQuery.cpp247
-rw-r--r--Swiften/Network/PlatformDomainNameServiceQuery.h33
-rw-r--r--Swiften/Network/PlatformNATTraversalWorker.cpp260
-rw-r--r--Swiften/Network/PlatformNATTraversalWorker.h82
-rw-r--r--Swiften/Network/PlatformNetworkEnvironment.h8
-rw-r--r--Swiften/Network/PlatformProxyProvider.h6
-rw-r--r--Swiften/Network/ProxiedConnection.cpp141
-rw-r--r--Swiften/Network/ProxiedConnection.h100
-rw-r--r--Swiften/Network/ProxyProvider.cpp8
-rw-r--r--Swiften/Network/ProxyProvider.h21
-rw-r--r--Swiften/Network/SConscript178
-rw-r--r--Swiften/Network/SOCKS5ProxiedConnection.cpp184
-rw-r--r--Swiften/Network/SOCKS5ProxiedConnection.h52
-rw-r--r--Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp10
-rw-r--r--Swiften/Network/SOCKS5ProxiedConnectionFactory.h28
-rw-r--r--Swiften/Network/SolarisNetworkEnvironment.cpp410
-rw-r--r--Swiften/Network/SolarisNetworkEnvironment.h18
-rw-r--r--Swiften/Network/StaticDomainNameResolver.cpp143
-rw-r--r--Swiften/Network/StaticDomainNameResolver.h79
-rw-r--r--Swiften/Network/TLSConnection.cpp76
-rw-r--r--Swiften/Network/TLSConnection.h74
-rw-r--r--Swiften/Network/TLSConnectionFactory.cpp8
-rw-r--r--Swiften/Network/TLSConnectionFactory.h26
-rw-r--r--Swiften/Network/Timer.h61
-rw-r--r--Swiften/Network/TimerFactory.h14
-rw-r--r--[-rwxr-xr-x]Swiften/Network/UnboundDomainNameResolver.cpp383
-rw-r--r--[-rwxr-xr-x]Swiften/Network/UnboundDomainNameResolver.h64
-rw-r--r--Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp868
-rw-r--r--Swiften/Network/UnitTest/BOSHConnectionTest.cpp546
-rw-r--r--Swiften/Network/UnitTest/ChainedConnectorTest.cpp325
-rw-r--r--Swiften/Network/UnitTest/ConnectorTest.cpp706
-rw-r--r--Swiften/Network/UnitTest/DomainNameServiceQueryTest.cpp106
-rw-r--r--Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp790
-rw-r--r--Swiften/Network/UnitTest/HostAddressTest.cpp77
-rw-r--r--Swiften/Network/UnixNetworkEnvironment.cpp76
-rw-r--r--Swiften/Network/UnixNetworkEnvironment.h12
-rw-r--r--Swiften/Network/UnixProxyProvider.cpp58
-rw-r--r--Swiften/Network/UnixProxyProvider.h22
-rw-r--r--Swiften/Network/WindowsNetworkEnvironment.cpp93
-rw-r--r--Swiften/Network/WindowsNetworkEnvironment.h17
-rw-r--r--Swiften/Network/WindowsProxyProvider.cpp171
-rw-r--r--Swiften/Network/WindowsProxyProvider.h29
-rw-r--r--Swiften/Parser/Attribute.h34
-rw-r--r--Swiften/Parser/AttributeMap.cpp57
-rw-r--r--Swiften/Parser/AttributeMap.h79
-rw-r--r--Swiften/Parser/AuthChallengeParser.cpp15
-rw-r--r--Swiften/Parser/AuthChallengeParser.h27
-rw-r--r--Swiften/Parser/AuthFailureParser.h12
-rw-r--r--Swiften/Parser/AuthRequestParser.cpp21
-rw-r--r--Swiften/Parser/AuthRequestParser.h27
-rw-r--r--Swiften/Parser/AuthResponseParser.cpp15
-rw-r--r--Swiften/Parser/AuthResponseParser.h27
-rw-r--r--Swiften/Parser/AuthSuccessParser.cpp15
-rw-r--r--Swiften/Parser/AuthSuccessParser.h27
-rw-r--r--Swiften/Parser/BOSHBodyExtractor.cpp223
-rw-r--r--Swiften/Parser/BOSHBodyExtractor.h38
-rw-r--r--Swiften/Parser/ComponentHandshakeParser.cpp15
-rw-r--r--Swiften/Parser/ComponentHandshakeParser.h27
-rw-r--r--Swiften/Parser/CompressFailureParser.h12
-rw-r--r--Swiften/Parser/CompressParser.cpp22
-rw-r--r--Swiften/Parser/CompressParser.h29
-rw-r--r--Swiften/Parser/CompressedParser.h12
-rw-r--r--Swiften/Parser/ElementParser.h22
-rw-r--r--Swiften/Parser/EnableStreamManagementParser.h12
-rw-r--r--Swiften/Parser/EnumParser.h47
-rw-r--r--Swiften/Parser/ExpatParser.cpp89
-rw-r--r--Swiften/Parser/ExpatParser.h25
-rw-r--r--Swiften/Parser/GenericElementParser.h53
-rw-r--r--Swiften/Parser/GenericPayloadParser.h59
-rw-r--r--Swiften/Parser/GenericPayloadParserFactory.h51
-rw-r--r--Swiften/Parser/GenericPayloadParserFactory2.h57
-rw-r--r--Swiften/Parser/GenericPayloadTreeParser.h76
-rw-r--r--Swiften/Parser/GenericStanzaParser.h49
-rw-r--r--Swiften/Parser/IQParser.cpp49
-rw-r--r--Swiften/Parser/IQParser.h16
-rw-r--r--Swiften/Parser/LibXMLParser.cpp125
-rw-r--r--Swiften/Parser/LibXMLParser.h37
-rw-r--r--Swiften/Parser/MessageParser.cpp42
-rw-r--r--Swiften/Parser/MessageParser.h16
-rw-r--r--Swiften/Parser/PayloadParser.h75
-rw-r--r--Swiften/Parser/PayloadParserFactory.h34
-rw-r--r--Swiften/Parser/PayloadParserFactoryCollection.cpp27
-rw-r--r--Swiften/Parser/PayloadParserFactoryCollection.h29
-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.cpp38
-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.cpp64
-rw-r--r--Swiften/Parser/PayloadParsers/CarbonsReceivedParser.h36
-rw-r--r--Swiften/Parser/PayloadParsers/CarbonsSentParser.cpp64
-rw-r--r--Swiften/Parser/PayloadParsers/CarbonsSentParser.h36
-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.cpp226
-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.cpp73
-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.cpp241
-rw-r--r--Swiften/Parser/PayloadParsers/ErrorParser.h36
-rw-r--r--Swiften/Parser/PayloadParsers/ErrorParserFactory.h28
-rw-r--r--Swiften/Parser/PayloadParsers/FormParser.cpp464
-rw-r--r--Swiften/Parser/PayloadParsers/FormParser.h63
-rw-r--r--Swiften/Parser/PayloadParsers/FormParserFactory.h24
-rw-r--r--Swiften/Parser/PayloadParsers/ForwardedParser.cpp89
-rw-r--r--Swiften/Parser/PayloadParsers/ForwardedParser.h52
-rw-r--r--Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp176
-rw-r--r--Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h22
-rw-r--r--Swiften/Parser/PayloadParsers/IBBParser.cpp92
-rw-r--r--Swiften/Parser/PayloadParsers/IBBParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/IdleParser.cpp12
-rw-r--r--Swiften/Parser/PayloadParsers/IdleParser.h22
-rw-r--r--Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.cpp200
-rw-r--r--Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.h38
-rw-r--r--Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.cpp60
-rw-r--r--Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/JingleContentPayloadParser.cpp132
-rw-r--r--Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h20
-rw-r--r--Swiften/Parser/PayloadParsers/JingleContentPayloadParserFactory.h40
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.cpp58
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h20
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParserFactory.h40
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.cpp96
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.h22
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.cpp55
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h18
-rw-r--r--Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp58
-rw-r--r--Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.h14
-rw-r--r--Swiften/Parser/PayloadParsers/JingleParser.cpp203
-rw-r--r--Swiften/Parser/PayloadParsers/JingleParser.h30
-rw-r--r--Swiften/Parser/PayloadParsers/JingleParserFactory.h40
-rw-r--r--Swiften/Parser/PayloadParsers/JingleReasonParser.cpp146
-rw-r--r--Swiften/Parser/PayloadParsers/JingleReasonParser.h26
-rw-r--r--Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp146
-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.cpp70
-rw-r--r--Swiften/Parser/PayloadParsers/MAMFinParser.h38
-rw-r--r--Swiften/Parser/PayloadParsers/MAMQueryParser.cpp96
-rw-r--r--Swiften/Parser/PayloadParsers/MAMQueryParser.h49
-rw-r--r--Swiften/Parser/PayloadParsers/MAMResultParser.cpp69
-rw-r--r--Swiften/Parser/PayloadParsers/MAMResultParser.h49
-rw-r--r--Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp11
-rw-r--r--Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.h8
-rw-r--r--Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.cpp16
-rw-r--r--Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.h8
-rw-r--r--Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.cpp19
-rw-r--r--Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.h8
-rw-r--r--Swiften/Parser/PayloadParsers/MUCItemParser.cpp111
-rw-r--r--Swiften/Parser/PayloadParsers/MUCItemParser.h14
-rw-r--r--Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.cpp53
-rw-r--r--Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/MUCOwnerPayloadParserFactory.h28
-rw-r--r--Swiften/Parser/PayloadParsers/MUCUserPayloadParser.cpp79
-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.cpp53
-rw-r--r--Swiften/Parser/PayloadParsers/PrivateStorageParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/PrivateStorageParserFactory.h30
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubAffiliationParser.cpp68
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubAffiliationParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.cpp71
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubConfigureParser.cpp64
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubConfigureParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubCreateParser.cpp59
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubCreateParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubDefaultParser.cpp68
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubDefaultParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubErrorParser.cpp160
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubErrorParser.h36
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubErrorParserFactory.h24
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.cpp61
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.cpp77
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.cpp72
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.cpp65
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.cpp59
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventItemParser.cpp74
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventItemParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventItemsParser.cpp77
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventParser.cpp95
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.cpp59
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.cpp59
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventRetractParser.cpp60
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventRetractParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.cpp88
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubItemParser.cpp68
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubItemParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubItemsParser.cpp86
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubItemsParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOptionsParser.cpp82
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOptionsParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.cpp73
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.cpp65
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.cpp72
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.cpp62
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.cpp65
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.cpp93
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.cpp60
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.cpp59
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.cpp72
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.cpp65
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubParser.cpp174
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubParser.h42
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubPublishParser.cpp65
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubPublishParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubRetractParser.cpp75
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubRetractParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.cpp53
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscribeParser.cpp67
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.cpp93
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.cpp65
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.h34
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.cpp75
-rw-r--r--Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h33
-rw-r--r--Swiften/Parser/PayloadParsers/RawXMLPayloadParser.cpp19
-rw-r--r--Swiften/Parser/PayloadParsers/RawXMLPayloadParser.h22
-rw-r--r--Swiften/Parser/PayloadParsers/RawXMLPayloadParserFactory.h25
-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.cpp86
-rw-r--r--Swiften/Parser/PayloadParsers/ResultSetParser.h36
-rw-r--r--Swiften/Parser/PayloadParsers/RosterItemExchangeParser.cpp89
-rw-r--r--Swiften/Parser/PayloadParsers/RosterItemExchangeParser.h36
-rw-r--r--Swiften/Parser/PayloadParsers/RosterParser.cpp154
-rw-r--r--Swiften/Parser/PayloadParsers/RosterParser.h38
-rw-r--r--Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp74
-rw-r--r--Swiften/Parser/PayloadParsers/S5BProxyRequestParser.h14
-rw-r--r--Swiften/Parser/PayloadParsers/SearchPayloadParser.cpp164
-rw-r--r--Swiften/Parser/PayloadParsers/SearchPayloadParser.h42
-rw-r--r--Swiften/Parser/PayloadParsers/SecurityLabelParser.cpp91
-rw-r--r--Swiften/Parser/PayloadParsers/SecurityLabelParser.h40
-rw-r--r--Swiften/Parser/PayloadParsers/SecurityLabelParserFactory.h8
-rw-r--r--Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.cpp98
-rw-r--r--Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.h44
-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.cpp84
-rw-r--r--Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.h22
-rw-r--r--Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp172
-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.cpp111
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/BodyParserTest.cpp22
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/CarbonsParserTest.cpp216
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/CommandParserTest.cpp122
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/DeliveryReceiptParserTest.cpp40
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/DiscoInfoParserTest.cpp154
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/DiscoItemsParserTest.cpp54
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/ErrorParserTest.cpp80
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/FormParserTest.cpp427
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/ForwardedParserTest.cpp188
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/IBBParserTest.cpp47
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/IdleParserTest.cpp48
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/InBandRegistrationPayloadParserTest.cpp88
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp1174
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/MAMFinParserTest.cpp82
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/MAMQueryParserTest.cpp206
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/MAMResultParserTest.cpp70
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/MUCAdminPayloadParserTest.cpp32
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp149
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h6
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h92
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/PriorityParserTest.cpp36
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/PrivateStorageParserTest.cpp154
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/PubSubRetractParserTest.cpp73
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/RawXMLPayloadParserTest.cpp42
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/ReplaceTest.cpp40
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/ResourceBindParserTest.cpp36
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/ResultSetParserTest.cpp98
-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.cpp330
-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.cpp106
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/UserLocationParserTest.cpp164
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/UserTuneParserTest.cpp84
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/VCardParserTest.cpp378
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/VCardUpdateParserTest.cpp32
-rw-r--r--Swiften/Parser/PayloadParsers/UserLocationParser.cpp158
-rw-r--r--Swiften/Parser/PayloadParsers/UserLocationParser.h30
-rw-r--r--Swiften/Parser/PayloadParsers/UserTuneParser.cpp66
-rw-r--r--Swiften/Parser/PayloadParsers/UserTuneParser.h30
-rw-r--r--Swiften/Parser/PayloadParsers/VCardParser.cpp520
-rw-r--r--Swiften/Parser/PayloadParsers/VCardParser.h51
-rw-r--r--Swiften/Parser/PayloadParsers/VCardUpdateParser.cpp18
-rw-r--r--Swiften/Parser/PayloadParsers/VCardUpdateParser.h30
-rw-r--r--Swiften/Parser/PayloadParsers/WhiteboardParser.cpp563
-rw-r--r--Swiften/Parser/PayloadParsers/WhiteboardParser.h38
-rw-r--r--Swiften/Parser/PlatformXMLParserFactory.cpp4
-rw-r--r--Swiften/Parser/PlatformXMLParserFactory.h14
-rw-r--r--Swiften/Parser/PresenceParser.cpp73
-rw-r--r--Swiften/Parser/PresenceParser.h16
-rw-r--r--Swiften/Parser/SConscript210
-rw-r--r--Swiften/Parser/SerializingParser.cpp44
-rw-r--r--Swiften/Parser/SerializingParser.h25
-rw-r--r--Swiften/Parser/StanzaAckParser.cpp20
-rw-r--r--Swiften/Parser/StanzaAckParser.h20
-rw-r--r--Swiften/Parser/StanzaAckRequestParser.h12
-rw-r--r--Swiften/Parser/StanzaParser.cpp108
-rw-r--r--Swiften/Parser/StanzaParser.h61
-rw-r--r--Swiften/Parser/StartTLSFailureParser.h12
-rw-r--r--Swiften/Parser/StartTLSParser.h12
-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.h37
-rw-r--r--Swiften/Parser/StreamManagementEnabledParser.cpp16
-rw-r--r--Swiften/Parser/StreamManagementEnabledParser.h30
-rw-r--r--Swiften/Parser/StreamManagementFailedParser.h12
-rw-r--r--Swiften/Parser/StreamResumeParser.cpp26
-rw-r--r--Swiften/Parser/StreamResumeParser.h28
-rw-r--r--Swiften/Parser/StreamResumedParser.cpp26
-rw-r--r--Swiften/Parser/StreamResumedParser.h28
-rw-r--r--Swiften/Parser/TLSProceedParser.h12
-rw-r--r--Swiften/Parser/Tree/NullParserElement.cpp4
-rw-r--r--Swiften/Parser/Tree/NullParserElement.h15
-rw-r--r--Swiften/Parser/Tree/ParserElement.cpp30
-rw-r--r--Swiften/Parser/Tree/ParserElement.h69
-rw-r--r--Swiften/Parser/Tree/TreeReparser.cpp60
-rw-r--r--Swiften/Parser/Tree/TreeReparser.h12
-rw-r--r--Swiften/Parser/UnitTest/AttributeMapTest.cpp102
-rw-r--r--Swiften/Parser/UnitTest/BOSHBodyExtractorTest.cpp176
-rw-r--r--Swiften/Parser/UnitTest/ElementParserTester.h5
-rw-r--r--Swiften/Parser/UnitTest/EnumParserTest.cpp38
-rw-r--r--Swiften/Parser/UnitTest/GenericPayloadTreeParserTest.cpp80
-rw-r--r--Swiften/Parser/UnitTest/IQParserTest.cpp78
-rw-r--r--Swiften/Parser/UnitTest/MessageParserTest.cpp92
-rw-r--r--Swiften/Parser/UnitTest/ParserTester.h71
-rw-r--r--Swiften/Parser/UnitTest/PayloadParserFactoryCollectionTest.cpp172
-rw-r--r--Swiften/Parser/UnitTest/PresenceParserTest.cpp138
-rw-r--r--Swiften/Parser/UnitTest/SerializingParserTest.cpp74
-rw-r--r--Swiften/Parser/UnitTest/StanzaAckParserTest.cpp54
-rw-r--r--Swiften/Parser/UnitTest/StanzaParserTest.cpp388
-rw-r--r--Swiften/Parser/UnitTest/StanzaParserTester.h2
-rw-r--r--Swiften/Parser/UnitTest/StreamFeaturesParserTest.cpp182
-rw-r--r--Swiften/Parser/UnitTest/StreamManagementEnabledParserTest.cpp34
-rw-r--r--Swiften/Parser/UnitTest/XMLParserTest.cpp548
-rw-r--r--Swiften/Parser/UnitTest/XMPPParserTest.cpp345
-rw-r--r--Swiften/Parser/UnknownElementParser.h12
-rw-r--r--Swiften/Parser/UnknownPayloadParser.h24
-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.cpp314
-rw-r--r--Swiften/Parser/XMPPParser.h81
-rw-r--r--Swiften/Parser/XMPPParserClient.h22
-rw-r--r--Swiften/Presence/DirectedPresenceSender.cpp65
-rw-r--r--Swiften/Presence/DirectedPresenceSender.h32
-rw-r--r--Swiften/Presence/PayloadAddingPresenceSender.cpp48
-rw-r--r--Swiften/Presence/PayloadAddingPresenceSender.h74
-rw-r--r--Swiften/Presence/PresenceOracle.cpp323
-rw-r--r--Swiften/Presence/PresenceOracle.h111
-rw-r--r--Swiften/Presence/PresenceSender.h12
-rw-r--r--Swiften/Presence/SConscript14
-rw-r--r--Swiften/Presence/StanzaChannelPresenceSender.cpp7
-rw-r--r--Swiften/Presence/StanzaChannelPresenceSender.h18
-rw-r--r--Swiften/Presence/SubscriptionManager.cpp45
-rw-r--r--Swiften/Presence/SubscriptionManager.h69
-rw-r--r--Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp267
-rw-r--r--Swiften/Presence/UnitTest/PayloadAddingPresenceSenderTest.cpp194
-rw-r--r--Swiften/Presence/UnitTest/PresenceOracleTest.cpp453
-rw-r--r--Swiften/PubSub/PubSubManager.h56
-rw-r--r--Swiften/PubSub/PubSubManagerImpl.cpp20
-rw-r--r--Swiften/PubSub/PubSubManagerImpl.h45
-rw-r--r--Swiften/PubSub/PubSubUtil.h37
-rw-r--r--Swiften/QA/ClientTest/ClientTest.cpp131
-rw-r--r--Swiften/QA/ClientTest/SConscript20
-rw-r--r--Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp73
-rw-r--r--Swiften/QA/ConcurrentFileTransferTest/SConscript20
-rw-r--r--Swiften/QA/DNSSDTest/DNSSDTest.cpp230
-rw-r--r--Swiften/QA/DNSSDTest/SConscript30
-rw-r--r--Swiften/QA/FileTransferTest/FileTransferTest.cpp675
-rw-r--r--Swiften/QA/FileTransferTest/SConscript24
-rw-r--r--Swiften/QA/NetworkTest/BoostConnectionServerTest.cpp389
-rwxr-xr-xSwiften/QA/NetworkTest/BoostConnectionTest.cpp290
-rw-r--r--Swiften/QA/NetworkTest/DomainNameResolverTest.cpp410
-rw-r--r--Swiften/QA/NetworkTest/SConscript30
-rw-r--r--Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp45
-rw-r--r--Swiften/QA/ProxyProviderTest/SConscript4
-rw-r--r--Swiften/QA/ReconnectTest/ReconnectTest.cpp91
-rw-r--r--Swiften/QA/ReconnectTest/SConscript36
-rw-r--r--Swiften/QA/SConscript20
-rw-r--r--Swiften/QA/ScriptedTests/SConscript8
-rw-r--r--Swiften/QA/StorageTest/FileReadBytestreamTest.cpp78
-rw-r--r--Swiften/QA/StorageTest/FileWriteBytestreamTest.cpp56
-rw-r--r--Swiften/QA/StorageTest/SConscript32
-rw-r--r--Swiften/QA/StorageTest/VCardFileStorageTest.cpp198
-rw-r--r--Swiften/QA/TLSTest/CertificateErrorTest.cpp364
-rw-r--r--Swiften/QA/TLSTest/CertificateTest.cpp152
-rw-r--r--Swiften/QA/TLSTest/SConscript40
-rw-r--r--Swiften/QA/TLSTest/jabber_org.crtbin2082 -> 2081 bytes
-rw-r--r--Swiften/Queries/DummyIQChannel.h30
-rw-r--r--Swiften/Queries/GenericRequest.h125
-rw-r--r--Swiften/Queries/GetResponder.h16
-rw-r--r--Swiften/Queries/IQChannel.h27
-rw-r--r--Swiften/Queries/IQHandler.cpp3
-rw-r--r--Swiften/Queries/IQHandler.h16
-rw-r--r--Swiften/Queries/IQRouter.cpp95
-rw-r--r--Swiften/Queries/IQRouter.h132
-rw-r--r--Swiften/Queries/PubSubRequest.h121
-rw-r--r--Swiften/Queries/RawRequest.h69
-rw-r--r--Swiften/Queries/Request.cpp121
-rw-r--r--Swiften/Queries/Request.h180
-rw-r--r--Swiften/Queries/Requests/EnableCarbonsRequest.h28
-rw-r--r--Swiften/Queries/Requests/GetInBandRegistrationFormRequest.cpp7
-rw-r--r--Swiften/Queries/Requests/GetInBandRegistrationFormRequest.h24
-rw-r--r--Swiften/Queries/Requests/GetPrivateStorageRequest.h64
-rw-r--r--Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h35
-rw-r--r--Swiften/Queries/Requests/GetSoftwareVersionRequest.h36
-rw-r--r--Swiften/Queries/Requests/SetPrivateStorageRequest.h52
-rw-r--r--Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.cpp7
-rw-r--r--Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.h40
-rw-r--r--Swiften/Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp187
-rw-r--r--Swiften/Queries/Responder.h246
-rw-r--r--Swiften/Queries/Responders/SoftwareVersionResponder.cpp19
-rw-r--r--Swiften/Queries/Responders/SoftwareVersionResponder.h28
-rw-r--r--Swiften/Queries/SetResponder.h16
-rw-r--r--Swiften/Queries/UnitTest/IQRouterTest.cpp285
-rw-r--r--Swiften/Queries/UnitTest/RequestTest.cpp699
-rw-r--r--Swiften/Queries/UnitTest/ResponderTest.cpp272
-rw-r--r--Swiften/Roster/GetRosterRequest.h37
-rw-r--r--Swiften/Roster/RosterMemoryStorage.cpp14
-rw-r--r--Swiften/Roster/RosterMemoryStorage.h22
-rw-r--r--Swiften/Roster/RosterPushResponder.h41
-rw-r--r--Swiften/Roster/RosterStorage.h16
-rw-r--r--Swiften/Roster/SetRosterRequest.h46
-rw-r--r--Swiften/Roster/UnitTest/XMPPRosterControllerTest.cpp681
-rw-r--r--Swiften/Roster/UnitTest/XMPPRosterImplTest.cpp172
-rw-r--r--Swiften/Roster/UnitTest/XMPPRosterSignalHandler.cpp25
-rw-r--r--Swiften/Roster/UnitTest/XMPPRosterSignalHandler.h74
-rw-r--r--Swiften/Roster/XMPPRoster.h165
-rw-r--r--Swiften/Roster/XMPPRosterController.cpp115
-rw-r--r--Swiften/Roster/XMPPRosterController.h63
-rw-r--r--Swiften/Roster/XMPPRosterImpl.cpp116
-rw-r--r--Swiften/Roster/XMPPRosterImpl.h44
-rw-r--r--Swiften/Roster/XMPPRosterItem.h77
-rw-r--r--Swiften/SASL/ClientAuthenticator.h79
-rw-r--r--Swiften/SASL/DIGESTMD5ClientAuthenticator.cpp134
-rw-r--r--Swiften/SASL/DIGESTMD5ClientAuthenticator.h42
-rw-r--r--Swiften/SASL/DIGESTMD5Properties.cpp191
-rw-r--r--Swiften/SASL/DIGESTMD5Properties.h33
-rw-r--r--Swiften/SASL/EXTERNALClientAuthenticator.cpp12
-rw-r--r--Swiften/SASL/EXTERNALClientAuthenticator.h20
-rw-r--r--Swiften/SASL/PLAINClientAuthenticator.cpp7
-rw-r--r--Swiften/SASL/PLAINClientAuthenticator.h16
-rw-r--r--Swiften/SASL/PLAINMessage.cpp49
-rw-r--r--Swiften/SASL/PLAINMessage.h48
-rw-r--r--Swiften/SASL/SCRAMSHA1ClientAuthenticator.cpp273
-rw-r--r--Swiften/SASL/SCRAMSHA1ClientAuthenticator.h79
-rw-r--r--Swiften/SASL/SConscript44
-rw-r--r--Swiften/SASL/UnitTest/DIGESTMD5ClientAuthenticatorTest.cpp101
-rw-r--r--Swiften/SASL/UnitTest/DIGESTMD5PropertiesTest.cpp76
-rw-r--r--Swiften/SASL/UnitTest/PLAINClientAuthenticatorTest.cpp37
-rw-r--r--Swiften/SASL/UnitTest/PLAINMessageTest.cpp102
-rw-r--r--Swiften/SASL/UnitTest/SCRAMSHA1ClientAuthenticatorTest.cpp312
-rw-r--r--Swiften/SASL/UnitTest/WindowsServicePrincipalNameTest.cpp284
-rw-r--r--Swiften/SASL/WindowsAuthentication.cpp524
-rw-r--r--Swiften/SASL/WindowsAuthentication.h284
-rw-r--r--Swiften/SASL/WindowsGSSAPIClientAuthenticator.cpp320
-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/SConscript1129
-rw-r--r--Swiften/Serializer/AuthChallengeSerializer.cpp30
-rw-r--r--Swiften/Serializer/AuthChallengeSerializer.h14
-rw-r--r--Swiften/Serializer/AuthFailureSerializer.h20
-rw-r--r--Swiften/Serializer/AuthRequestSerializer.cpp32
-rw-r--r--Swiften/Serializer/AuthRequestSerializer.h14
-rw-r--r--Swiften/Serializer/AuthResponseSerializer.cpp32
-rw-r--r--Swiften/Serializer/AuthResponseSerializer.h14
-rw-r--r--Swiften/Serializer/AuthSuccessSerializer.cpp30
-rw-r--r--Swiften/Serializer/AuthSuccessSerializer.h14
-rw-r--r--Swiften/Serializer/ComponentHandshakeSerializer.cpp8
-rw-r--r--Swiften/Serializer/ComponentHandshakeSerializer.h14
-rw-r--r--Swiften/Serializer/CompressFailureSerializer.h20
-rw-r--r--Swiften/Serializer/CompressRequestSerializer.cpp12
-rw-r--r--Swiften/Serializer/CompressRequestSerializer.h16
-rw-r--r--Swiften/Serializer/ElementSerializer.h18
-rw-r--r--Swiften/Serializer/EnableStreamManagementSerializer.h20
-rw-r--r--Swiften/Serializer/GenericElementSerializer.h20
-rw-r--r--Swiften/Serializer/GenericPayloadSerializer.h26
-rw-r--r--Swiften/Serializer/GenericStanzaSerializer.h36
-rw-r--r--Swiften/Serializer/IQSerializer.h42
-rw-r--r--Swiften/Serializer/MessageSerializer.cpp33
-rw-r--r--Swiften/Serializer/MessageSerializer.h26
-rw-r--r--Swiften/Serializer/PayloadSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializerCollection.cpp25
-rw-r--r--Swiften/Serializer/PayloadSerializerCollection.h26
-rw-r--r--Swiften/Serializer/PayloadSerializers/BlockSerializer.h40
-rw-r--r--Swiften/Serializer/PayloadSerializers/BodySerializer.h20
-rw-r--r--Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp43
-rw-r--r--Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.h16
-rw-r--r--Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.cpp16
-rw-r--r--Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.cpp18
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.cpp18
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.cpp18
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.cpp28
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.h20
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.cpp26
-rw-r--r--Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/ChatStateSerializer.cpp24
-rw-r--r--Swiften/Serializer/PayloadSerializers/ChatStateSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp134
-rw-r--r--Swiften/Serializer/PayloadSerializers/CommandSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/DelaySerializer.cpp21
-rw-r--r--Swiften/Serializer/PayloadSerializers/DelaySerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.cpp14
-rw-r--r--Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.h20
-rw-r--r--Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.cpp15
-rw-r--r--Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp56
-rw-r--r--Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp35
-rw-r--r--Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/ErrorSerializer.cpp101
-rw-r--r--Swiften/Serializer/PayloadSerializers/ErrorSerializer.h20
-rw-r--r--Swiften/Serializer/PayloadSerializers/FormSerializer.cpp349
-rw-r--r--Swiften/Serializer/PayloadSerializers/FormSerializer.h32
-rw-r--r--Swiften/Serializer/PayloadSerializers/ForwardedSerializer.cpp68
-rw-r--r--Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h25
-rw-r--r--Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp172
-rw-r--r--Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp67
-rw-r--r--Swiften/Serializer/PayloadSerializers/IBBSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/IdleSerializer.h20
-rw-r--r--Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp140
-rw-r--r--Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.cpp23
-rw-r--r--Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h31
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp111
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h26
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp27
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h26
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp67
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h17
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp31
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp27
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h22
-rw-r--r--Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp231
-rw-r--r--Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h40
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp127
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h30
-rw-r--r--Swiften/Serializer/PayloadSerializers/LastSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/MAMFinSerializer.cpp49
-rw-r--r--Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h21
-rw-r--r--Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.cpp49
-rw-r--r--Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h21
-rw-r--r--Swiften/Serializer/PayloadSerializers/MAMResultSerializer.cpp35
-rw-r--r--Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h25
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp22
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp28
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.h16
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp51
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.h16
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h107
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp24
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.h20
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.cpp75
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp91
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.h20
-rw-r--r--Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp13
-rw-r--r--Swiften/Serializer/PayloadSerializers/NicknameSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/PrioritySerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp30
-rw-r--r--Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.h20
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.cpp47
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h30
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp34
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.cpp26
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.cpp25
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.cpp45
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h30
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.cpp176
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.h26
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.cpp25
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.cpp31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.cpp28
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.cpp25
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.cpp25
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp46
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.cpp36
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.cpp25
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.cpp25
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.cpp25
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp57
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h33
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.cpp52
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h30
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp34
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp51
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.cpp36
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.cpp46
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h30
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp30
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.cpp34
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.cpp28
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.cpp25
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.cpp57
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h33
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.cpp27
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.cpp27
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.cpp43
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h30
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp30
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.cpp30
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.cpp34
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h30
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp81
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.cpp25
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.cpp31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.cpp55
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.cpp34
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h31
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.cpp39
-rw-r--r--Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/RawXMLPayloadSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/ReplaceSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.cpp31
-rw-r--r--Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/ResultSetSerializer.cpp71
-rw-r--r--Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h21
-rw-r--r--Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp60
-rw-r--r--Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp84
-rw-r--r--Swiften/Serializer/PayloadSerializers/RosterSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h43
-rw-r--r--Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp68
-rw-r--r--Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.h16
-rw-r--r--Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp58
-rw-r--r--Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp58
-rw-r--r--Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.cpp28
-rw-r--r--Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/StartSessionSerializer.h16
-rw-r--r--Swiften/Serializer/PayloadSerializers/StatusSerializer.h24
-rw-r--r--Swiften/Serializer/PayloadSerializers/StatusShowSerializer.h48
-rw-r--r--Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp64
-rw-r--r--Swiften/Serializer/PayloadSerializers/StorageSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp71
-rw-r--r--Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h21
-rw-r--r--Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp91
-rw-r--r--Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/SubjectSerializer.h20
-rw-r--r--Swiften/Serializer/PayloadSerializers/ThreadSerializer.cpp24
-rw-r--r--Swiften/Serializer/PayloadSerializers/ThreadSerializer.h16
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/BlockSerializerTest.cpp74
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/CapsInfoSerializerTest.cpp22
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/CarbonsSerializerTest.cpp226
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/ChatStateSerializerTest.cpp78
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/DeliveryReceiptSerializerTest.cpp45
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/DiscoInfoSerializerTest.cpp84
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/ErrorSerializerTest.cpp57
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/FormSerializerTest.cpp568
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/ForwardedSerializerTest.cpp190
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/IBBSerializerTest.cpp46
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/IdleSerializerTest.cpp30
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/InBandRegistrationPayloadSerializerTest.cpp93
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/IsodeIQDelegationSerializerTest.cpp210
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp761
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/MAMFinSerializerTest.cpp76
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/MAMQuerySerializerTest.cpp86
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/MAMResultSerializerTest.cpp82
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/MUCAdminPayloadSerializerTest.cpp44
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.cpp20
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.h18
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/PrioritySerializerTest.cpp22
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/PrivateStorageSerializerTest.cpp66
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemSerializerTest.cpp60
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemsSerializerTest.cpp90
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/PubSubRetractSerializerTest.cpp57
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/ReplaceSerializerTest.cpp28
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/ResourceBindSerializerTest.cpp76
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/ResultSetSerializerTest.cpp152
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/RosterItemExchangeSerializerTest.cpp78
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/RosterSerializerTest.cpp170
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/SearchPayloadSerializerTest.cpp321
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelSerializerTest.cpp88
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelsCatalogSerializerTest.cpp104
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/SoftwareVersionSerializerTest.cpp22
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/StatusSerializerTest.cpp22
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/StatusShowSerializerTest.cpp80
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/StorageSerializerTest.cpp100
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/StreamInitiationSerializerTest.cpp96
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/UserLocationSerializerTest.cpp155
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/UserTuneSerializerTest.cpp97
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp262
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/VCardUpdateSerializerTest.cpp32
-rw-r--r--Swiften/Serializer/PayloadSerializers/UserLocationSerializer.cpp158
-rw-r--r--Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/UserTuneSerializer.cpp66
-rw-r--r--Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h29
-rw-r--r--Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp460
-rw-r--r--Swiften/Serializer/PayloadSerializers/VCardSerializer.h17
-rw-r--r--Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp17
-rw-r--r--Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.h14
-rw-r--r--Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp380
-rw-r--r--Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.h58
-rw-r--r--Swiften/Serializer/PresenceSerializer.cpp34
-rw-r--r--Swiften/Serializer/PresenceSerializer.h26
-rw-r--r--Swiften/Serializer/StanzaAckRequestSerializer.h20
-rw-r--r--Swiften/Serializer/StanzaAckSerializer.h29
-rw-r--r--Swiften/Serializer/StanzaSerializer.cpp79
-rw-r--r--Swiften/Serializer/StanzaSerializer.h41
-rw-r--r--Swiften/Serializer/StartTLSFailureSerializer.h20
-rw-r--r--Swiften/Serializer/StartTLSRequestSerializer.h20
-rw-r--r--Swiften/Serializer/StreamErrorSerializer.cpp82
-rw-r--r--Swiften/Serializer/StreamErrorSerializer.h14
-rw-r--r--Swiften/Serializer/StreamFeaturesSerializer.cpp81
-rw-r--r--Swiften/Serializer/StreamFeaturesSerializer.h14
-rw-r--r--Swiften/Serializer/StreamManagementEnabledSerializer.cpp24
-rw-r--r--Swiften/Serializer/StreamManagementEnabledSerializer.h14
-rw-r--r--Swiften/Serializer/StreamManagementFailedSerializer.h20
-rw-r--r--Swiften/Serializer/StreamResumeSerializer.cpp21
-rw-r--r--Swiften/Serializer/StreamResumeSerializer.h14
-rw-r--r--Swiften/Serializer/StreamResumedSerializer.cpp21
-rw-r--r--Swiften/Serializer/StreamResumedSerializer.h14
-rw-r--r--Swiften/Serializer/TLSProceedSerializer.h20
-rw-r--r--Swiften/Serializer/UnitTest/AuthChallengeSerializerTest.cpp80
-rw-r--r--Swiften/Serializer/UnitTest/AuthRequestSerializerTest.cpp80
-rw-r--r--Swiften/Serializer/UnitTest/AuthResponseSerializerTest.cpp80
-rw-r--r--Swiften/Serializer/UnitTest/AuthSuccessSerializerTest.cpp80
-rw-r--r--Swiften/Serializer/UnitTest/StreamFeaturesSerializerTest.cpp79
-rw-r--r--Swiften/Serializer/UnitTest/XMPPSerializerTest.cpp96
-rw-r--r--Swiften/Serializer/XML/UnitTest/XMLElementTest.cpp104
-rw-r--r--Swiften/Serializer/XML/XMLElement.cpp72
-rw-r--r--Swiften/Serializer/XML/XMLElement.h31
-rw-r--r--Swiften/Serializer/XML/XMLNode.h10
-rw-r--r--Swiften/Serializer/XML/XMLRawTextNode.h20
-rw-r--r--Swiften/Serializer/XML/XMLTextNode.h46
-rw-r--r--Swiften/Serializer/XMPPSerializer.cpp152
-rw-r--r--Swiften/Serializer/XMPPSerializer.h46
-rw-r--r--Swiften/Session/BOSHSessionStream.cpp201
-rw-r--r--Swiften/Session/BOSHSessionStream.h144
-rw-r--r--Swiften/Session/BasicSessionStream.cpp239
-rw-r--r--Swiften/Session/BasicSessionStream.h129
-rw-r--r--Swiften/Session/Session.cpp136
-rw-r--r--Swiften/Session/Session.h198
-rw-r--r--Swiften/Session/SessionStream.h150
-rw-r--r--Swiften/Session/SessionTracer.cpp21
-rw-r--r--Swiften/Session/SessionTracer.h18
-rw-r--r--Swiften/StreamManagement/SConscript6
-rw-r--r--Swiften/StreamManagement/StanzaAckRequester.cpp38
-rw-r--r--Swiften/StreamManagement/StanzaAckRequester.h39
-rw-r--r--Swiften/StreamManagement/StanzaAckResponder.cpp4
-rw-r--r--Swiften/StreamManagement/StanzaAckResponder.h29
-rw-r--r--Swiften/StreamManagement/UnitTest/StanzaAckRequesterTest.cpp289
-rw-r--r--Swiften/StreamManagement/UnitTest/StanzaAckResponderTest.cpp157
-rw-r--r--Swiften/StreamStack/CompressionLayer.h72
-rw-r--r--Swiften/StreamStack/ConnectionLayer.cpp12
-rw-r--r--Swiften/StreamStack/ConnectionLayer.h28
-rw-r--r--Swiften/StreamStack/DummyStreamLayer.h28
-rw-r--r--Swiften/StreamStack/HighLayer.cpp12
-rw-r--r--Swiften/StreamStack/HighLayer.h38
-rw-r--r--Swiften/StreamStack/LowLayer.cpp8
-rw-r--r--Swiften/StreamStack/LowLayer.h40
-rw-r--r--Swiften/StreamStack/SConscript16
-rw-r--r--Swiften/StreamStack/StreamLayer.h12
-rw-r--r--Swiften/StreamStack/StreamStack.cpp23
-rw-r--r--Swiften/StreamStack/StreamStack.h67
-rw-r--r--Swiften/StreamStack/TLSLayer.cpp32
-rw-r--r--Swiften/StreamStack/TLSLayer.h49
-rw-r--r--Swiften/StreamStack/UnitTest/StreamStackTest.cpp323
-rw-r--r--Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp244
-rw-r--r--Swiften/StreamStack/WhitespacePingLayer.cpp32
-rw-r--r--Swiften/StreamStack/WhitespacePingLayer.h51
-rw-r--r--Swiften/StreamStack/XMPPLayer.cpp102
-rw-r--r--Swiften/StreamStack/XMPPLayer.h98
-rw-r--r--Swiften/StringCodecs/Base64.cpp157
-rw-r--r--Swiften/StringCodecs/Base64.h15
-rw-r--r--Swiften/StringCodecs/Hexify.cpp78
-rw-r--r--Swiften/StringCodecs/Hexify.h12
-rw-r--r--Swiften/StringCodecs/PBKDF2.h36
-rw-r--r--Swiften/StringCodecs/SHA1_Windows.cpp128
-rw-r--r--Swiften/StringCodecs/SHA1_Windows.h38
-rw-r--r--Swiften/StringCodecs/UnitTest/Base64Test.cpp98
-rw-r--r--Swiften/StringCodecs/UnitTest/HexifyTest.cpp45
-rw-r--r--Swiften/StringCodecs/UnitTest/PBKDF2Test.cpp53
-rw-r--r--Swiften/TLS/BlindCertificateTrustChecker.h28
-rw-r--r--Swiften/TLS/CAPICertificate.cpp581
-rw-r--r--Swiften/TLS/CAPICertificate.h68
-rw-r--r--Swiften/TLS/Certificate.cpp18
-rw-r--r--Swiften/TLS/Certificate.h45
-rw-r--r--Swiften/TLS/CertificateFactory.h10
-rw-r--r--Swiften/TLS/CertificateTrustChecker.h36
-rw-r--r--Swiften/TLS/CertificateVerificationError.h63
-rw-r--r--Swiften/TLS/CertificateWithKey.h16
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp144
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLCertificate.h115
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h12
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContext.cpp502
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContext.h54
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp23
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContextFactory.h22
-rw-r--r--Swiften/TLS/PKCS12Certificate.h87
-rw-r--r--Swiften/TLS/PlatformTLSFactories.cpp39
-rw-r--r--Swiften/TLS/PlatformTLSFactories.h24
-rw-r--r--Swiften/TLS/SConscript62
-rw-r--r--Swiften/TLS/Schannel/SchannelCertificate.cpp290
-rw-r--r--Swiften/TLS/Schannel/SchannelCertificate.h154
-rw-r--r--Swiften/TLS/Schannel/SchannelCertificateFactory.h12
-rw-r--r--Swiften/TLS/Schannel/SchannelContext.cpp1082
-rw-r--r--Swiften/TLS/Schannel/SchannelContext.h126
-rw-r--r--Swiften/TLS/Schannel/SchannelContextFactory.cpp21
-rw-r--r--Swiften/TLS/Schannel/SchannelContextFactory.h22
-rw-r--r--Swiften/TLS/Schannel/SchannelUtil.h820
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportCertificate.h39
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportCertificate.mm170
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportCertificateFactory.h12
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportContext.h62
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportContext.mm796
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp14
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportContextFactory.h20
-rw-r--r--Swiften/TLS/ServerIdentityVerifier.cpp127
-rw-r--r--Swiften/TLS/ServerIdentityVerifier.h32
-rw-r--r--Swiften/TLS/SimpleCertificate.h129
-rw-r--r--Swiften/TLS/TLSContext.cpp4
-rw-r--r--Swiften/TLS/TLSContext.h43
-rw-r--r--Swiften/TLS/TLSContextFactory.h18
-rw-r--r--Swiften/TLS/TLSError.h33
-rw-r--r--Swiften/TLS/TLSOptions.h22
-rw-r--r--Swiften/TLS/UnitTest/CertificateTest.cpp28
-rw-r--r--Swiften/TLS/UnitTest/ServerIdentityVerifierTest.cpp300
-rw-r--r--Swiften/VCards/GetVCardRequest.h24
-rw-r--r--Swiften/VCards/SConscript6
-rw-r--r--Swiften/VCards/SetVCardRequest.h24
-rw-r--r--Swiften/VCards/UnitTest/VCardManagerTest.cpp370
-rw-r--r--Swiften/VCards/VCardManager.cpp79
-rw-r--r--Swiften/VCards/VCardManager.h81
-rw-r--r--Swiften/VCards/VCardMemoryStorage.h73
-rw-r--r--Swiften/VCards/VCardStorage.cpp18
-rw-r--r--Swiften/VCards/VCardStorage.h30
-rw-r--r--Swiften/Whiteboard/IncomingWhiteboardSession.cpp97
-rw-r--r--Swiften/Whiteboard/IncomingWhiteboardSession.h35
-rw-r--r--Swiften/Whiteboard/OutgoingWhiteboardSession.cpp95
-rw-r--r--Swiften/Whiteboard/OutgoingWhiteboardSession.h47
-rw-r--r--Swiften/Whiteboard/UnitTest/WhiteboardClientTest.cpp1317
-rw-r--r--Swiften/Whiteboard/UnitTest/WhiteboardServerTest.cpp215
-rw-r--r--Swiften/Whiteboard/WhiteboardClient.cpp228
-rw-r--r--Swiften/Whiteboard/WhiteboardClient.h53
-rw-r--r--Swiften/Whiteboard/WhiteboardResponder.cpp53
-rw-r--r--Swiften/Whiteboard/WhiteboardResponder.h24
-rw-r--r--Swiften/Whiteboard/WhiteboardServer.cpp82
-rw-r--r--Swiften/Whiteboard/WhiteboardServer.h26
-rw-r--r--Swiften/Whiteboard/WhiteboardSession.cpp99
-rw-r--r--Swiften/Whiteboard/WhiteboardSession.h85
-rw-r--r--Swiften/Whiteboard/WhiteboardSessionManager.cpp199
-rw-r--r--Swiften/Whiteboard/WhiteboardSessionManager.h81
-rw-r--r--Swiften/Whiteboard/WhiteboardTransformer.cpp413
-rw-r--r--Swiften/Whiteboard/WhiteboardTransformer.h37
2985 files changed, 146374 insertions, 126425 deletions
diff --git a/.clang-format b/.clang-format
new file mode 100644
index 0000000..8c8601e
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,39 @@
+---
+Language: Cpp
+UseTab: Never
+TabWidth: 2
+Standard: Cpp11
+ConstructorInitializerIndentWidth: 2
+ContinuationIndentWidth: 2
+IndentWidth: 2
+PointerAlignment: Left
+ReflowComments: false
+# clang-format does not correctly detect corresponding header files at the moment.
+# Use BuildTools/FixIncludes.py for now. Enable this when it does.
+SortIncludes: false
+AccessModifierOffset: -2
+NamespaceIndentation: All
+# A ultra high column limit is required as a column limit of 0 does not work as documented.
+ColumnLimit: 900
+AllowShortBlocksOnASingleLine: false
+AllowShortFunctionsOnASingleLine: Empty
+AllowShortLoopsOnASingleLine: false
+IndentCaseLabels: true
+BreakBeforeBraces: Custom
+BraceWrapping:
+ AfterClass: false
+ AfterControlStatement: false
+ AfterEnum: false
+ AfterFunction: false
+ AfterNamespace: false
+ AfterObjCDeclaration: false
+ AfterStruct: false
+ AfterUnion: false
+ BeforeCatch: true
+ BeforeElse: true
+ IndentBraces: false
+ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
+BreakConstructorInitializersBeforeComma: false
+AlignAfterOpenBracket: Align
+ConstructorInitializerAllOnOneLineOrOnePerLine: true
+AlwaysBreakTemplateDeclarations: true \ No newline at end of file
diff --git a/.scons2ninja.conf b/.scons2ninja.conf
index 0ad2ef4..3893874 100644
--- a/.scons2ninja.conf
+++ b/.scons2ninja.conf
@@ -1,6 +1,6 @@
import glob, re, os.path
-scons_cmd = "python 3rdParty/SCons/scons.py"
+scons_cmd = "python 3rdParty/SCons/scons-2.4.0/script/scons"
scons_dependencies += glob.glob("BuildTools/SCons/**/*.py") + glob.glob("BuildTools/SCons/SCons*") + ["config.py"]
def ninja_post(ninja) :
diff --git a/3rdParty/Boost/SConscript b/3rdParty/Boost/SConscript
index d56f5e3..8708eb9 100644
--- a/3rdParty/Boost/SConscript
+++ b/3rdParty/Boost/SConscript
@@ -1,17 +1,19 @@
+import os
+
Import("env")
# FIXME: Remove this when Boost UUID is present on most distros
if env.get("BOOST_BUNDLED_UUID_ONLY", False) :
- # Cherry pick UUID out of the 3rdParty dir, install it in a separate
- # dir, and use this as an include path.
- if env["SCONS_STAGE"] == "flags" :
- if env["PLATFORM"] == "win32" :
- uuid_cppflags = ["/I" + Dir("uuid").abspath]
- else :
- uuid_cppflags = [("-isystem", Dir("uuid").abspath)]
- env["BOOST_FLAGS"]["CPPFLAGS"] = env["BOOST_FLAGS"].get("CPPFLAGS", []) + uuid_cppflags
- elif env["SCONS_STAGE"] == "build" :
- env.Install("uuid/boost", "src/boost/uuid")
+ # Cherry pick UUID out of the 3rdParty dir, install it in a separate
+ # dir, and use this as an include path.
+ if env["SCONS_STAGE"] == "flags" :
+ if env["PLATFORM"] == "win32" :
+ uuid_cppflags = ["/I" + Dir("uuid").abspath]
+ else :
+ uuid_cppflags = [("-isystem", Dir("uuid").abspath)]
+ env["BOOST_FLAGS"]["CPPFLAGS"] = env["BOOST_FLAGS"].get("CPPFLAGS", []) + uuid_cppflags
+ elif env["SCONS_STAGE"] == "build" :
+ env.Install("uuid/boost", "src/boost/uuid")
elif env.get("BOOST_BUNDLED", False) :
@@ -19,167 +21,153 @@ elif env.get("BOOST_BUNDLED", False) :
# Common
################################################################################
- cppdefines = ["BOOST_ALL_NO_LIB", "BOOST_SYSTEM_NO_DEPRECATED"]
- #if env["PLATFORM"] == "darwin" :
- # cppdefines += ["BOOST_ASIO_DISABLE_KQUEUE"]
- if env["PLATFORM"] == "win32" :
- cppflags = ["/I" + Dir("#/3rdParty/Boost/src").abspath]
- else :
- cppflags = [("-isystem", Dir("#/3rdParty/Boost/src").abspath)]
+ cppdefines = ["BOOST_ALL_NO_LIB", "BOOST_SYSTEM_NO_DEPRECATED"]
+ #if env["PLATFORM"] == "darwin" :
+ # cppdefines += ["BOOST_ASIO_DISABLE_KQUEUE"]
+ if env["PLATFORM"] == "win32" :
+ cppflags = ["/I" + Dir("#/3rdParty/Boost/src").abspath]
+ else :
+ cppflags = [("-isystem", Dir("#/3rdParty/Boost/src").abspath)]
################################################################################
# Flags
################################################################################
- if env["SCONS_STAGE"] == "flags" :
- env["BOOST_FLAGS"] = {
- "CPPFLAGS": cppflags,
- "CPPDEFINES": cppdefines + ['BOOST_SIGNALS_NO_DEPRECATION_WARNING'],
- "LIBPATH": [Dir(".")],
- "LIBS": ["Swiften_Boost"]
- }
- if env["PLATFORM"] == "win32" :
- # 0x0600 = _WIN32_WINNT_VISTA
- env["BOOST_FLAGS"]["CPPDEFINES"] += [("_WIN32_WINNT", "0x0600")]
- if env["PLATFORM"] == "cygwin" :
- env["BOOST_FLAGS"]["CPPDEFINES"] += ["__USE_W32_SOCKETS"]
- elif env["PLATFORM"] == "posix" :
- env["BOOST_FLAGS"]["LIBS"] += ["rt"]
+ if env["SCONS_STAGE"] == "flags" :
+ env["BOOST_FLAGS"] = {
+ "CPPFLAGS": cppflags,
+ "CPPDEFINES": cppdefines,
+ "LIBPATH": [Dir(".")],
+ "LIBS": ["Swiften_Boost"]
+ }
+ if env["PLATFORM"] == "win32" :
+ # 0x0600 = _WIN32_WINNT_VISTA
+ env["BOOST_FLAGS"]["CPPDEFINES"] += [("_WIN32_WINNT", "0x0600")]
+ if env["PLATFORM"] == "cygwin" :
+ env["BOOST_FLAGS"]["CPPDEFINES"] += ["__USE_W32_SOCKETS"]
+ elif env["PLATFORM"] == "posix" :
+ env["BOOST_FLAGS"]["LIBS"] += ["rt"]
################################################################################
# Build
################################################################################
- if env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
- myenv.Replace(CXXFLAGS = [flag for flag in env["CXXFLAGS"] if not flag.startswith("-W")])
-
- sources = [
- "src/libs/atomic/src/lockpool.cpp",
- "src/libs/date_time/src/gregorian/date_generators.cpp",
- "src/libs/date_time/src/gregorian/greg_month.cpp",
- "src/libs/date_time/src/gregorian/greg_weekday.cpp",
- "src/libs/date_time/src/gregorian/gregorian_types.cpp",
- "src/libs/date_time/src/posix_time/posix_time_types.cpp",
- "src/libs/system/src/error_code.cpp",
- "src/libs/thread/src/tss_null.cpp",
- "src/libs/signals/src/connection.cpp",
- "src/libs/signals/src/named_slot_map.cpp",
- "src/libs/signals/src/signal_base.cpp",
- "src/libs/signals/src/slot.cpp",
- "src/libs/signals/src/trackable.cpp",
- "src/libs/filesystem/src/codecvt_error_category.cpp",
- "src/libs/filesystem/src/operations.cpp",
- "src/libs/filesystem/src/path.cpp",
- "src/libs/filesystem/src/path_traits.cpp",
- "src/libs/filesystem/src/portability.cpp",
- "src/libs/filesystem/src/unique_path.cpp",
- "src/libs/filesystem/src/windows_file_codecvt.cpp",
- "src/libs/filesystem/src/filesystem_utf8_codecvt_facet.cpp",
- "src/libs/regex/src/c_regex_traits.cpp",
- "src/libs/regex/src/cpp_regex_traits.cpp",
- "src/libs/regex/src/cregex.cpp",
- "src/libs/regex/src/fileiter.cpp",
- "src/libs/regex/src/icu.cpp",
- "src/libs/regex/src/instances.cpp",
- "src/libs/regex/src/posix_api.cpp",
- "src/libs/regex/src/regex.cpp",
- "src/libs/regex/src/regex_debug.cpp",
- "src/libs/regex/src/regex_raw_buffer.cpp",
- "src/libs/regex/src/regex_traits_defaults.cpp",
- "src/libs/regex/src/static_mutex.cpp",
- "src/libs/regex/src/w32_regex_traits.cpp",
- "src/libs/regex/src/wc_regex_traits.cpp",
- "src/libs/regex/src/wide_posix_api.cpp",
- "src/libs/regex/src/winstances.cpp",
- "src/libs/regex/src/usinstances.cpp",
- "src/libs/program_options/src/cmdline.cpp",
- "src/libs/program_options/src/config_file.cpp",
- "src/libs/program_options/src/convert.cpp",
- "src/libs/program_options/src/options_description.cpp",
- "src/libs/program_options/src/positional_options.cpp",
- "src/libs/program_options/src/split.cpp",
- "src/libs/program_options/src/program_options_utf8_codecvt_facet.cpp",
- "src/libs/program_options/src/value_semantic.cpp",
- "src/libs/program_options/src/variables_map.cpp",
- "src/libs/program_options/src/winmain.cpp",
- "src/libs/serialization/src/archive_exception.cpp",
- "src/libs/serialization/src/basic_archive.cpp",
- "src/libs/serialization/src/basic_iarchive.cpp",
- "src/libs/serialization/src/basic_iserializer.cpp",
- "src/libs/serialization/src/basic_oarchive.cpp",
- "src/libs/serialization/src/basic_oserializer.cpp",
- "src/libs/serialization/src/basic_pointer_iserializer.cpp",
- "src/libs/serialization/src/basic_pointer_oserializer.cpp",
- "src/libs/serialization/src/basic_serializer_map.cpp",
- "src/libs/serialization/src/basic_text_iprimitive.cpp",
- "src/libs/serialization/src/basic_text_oprimitive.cpp",
- "src/libs/serialization/src/basic_text_wiprimitive.cpp",
- "src/libs/serialization/src/basic_text_woprimitive.cpp",
- "src/libs/serialization/src/basic_xml_archive.cpp",
- "src/libs/serialization/src/binary_iarchive.cpp",
- "src/libs/serialization/src/binary_oarchive.cpp",
- "src/libs/serialization/src/binary_wiarchive.cpp",
- "src/libs/serialization/src/binary_woarchive.cpp",
- "src/libs/serialization/src/codecvt_null.cpp",
- "src/libs/serialization/src/extended_type_info.cpp",
- "src/libs/serialization/src/extended_type_info_no_rtti.cpp",
- "src/libs/serialization/src/extended_type_info_typeid.cpp",
- "src/libs/serialization/src/polymorphic_iarchive.cpp",
- "src/libs/serialization/src/polymorphic_oarchive.cpp",
- "src/libs/serialization/src/stl_port.cpp",
- "src/libs/serialization/src/text_iarchive.cpp",
- "src/libs/serialization/src/text_oarchive.cpp",
- "src/libs/serialization/src/text_wiarchive.cpp",
- "src/libs/serialization/src/text_woarchive.cpp",
- "src/libs/serialization/src/utf8_codecvt_facet.cpp",
- "src/libs/serialization/src/void_cast.cpp",
- "src/libs/serialization/src/xml_archive_exception.cpp",
- "src/libs/serialization/src/xml_grammar.cpp",
- "src/libs/serialization/src/xml_iarchive.cpp",
- "src/libs/serialization/src/xml_oarchive.cpp",
- "src/libs/serialization/src/xml_wgrammar.cpp",
- "src/libs/serialization/src/xml_wiarchive.cpp",
- "src/libs/serialization/src/xml_woarchive.cpp"]
+ if env["SCONS_STAGE"] == "build" :
+ myenv = env.Clone()
+ myenv.Replace(CXXFLAGS = [flag for flag in env["CXXFLAGS"] if not flag.startswith("-W")])
+ if os.path.basename(env["CXX"]) in ["clang", "clang++"] :
+ myenv.Append(CXXFLAGS = [
+ "-Wno-deprecated-register", # The register keyword will be reserved in C++17, we only use C++11 though.
+ ])
- if env["PLATFORM"] != "darwin" or env["target"] == "native" :
- sources += [
- "src/libs/program_options/src/parsers.cpp",
- ]
+ sources = [
+ "src/libs/atomic/src/lockpool.cpp",
+ "src/libs/date_time/src/gregorian/date_generators.cpp",
+ "src/libs/date_time/src/gregorian/greg_month.cpp",
+ "src/libs/date_time/src/gregorian/greg_weekday.cpp",
+ "src/libs/date_time/src/gregorian/gregorian_types.cpp",
+ "src/libs/date_time/src/posix_time/posix_time_types.cpp",
+ "src/libs/system/src/error_code.cpp",
+ "src/libs/filesystem/src/codecvt_error_category.cpp",
+ "src/libs/filesystem/src/operations.cpp",
+ "src/libs/filesystem/src/path.cpp",
+ "src/libs/filesystem/src/path_traits.cpp",
+ "src/libs/filesystem/src/portability.cpp",
+ "src/libs/filesystem/src/unique_path.cpp",
+ "src/libs/filesystem/src/windows_file_codecvt.cpp",
+ "src/libs/filesystem/src/filesystem_utf8_codecvt_facet.cpp",
+ "src/libs/regex/src/c_regex_traits.cpp",
+ "src/libs/regex/src/cpp_regex_traits.cpp",
+ "src/libs/regex/src/cregex.cpp",
+ "src/libs/regex/src/fileiter.cpp",
+ "src/libs/regex/src/icu.cpp",
+ "src/libs/regex/src/instances.cpp",
+ "src/libs/regex/src/posix_api.cpp",
+ "src/libs/regex/src/regex.cpp",
+ "src/libs/regex/src/regex_debug.cpp",
+ "src/libs/regex/src/regex_raw_buffer.cpp",
+ "src/libs/regex/src/regex_traits_defaults.cpp",
+ "src/libs/regex/src/static_mutex.cpp",
+ "src/libs/regex/src/w32_regex_traits.cpp",
+ "src/libs/regex/src/wc_regex_traits.cpp",
+ "src/libs/regex/src/wide_posix_api.cpp",
+ "src/libs/regex/src/winstances.cpp",
+ "src/libs/regex/src/usinstances.cpp",
+ "src/libs/program_options/src/cmdline.cpp",
+ "src/libs/program_options/src/config_file.cpp",
+ "src/libs/program_options/src/convert.cpp",
+ "src/libs/program_options/src/options_description.cpp",
+ "src/libs/program_options/src/positional_options.cpp",
+ "src/libs/program_options/src/split.cpp",
+ "src/libs/program_options/src/program_options_utf8_codecvt_facet.cpp",
+ "src/libs/program_options/src/value_semantic.cpp",
+ "src/libs/program_options/src/variables_map.cpp",
+ "src/libs/program_options/src/winmain.cpp",
+ "src/libs/serialization/src/archive_exception.cpp",
+ "src/libs/serialization/src/basic_archive.cpp",
+ "src/libs/serialization/src/basic_iarchive.cpp",
+ "src/libs/serialization/src/basic_iserializer.cpp",
+ "src/libs/serialization/src/basic_oarchive.cpp",
+ "src/libs/serialization/src/basic_oserializer.cpp",
+ "src/libs/serialization/src/basic_pointer_iserializer.cpp",
+ "src/libs/serialization/src/basic_pointer_oserializer.cpp",
+ "src/libs/serialization/src/basic_serializer_map.cpp",
+ "src/libs/serialization/src/basic_text_iprimitive.cpp",
+ "src/libs/serialization/src/basic_text_oprimitive.cpp",
+ "src/libs/serialization/src/basic_text_wiprimitive.cpp",
+ "src/libs/serialization/src/basic_text_woprimitive.cpp",
+ "src/libs/serialization/src/basic_xml_archive.cpp",
+ "src/libs/serialization/src/binary_iarchive.cpp",
+ "src/libs/serialization/src/binary_oarchive.cpp",
+ "src/libs/serialization/src/binary_wiarchive.cpp",
+ "src/libs/serialization/src/binary_woarchive.cpp",
+ "src/libs/serialization/src/codecvt_null.cpp",
+ "src/libs/serialization/src/extended_type_info.cpp",
+ "src/libs/serialization/src/extended_type_info_no_rtti.cpp",
+ "src/libs/serialization/src/extended_type_info_typeid.cpp",
+ "src/libs/serialization/src/polymorphic_iarchive.cpp",
+ "src/libs/serialization/src/polymorphic_oarchive.cpp",
+ "src/libs/serialization/src/stl_port.cpp",
+ "src/libs/serialization/src/text_iarchive.cpp",
+ "src/libs/serialization/src/text_oarchive.cpp",
+ "src/libs/serialization/src/text_wiarchive.cpp",
+ "src/libs/serialization/src/text_woarchive.cpp",
+ "src/libs/serialization/src/utf8_codecvt_facet.cpp",
+ "src/libs/serialization/src/void_cast.cpp",
+ "src/libs/serialization/src/xml_archive_exception.cpp",
+ "src/libs/serialization/src/xml_grammar.cpp",
+ "src/libs/serialization/src/xml_iarchive.cpp",
+ "src/libs/serialization/src/xml_oarchive.cpp",
+ "src/libs/serialization/src/xml_wgrammar.cpp",
+ "src/libs/serialization/src/xml_wiarchive.cpp",
+ "src/libs/serialization/src/xml_woarchive.cpp"]
- if env["PLATFORM"] != "win32" :
- sources += [
- "src/libs/thread/src/pthread/once.cpp",
- "src/libs/thread/src/pthread/once_atomic.cpp",
- "src/libs/thread/src/pthread/thread.cpp"]
- else :
- sources += [
- "win32_stubs.cpp",
- "src/libs/thread/src/win32/thread.cpp",
- "src/libs/thread/src/win32/tss_dll.cpp",
- "src/libs/thread/src/win32/tss_pe.cpp"]
+ if env["PLATFORM"] != "darwin" or env["target"] == "native" :
+ sources += [
+ "src/libs/program_options/src/parsers.cpp",
+ ]
- myenv.MergeFlags(myenv["BOOST_FLAGS"])
- myenv.StaticLibrary("Swiften_Boost", sources)
+ myenv.MergeFlags(myenv["BOOST_FLAGS"])
+ myenv.StaticLibrary("Swiften_Boost", sources)
- if ARGUMENTS.get("BOOST_BUILD_BCP") or env.get("BOOST_BUILD_BCP", False) or env.GetOption("clean") :
- bcp_env = myenv.Clone()
- bcp_env.MergeFlags(bcp_env["BOOST_FLAGS"])
- bcp_env.Append(CPPPATH = ["src/tools/bcp"])
- bcp_env.Replace(CPPDEFINES = [flag for flag in bcp_env["CPPDEFINES"] if flag[0] != "BOOST_FILESYSTEM_VERSION"])
- bcp_env.UseFlags(bcp_env["PLATFORM_FLAGS"])
- bcp_env.Program("bcp", [
- "src/tools/bcp/add_path.cpp",
- "src/tools/bcp/add_dependent_lib.cpp",
- "src/tools/bcp/bcp_imp.cpp",
- "src/tools/bcp/copy_path.cpp",
- "src/tools/bcp/file_types.cpp",
- "src/tools/bcp/fileview.cpp",
- "src/tools/bcp/licence_info.cpp",
- "src/tools/bcp/output_licence_info.cpp",
- "src/tools/bcp/path_operations.cpp",
- "src/tools/bcp/scan_cvs_path.cpp",
- "src/tools/bcp/scan_licence.cpp",
- "bcp.cpp",
- ])
+ if ARGUMENTS.get("BOOST_BUILD_BCP") or env.get("BOOST_BUILD_BCP", False) or env.GetOption("clean") :
+ bcp_env = myenv.Clone()
+ bcp_env.MergeFlags(bcp_env["BOOST_FLAGS"])
+ bcp_env.Append(CPPPATH = ["src/tools/bcp"])
+ bcp_env.Replace(CPPDEFINES = [flag for flag in bcp_env["CPPDEFINES"] if flag[0] != "BOOST_FILESYSTEM_VERSION"])
+ bcp_env.UseFlags(bcp_env["PLATFORM_FLAGS"])
+ bcp_env.Program("bcp", [
+ "src/tools/bcp/add_path.cpp",
+ "src/tools/bcp/add_dependent_lib.cpp",
+ "src/tools/bcp/bcp_imp.cpp",
+ "src/tools/bcp/copy_path.cpp",
+ "src/tools/bcp/file_types.cpp",
+ "src/tools/bcp/fileview.cpp",
+ "src/tools/bcp/licence_info.cpp",
+ "src/tools/bcp/output_licence_info.cpp",
+ "src/tools/bcp/path_operations.cpp",
+ "src/tools/bcp/scan_cvs_path.cpp",
+ "src/tools/bcp/scan_licence.cpp",
+ "bcp.cpp",
+ ])
diff --git a/3rdParty/Boost/src/boost/cstdlib.hpp b/3rdParty/Boost/src/boost/cstdlib.hpp
new file mode 100644
index 0000000..6322146
--- /dev/null
+++ b/3rdParty/Boost/src/boost/cstdlib.hpp
@@ -0,0 +1,41 @@
+// boost/cstdlib.hpp header ------------------------------------------------//
+
+// Copyright Beman Dawes 2001. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying file
+// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org/libs/utility/cstdlib.html for documentation.
+
+// Revision History
+// 26 Feb 01 Initial version (Beman Dawes)
+
+#ifndef BOOST_CSTDLIB_HPP
+#define BOOST_CSTDLIB_HPP
+
+#include <cstdlib>
+
+namespace boost
+{
+ // The intent is to propose the following for addition to namespace std
+ // in the C++ Standard Library, and to then deprecate EXIT_SUCCESS and
+ // EXIT_FAILURE. As an implementation detail, this header defines the
+ // new constants in terms of EXIT_SUCCESS and EXIT_FAILURE. In a new
+ // standard, the constants would be implementation-defined, although it
+ // might be worthwhile to "suggest" (which a standard is allowed to do)
+ // values of 0 and 1 respectively.
+
+ // Rationale for having multiple failure values: some environments may
+ // wish to distinguish between different classes of errors.
+ // Rationale for choice of values: programs often use values < 100 for
+ // their own error reporting. Values > 255 are sometimes reserved for
+ // system detected errors. 200/201 were suggested to minimize conflict.
+
+ const int exit_success = EXIT_SUCCESS; // implementation-defined value
+ const int exit_failure = EXIT_FAILURE; // implementation-defined value
+ const int exit_exception_failure = 200; // otherwise uncaught exception
+ const int exit_test_failure = 201; // report_error or
+ // report_critical_error called.
+}
+
+#endif
+
diff --git a/3rdParty/Boost/src/boost/detail/binary_search.hpp b/3rdParty/Boost/src/boost/detail/binary_search.hpp
new file mode 100644
index 0000000..3dca9b6
--- /dev/null
+++ b/3rdParty/Boost/src/boost/detail/binary_search.hpp
@@ -0,0 +1,216 @@
+// Copyright (c) 2000 David Abrahams.
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// Copyright (c) 1994
+// Hewlett-Packard Company
+//
+// Permission to use, copy, modify, distribute and sell this software
+// and its documentation for any purpose is hereby granted without fee,
+// provided that the above copyright notice appear in all copies and
+// that both that copyright notice and this permission notice appear
+// in supporting documentation. Hewlett-Packard Company makes no
+// representations about the suitability of this software for any
+// purpose. It is provided "as is" without express or implied warranty.
+//
+// Copyright (c) 1996
+// Silicon Graphics Computer Systems, Inc.
+//
+// Permission to use, copy, modify, distribute and sell this software
+// and its documentation for any purpose is hereby granted without fee,
+// provided that the above copyright notice appear in all copies and
+// that both that copyright notice and this permission notice appear
+// in supporting documentation. Silicon Graphics makes no
+// representations about the suitability of this software for any
+// purpose. It is provided "as is" without express or implied warranty.
+//
+#ifndef BINARY_SEARCH_DWA_122600_H_
+# define BINARY_SEARCH_DWA_122600_H_
+
+# include <boost/detail/iterator.hpp>
+# include <utility>
+
+namespace boost { namespace detail {
+
+template <class ForwardIter, class Tp>
+ForwardIter lower_bound(ForwardIter first, ForwardIter last,
+ const Tp& val)
+{
+ typedef detail::iterator_traits<ForwardIter> traits;
+
+ typename traits::difference_type len = boost::detail::distance(first, last);
+ typename traits::difference_type half;
+ ForwardIter middle;
+
+ while (len > 0) {
+ half = len >> 1;
+ middle = first;
+ std::advance(middle, half);
+ if (*middle < val) {
+ first = middle;
+ ++first;
+ len = len - half - 1;
+ }
+ else
+ len = half;
+ }
+ return first;
+}
+
+template <class ForwardIter, class Tp, class Compare>
+ForwardIter lower_bound(ForwardIter first, ForwardIter last,
+ const Tp& val, Compare comp)
+{
+ typedef detail::iterator_traits<ForwardIter> traits;
+
+ typename traits::difference_type len = boost::detail::distance(first, last);
+ typename traits::difference_type half;
+ ForwardIter middle;
+
+ while (len > 0) {
+ half = len >> 1;
+ middle = first;
+ std::advance(middle, half);
+ if (comp(*middle, val)) {
+ first = middle;
+ ++first;
+ len = len - half - 1;
+ }
+ else
+ len = half;
+ }
+ return first;
+}
+
+template <class ForwardIter, class Tp>
+ForwardIter upper_bound(ForwardIter first, ForwardIter last,
+ const Tp& val)
+{
+ typedef detail::iterator_traits<ForwardIter> traits;
+
+ typename traits::difference_type len = boost::detail::distance(first, last);
+ typename traits::difference_type half;
+ ForwardIter middle;
+
+ while (len > 0) {
+ half = len >> 1;
+ middle = first;
+ std::advance(middle, half);
+ if (val < *middle)
+ len = half;
+ else {
+ first = middle;
+ ++first;
+ len = len - half - 1;
+ }
+ }
+ return first;
+}
+
+template <class ForwardIter, class Tp, class Compare>
+ForwardIter upper_bound(ForwardIter first, ForwardIter last,
+ const Tp& val, Compare comp)
+{
+ typedef detail::iterator_traits<ForwardIter> traits;
+
+ typename traits::difference_type len = boost::detail::distance(first, last);
+ typename traits::difference_type half;
+ ForwardIter middle;
+
+ while (len > 0) {
+ half = len >> 1;
+ middle = first;
+ std::advance(middle, half);
+ if (comp(val, *middle))
+ len = half;
+ else {
+ first = middle;
+ ++first;
+ len = len - half - 1;
+ }
+ }
+ return first;
+}
+
+template <class ForwardIter, class Tp>
+std::pair<ForwardIter, ForwardIter>
+equal_range(ForwardIter first, ForwardIter last, const Tp& val)
+{
+ typedef detail::iterator_traits<ForwardIter> traits;
+
+ typename traits::difference_type len = boost::detail::distance(first, last);
+ typename traits::difference_type half;
+ ForwardIter middle, left, right;
+
+ while (len > 0) {
+ half = len >> 1;
+ middle = first;
+ std::advance(middle, half);
+ if (*middle < val) {
+ first = middle;
+ ++first;
+ len = len - half - 1;
+ }
+ else if (val < *middle)
+ len = half;
+ else {
+ left = boost::detail::lower_bound(first, middle, val);
+ std::advance(first, len);
+ right = boost::detail::upper_bound(++middle, first, val);
+ return std::pair<ForwardIter, ForwardIter>(left, right);
+ }
+ }
+ return std::pair<ForwardIter, ForwardIter>(first, first);
+}
+
+template <class ForwardIter, class Tp, class Compare>
+std::pair<ForwardIter, ForwardIter>
+equal_range(ForwardIter first, ForwardIter last, const Tp& val,
+ Compare comp)
+{
+ typedef detail::iterator_traits<ForwardIter> traits;
+
+ typename traits::difference_type len = boost::detail::distance(first, last);
+ typename traits::difference_type half;
+ ForwardIter middle, left, right;
+
+ while (len > 0) {
+ half = len >> 1;
+ middle = first;
+ std::advance(middle, half);
+ if (comp(*middle, val)) {
+ first = middle;
+ ++first;
+ len = len - half - 1;
+ }
+ else if (comp(val, *middle))
+ len = half;
+ else {
+ left = boost::detail::lower_bound(first, middle, val, comp);
+ std::advance(first, len);
+ right = boost::detail::upper_bound(++middle, first, val, comp);
+ return std::pair<ForwardIter, ForwardIter>(left, right);
+ }
+ }
+ return std::pair<ForwardIter, ForwardIter>(first, first);
+}
+
+template <class ForwardIter, class Tp>
+bool binary_search(ForwardIter first, ForwardIter last,
+ const Tp& val) {
+ ForwardIter i = boost::detail::lower_bound(first, last, val);
+ return i != last && !(val < *i);
+}
+
+template <class ForwardIter, class Tp, class Compare>
+bool binary_search(ForwardIter first, ForwardIter last,
+ const Tp& val,
+ Compare comp) {
+ ForwardIter i = boost::detail::lower_bound(first, last, val, comp);
+ return i != last && !comp(val, *i);
+}
+
+}} // namespace boost::detail
+
+#endif // BINARY_SEARCH_DWA_122600_H_
diff --git a/3rdParty/Boost/src/boost/detail/is_xxx.hpp b/3rdParty/Boost/src/boost/detail/is_xxx.hpp
new file mode 100644
index 0000000..3f9a126
--- /dev/null
+++ b/3rdParty/Boost/src/boost/detail/is_xxx.hpp
@@ -0,0 +1,27 @@
+// Copyright David Abrahams 2005. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+#ifndef BOOST_DETAIL_IS_XXX_DWA20051011_HPP
+# define BOOST_DETAIL_IS_XXX_DWA20051011_HPP
+
+# include <boost/config.hpp>
+# include <boost/mpl/bool.hpp>
+# include <boost/preprocessor/enum_params.hpp>
+
+
+# define BOOST_DETAIL_IS_XXX_DEF(name, qualified_name, nargs) \
+template <class T> \
+struct is_##name : mpl::false_ \
+{ \
+}; \
+ \
+template < BOOST_PP_ENUM_PARAMS_Z(1, nargs, class T) > \
+struct is_##name< \
+ qualified_name< BOOST_PP_ENUM_PARAMS_Z(1, nargs, T) > \
+> \
+ : mpl::true_ \
+{ \
+};
+
+
+#endif // BOOST_DETAIL_IS_XXX_DWA20051011_HPP
diff --git a/3rdParty/Boost/src/boost/function/function_typeof.hpp b/3rdParty/Boost/src/boost/function/function_typeof.hpp
deleted file mode 100644
index 246dc15..0000000
--- a/3rdParty/Boost/src/boost/function/function_typeof.hpp
+++ /dev/null
@@ -1,45 +0,0 @@
-// Boost.Function library - Typeof support
-// Copyright (C) Douglas Gregor 2008
-//
-// Use, modification and distribution is subject to the Boost
-// Software License, Version 1.0. (See accompanying file
-// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
-//
-// For more information, see http://www.boost.org
-#ifndef BOOST_FUNCTION_TYPEOF_HPP
-#define BOOST_FUNCTION_TYPEOF_HPP
-#include <boost/function/function_fwd.hpp>
-#include <boost/typeof/typeof.hpp>
-
-#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()
-
-BOOST_TYPEOF_REGISTER_TYPE(boost::bad_function_call)
-
-#if !defined(BOOST_FUNCTION_NO_FUNCTION_TYPE_SYNTAX)
-BOOST_TYPEOF_REGISTER_TEMPLATE(boost::function, (typename))
-#endif
-
-BOOST_TYPEOF_REGISTER_TEMPLATE(boost::function0, (typename))
-BOOST_TYPEOF_REGISTER_TEMPLATE(boost::function1, (typename)(typename))
-BOOST_TYPEOF_REGISTER_TEMPLATE(boost::function2, (typename)(typename)(typename))
-BOOST_TYPEOF_REGISTER_TEMPLATE(boost::function3,
- (typename)(typename)(typename)(typename))
-BOOST_TYPEOF_REGISTER_TEMPLATE(boost::function4,
- (typename)(typename)(typename)(typename)(typename))
-BOOST_TYPEOF_REGISTER_TEMPLATE(boost::function5,
- (typename)(typename)(typename)(typename)(typename)(typename))
-BOOST_TYPEOF_REGISTER_TEMPLATE(boost::function6,
- (typename)(typename)(typename)(typename)(typename)(typename)(typename))
-BOOST_TYPEOF_REGISTER_TEMPLATE(boost::function7,
- (typename)(typename)(typename)(typename)(typename)(typename)(typename)
- (typename))
-BOOST_TYPEOF_REGISTER_TEMPLATE(boost::function8,
- (typename)(typename)(typename)(typename)(typename)(typename)(typename)
- (typename)(typename))
-BOOST_TYPEOF_REGISTER_TEMPLATE(boost::function9,
- (typename)(typename)(typename)(typename)(typename)(typename)(typename)
- (typename)(typename)(typename))
-BOOST_TYPEOF_REGISTER_TEMPLATE(boost::function10,
- (typename)(typename)(typename)(typename)(typename)(typename)(typename)
- (typename)(typename)(typename)(typename))
-#endif
diff --git a/3rdParty/Boost/src/boost/function/gen_function_N.pl b/3rdParty/Boost/src/boost/function/gen_function_N.pl
deleted file mode 100644
index d8f1249..0000000
--- a/3rdParty/Boost/src/boost/function/gen_function_N.pl
+++ /dev/null
@@ -1,26 +0,0 @@
-#!/usr/bin/perl -w
-#
-# Boost.Function library
-#
-# Copyright Douglas Gregor 2001-2003. Use, modification and
-# distribution is subject to the Boost Software License, Version
-# 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-# http://www.boost.org/LICENSE_1_0.txt)
-#
-# For more information, see http://www.boost.org
-use English;
-
-if ($#ARGV < 0) {
- print "Usage: perl gen_function_N <number of arguments>\n";
- exit;
-}
-
-
-$totalNumArgs = $ARGV[0];
-for ($numArgs = 0; $numArgs <= $totalNumArgs; ++$numArgs) {
- open OUT, ">function$numArgs.hpp";
- print OUT "#define BOOST_FUNCTION_NUM_ARGS $numArgs\n";
- print OUT "#include <boost/function/detail/maybe_include.hpp>\n";
- print OUT "#undef BOOST_FUNCTION_NUM_ARGS\n";
- close OUT;
-}
diff --git a/3rdParty/Boost/src/boost/function_output_iterator.hpp b/3rdParty/Boost/src/boost/function_output_iterator.hpp
new file mode 100644
index 0000000..9720f3f
--- /dev/null
+++ b/3rdParty/Boost/src/boost/function_output_iterator.hpp
@@ -0,0 +1,56 @@
+// (C) Copyright Jeremy Siek 2001.
+// Distributed under the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// Revision History:
+
+// 27 Feb 2001 Jeremy Siek
+// Initial checkin.
+
+#ifndef BOOST_FUNCTION_OUTPUT_ITERATOR_HPP
+#define BOOST_FUNCTION_OUTPUT_ITERATOR_HPP
+
+#include <iterator>
+
+namespace boost {
+
+ template <class UnaryFunction>
+ class function_output_iterator {
+ typedef function_output_iterator self;
+ public:
+ typedef std::output_iterator_tag iterator_category;
+ typedef void value_type;
+ typedef void difference_type;
+ typedef void pointer;
+ typedef void reference;
+
+ explicit function_output_iterator() {}
+
+ explicit function_output_iterator(const UnaryFunction& f)
+ : m_f(f) {}
+
+ struct output_proxy {
+ output_proxy(UnaryFunction& f) : m_f(f) { }
+ template <class T> output_proxy& operator=(const T& value) {
+ m_f(value);
+ return *this;
+ }
+ UnaryFunction& m_f;
+ };
+ output_proxy operator*() { return output_proxy(m_f); }
+ self& operator++() { return *this; }
+ self& operator++(int) { return *this; }
+ private:
+ UnaryFunction m_f;
+ };
+
+ template <class UnaryFunction>
+ inline function_output_iterator<UnaryFunction>
+ make_function_output_iterator(const UnaryFunction& f = UnaryFunction()) {
+ return function_output_iterator<UnaryFunction>(f);
+ }
+
+} // namespace boost
+
+#endif // BOOST_FUNCTION_OUTPUT_ITERATOR_HPP
diff --git a/3rdParty/Boost/src/boost/last_value.hpp b/3rdParty/Boost/src/boost/last_value.hpp
deleted file mode 100644
index 183a739..0000000
--- a/3rdParty/Boost/src/boost/last_value.hpp
+++ /dev/null
@@ -1,54 +0,0 @@
-// last_value function object (documented as part of Boost.Signals)
-
-// Copyright Douglas Gregor 2001-2003. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org/libs/signals
-
-#ifndef BOOST_LAST_VALUE_HPP
-#define BOOST_LAST_VALUE_HPP
-
-#include <cassert>
-#include <boost/config.hpp>
-
-namespace boost {
- template<typename T>
- struct last_value {
- typedef T result_type;
-
- template<typename InputIterator>
- T operator()(InputIterator first, InputIterator last) const
- {
- assert(first != last);
- T value = *first++;
- while (first != last)
- value = *first++;
- return value;
- }
- };
-
- template<>
- struct last_value<void> {
-#ifdef BOOST_NO_VOID_RETURNS
- struct unusable {};
-
- public:
- typedef unusable result_type;
-#else
- public:
- typedef void result_type;
-#endif // BOOST_NO_VOID_RETURNS
-
- template<typename InputIterator>
- result_type
- operator()(InputIterator first, InputIterator last) const
- {
- while (first != last)
- *first++;
- return result_type();
- }
- };
-}
-#endif // BOOST_SIGNALS_LAST_VALUE_HPP
diff --git a/3rdParty/Boost/src/boost/make_shared.hpp b/3rdParty/Boost/src/boost/make_shared.hpp
deleted file mode 100644
index c04938f..0000000
--- a/3rdParty/Boost/src/boost/make_shared.hpp
+++ /dev/null
@@ -1,17 +0,0 @@
-#ifndef BOOST_MAKE_SHARED_HPP_INCLUDED
-#define BOOST_MAKE_SHARED_HPP_INCLUDED
-
-// make_shared.hpp
-//
-// Copyright (c) 2007, 2008 Peter Dimov
-//
-// Distributed under the Boost Software License, Version 1.0.
-// See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt
-//
-// See http://www.boost.org/libs/smart_ptr/make_shared.html
-// for documentation.
-
-#include <boost/smart_ptr/make_shared.hpp>
-
-#endif // #ifndef BOOST_MAKE_SHARED_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/aux_/unwrap.hpp b/3rdParty/Boost/src/boost/mpl/aux_/unwrap.hpp
new file mode 100644
index 0000000..caeb97d
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/aux_/unwrap.hpp
@@ -0,0 +1,51 @@
+
+#ifndef BOOST_MPL_AUX_UNWRAP_HPP_INCLUDED
+#define BOOST_MPL_AUX_UNWRAP_HPP_INCLUDED
+
+// Copyright Peter Dimov and Multi Media Ltd 2001, 2002
+// Copyright David Abrahams 2001
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/ref.hpp>
+#include <boost/mpl/aux_/config/gpu.hpp>
+
+namespace boost { namespace mpl { namespace aux {
+
+template< typename F >
+BOOST_MPL_CFG_GPU_ENABLED
+inline
+F& unwrap(F& f, long)
+{
+ return f;
+}
+
+template< typename F >
+BOOST_MPL_CFG_GPU_ENABLED
+inline
+F&
+unwrap(reference_wrapper<F>& f, int)
+{
+ return f;
+}
+
+template< typename F >
+BOOST_MPL_CFG_GPU_ENABLED
+inline
+F&
+unwrap(reference_wrapper<F> const& f, int)
+{
+ return f;
+}
+
+}}}
+
+#endif // BOOST_MPL_AUX_UNWRAP_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/for_each.hpp b/3rdParty/Boost/src/boost/mpl/for_each.hpp
new file mode 100644
index 0000000..6b40ce1
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/for_each.hpp
@@ -0,0 +1,123 @@
+
+#ifndef BOOST_MPL_FOR_EACH_HPP_INCLUDED
+#define BOOST_MPL_FOR_EACH_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2000-2008
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/is_sequence.hpp>
+#include <boost/mpl/begin_end.hpp>
+#include <boost/mpl/apply.hpp>
+#include <boost/mpl/bool.hpp>
+#include <boost/mpl/next_prior.hpp>
+#include <boost/mpl/deref.hpp>
+#include <boost/mpl/identity.hpp>
+#include <boost/mpl/assert.hpp>
+#include <boost/mpl/aux_/config/gpu.hpp>
+#include <boost/mpl/aux_/unwrap.hpp>
+
+#include <boost/type_traits/is_same.hpp>
+#include <boost/utility/value_init.hpp>
+
+namespace boost { namespace mpl {
+
+namespace aux {
+
+template< bool done = true >
+struct for_each_impl
+{
+ template<
+ typename Iterator
+ , typename LastIterator
+ , typename TransformFunc
+ , typename F
+ >
+ BOOST_MPL_CFG_GPU_ENABLED
+ static void execute(
+ Iterator*
+ , LastIterator*
+ , TransformFunc*
+ , F
+ )
+ {
+ }
+};
+
+template<>
+struct for_each_impl<false>
+{
+ template<
+ typename Iterator
+ , typename LastIterator
+ , typename TransformFunc
+ , typename F
+ >
+ BOOST_MPL_CFG_GPU_ENABLED
+ static void execute(
+ Iterator*
+ , LastIterator*
+ , TransformFunc*
+ , F f
+ )
+ {
+ typedef typename deref<Iterator>::type item;
+ typedef typename apply1<TransformFunc,item>::type arg;
+
+ // dwa 2002/9/10 -- make sure not to invoke undefined behavior
+ // when we pass arg.
+ value_initialized<arg> x;
+ aux::unwrap(f, 0)(boost::get(x));
+
+ typedef typename mpl::next<Iterator>::type iter;
+ for_each_impl<boost::is_same<iter,LastIterator>::value>
+ ::execute( static_cast<iter*>(0), static_cast<LastIterator*>(0), static_cast<TransformFunc*>(0), f);
+ }
+};
+
+} // namespace aux
+
+// agurt, 17/mar/02: pointer default parameters are necessary to workaround
+// MSVC 6.5 function template signature's mangling bug
+template<
+ typename Sequence
+ , typename TransformOp
+ , typename F
+ >
+BOOST_MPL_CFG_GPU_ENABLED
+inline
+void for_each(F f, Sequence* = 0, TransformOp* = 0)
+{
+ BOOST_MPL_ASSERT(( is_sequence<Sequence> ));
+
+ typedef typename begin<Sequence>::type first;
+ typedef typename end<Sequence>::type last;
+
+ aux::for_each_impl< boost::is_same<first,last>::value >
+ ::execute(static_cast<first*>(0), static_cast<last*>(0), static_cast<TransformOp*>(0), f);
+}
+
+template<
+ typename Sequence
+ , typename F
+ >
+BOOST_MPL_CFG_GPU_ENABLED
+inline
+void for_each(F f, Sequence* = 0)
+{
+ // jfalcou: fully qualifying this call so it doesnt clash with phoenix::for_each
+ // ons ome compilers -- done on 02/28/2011
+ boost::mpl::for_each<Sequence, identity<> >(f);
+}
+
+}}
+
+#endif // BOOST_MPL_FOR_EACH_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/at_impl.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/at_impl.hpp
new file mode 100644
index 0000000..89119c4
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/at_impl.hpp
@@ -0,0 +1,40 @@
+
+#ifndef BOOST_MPL_SET_AUX_AT_IMPL_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_AT_IMPL_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/at_fwd.hpp>
+#include <boost/mpl/set/aux_/has_key_impl.hpp>
+#include <boost/mpl/set/aux_/tag.hpp>
+#include <boost/mpl/if.hpp>
+#include <boost/mpl/void.hpp>
+
+namespace boost { namespace mpl {
+
+template<>
+struct at_impl< aux::set_tag >
+{
+ template< typename Set, typename T > struct apply
+ {
+ typedef typename if_<
+ has_key_impl<aux::set_tag>::apply<Set,T>
+ , T
+ , void_
+ >::type type;
+ };
+};
+
+}}
+
+#endif // BOOST_MPL_SET_AUX_AT_IMPL_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/begin_end_impl.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/begin_end_impl.hpp
new file mode 100644
index 0000000..2595280
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/begin_end_impl.hpp
@@ -0,0 +1,43 @@
+
+#ifndef BOOST_MPL_SET_AUX_BEGIN_END_IMPL_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_BEGIN_END_IMPL_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2007
+// Copyright David Abrahams 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/begin_end_fwd.hpp>
+#include <boost/mpl/set/aux_/iterator.hpp>
+
+namespace boost { namespace mpl {
+
+template<>
+struct begin_impl< aux::set_tag >
+{
+ template< typename Set > struct apply
+ : s_iter_get<Set,typename Set::item_>
+ {
+ };
+};
+
+template<>
+struct end_impl< aux::set_tag >
+{
+ template< typename Set > struct apply
+ {
+ typedef s_iter< Set,set0<> > type;
+ };
+};
+
+}}
+
+#endif // BOOST_MPL_SET_AUX_BEGIN_END_IMPL_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/clear_impl.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/clear_impl.hpp
new file mode 100644
index 0000000..9c6c760
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/clear_impl.hpp
@@ -0,0 +1,35 @@
+
+#ifndef BOOST_MPL_SET_AUX_CLEAR_IMPL_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_CLEAR_IMPL_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2004
+// Copyright David Abrahams 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/clear_fwd.hpp>
+#include <boost/mpl/set/aux_/set0.hpp>
+#include <boost/mpl/set/aux_/tag.hpp>
+
+namespace boost { namespace mpl {
+
+template<>
+struct clear_impl< aux::set_tag >
+{
+ template< typename Set > struct apply
+ {
+ typedef set0<> type;
+ };
+};
+
+}}
+
+#endif // BOOST_MPL_SET_AUX_CLEAR_IMPL_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/empty_impl.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/empty_impl.hpp
new file mode 100644
index 0000000..997ff02
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/empty_impl.hpp
@@ -0,0 +1,34 @@
+
+#ifndef BOOST_MPL_SET_AUX_EMPTY_IMPL_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_EMPTY_IMPL_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/empty_fwd.hpp>
+#include <boost/mpl/not.hpp>
+#include <boost/mpl/set/aux_/tag.hpp>
+
+namespace boost { namespace mpl {
+
+template<>
+struct empty_impl< aux::set_tag >
+{
+ template< typename Set > struct apply
+ : not_< typename Set::size >
+ {
+ };
+};
+
+}}
+
+#endif // BOOST_MPL_SET_AUX_EMPTY_IMPL_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/erase_impl.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/erase_impl.hpp
new file mode 100644
index 0000000..c4a95b4
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/erase_impl.hpp
@@ -0,0 +1,41 @@
+
+#ifndef BOOST_MPL_SET_AUX_ERASE_IMPL_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_ERASE_IMPL_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2004
+// Copyright David Abrahams 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/erase_fwd.hpp>
+#include <boost/mpl/set/aux_/erase_key_impl.hpp>
+#include <boost/mpl/set/aux_/tag.hpp>
+
+namespace boost { namespace mpl {
+
+template<>
+struct erase_impl< aux::set_tag >
+{
+ template<
+ typename Set
+ , typename Pos
+ , typename unused_
+ >
+ struct apply
+ : erase_key_impl<aux::set_tag>
+ ::apply<Set,typename Pos::type>
+ {
+ };
+};
+
+}}
+
+#endif // BOOST_MPL_SET_AUX_ERASE_IMPL_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/erase_key_impl.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/erase_key_impl.hpp
new file mode 100644
index 0000000..f945d4f
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/erase_key_impl.hpp
@@ -0,0 +1,53 @@
+
+#ifndef BOOST_MPL_SET_AUX_ERASE_KEY_IMPL_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_ERASE_KEY_IMPL_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2007
+// Copyright David Abrahams 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/erase_key_fwd.hpp>
+#include <boost/mpl/set/aux_/has_key_impl.hpp>
+#include <boost/mpl/set/aux_/item.hpp>
+#include <boost/mpl/set/aux_/tag.hpp>
+#include <boost/mpl/identity.hpp>
+#include <boost/mpl/base.hpp>
+#include <boost/mpl/eval_if.hpp>
+
+#include <boost/type_traits/is_same.hpp>
+
+namespace boost { namespace mpl {
+
+template<>
+struct erase_key_impl< aux::set_tag >
+{
+ template<
+ typename Set
+ , typename T
+ >
+ struct apply
+ : eval_if<
+ has_key_impl<aux::set_tag>::apply<Set,T>
+ , eval_if<
+ is_same< T,typename Set::item_type_ >
+ , base<Set>
+ , identity< s_mask<T,typename Set::item_> >
+ >
+ , identity<Set>
+ >
+ {
+ };
+};
+
+}}
+
+#endif // BOOST_MPL_SET_AUX_ERASE_KEY_IMPL_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/has_key_impl.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/has_key_impl.hpp
new file mode 100644
index 0000000..bdc3273
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/has_key_impl.hpp
@@ -0,0 +1,60 @@
+
+#ifndef BOOST_MPL_SET_AUX_HAS_KEY_IMPL_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_HAS_KEY_IMPL_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2004
+// Copyright David Abrahams 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/set/aux_/tag.hpp>
+#include <boost/mpl/has_key_fwd.hpp>
+#include <boost/mpl/bool.hpp>
+#include <boost/mpl/aux_/overload_names.hpp>
+#include <boost/mpl/aux_/static_cast.hpp>
+#include <boost/mpl/aux_/yes_no.hpp>
+#include <boost/mpl/aux_/type_wrapper.hpp>
+#include <boost/mpl/aux_/config/workaround.hpp>
+#include <boost/mpl/aux_/config/static_constant.hpp>
+
+namespace boost { namespace mpl {
+
+template<>
+struct has_key_impl< aux::set_tag >
+{
+ template< typename Set, typename T > struct apply
+#if BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1400)) \
+ || BOOST_WORKAROUND(__EDG_VERSION__, <= 245)
+ {
+ BOOST_STATIC_CONSTANT(bool, value =
+ ( sizeof( BOOST_MPL_AUX_OVERLOAD_CALL_IS_MASKED(
+ Set
+ , BOOST_MPL_AUX_STATIC_CAST(aux::type_wrapper<T>*, 0)
+ ) ) == sizeof(aux::no_tag) )
+ );
+
+ typedef bool_<value> type;
+
+#else // ISO98 C++
+ : bool_<
+ ( sizeof( BOOST_MPL_AUX_OVERLOAD_CALL_IS_MASKED(
+ Set
+ , BOOST_MPL_AUX_STATIC_CAST(aux::type_wrapper<T>*, 0)
+ ) ) == sizeof(aux::no_tag) )
+ >
+ {
+#endif
+ };
+};
+
+}}
+
+#endif // BOOST_MPL_SET_AUX_HAS_KEY_IMPL_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/insert_impl.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/insert_impl.hpp
new file mode 100644
index 0000000..ff180ac
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/insert_impl.hpp
@@ -0,0 +1,65 @@
+
+#ifndef BOOST_MPL_SET_AUX_INSERT_IMPL_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_INSERT_IMPL_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2007
+// Copyright David Abrahams 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/insert_fwd.hpp>
+#include <boost/mpl/set/aux_/has_key_impl.hpp>
+#include <boost/mpl/set/aux_/item.hpp>
+#include <boost/mpl/set/aux_/tag.hpp>
+#include <boost/mpl/identity.hpp>
+#include <boost/mpl/base.hpp>
+#include <boost/mpl/eval_if.hpp>
+#include <boost/mpl/aux_/na.hpp>
+
+#include <boost/type_traits/is_same.hpp>
+
+namespace boost { namespace mpl {
+
+namespace aux {
+template< typename Set, typename T > struct set_insert_impl
+ : eval_if<
+ has_key_impl<aux::set_tag>::apply<Set,T>
+ , identity<Set>
+ , eval_if<
+ is_same< T,typename Set::last_masked_ >
+ , base<Set>
+ , identity< s_item<T,typename Set::item_> >
+ >
+ >
+{
+};
+}
+
+template<>
+struct insert_impl< aux::set_tag >
+{
+ template<
+ typename Set
+ , typename PosOrKey
+ , typename KeyOrNA
+ >
+ struct apply
+ : aux::set_insert_impl<
+ Set
+ , typename if_na<KeyOrNA,PosOrKey>::type
+ >
+ {
+ };
+};
+
+}}
+
+#endif // BOOST_MPL_SET_AUX_INSERT_IMPL_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/item.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/item.hpp
new file mode 100644
index 0000000..e90e490
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/item.hpp
@@ -0,0 +1,80 @@
+
+#ifndef BOOST_MPL_SET_AUX_ITEM_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_ITEM_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2007
+// Copyright David Abrahams 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/long.hpp>
+#include <boost/mpl/void.hpp>
+#include <boost/mpl/next.hpp>
+#include <boost/mpl/prior.hpp>
+#include <boost/mpl/set/aux_/set0.hpp>
+#include <boost/mpl/aux_/type_wrapper.hpp>
+#include <boost/mpl/aux_/config/arrays.hpp>
+
+namespace boost { namespace mpl {
+
+template< typename T, typename Base >
+struct s_item
+ : Base
+{
+ typedef s_item<T,Base> item_;
+ typedef void_ last_masked_;
+ typedef T item_type_;
+ typedef typename Base::item_ base;
+
+ typedef typename next< typename Base::size >::type size;
+ typedef typename next< typename Base::order >::type order;
+
+#if defined(BOOST_MPL_CFG_NO_DEPENDENT_ARRAY_TYPES)
+ typedef typename aux::weighted_tag<BOOST_MPL_AUX_MSVC_VALUE_WKND(order)::value>::type order_tag_;
+#else
+ typedef char (&order_tag_)[BOOST_MPL_AUX_MSVC_VALUE_WKND(order)::value];
+#endif
+
+ BOOST_MPL_AUX_SET_OVERLOAD( order_tag_, ORDER_BY_KEY, s_item, aux::type_wrapper<T>* );
+ BOOST_MPL_AUX_SET_OVERLOAD( aux::no_tag, IS_MASKED, s_item, aux::type_wrapper<T>* );
+};
+
+
+template< typename T, typename Base >
+struct s_mask
+ : Base
+{
+ typedef s_mask<T,Base> item_;
+ typedef T last_masked_;
+ typedef void_ item_type_;
+ typedef typename Base::item_ base;
+ typedef typename prior< typename Base::size >::type size;
+
+ BOOST_MPL_AUX_SET_OVERLOAD( aux::yes_tag, IS_MASKED, s_mask, aux::type_wrapper<T>* );
+};
+
+
+template< typename T, typename Base >
+struct s_unmask
+ : Base
+{
+ typedef s_unmask<T,Base> item_;
+ typedef void_ last_masked_;
+ typedef T item_type_;
+ typedef typename Base::item_ base;
+ typedef typename next< typename Base::size >::type size;
+
+ BOOST_MPL_AUX_SET_OVERLOAD( aux::no_tag, IS_MASKED, s_unmask, aux::type_wrapper<T>* );
+};
+
+}}
+
+#endif // BOOST_MPL_SET_AUX_ITEM_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/iterator.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/iterator.hpp
new file mode 100644
index 0000000..9a58a25
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/iterator.hpp
@@ -0,0 +1,98 @@
+
+#ifndef BOOST_MPL_SET_AUX_ITERATOR_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_ITERATOR_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2007
+// Copyright David Abrahams 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/set/aux_/set0.hpp>
+#include <boost/mpl/has_key.hpp>
+#include <boost/mpl/iterator_tags.hpp>
+#include <boost/mpl/next.hpp>
+#include <boost/mpl/eval_if.hpp>
+#include <boost/mpl/if.hpp>
+#include <boost/mpl/identity.hpp>
+#include <boost/mpl/aux_/config/ctps.hpp>
+
+namespace boost { namespace mpl {
+
+// used by 's_iter_get'
+template< typename Set, typename Tail > struct s_iter;
+
+template< typename Set, typename Tail > struct s_iter_get
+ : eval_if<
+ has_key< Set,typename Tail::item_type_ >
+ , identity< s_iter<Set,Tail> >
+ , next< s_iter<Set,Tail> >
+ >
+{
+};
+
+template< typename Set, typename Tail > struct s_iter_impl
+{
+ typedef Tail tail_;
+ typedef forward_iterator_tag category;
+ typedef typename Tail::item_type_ type;
+
+#if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
+ typedef typename s_iter_get< Set,typename Tail::base >::type next;
+#endif
+};
+
+#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
+
+template< typename Set, typename Tail >
+struct next< s_iter<Set,Tail> >
+ : s_iter_get< Set,typename Tail::base >
+{
+};
+
+template< typename Set >
+struct next< s_iter<Set,set0<> > >
+{
+ typedef s_iter<Set,set0<> > type;
+};
+
+template< typename Set, typename Tail > struct s_iter
+ : s_iter_impl<Set,Tail>
+{
+};
+
+template< typename Set > struct s_iter<Set, set0<> >
+{
+ typedef forward_iterator_tag category;
+};
+
+#else
+
+template< typename Set >
+struct s_end_iter
+{
+ typedef forward_iterator_tag category;
+ typedef s_iter<Set,set0<> > next;
+};
+
+template< typename Set, typename Tail > struct s_iter
+ : if_<
+ is_same< Tail,set0<> >
+ , s_end_iter<Set>
+ , s_iter_impl<Set,Tail>
+ >::type
+{
+};
+
+#endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
+
+}}
+
+#endif // BOOST_MPL_SET_AUX_ITERATOR_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/key_type_impl.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/key_type_impl.hpp
new file mode 100644
index 0000000..8e8a090
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/key_type_impl.hpp
@@ -0,0 +1,34 @@
+
+#ifndef BOOST_MPL_SET_AUX_KEY_TYPE_IMPL_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_KEY_TYPE_IMPL_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2004
+// Copyright David Abrahams 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/key_type_fwd.hpp>
+#include <boost/mpl/set/aux_/tag.hpp>
+
+namespace boost { namespace mpl {
+
+template<>
+struct key_type_impl< aux::set_tag >
+{
+ template< typename Set, typename T > struct apply
+ {
+ typedef T type;
+ };
+};
+
+}}
+
+#endif // BOOST_MPL_SET_AUX_KEY_TYPE_IMPL_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/set0.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/set0.hpp
new file mode 100644
index 0000000..65f52a8
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/set0.hpp
@@ -0,0 +1,69 @@
+
+#ifndef BOOST_MPL_SET_AUX_SET0_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_SET0_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2004
+// Copyright David Abrahams 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/long.hpp>
+#include <boost/mpl/void.hpp>
+#include <boost/mpl/aux_/na.hpp>
+#include <boost/mpl/set/aux_/tag.hpp>
+#include <boost/mpl/aux_/yes_no.hpp>
+#include <boost/mpl/aux_/overload_names.hpp>
+#include <boost/mpl/aux_/config/operators.hpp>
+
+#include <boost/preprocessor/cat.hpp>
+
+namespace boost { namespace mpl {
+
+#if defined(BOOST_MPL_CFG_USE_OPERATORS_OVERLOADING)
+
+# define BOOST_MPL_AUX_SET0_OVERLOAD(R, f, X, T) \
+ friend R BOOST_PP_CAT(BOOST_MPL_AUX_OVERLOAD_,f)(X const&, T) \
+/**/
+
+# define BOOST_MPL_AUX_SET_OVERLOAD(R, f, X, T) \
+ BOOST_MPL_AUX_SET0_OVERLOAD(R, f, X, T) \
+/**/
+
+#else
+
+# define BOOST_MPL_AUX_SET0_OVERLOAD(R, f, X, T) \
+ static R BOOST_PP_CAT(BOOST_MPL_AUX_OVERLOAD_,f)(X const&, T) \
+/**/
+
+# define BOOST_MPL_AUX_SET_OVERLOAD(R, f, X, T) \
+ BOOST_MPL_AUX_SET0_OVERLOAD(R, f, X, T); \
+ using Base::BOOST_PP_CAT(BOOST_MPL_AUX_OVERLOAD_,f) \
+/**/
+
+#endif
+
+template< typename Dummy = na > struct set0
+{
+ typedef set0<> item_;
+ typedef item_ type;
+ typedef aux::set_tag tag;
+ typedef void_ last_masked_;
+ typedef void_ item_type_;
+ typedef long_<0> size;
+ typedef long_<1> order;
+
+ BOOST_MPL_AUX_SET0_OVERLOAD( aux::no_tag, ORDER_BY_KEY, set0<>, void const volatile* );
+ BOOST_MPL_AUX_SET0_OVERLOAD( aux::yes_tag, IS_MASKED, set0<>, void const volatile* );
+};
+
+}}
+
+#endif // BOOST_MPL_SET_AUX_SET0_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/size_impl.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/size_impl.hpp
new file mode 100644
index 0000000..e865596
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/size_impl.hpp
@@ -0,0 +1,33 @@
+
+#ifndef BOOST_MPL_SET_AUX_SIZE_IMPL_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_SIZE_IMPL_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/size_fwd.hpp>
+#include <boost/mpl/set/aux_/tag.hpp>
+
+namespace boost { namespace mpl {
+
+template<>
+struct size_impl< aux::set_tag >
+{
+ template< typename Set > struct apply
+ : Set::size
+ {
+ };
+};
+
+}}
+
+#endif // BOOST_MPL_SET_AUX_SIZE_IMPL_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/tag.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/tag.hpp
new file mode 100644
index 0000000..f11fc2b
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/tag.hpp
@@ -0,0 +1,24 @@
+
+#ifndef BOOST_MPL_SET_AUX_TAG_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_TAG_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2004
+// Copyright David Abrahams 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+namespace boost { namespace mpl { namespace aux {
+
+struct set_tag;
+
+}}}
+
+#endif // BOOST_MPL_SET_AUX_TAG_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/aux_/value_type_impl.hpp b/3rdParty/Boost/src/boost/mpl/set/aux_/value_type_impl.hpp
new file mode 100644
index 0000000..91cf0d0
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/aux_/value_type_impl.hpp
@@ -0,0 +1,34 @@
+
+#ifndef BOOST_MPL_SET_AUX_VALUE_TYPE_IMPL_HPP_INCLUDED
+#define BOOST_MPL_SET_AUX_VALUE_TYPE_IMPL_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2004
+// Copyright David Abrahams 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/value_type_fwd.hpp>
+#include <boost/mpl/set/aux_/tag.hpp>
+
+namespace boost { namespace mpl {
+
+template<>
+struct value_type_impl< aux::set_tag >
+{
+ template< typename Set, typename T > struct apply
+ {
+ typedef T type;
+ };
+};
+
+}}
+
+#endif // BOOST_MPL_SET_AUX_VALUE_TYPE_IMPL_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/mpl/set/set0.hpp b/3rdParty/Boost/src/boost/mpl/set/set0.hpp
new file mode 100644
index 0000000..8403731
--- /dev/null
+++ b/3rdParty/Boost/src/boost/mpl/set/set0.hpp
@@ -0,0 +1,35 @@
+
+#ifndef BOOST_MPL_SET_SET0_HPP_INCLUDED
+#define BOOST_MPL_SET_SET0_HPP_INCLUDED
+
+// Copyright Aleksey Gurtovoy 2003-2004
+// Copyright David Abrahams 2003-2004
+//
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// See http://www.boost.org/libs/mpl for documentation.
+
+// $Id$
+// $Date$
+// $Revision$
+
+#include <boost/mpl/set/aux_/at_impl.hpp>
+#include <boost/mpl/set/aux_/clear_impl.hpp>
+//#include <boost/mpl/set/aux_/O1_size.hpp>
+#include <boost/mpl/set/aux_/size_impl.hpp>
+#include <boost/mpl/set/aux_/empty_impl.hpp>
+#include <boost/mpl/set/aux_/insert_impl.hpp>
+#include <boost/mpl/set/aux_/erase_impl.hpp>
+#include <boost/mpl/set/aux_/erase_key_impl.hpp>
+#include <boost/mpl/set/aux_/has_key_impl.hpp>
+#include <boost/mpl/set/aux_/key_type_impl.hpp>
+#include <boost/mpl/set/aux_/value_type_impl.hpp>
+#include <boost/mpl/set/aux_/begin_end_impl.hpp>
+#include <boost/mpl/set/aux_/iterator.hpp>
+#include <boost/mpl/set/aux_/item.hpp>
+#include <boost/mpl/set/aux_/set0.hpp>
+#include <boost/mpl/set/aux_/tag.hpp>
+
+#endif // BOOST_MPL_SET_SET0_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/multi_index/detail/scope_guard.hpp b/3rdParty/Boost/src/boost/multi_index/detail/scope_guard.hpp
new file mode 100644
index 0000000..116f8f5
--- /dev/null
+++ b/3rdParty/Boost/src/boost/multi_index/detail/scope_guard.hpp
@@ -0,0 +1,453 @@
+/* Copyright 2003-2013 Joaquin M Lopez Munoz.
+ * Distributed under the Boost Software License, Version 1.0.
+ * (See accompanying file LICENSE_1_0.txt or copy at
+ * http://www.boost.org/LICENSE_1_0.txt)
+ *
+ * See http://www.boost.org/libs/multi_index for library home page.
+ */
+
+#ifndef BOOST_MULTI_INDEX_DETAIL_SCOPE_GUARD_HPP
+#define BOOST_MULTI_INDEX_DETAIL_SCOPE_GUARD_HPP
+
+#if defined(_MSC_VER)
+#pragma once
+#endif
+
+#include <boost/detail/no_exceptions_support.hpp>
+#include <boost/mpl/if.hpp>
+
+namespace boost{
+
+namespace multi_index{
+
+namespace detail{
+
+/* Until some official version of the ScopeGuard idiom makes it into Boost,
+ * we locally define our own. This is a merely reformated version of
+ * ScopeGuard.h as defined in:
+ * Alexandrescu, A., Marginean, P.:"Generic<Programming>: Change the Way You
+ * Write Exception-Safe Code - Forever", C/C++ Users Jornal, Dec 2000,
+ * http://www.drdobbs.com/184403758
+ * with the following modifications:
+ * - General pretty formatting (pretty to my taste at least.)
+ * - Naming style changed to standard C++ library requirements.
+ * - Added scope_guard_impl4 and obj_scope_guard_impl3, (Boost.MultiIndex
+ * needs them). A better design would provide guards for many more
+ * arguments through the Boost Preprocessor Library.
+ * - Added scope_guard_impl_base::touch (see below.)
+ * - Removed RefHolder and ByRef, whose functionality is provided
+ * already by Boost.Ref.
+ * - Removed static make_guard's and make_obj_guard's, so that the code
+ * will work even if BOOST_NO_MEMBER_TEMPLATES is defined. This forces
+ * us to move some private ctors to public, though.
+ *
+ * NB: CodeWarrior Pro 8 seems to have problems looking up safe_execute
+ * without an explicit qualification.
+ *
+ * We also define the following variants of the idiom:
+ *
+ * - make_guard_if_c<bool>( ... )
+ * - make_guard_if<IntegralConstant>( ... )
+ * - make_obj_guard_if_c<bool>( ... )
+ * - make_obj_guard_if<IntegralConstant>( ... )
+ * which may be used with a compile-time constant to yield
+ * a "null_guard" if the boolean compile-time parameter is false,
+ * or conversely, the guard is only constructed if the constant is true.
+ * This is useful to avoid extra tagging, because the returned
+ * null_guard can be optimzed comlpetely away by the compiler.
+ */
+
+class scope_guard_impl_base
+{
+public:
+ scope_guard_impl_base():dismissed_(false){}
+ void dismiss()const{dismissed_=true;}
+
+ /* This helps prevent some "unused variable" warnings under, for instance,
+ * GCC 3.2.
+ */
+ void touch()const{}
+
+protected:
+ ~scope_guard_impl_base(){}
+
+ scope_guard_impl_base(const scope_guard_impl_base& other):
+ dismissed_(other.dismissed_)
+ {
+ other.dismiss();
+ }
+
+ template<typename J>
+ static void safe_execute(J& j){
+ BOOST_TRY{
+ if(!j.dismissed_)j.execute();
+ }
+ BOOST_CATCH(...){}
+ BOOST_CATCH_END
+ }
+
+ mutable bool dismissed_;
+
+private:
+ scope_guard_impl_base& operator=(const scope_guard_impl_base&);
+};
+
+typedef const scope_guard_impl_base& scope_guard;
+
+struct null_guard : public scope_guard_impl_base
+{
+ template< class T1 >
+ null_guard( const T1& )
+ { }
+
+ template< class T1, class T2 >
+ null_guard( const T1&, const T2& )
+ { }
+
+ template< class T1, class T2, class T3 >
+ null_guard( const T1&, const T2&, const T3& )
+ { }
+
+ template< class T1, class T2, class T3, class T4 >
+ null_guard( const T1&, const T2&, const T3&, const T4& )
+ { }
+
+ template< class T1, class T2, class T3, class T4, class T5 >
+ null_guard( const T1&, const T2&, const T3&, const T4&, const T5& )
+ { }
+};
+
+template< bool cond, class T >
+struct null_guard_return
+{
+ typedef typename boost::mpl::if_c<cond,T,null_guard>::type type;
+};
+
+template<typename F>
+class scope_guard_impl0:public scope_guard_impl_base
+{
+public:
+ scope_guard_impl0(F fun):fun_(fun){}
+ ~scope_guard_impl0(){scope_guard_impl_base::safe_execute(*this);}
+ void execute(){fun_();}
+
+protected:
+
+ F fun_;
+};
+
+template<typename F>
+inline scope_guard_impl0<F> make_guard(F fun)
+{
+ return scope_guard_impl0<F>(fun);
+}
+
+template<bool cond, typename F>
+inline typename null_guard_return<cond,scope_guard_impl0<F> >::type
+make_guard_if_c(F fun)
+{
+ return typename null_guard_return<cond,scope_guard_impl0<F> >::type(fun);
+}
+
+template<typename C, typename F>
+inline typename null_guard_return<C::value,scope_guard_impl0<F> >::type
+make_guard_if(F fun)
+{
+ return make_guard_if<C::value>(fun);
+}
+
+template<typename F,typename P1>
+class scope_guard_impl1:public scope_guard_impl_base
+{
+public:
+ scope_guard_impl1(F fun,P1 p1):fun_(fun),p1_(p1){}
+ ~scope_guard_impl1(){scope_guard_impl_base::safe_execute(*this);}
+ void execute(){fun_(p1_);}
+
+protected:
+ F fun_;
+ const P1 p1_;
+};
+
+template<typename F,typename P1>
+inline scope_guard_impl1<F,P1> make_guard(F fun,P1 p1)
+{
+ return scope_guard_impl1<F,P1>(fun,p1);
+}
+
+template<bool cond, typename F,typename P1>
+inline typename null_guard_return<cond,scope_guard_impl1<F,P1> >::type
+make_guard_if_c(F fun,P1 p1)
+{
+ return typename null_guard_return<cond,scope_guard_impl1<F,P1> >::type(fun,p1);
+}
+
+template<typename C, typename F,typename P1>
+inline typename null_guard_return<C::value,scope_guard_impl1<F,P1> >::type
+make_guard_if(F fun,P1 p1)
+{
+ return make_guard_if_c<C::value>(fun,p1);
+}
+
+template<typename F,typename P1,typename P2>
+class scope_guard_impl2:public scope_guard_impl_base
+{
+public:
+ scope_guard_impl2(F fun,P1 p1,P2 p2):fun_(fun),p1_(p1),p2_(p2){}
+ ~scope_guard_impl2(){scope_guard_impl_base::safe_execute(*this);}
+ void execute(){fun_(p1_,p2_);}
+
+protected:
+ F fun_;
+ const P1 p1_;
+ const P2 p2_;
+};
+
+template<typename F,typename P1,typename P2>
+inline scope_guard_impl2<F,P1,P2> make_guard(F fun,P1 p1,P2 p2)
+{
+ return scope_guard_impl2<F,P1,P2>(fun,p1,p2);
+}
+
+template<bool cond, typename F,typename P1,typename P2>
+inline typename null_guard_return<cond,scope_guard_impl2<F,P1,P2> >::type
+make_guard_if_c(F fun,P1 p1,P2 p2)
+{
+ return typename null_guard_return<cond,scope_guard_impl2<F,P1,P2> >::type(fun,p1,p2);
+}
+
+template<typename C, typename F,typename P1,typename P2>
+inline typename null_guard_return<C::value,scope_guard_impl2<F,P1,P2> >::type
+make_guard_if(F fun,P1 p1,P2 p2)
+{
+ return make_guard_if_c<C::value>(fun,p1,p2);
+}
+
+template<typename F,typename P1,typename P2,typename P3>
+class scope_guard_impl3:public scope_guard_impl_base
+{
+public:
+ scope_guard_impl3(F fun,P1 p1,P2 p2,P3 p3):fun_(fun),p1_(p1),p2_(p2),p3_(p3){}
+ ~scope_guard_impl3(){scope_guard_impl_base::safe_execute(*this);}
+ void execute(){fun_(p1_,p2_,p3_);}
+
+protected:
+ F fun_;
+ const P1 p1_;
+ const P2 p2_;
+ const P3 p3_;
+};
+
+template<typename F,typename P1,typename P2,typename P3>
+inline scope_guard_impl3<F,P1,P2,P3> make_guard(F fun,P1 p1,P2 p2,P3 p3)
+{
+ return scope_guard_impl3<F,P1,P2,P3>(fun,p1,p2,p3);
+}
+
+template<bool cond,typename F,typename P1,typename P2,typename P3>
+inline typename null_guard_return<cond,scope_guard_impl3<F,P1,P2,P3> >::type
+make_guard_if_c(F fun,P1 p1,P2 p2,P3 p3)
+{
+ return typename null_guard_return<cond,scope_guard_impl3<F,P1,P2,P3> >::type(fun,p1,p2,p3);
+}
+
+template<typename C,typename F,typename P1,typename P2,typename P3>
+inline typename null_guard_return< C::value,scope_guard_impl3<F,P1,P2,P3> >::type
+make_guard_if(F fun,P1 p1,P2 p2,P3 p3)
+{
+ return make_guard_if_c<C::value>(fun,p1,p2,p3);
+}
+
+template<typename F,typename P1,typename P2,typename P3,typename P4>
+class scope_guard_impl4:public scope_guard_impl_base
+{
+public:
+ scope_guard_impl4(F fun,P1 p1,P2 p2,P3 p3,P4 p4):
+ fun_(fun),p1_(p1),p2_(p2),p3_(p3),p4_(p4){}
+ ~scope_guard_impl4(){scope_guard_impl_base::safe_execute(*this);}
+ void execute(){fun_(p1_,p2_,p3_,p4_);}
+
+protected:
+ F fun_;
+ const P1 p1_;
+ const P2 p2_;
+ const P3 p3_;
+ const P4 p4_;
+};
+
+template<typename F,typename P1,typename P2,typename P3,typename P4>
+inline scope_guard_impl4<F,P1,P2,P3,P4> make_guard(
+ F fun,P1 p1,P2 p2,P3 p3,P4 p4)
+{
+ return scope_guard_impl4<F,P1,P2,P3,P4>(fun,p1,p2,p3,p4);
+}
+
+template<bool cond, typename F,typename P1,typename P2,typename P3,typename P4>
+inline typename null_guard_return<cond,scope_guard_impl4<F,P1,P2,P3,P4> >::type
+make_guard_if_c(
+ F fun,P1 p1,P2 p2,P3 p3,P4 p4)
+{
+ return typename null_guard_return<cond,scope_guard_impl4<F,P1,P2,P3,P4> >::type(fun,p1,p2,p3,p4);
+}
+
+template<typename C, typename F,typename P1,typename P2,typename P3,typename P4>
+inline typename null_guard_return<C::value,scope_guard_impl4<F,P1,P2,P3,P4> >::type
+make_guard_if(
+ F fun,P1 p1,P2 p2,P3 p3,P4 p4)
+{
+ return make_guard_if_c<C::value>(fun,p1,p2,p3,p4);
+}
+
+template<class Obj,typename MemFun>
+class obj_scope_guard_impl0:public scope_guard_impl_base
+{
+public:
+ obj_scope_guard_impl0(Obj& obj,MemFun mem_fun):obj_(obj),mem_fun_(mem_fun){}
+ ~obj_scope_guard_impl0(){scope_guard_impl_base::safe_execute(*this);}
+ void execute(){(obj_.*mem_fun_)();}
+
+protected:
+ Obj& obj_;
+ MemFun mem_fun_;
+};
+
+template<class Obj,typename MemFun>
+inline obj_scope_guard_impl0<Obj,MemFun> make_obj_guard(Obj& obj,MemFun mem_fun)
+{
+ return obj_scope_guard_impl0<Obj,MemFun>(obj,mem_fun);
+}
+
+template<bool cond, class Obj,typename MemFun>
+inline typename null_guard_return<cond,obj_scope_guard_impl0<Obj,MemFun> >::type
+make_obj_guard_if_c(Obj& obj,MemFun mem_fun)
+{
+ return typename null_guard_return<cond,obj_scope_guard_impl0<Obj,MemFun> >::type(obj,mem_fun);
+}
+
+template<typename C, class Obj,typename MemFun>
+inline typename null_guard_return<C::value,obj_scope_guard_impl0<Obj,MemFun> >::type
+make_obj_guard_if(Obj& obj,MemFun mem_fun)
+{
+ return make_obj_guard_if_c<C::value>(obj,mem_fun);
+}
+
+template<class Obj,typename MemFun,typename P1>
+class obj_scope_guard_impl1:public scope_guard_impl_base
+{
+public:
+ obj_scope_guard_impl1(Obj& obj,MemFun mem_fun,P1 p1):
+ obj_(obj),mem_fun_(mem_fun),p1_(p1){}
+ ~obj_scope_guard_impl1(){scope_guard_impl_base::safe_execute(*this);}
+ void execute(){(obj_.*mem_fun_)(p1_);}
+
+protected:
+ Obj& obj_;
+ MemFun mem_fun_;
+ const P1 p1_;
+};
+
+template<class Obj,typename MemFun,typename P1>
+inline obj_scope_guard_impl1<Obj,MemFun,P1> make_obj_guard(
+ Obj& obj,MemFun mem_fun,P1 p1)
+{
+ return obj_scope_guard_impl1<Obj,MemFun,P1>(obj,mem_fun,p1);
+}
+
+template<bool cond, class Obj,typename MemFun,typename P1>
+inline typename null_guard_return<cond,obj_scope_guard_impl1<Obj,MemFun,P1> >::type
+make_obj_guard_if_c( Obj& obj,MemFun mem_fun,P1 p1)
+{
+ return typename null_guard_return<cond,obj_scope_guard_impl1<Obj,MemFun,P1> >::type(obj,mem_fun,p1);
+}
+
+template<typename C, class Obj,typename MemFun,typename P1>
+inline typename null_guard_return<C::value,obj_scope_guard_impl1<Obj,MemFun,P1> >::type
+make_obj_guard_if( Obj& obj,MemFun mem_fun,P1 p1)
+{
+ return make_obj_guard_if_c<C::value>(obj,mem_fun,p1);
+}
+
+template<class Obj,typename MemFun,typename P1,typename P2>
+class obj_scope_guard_impl2:public scope_guard_impl_base
+{
+public:
+ obj_scope_guard_impl2(Obj& obj,MemFun mem_fun,P1 p1,P2 p2):
+ obj_(obj),mem_fun_(mem_fun),p1_(p1),p2_(p2)
+ {}
+ ~obj_scope_guard_impl2(){scope_guard_impl_base::safe_execute(*this);}
+ void execute(){(obj_.*mem_fun_)(p1_,p2_);}
+
+protected:
+ Obj& obj_;
+ MemFun mem_fun_;
+ const P1 p1_;
+ const P2 p2_;
+};
+
+template<class Obj,typename MemFun,typename P1,typename P2>
+inline obj_scope_guard_impl2<Obj,MemFun,P1,P2>
+make_obj_guard(Obj& obj,MemFun mem_fun,P1 p1,P2 p2)
+{
+ return obj_scope_guard_impl2<Obj,MemFun,P1,P2>(obj,mem_fun,p1,p2);
+}
+
+template<bool cond, class Obj,typename MemFun,typename P1,typename P2>
+inline typename null_guard_return<cond,obj_scope_guard_impl2<Obj,MemFun,P1,P2> >::type
+make_obj_guard_if_c(Obj& obj,MemFun mem_fun,P1 p1,P2 p2)
+{
+ return typename null_guard_return<cond,obj_scope_guard_impl2<Obj,MemFun,P1,P2> >::type(obj,mem_fun,p1,p2);
+}
+
+template<typename C, class Obj,typename MemFun,typename P1,typename P2>
+inline typename null_guard_return<C::value,obj_scope_guard_impl2<Obj,MemFun,P1,P2> >::type
+make_obj_guard_if(Obj& obj,MemFun mem_fun,P1 p1,P2 p2)
+{
+ return make_obj_guard_if_c<C::value>(obj,mem_fun,p1,p2);
+}
+
+template<class Obj,typename MemFun,typename P1,typename P2,typename P3>
+class obj_scope_guard_impl3:public scope_guard_impl_base
+{
+public:
+ obj_scope_guard_impl3(Obj& obj,MemFun mem_fun,P1 p1,P2 p2,P3 p3):
+ obj_(obj),mem_fun_(mem_fun),p1_(p1),p2_(p2),p3_(p3)
+ {}
+ ~obj_scope_guard_impl3(){scope_guard_impl_base::safe_execute(*this);}
+ void execute(){(obj_.*mem_fun_)(p1_,p2_,p3_);}
+
+protected:
+ Obj& obj_;
+ MemFun mem_fun_;
+ const P1 p1_;
+ const P2 p2_;
+ const P3 p3_;
+};
+
+template<class Obj,typename MemFun,typename P1,typename P2,typename P3>
+inline obj_scope_guard_impl3<Obj,MemFun,P1,P2,P3>
+make_obj_guard(Obj& obj,MemFun mem_fun,P1 p1,P2 p2,P3 p3)
+{
+ return obj_scope_guard_impl3<Obj,MemFun,P1,P2,P3>(obj,mem_fun,p1,p2,p3);
+}
+
+template<bool cond, class Obj,typename MemFun,typename P1,typename P2,typename P3>
+inline typename null_guard_return<cond,obj_scope_guard_impl3<Obj,MemFun,P1,P2,P3> >::type
+make_obj_guard_if_c(Obj& obj,MemFun mem_fun,P1 p1,P2 p2,P3 p3)
+{
+ return typename null_guard_return<cond,obj_scope_guard_impl3<Obj,MemFun,P1,P2,P3> >::type(obj,mem_fun,p1,p2,p3);
+}
+
+template<typename C, class Obj,typename MemFun,typename P1,typename P2,typename P3>
+inline typename null_guard_return<C::value,obj_scope_guard_impl3<Obj,MemFun,P1,P2,P3> >::type
+make_obj_guard_if(Obj& obj,MemFun mem_fun,P1 p1,P2 p2,P3 p3)
+{
+ return make_obj_guard_if_c<C::value>(obj,mem_fun,p1,p2,p3);
+}
+
+} /* namespace multi_index::detail */
+
+} /* namespace multi_index */
+
+} /* namespace boost */
+
+#endif
diff --git a/3rdParty/Boost/src/boost/parameter.hpp b/3rdParty/Boost/src/boost/parameter.hpp
new file mode 100755
index 0000000..3cc70cb
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter.hpp
@@ -0,0 +1,21 @@
+// Copyright David Abrahams, Daniel Wallin 2005. Use, modification and
+// distribution is subject to the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// See www.boost.org/libs/parameter for documentation.
+
+#ifndef BOOST_PARAMETER_050401_HPP
+#define BOOST_PARAMETER_050401_HPP
+
+#include <boost/parameter/parameters.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/parameter/binding.hpp>
+#include <boost/parameter/value_type.hpp>
+#include <boost/parameter/macros.hpp>
+#include <boost/parameter/match.hpp>
+#include <boost/parameter/name.hpp>
+#include <boost/parameter/preprocessor.hpp>
+
+#endif // BOOST_PARAMETER_050401_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/arg_list.hpp b/3rdParty/Boost/src/boost/parameter/aux_/arg_list.hpp
new file mode 100644
index 0000000..ed3929d
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/arg_list.hpp
@@ -0,0 +1,459 @@
+// Copyright Daniel Wallin, David Abrahams 2005. Use, modification and
+// distribution is subject to the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef ARG_LIST_050329_HPP
+#define ARG_LIST_050329_HPP
+
+#include <boost/parameter/aux_/void.hpp>
+#include <boost/parameter/aux_/result_of0.hpp>
+#include <boost/parameter/aux_/default.hpp>
+#include <boost/parameter/aux_/parameter_requirements.hpp>
+#include <boost/parameter/aux_/yesno.hpp>
+#include <boost/parameter/aux_/is_maybe.hpp>
+#include <boost/parameter/config.hpp>
+
+#include <boost/mpl/apply.hpp>
+#include <boost/mpl/assert.hpp>
+#include <boost/mpl/begin.hpp>
+#include <boost/mpl/end.hpp>
+#include <boost/mpl/iterator_tags.hpp>
+
+#include <boost/type_traits/add_reference.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/preprocessor/repetition/enum_params.hpp>
+#include <boost/preprocessor/repetition/enum_binary_params.hpp>
+#include <boost/preprocessor/facilities/intercept.hpp>
+
+namespace boost { namespace parameter {
+
+// Forward declaration for aux::arg_list, below.
+template<class T> struct keyword;
+
+namespace aux {
+
+// Tag type passed to MPL lambda.
+struct lambda_tag;
+
+//
+// Structures used to build the tuple of actual arguments. The
+// tuple is a nested cons-style list of arg_list specializations
+// terminated by an empty_arg_list.
+//
+// Each specialization of arg_list is derived from its successor in
+// the list type. This feature is used along with using
+// declarations to build member function overload sets that can
+// match against keywords.
+//
+
+// MPL sequence support
+struct arg_list_tag;
+
+// Terminates arg_list<> and represents an empty list. Since this
+// is just the terminating case you might want to look at arg_list
+// first, to get a feel for what's really happening here.
+
+struct empty_arg_list
+{
+ empty_arg_list() {}
+
+ // Constructor taking BOOST_PARAMETER_MAX_ARITY empty_arg_list
+ // arguments; this makes initialization
+ empty_arg_list(
+ BOOST_PP_ENUM_PARAMS(
+ BOOST_PARAMETER_MAX_ARITY, void_ BOOST_PP_INTERCEPT
+ ))
+ {}
+
+ // A metafunction class that, given a keyword and a default
+ // type, returns the appropriate result type for a keyword
+ // lookup given that default
+ struct binding
+ {
+ template<class KW, class Default, class Reference>
+ struct apply
+ {
+ typedef Default type;
+ };
+ };
+
+#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
+ // Terminator for has_key, indicating that the keyword is unique
+ template <class KW>
+ static no_tag has_key(KW*);
+#endif
+
+#if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) \
+ || (BOOST_WORKAROUND(__GNUC__, < 3)) \
+ || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+
+ // The overload set technique doesn't work with these older
+ // compilers, so they need some explicit handholding.
+
+ // A metafunction class that, given a keyword, returns the type
+ // of the base sublist whose get() function can produce the
+ // value for that key
+ struct key_owner
+ {
+ template<class KW>
+ struct apply
+ {
+ typedef empty_arg_list type;
+ };
+ };
+
+ template <class K, class T>
+ T& get(default_<K,T> x) const
+ {
+ return x.value;
+ }
+
+ template <class K, class F>
+ typename result_of0<F>::type
+ get(lazy_default<K,F> x) const
+ {
+ return x.compute_default();
+ }
+#endif
+
+ // If this function is called, it means there is no argument
+ // in the list that matches the supplied keyword. Just return
+ // the default value.
+ template <class K, class Default>
+ Default& operator[](default_<K, Default> x) const
+ {
+ return x.value;
+ }
+
+ // If this function is called, it means there is no argument
+ // in the list that matches the supplied keyword. Just evaluate
+ // and return the default value.
+ template <class K, class F>
+ typename result_of0<F>::type
+ operator[](
+ BOOST_PARAMETER_lazy_default_fallback<K,F> x) const
+ {
+ return x.compute_default();
+ }
+
+ // No argument corresponding to ParameterRequirements::key_type
+ // was found if we match this overload, so unless that parameter
+ // has a default, we indicate that the actual arguments don't
+ // match the function's requirements.
+ template <class ParameterRequirements, class ArgPack>
+ static typename ParameterRequirements::has_default
+ satisfies(ParameterRequirements*, ArgPack*);
+
+ // MPL sequence support
+ typedef empty_arg_list type; // convenience
+ typedef arg_list_tag tag; // For dispatching to sequence intrinsics
+};
+
+#if BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
+template<class KW>
+no_tag operator*(empty_arg_list, KW*);
+#endif
+
+// Forward declaration for arg_list::operator,
+template <class KW, class T>
+struct tagged_argument;
+
+template <class T>
+struct get_reference
+{
+ typedef typename T::reference type;
+};
+
+// A tuple of tagged arguments, terminated with empty_arg_list.
+// Every TaggedArg is an instance of tagged_argument<>.
+template <class TaggedArg, class Next = empty_arg_list>
+struct arg_list : Next
+{
+ typedef arg_list<TaggedArg,Next> self;
+ typedef typename TaggedArg::key_type key_type;
+
+ typedef typename is_maybe<typename TaggedArg::value_type>::type holds_maybe;
+
+ typedef typename mpl::eval_if<
+ holds_maybe
+ , get_reference<typename TaggedArg::value_type>
+ , get_reference<TaggedArg>
+ >::type reference;
+
+ typedef typename mpl::if_<
+ holds_maybe
+ , reference
+ , typename TaggedArg::value_type
+ >::type value_type;
+
+ TaggedArg arg; // Stores the argument
+
+ // Store the arguments in successive nodes of this list
+ template< // class A0, class A1, ...
+ BOOST_PP_ENUM_PARAMS(BOOST_PARAMETER_MAX_ARITY, class A)
+ >
+ arg_list( // A0& a0, A1& a1, ...
+ BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PARAMETER_MAX_ARITY, A, & a)
+ )
+ : Next( // a1, a2, ...
+ BOOST_PP_ENUM_SHIFTED_PARAMS(BOOST_PARAMETER_MAX_ARITY, a)
+ , void_reference()
+ )
+ , arg(a0)
+ {}
+
+ // Create a new list by prepending arg to a copy of tail. Used
+ // when incrementally building this structure with the comma
+ // operator.
+ arg_list(TaggedArg head, Next const& tail)
+ : Next(tail)
+ , arg(head)
+ {}
+
+ // A metafunction class that, given a keyword and a default
+ // type, returns the appropriate result type for a keyword
+ // lookup given that default
+ struct binding
+ {
+ template <class KW, class Default, class Reference>
+ struct apply
+ {
+ typedef typename mpl::eval_if<
+ boost::is_same<KW, key_type>
+ , mpl::if_<Reference, reference, value_type>
+ , mpl::apply_wrap3<typename Next::binding, KW, Default, Reference>
+ >::type type;
+ };
+ };
+
+#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) && !BOOST_WORKAROUND(__GNUC__, == 2)
+# if BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
+ friend yes_tag operator*(arg_list, key_type*);
+# define BOOST_PARAMETER_CALL_HAS_KEY(next, key) (*(next*)0 * (key*)0)
+# else
+ // Overload for key_type, so the assert below will fire if the
+ // same keyword is used again
+ static yes_tag has_key(key_type*);
+ using Next::has_key;
+
+# define BOOST_PARAMETER_CALL_HAS_KEY(next, key) next::has_key((key*)0)
+# endif
+
+ BOOST_MPL_ASSERT_MSG(
+ sizeof(BOOST_PARAMETER_CALL_HAS_KEY(Next,key_type)) == sizeof(no_tag)
+ , duplicate_keyword, (key_type)
+ );
+
+# undef BOOST_PARAMETER_CALL_HAS_KEY
+#endif
+ //
+ // Begin implementation of indexing operators for looking up
+ // specific arguments by name
+ //
+
+ // Helpers that handle the case when TaggedArg is
+ // empty<T>.
+ template <class D>
+ reference get_default(D const&, mpl::false_) const
+ {
+ return arg.value;
+ }
+
+ template <class D>
+ reference get_default(D const& d, mpl::true_) const
+ {
+ return arg.value ? arg.value.get() : arg.value.construct(d.value);
+ }
+
+#if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) \
+ || BOOST_WORKAROUND(__GNUC__, < 3) \
+ || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+ // These older compilers don't support the overload set creation
+ // idiom well, so we need to do all the return type calculation
+ // for the compiler and dispatch through an outer function template
+
+ // A metafunction class that, given a keyword, returns the base
+ // sublist whose get() function can produce the value for that
+ // key.
+ struct key_owner
+ {
+ template<class KW>
+ struct apply
+ {
+ typedef typename mpl::eval_if<
+ boost::is_same<KW, key_type>
+ , mpl::identity<arg_list<TaggedArg,Next> >
+ , mpl::apply_wrap1<typename Next::key_owner,KW>
+ >::type type;
+ };
+ };
+
+ // Outer indexing operators that dispatch to the right node's
+ // get() function.
+ template <class KW>
+ typename mpl::apply_wrap3<binding, KW, void_, mpl::true_>::type
+ operator[](keyword<KW> const& x) const
+ {
+ typename mpl::apply_wrap1<key_owner, KW>::type const& sublist = *this;
+ return sublist.get(x);
+ }
+
+ template <class KW, class Default>
+ typename mpl::apply_wrap3<binding, KW, Default&, mpl::true_>::type
+ operator[](default_<KW, Default> x) const
+ {
+ typename mpl::apply_wrap1<key_owner, KW>::type const& sublist = *this;
+ return sublist.get(x);
+ }
+
+ template <class KW, class F>
+ typename mpl::apply_wrap3<
+ binding,KW
+ , typename result_of0<F>::type
+ , mpl::true_
+ >::type
+ operator[](lazy_default<KW,F> x) const
+ {
+ typename mpl::apply_wrap1<key_owner, KW>::type const& sublist = *this;
+ return sublist.get(x);
+ }
+
+ // These just return the stored value; when empty_arg_list is
+ // reached, indicating no matching argument was passed, the
+ // default is returned, or if no default_ or lazy_default was
+ // passed, compilation fails.
+ reference get(keyword<key_type> const&) const
+ {
+ BOOST_MPL_ASSERT_NOT((holds_maybe));
+ return arg.value;
+ }
+
+ template <class Default>
+ reference get(default_<key_type,Default> const& d) const
+ {
+ return get_default(d, holds_maybe());
+ }
+
+ template <class Default>
+ reference get(lazy_default<key_type, Default>) const
+ {
+ return arg.value;
+ }
+
+#else
+
+ reference operator[](keyword<key_type> const&) const
+ {
+ BOOST_MPL_ASSERT_NOT((holds_maybe));
+ return arg.value;
+ }
+
+ template <class Default>
+ reference operator[](default_<key_type, Default> const& d) const
+ {
+ return get_default(d, holds_maybe());
+ }
+
+ template <class Default>
+ reference operator[](lazy_default<key_type, Default>) const
+ {
+ return arg.value;
+ }
+
+ // Builds an overload set including operator[]s defined in base
+ // classes.
+ using Next::operator[];
+
+ //
+ // End of indexing support
+ //
+
+
+ //
+ // For parameter_requirements matching this node's key_type,
+ // return a bool constant wrapper indicating whether the
+ // requirements are satisfied by TaggedArg. Used only for
+ // compile-time computation and never really called, so a
+ // declaration is enough.
+ //
+ template <class HasDefault, class Predicate, class ArgPack>
+ static typename mpl::apply_wrap2<
+ typename mpl::lambda<Predicate, lambda_tag>::type
+ , value_type, ArgPack
+ >::type
+ satisfies(
+ parameter_requirements<key_type,Predicate,HasDefault>*
+ , ArgPack*
+ );
+
+ // Builds an overload set including satisfies functions defined
+ // in base classes.
+ using Next::satisfies;
+#endif
+
+ // Comma operator to compose argument list without using parameters<>.
+ // Useful for argument lists with undetermined length.
+ template <class KW, class T2>
+ arg_list<tagged_argument<KW, T2>, self>
+ operator,(tagged_argument<KW,T2> x) const
+ {
+ return arg_list<tagged_argument<KW,T2>, self>(x, *this);
+ }
+
+ // MPL sequence support
+ typedef self type; // Convenience for users
+ typedef Next tail_type; // For the benefit of iterators
+ typedef arg_list_tag tag; // For dispatching to sequence intrinsics
+};
+
+#if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) // ETI workaround
+template <> struct arg_list<int,int> {};
+#endif
+
+// MPL sequence support
+template <class ArgumentPack>
+struct arg_list_iterator
+{
+ typedef mpl::forward_iterator_tag category;
+
+ // The incremented iterator
+ typedef arg_list_iterator<typename ArgumentPack::tail_type> next;
+
+ // dereferencing yields the key type
+ typedef typename ArgumentPack::key_type type;
+};
+
+template <>
+struct arg_list_iterator<empty_arg_list> {};
+
+}} // namespace parameter::aux
+
+// MPL sequence support
+namespace mpl
+{
+ template <>
+ struct begin_impl<parameter::aux::arg_list_tag>
+ {
+ template <class S>
+ struct apply
+ {
+ typedef parameter::aux::arg_list_iterator<S> type;
+ };
+ };
+
+ template <>
+ struct end_impl<parameter::aux::arg_list_tag>
+ {
+ template <class>
+ struct apply
+ {
+ typedef parameter::aux::arg_list_iterator<parameter::aux::empty_arg_list> type;
+ };
+ };
+}
+
+} // namespace boost
+
+#endif // ARG_LIST_050329_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/cast.hpp b/3rdParty/Boost/src/boost/parameter/aux_/cast.hpp
new file mode 100644
index 0000000..b94c764
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/cast.hpp
@@ -0,0 +1,143 @@
+// Copyright Daniel Wallin 2006. Use, modification and distribution is
+// subject to the Boost Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_PARAMETER_CAST_060902_HPP
+# define BOOST_PARAMETER_CAST_060902_HPP
+
+# include <boost/detail/workaround.hpp>
+
+# if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \
+ && !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+# include <boost/type_traits/add_reference.hpp>
+# include <boost/type_traits/remove_const.hpp>
+# endif
+
+namespace boost { namespace parameter { namespace aux {
+
+struct use_default_tag {};
+
+# if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \
+ || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+
+# define BOOST_PARAMETER_FUNCTION_CAST(value, predicate) value
+
+# else
+
+// Handles possible implicit casts. Used by preprocessor.hpp to
+// normalize user input.
+//
+// cast<void*>::execute() is identity
+// cast<void*(X)>::execute() is identity
+// cast<void(X)>::execute() casts to X
+//
+// preprocessor.hpp uses this like this:
+//
+// #define X(value, predicate)
+// cast<void predicate>::execute(value)
+//
+// X(something, *)
+// X(something, *(predicate))
+// X(something, (int))
+
+template <class T, class Args>
+struct cast;
+
+template <class Args>
+struct cast<void*, Args>
+{
+ static use_default_tag execute(use_default_tag)
+ {
+ return use_default_tag();
+ }
+
+ static use_default_tag remove_const(use_default_tag)
+ {
+ return use_default_tag();
+ }
+
+ template <class U>
+ static U& execute(U& value)
+ {
+ return value;
+ }
+
+ template <class U>
+ static U& remove_const(U& x)
+ {
+ return x;
+ }
+};
+
+#if BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x580))
+
+typedef void* voidstar;
+
+template <class T, class Args>
+struct cast<voidstar(T), Args>
+ : cast<void*, Args>
+{
+};
+
+#else
+
+template <class T, class Args>
+struct cast<void*(T), Args>
+ : cast<void*, Args>
+{
+};
+
+#endif
+
+// This is a hack used in cast<> to turn the user supplied type,
+// which may or may not be a placeholder expression into one, so
+// that it will be properly evaluated by mpl::apply.
+template <class T, class Dummy = mpl::_1>
+struct as_placeholder_expr
+{
+ typedef T type;
+};
+
+template <class T, class Args>
+struct cast<void(T), Args>
+{
+ typedef typename mpl::apply2<
+ as_placeholder_expr<T>, Args, Args>::type type0;
+
+ typedef typename boost::add_reference<
+ typename boost::remove_const<type0>::type
+ >::type reference;
+
+ static use_default_tag execute(use_default_tag)
+ {
+ return use_default_tag();
+ }
+
+ static use_default_tag remove_const(use_default_tag)
+ {
+ return use_default_tag();
+ }
+
+ static type0 execute(type0 value)
+ {
+ return value;
+ }
+
+ template <class U>
+ static reference remove_const(U const& x)
+ {
+ return const_cast<reference>(x);
+ }
+};
+
+# define BOOST_PARAMETER_FUNCTION_CAST(value, predicate, args) \
+ boost::parameter::aux::cast<void predicate, args>::remove_const( \
+ boost::parameter::aux::cast<void predicate, args>::execute(value) \
+ )
+
+# endif
+
+}}} // namespace boost::parameter::aux
+
+#endif // BOOST_PARAMETER_CAST_060902_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/default.hpp b/3rdParty/Boost/src/boost/parameter/aux_/default.hpp
new file mode 100644
index 0000000..604da61
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/default.hpp
@@ -0,0 +1,69 @@
+// Copyright Daniel Wallin, David Abrahams 2005. Use, modification and
+// distribution is subject to the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef DEFAULT_050329_HPP
+# define DEFAULT_050329_HPP
+
+# include <boost/detail/workaround.hpp>
+
+namespace boost { namespace parameter { namespace aux {
+
+// A wrapper for the default value passed by the user when resolving
+// the value of the parameter with the given Keyword
+template <class Keyword, class Value>
+struct default_
+{
+ default_(Value& x)
+ : value(x)
+ {}
+
+ Value& value;
+};
+
+//
+// lazy_default --
+//
+// A wrapper for the default value computation function passed by
+// the user when resolving the value of the parameter with the
+// given keyword
+//
+# if BOOST_WORKAROUND(__EDG_VERSION__, <= 300)
+// These compilers need a little extra help with overload
+// resolution; we have empty_arg_list's operator[] accept a base
+// class to make that overload less preferable.
+template <class KW, class DefaultComputer>
+struct lazy_default_base
+{
+ lazy_default_base(DefaultComputer const& x)
+ : compute_default(x)
+ {}
+ DefaultComputer const& compute_default;
+};
+
+template <class KW, class DefaultComputer>
+struct lazy_default
+ : lazy_default_base<KW,DefaultComputer>
+ {
+ lazy_default(DefaultComputer const & x)
+ : lazy_default_base<KW,DefaultComputer>(x)
+ {}
+ };
+# define BOOST_PARAMETER_lazy_default_fallback lazy_default_base
+# else
+template <class KW, class DefaultComputer>
+struct lazy_default
+{
+ lazy_default(const DefaultComputer& x)
+ : compute_default(x)
+ {}
+ DefaultComputer const& compute_default;
+};
+# define BOOST_PARAMETER_lazy_default_fallback lazy_default
+# endif
+
+}}} // namespace boost::parameter::aux
+
+#endif // DEFAULT_050329_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/is_maybe.hpp b/3rdParty/Boost/src/boost/parameter/aux_/is_maybe.hpp
new file mode 100644
index 0000000..b875852
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/is_maybe.hpp
@@ -0,0 +1,26 @@
+// Copyright Daniel Wallin, David Abrahams 2010. Use, modification and
+// distribution is subject to the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_PARAMETER_IS_MAYBE_050329_HPP
+#define BOOST_PARAMETER_IS_MAYBE_050329_HPP
+
+#include <boost/type_traits/is_base_and_derived.hpp>
+
+namespace boost {
+namespace parameter {
+namespace aux {
+
+struct maybe_base {};
+
+template <class T>
+struct is_maybe
+ : is_base_and_derived<maybe_base, T>
+{};
+
+} // namespace aux
+} // namespace parameter
+} // namespace boost
+
+#endif // BOOST_PARAMETER_IS_MAYBE_050329_HPP
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/overloads.hpp b/3rdParty/Boost/src/boost/parameter/aux_/overloads.hpp
new file mode 100755
index 0000000..dcc92d4
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/overloads.hpp
@@ -0,0 +1,88 @@
+// Copyright David Abrahams, Daniel Wallin 2003. Use, modification and
+// distribution is subject to the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// This file generates overloads in this format:
+//
+// template<class A0, class A1>
+// typename mpl::apply_wrap1<
+// aux::make_arg_list<
+// PS0,A0
+// , aux::make_arg_list<
+// PS1,A1
+// , mpl::identity<aux::empty_arg_list>
+// >
+// >
+// , unnamed_list
+// >::type
+// operator()(A0 const& a0, A1 const& a1) const
+// {
+// typedef typename mpl::apply_wrap1<
+// aux::make_arg_list<
+// PS0,A0
+// , aux::make_arg_list<
+// PS1,A1
+// , mpl::identity<aux::empty_arg_list>
+// >
+// >
+// >::type arg_tuple;
+//
+// return arg_tuple(
+// a0
+// , a1
+// , aux::void_()
+// ...
+// );
+// }
+//
+
+#if !defined(BOOST_PP_IS_ITERATING)
+# error Boost.Parameters - do not include this file!
+#endif
+
+#define N BOOST_PP_ITERATION()
+
+#define BOOST_PARAMETER_open_list(z, n, text) \
+ aux::item< \
+ BOOST_PP_CAT(PS, n), BOOST_PP_CAT(A, n)
+
+#define BOOST_PARAMETER_close_list(z, n, text) >
+
+#define BOOST_PARAMETER_arg_list(n) \
+ aux::make_arg_list< \
+ BOOST_PP_ENUM(N, BOOST_PARAMETER_open_list, _) \
+ , void_ \
+ BOOST_PP_REPEAT(N, BOOST_PARAMETER_close_list, _) \
+ , deduced_list \
+ , aux::tag_keyword_arg \
+ >
+
+#define BOOST_PARAMETER_arg_pack_init(z, n, limit) \
+ BOOST_PP_CAT(a, BOOST_PP_SUB(limit,n))
+
+template<BOOST_PP_ENUM_PARAMS(N, class A)>
+typename mpl::first<
+ typename BOOST_PARAMETER_arg_list(N)::type
+>::type
+operator()(BOOST_PP_ENUM_BINARY_PARAMS(N, A, & a)) const
+{
+ typedef typename BOOST_PARAMETER_arg_list(N)::type result;
+
+ typedef typename mpl::first<result>::type result_type;
+ typedef typename mpl::second<result>::type error;
+ error();
+
+ return result_type(
+ BOOST_PP_ENUM(N, BOOST_PARAMETER_arg_pack_init, BOOST_PP_DEC(N))
+ BOOST_PP_ENUM_TRAILING_PARAMS(
+ BOOST_PP_SUB(BOOST_PARAMETER_MAX_ARITY, N)
+ , aux::void_reference() BOOST_PP_INTERCEPT
+ ));
+}
+
+#undef BOOST_PARAMETER_arg_list
+#undef BOOST_PARAMETER_open_list
+#undef BOOST_PARAMETER_close_list
+#undef N
+
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/parameter_requirements.hpp b/3rdParty/Boost/src/boost/parameter/aux_/parameter_requirements.hpp
new file mode 100755
index 0000000..ad7a129
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/parameter_requirements.hpp
@@ -0,0 +1,25 @@
+// Copyright Daniel Wallin, David Abrahams 2005. Use, modification and
+// distribution is subject to the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef PARAMETER_REQUIREMENTS_050331_HPP
+#define PARAMETER_REQUIREMENTS_050331_HPP
+
+namespace boost { namespace parameter { namespace aux {
+
+// Used to pass static information about parameter requirements
+// through the satisfies() overload set (below). The
+// matched function is never invoked, but its type indicates whether
+// a parameter matches at compile-time
+template <class Keyword, class Predicate, class HasDefault>
+struct parameter_requirements
+{
+ typedef Keyword keyword;
+ typedef Predicate predicate;
+ typedef HasDefault has_default;
+};
+
+}}} // namespace boost::parameter::aux
+
+#endif // PARAMETER_REQUIREMENTS_050331_HPP
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/parenthesized_type.hpp b/3rdParty/Boost/src/boost/parameter/aux_/parenthesized_type.hpp
new file mode 100755
index 0000000..c6ddd77
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/parenthesized_type.hpp
@@ -0,0 +1,119 @@
+// Copyright David Abrahams 2006. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+#ifndef BOOST_PARAMETER_AUX_PARENTHESIZED_TYPE_DWA2006414_HPP
+# define BOOST_PARAMETER_AUX_PARENTHESIZED_TYPE_DWA2006414_HPP
+
+# include <boost/config.hpp>
+# include <boost/detail/workaround.hpp>
+
+namespace boost { namespace parameter { namespace aux {
+
+// A macro that takes a parenthesized C++ type name (T) and transforms
+// it into an un-parenthesized type expression equivalent to T.
+# define BOOST_PARAMETER_PARENTHESIZED_TYPE(x) \
+ boost::parameter::aux::unaryfunptr_arg_type< void(*)x >::type
+
+// A metafunction that transforms void(*)(T) -> T
+template <class UnaryFunctionPointer>
+struct unaryfunptr_arg_type;
+
+# if !BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
+
+template <class Arg>
+struct unaryfunptr_arg_type<void(*)(Arg)>
+{
+ typedef Arg type;
+};
+
+# else
+
+// Use the "native typeof" bugfeatures of older versions of MSVC to
+// accomplish what we'd normally do with partial specialization. This
+// capability was discovered by Igor Chesnokov.
+
+# if BOOST_WORKAROUND(BOOST_MSVC, != 1300)
+
+// This version applies to VC6.5 and VC7.1 (except that we can just
+// use partial specialization for the latter in this case).
+
+// This gets used as a base class.
+template<typename Address>
+struct msvc_type_memory
+{
+ // A nullary metafunction that will yield the Value type "stored"
+ // at this Address.
+ struct storage;
+};
+
+template<typename Value, typename Address>
+struct msvc_store_type : msvc_type_memory<Address>
+{
+ // VC++ somehow lets us define the base's nested storage
+ // metafunction here, where we have the Value type we'd like to
+ // "store" in it. Later we can come back to the base class and
+ // extract the "stored type."
+ typedef msvc_type_memory<Address> location;
+ struct location::storage
+ {
+ typedef Value type;
+ };
+};
+
+# else
+
+// This slightly more complicated version of the same thing is
+// required for msvc-7.0
+template<typename Address>
+struct msvc_type_memory
+{
+ template<bool>
+ struct storage_impl;
+
+ typedef storage_impl<true> storage;
+};
+
+template<typename Value, typename Address>
+struct msvc_store_type : msvc_type_memory<Address>
+{
+ // Rather than supplying a definition for the base class' nested
+ // class, we specialize the base class' nested template
+ template<>
+ struct storage_impl<true>
+ {
+ typedef Value type;
+ };
+};
+
+# endif
+
+// Function template argument deduction does many of the same things
+// as type matching during partial specialization, so we call a
+// function template to "store" T into the type memory addressed by
+// void(*)(T).
+template <class T>
+msvc_store_type<T,void(*)(T)>
+msvc_store_argument_type(void(*)(T));
+
+template <class FunctionPointer>
+struct unaryfunptr_arg_type
+{
+ // We don't want the function to be evaluated, just instantiated,
+ // so protect it inside of sizeof.
+ enum { dummy = sizeof(msvc_store_argument_type((FunctionPointer)0)) };
+
+ // Now pull the type out of the instantiated base class
+ typedef typename msvc_type_memory<FunctionPointer>::storage::type type;
+};
+
+# endif
+
+template <>
+struct unaryfunptr_arg_type<void(*)(void)>
+{
+ typedef void type;
+};
+
+}}} // namespace boost::parameter::aux
+
+#endif // BOOST_PARAMETER_AUX_PARENTHESIZED_TYPE_DWA2006414_HPP
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/preprocessor/flatten.hpp b/3rdParty/Boost/src/boost/parameter/aux_/preprocessor/flatten.hpp
new file mode 100755
index 0000000..5d7615e
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/preprocessor/flatten.hpp
@@ -0,0 +1,115 @@
+// Copyright Daniel Wallin 2005. Use, modification and distribution is
+// subject to the Boost Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_PARAMETER_FLATTEN_051217_HPP
+# define BOOST_PARAMETER_FLATTEN_051217_HPP
+
+# include <boost/preprocessor/tuple/elem.hpp>
+# include <boost/preprocessor/tuple/rem.hpp>
+# include <boost/preprocessor/cat.hpp>
+# include <boost/preprocessor/seq/for_each.hpp>
+# include <boost/preprocessor/seq/for_each_i.hpp>
+# include <boost/preprocessor/identity.hpp>
+# include <boost/preprocessor/selection/max.hpp>
+# include <boost/preprocessor/arithmetic/sub.hpp>
+# include <boost/preprocessor/repetition/enum_trailing.hpp>
+# include <boost/parameter/aux_/preprocessor/for_each.hpp>
+
+# define BOOST_PARAMETER_FLATTEN_SPLIT_required required,
+# define BOOST_PARAMETER_FLATTEN_SPLIT_optional optional,
+# define BOOST_PARAMETER_FLATTEN_SPLIT_deduced deduced,
+
+# define BOOST_PARAMETER_FLATTEN_SPLIT(sub) \
+ BOOST_PP_CAT(BOOST_PARAMETER_FLATTEN_SPLIT_, sub)
+
+# define BOOST_PARAMETER_FLATTEN_QUALIFIER(sub) \
+ BOOST_PP_SPLIT(0, BOOST_PARAMETER_FLATTEN_SPLIT(sub))
+
+# define BOOST_PARAMETER_FLATTEN_ARGS(sub) \
+ BOOST_PP_SPLIT(1, BOOST_PARAMETER_FLATTEN_SPLIT(sub))
+
+# define BOOST_PARAMETER_FLATTEN_ARITY_optional(arities) \
+ BOOST_PP_TUPLE_ELEM(3,0,arities)
+
+# define BOOST_PARAMETER_FLATTEN_ARITY_required(arities) \
+ BOOST_PP_TUPLE_ELEM(3,1,arities)
+
+# define BOOST_PARAMETER_FLATTEN_SPEC0_DUMMY_ELEM(z, n, data) ~
+# define BOOST_PARAMETER_FLATTEN_SPEC0(r, n, elem, data) \
+ (( \
+ BOOST_PP_TUPLE_ELEM(3,2,data) \
+ , BOOST_PP_TUPLE_REM(BOOST_PP_TUPLE_ELEM(3,0,data)) elem \
+ BOOST_PP_ENUM_TRAILING( \
+ BOOST_PP_SUB( \
+ BOOST_PP_TUPLE_ELEM(3,1,data) \
+ , BOOST_PP_TUPLE_ELEM(3,0,data) \
+ ) \
+ , BOOST_PARAMETER_FLATTEN_SPEC0_DUMMY_ELEM \
+ , ~ \
+ ) \
+ ))
+
+# define BOOST_PARAMETER_FLATTEN_SPEC_AUX(r, arity, max_arity, spec, transform) \
+ BOOST_PARAMETER_FOR_EACH_R( \
+ r \
+ , arity \
+ , BOOST_PARAMETER_FLATTEN_ARGS(spec) \
+ , (arity, max_arity, transform(BOOST_PARAMETER_FLATTEN_QUALIFIER(spec))) \
+ , BOOST_PARAMETER_FLATTEN_SPEC0 \
+ )
+
+# define BOOST_PARAMETER_FLATTEN_IDENTITY(x) x
+
+# define BOOST_PARAMETER_FLATTEN_SPEC_optional(r, arities, spec) \
+ BOOST_PARAMETER_FLATTEN_SPEC_AUX( \
+ r \
+ , BOOST_PP_CAT( \
+ BOOST_PARAMETER_FLATTEN_ARITY_, BOOST_PARAMETER_FLATTEN_QUALIFIER(spec) \
+ )(arities) \
+ , BOOST_PP_TUPLE_ELEM(3,2,arities) \
+ , spec \
+ , BOOST_PARAMETER_FLATTEN_IDENTITY \
+ )
+
+# define BOOST_PARAMETER_FLATTEN_SPEC_required(r, arities, spec) \
+ BOOST_PARAMETER_FLATTEN_SPEC_optional(r, arities, spec)
+
+# define BOOST_PARAMETER_FLATTEN_SPEC_AS_DEDUCED(x) BOOST_PP_CAT(deduced_,x)
+
+# define BOOST_PARAMETER_FLATTEN_SPEC_deduced_M(r, arities, n, spec) \
+ BOOST_PARAMETER_FLATTEN_SPEC_AUX( \
+ r \
+ , BOOST_PP_CAT( \
+ BOOST_PARAMETER_FLATTEN_ARITY_, BOOST_PARAMETER_FLATTEN_QUALIFIER(spec) \
+ )(arities) \
+ , BOOST_PP_TUPLE_ELEM(3,2,arities) \
+ , spec \
+ , BOOST_PARAMETER_FLATTEN_SPEC_AS_DEDUCED \
+ )
+
+# define BOOST_PARAMETER_FLATTEN_SPEC_deduced(r, arities, spec) \
+ BOOST_PP_SEQ_FOR_EACH_I_R( \
+ r \
+ , BOOST_PARAMETER_FLATTEN_SPEC_deduced_M \
+ , arities \
+ , BOOST_PARAMETER_FLATTEN_ARGS(spec) \
+ )
+
+# define BOOST_PARAMETER_FLATTEN_SPEC(r, arities, spec) \
+ BOOST_PP_CAT( \
+ BOOST_PARAMETER_FLATTEN_SPEC_, BOOST_PARAMETER_FLATTEN_QUALIFIER(spec) \
+ )(r, arities, spec)
+
+# define BOOST_PARAMETER_FLATTEN(optional_arity, required_arity, wanted_arity, specs) \
+ BOOST_PP_SEQ_FOR_EACH( \
+ BOOST_PARAMETER_FLATTEN_SPEC \
+ , ( \
+ optional_arity, required_arity \
+ , wanted_arity \
+ ) \
+ , specs \
+ )
+
+#endif // BOOST_PARAMETER_FLATTEN_051217_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/preprocessor/for_each.hpp b/3rdParty/Boost/src/boost/parameter/aux_/preprocessor/for_each.hpp
new file mode 100755
index 0000000..0eb1f70
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/preprocessor/for_each.hpp
@@ -0,0 +1,103 @@
+// Copyright Daniel Wallin 2005. Use, modification and distribution is
+// subject to the Boost Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_PARAMETER_FOR_EACH_051217_HPP
+# define BOOST_PARAMETER_FOR_EACH_051217_HPP
+
+# include <boost/preprocessor/cat.hpp>
+# include <boost/preprocessor/detail/split.hpp>
+# include <boost/preprocessor/logical/not.hpp>
+# include <boost/preprocessor/facilities/is_empty.hpp>
+# include <boost/preprocessor/tuple/eat.hpp>
+# include <boost/preprocessor/arithmetic/inc.hpp>
+# include <boost/preprocessor/repeat.hpp>
+# include <boost/preprocessor/punctuation/comma_if.hpp>
+# include <boost/preprocessor/for.hpp>
+# include <boost/preprocessor/repetition/deduce_r.hpp>
+
+# define BOOST_PARAMETER_FOR_EACH_head_aux2(x,y) (x,y), ~
+# define BOOST_PARAMETER_FOR_EACH_head_aux3(x,y,z) (x,y,z), ~
+# define BOOST_PARAMETER_FOR_EACH_head_aux4(x,y,z,u) (x,y,z,u), ~
+# define BOOST_PARAMETER_FOR_EACH_head(n,x) \
+ BOOST_PP_SPLIT(0, BOOST_PP_CAT(BOOST_PARAMETER_FOR_EACH_head_aux,n) x)
+
+# define BOOST_PARAMETER_FOR_EACH_pred_aux_BOOST_PARAMETER_FOR_EACH_END_SENTINEL
+# define BOOST_PARAMETER_FOR_EACH_pred_aux_check(x) \
+ BOOST_PP_NOT(BOOST_PP_IS_EMPTY( \
+ BOOST_PP_CAT(BOOST_PARAMETER_FOR_EACH_pred_aux_, x) \
+ )), ~
+
+# define BOOST_PARAMETER_FOR_EACH_pred_aux2(x,y) \
+ BOOST_PARAMETER_FOR_EACH_pred_aux_check(x)
+# define BOOST_PARAMETER_FOR_EACH_pred_aux3(x,y,z) \
+ BOOST_PARAMETER_FOR_EACH_pred_aux_check(x)
+# define BOOST_PARAMETER_FOR_EACH_pred_aux4(x,y,z,u) \
+ BOOST_PARAMETER_FOR_EACH_pred_aux_check(x)
+
+# define BOOST_PARAMETER_FOR_EACH_pred_aux0(n,x) \
+ BOOST_PP_CAT(BOOST_PARAMETER_FOR_EACH_pred_aux,n) x
+
+# if BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_MSVC()
+# define BOOST_PARAMETER_FOR_EACH_pred_SPLIT_FIRST(x) \
+ BOOST_PP_SPLIT(0, x)
+
+# define BOOST_PARAMETER_FOR_EACH_pred(r, state) \
+ BOOST_PARAMETER_FOR_EACH_pred_SPLIT_FIRST( \
+ BOOST_PARAMETER_FOR_EACH_pred_aux0( \
+ BOOST_PP_TUPLE_ELEM(5,3,state) \
+ , BOOST_PP_TUPLE_ELEM(5,0,state) \
+ ) \
+ )
+# else
+# define BOOST_PARAMETER_FOR_EACH_pred(r, state) \
+ BOOST_PP_SPLIT( \
+ 0 \
+ , BOOST_PARAMETER_FOR_EACH_pred_aux0( \
+ BOOST_PP_TUPLE_ELEM(5,3,state) \
+ , BOOST_PP_TUPLE_ELEM(5,0,state) \
+ ) \
+ )
+# endif
+
+# define BOOST_PARAMETER_FOR_EACH_op(r, state) \
+ ( \
+ BOOST_PP_TUPLE_EAT(BOOST_PP_TUPLE_ELEM(5,3,state)) \
+ BOOST_PP_TUPLE_ELEM(5,0,state) \
+ , BOOST_PP_TUPLE_ELEM(5,1,state) \
+ , BOOST_PP_TUPLE_ELEM(5,2,state) \
+ , BOOST_PP_TUPLE_ELEM(5,3,state) \
+ , BOOST_PP_INC(BOOST_PP_TUPLE_ELEM(5,4,state)) \
+ )
+
+# define BOOST_PARAMETER_FOR_EACH_macro(r, state) \
+ BOOST_PP_TUPLE_ELEM(5,2,state)( \
+ r \
+ , BOOST_PP_TUPLE_ELEM(5,4,state) \
+ , BOOST_PARAMETER_FOR_EACH_head( \
+ BOOST_PP_TUPLE_ELEM(5,3,state) \
+ , BOOST_PP_TUPLE_ELEM(5,0,state) \
+ ) \
+ , BOOST_PP_TUPLE_ELEM(5,1,state) \
+ )
+
+# define BOOST_PARAMETER_FOR_EACH_build_end_sentinel(z,n,text) \
+ BOOST_PP_COMMA_IF(n) BOOST_PARAMETER_FOR_EACH_END_SENTINEL
+# define BOOST_PARAMETER_FOR_EACH_build_end_sentinel_tuple(arity) \
+ ( \
+ BOOST_PP_REPEAT(arity, BOOST_PARAMETER_FOR_EACH_build_end_sentinel, _) \
+ )
+
+# define BOOST_PARAMETER_FOR_EACH_R(r, arity, list, data, macro) \
+ BOOST_PP_CAT(BOOST_PP_FOR_, r)( \
+ (list BOOST_PARAMETER_FOR_EACH_build_end_sentinel_tuple(arity), data, macro, arity, 0) \
+ , BOOST_PARAMETER_FOR_EACH_pred \
+ , BOOST_PARAMETER_FOR_EACH_op \
+ , BOOST_PARAMETER_FOR_EACH_macro \
+ )
+
+# define BOOST_PARAMETER_FOR_EACH(arity, list, data, macro) \
+ BOOST_PARAMETER_FOR_EACH_R(BOOST_PP_DEDUCE_R(), arity, list, data, macro)
+
+#endif // BOOST_PARAMETER_FOR_EACH_051217_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/result_of0.hpp b/3rdParty/Boost/src/boost/parameter/aux_/result_of0.hpp
new file mode 100755
index 0000000..e009614
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/result_of0.hpp
@@ -0,0 +1,36 @@
+// Copyright David Abrahams 2005. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+#ifndef BOOST_PARAMETER_AUX_RESULT_OF0_DWA2005511_HPP
+# define BOOST_PARAMETER_AUX_RESULT_OF0_DWA2005511_HPP
+
+# include <boost/utility/result_of.hpp>
+
+// A metafunction returning the result of invoking a nullary function
+// object of the given type.
+
+#ifndef BOOST_NO_RESULT_OF
+
+# include <boost/utility/result_of.hpp>
+namespace boost { namespace parameter { namespace aux {
+template <class F>
+struct result_of0 : result_of<F()>
+{};
+
+}}} // namespace boost::parameter::aux_
+
+#else
+
+namespace boost { namespace parameter { namespace aux {
+template <class F>
+struct result_of0
+{
+ typedef typename F::result_type type;
+};
+
+}}} // namespace boost::parameter::aux_
+
+#endif
+
+
+#endif // BOOST_PARAMETER_AUX_RESULT_OF0_DWA2005511_HPP
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/set.hpp b/3rdParty/Boost/src/boost/parameter/aux_/set.hpp
new file mode 100644
index 0000000..1c4ccf5
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/set.hpp
@@ -0,0 +1,67 @@
+// Copyright Daniel Wallin 2006. Use, modification and distribution is
+// subject to the Boost Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_PARAMETER_SET_060912_HPP
+# define BOOST_PARAMETER_SET_060912_HPP
+
+# include <boost/detail/workaround.hpp>
+
+# if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) \
+ && !BOOST_WORKAROUND(__GNUC__, < 3)
+# include <boost/mpl/insert.hpp>
+# include <boost/mpl/set/set0.hpp>
+# include <boost/mpl/has_key.hpp>
+
+namespace boost { namespace parameter { namespace aux {
+
+typedef mpl::set0<> set0;
+
+template <class Set, class K>
+struct insert_
+{
+ typedef typename mpl::insert<Set, K>::type type;
+};
+
+template <class Set, class K>
+struct has_key_
+{
+ typedef typename mpl::has_key<Set, K>::type type;
+};
+
+}}} // namespace boost::parameter::aux
+
+# else
+
+# include <boost/mpl/list.hpp>
+# include <boost/mpl/end.hpp>
+# include <boost/mpl/find.hpp>
+# include <boost/mpl/not.hpp>
+# include <boost/mpl/push_front.hpp>
+
+namespace boost { namespace parameter { namespace aux {
+
+typedef mpl::list0<> set0;
+
+template <class Set, class K>
+struct insert_
+{
+ typedef typename mpl::push_front<Set, K>::type type;
+};
+
+template <class Set, class K>
+struct has_key_
+{
+ typedef typename mpl::find<Set, K>::type iter;
+ typedef mpl::not_<
+ is_same<iter, typename mpl::end<Set>::type>
+ > type;
+};
+
+}}} // namespace boost::parameter::aux
+
+# endif
+
+
+#endif // BOOST_PARAMETER_SET_060912_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/tag.hpp b/3rdParty/Boost/src/boost/parameter/aux_/tag.hpp
new file mode 100755
index 0000000..475efb9
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/tag.hpp
@@ -0,0 +1,38 @@
+// Copyright David Abrahams 2005. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+#ifndef BOOST_PARAMETER_AUX_TAG_DWA2005610_HPP
+# define BOOST_PARAMETER_AUX_TAG_DWA2005610_HPP
+
+# include <boost/parameter/aux_/unwrap_cv_reference.hpp>
+# include <boost/parameter/aux_/tagged_argument.hpp>
+
+namespace boost { namespace parameter { namespace aux {
+
+template <class Keyword, class ActualArg
+#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+ , class = typename is_cv_reference_wrapper<ActualArg>::type
+#endif
+ >
+struct tag
+{
+ typedef tagged_argument<
+ Keyword
+ , typename unwrap_cv_reference<ActualArg>::type
+ > type;
+};
+
+#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+template <class Keyword, class ActualArg>
+struct tag<Keyword,ActualArg,mpl::false_>
+{
+ typedef tagged_argument<
+ Keyword
+ , ActualArg
+ > type;
+};
+#endif
+
+}}} // namespace boost::parameter::aux_
+
+#endif // BOOST_PARAMETER_AUX_TAG_DWA2005610_HPP
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/tagged_argument.hpp b/3rdParty/Boost/src/boost/parameter/aux_/tagged_argument.hpp
new file mode 100644
index 0000000..6248be2
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/tagged_argument.hpp
@@ -0,0 +1,188 @@
+// Copyright Daniel Wallin, David Abrahams 2005. Use, modification and
+// distribution is subject to the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_PARAMETER_TAGGED_ARGUMENT_050328_HPP
+# define BOOST_PARAMETER_TAGGED_ARGUMENT_050328_HPP
+
+# include <boost/parameter/aux_/void.hpp>
+# include <boost/parameter/aux_/arg_list.hpp>
+# include <boost/parameter/aux_/result_of0.hpp>
+# include <boost/mpl/if.hpp>
+# include <boost/mpl/apply_wrap.hpp>
+# include <boost/mpl/and.hpp>
+# include <boost/mpl/not.hpp>
+# include <boost/type_traits/is_same.hpp>
+# include <boost/type_traits/is_convertible.hpp>
+# include <boost/type_traits/is_reference.hpp>
+
+namespace boost { namespace parameter { namespace aux {
+
+struct empty_arg_list;
+struct arg_list_tag;
+
+struct tagged_argument_base {};
+
+// Holds a reference to an argument of type Arg associated with
+// keyword Keyword
+
+template <class Keyword, class Arg>
+struct tagged_argument : tagged_argument_base
+{
+ typedef Keyword key_type;
+ typedef Arg value_type;
+ typedef Arg& reference;
+
+ tagged_argument(reference x) : value(x) {}
+
+ // A metafunction class that, given a keyword and a default
+ // type, returns the appropriate result type for a keyword
+ // lookup given that default
+ struct binding
+ {
+ template <class KW, class Default, class Reference>
+ struct apply
+ {
+ typedef typename mpl::eval_if<
+ boost::is_same<KW, key_type>
+ , mpl::if_<Reference, reference, value_type>
+ , mpl::identity<Default>
+ >::type type;
+ };
+ };
+
+ // Comma operator to compose argument list without using parameters<>.
+ // Useful for argument lists with undetermined length.
+ template <class Keyword2, class Arg2>
+ arg_list<
+ tagged_argument<Keyword, Arg>
+ , arg_list<tagged_argument<Keyword2, Arg2> >
+ >
+ operator,(tagged_argument<Keyword2, Arg2> x) const
+ {
+ return arg_list<
+ tagged_argument<Keyword, Arg>
+ , arg_list<tagged_argument<Keyword2, Arg2> >
+ >(
+ *this
+ , arg_list<tagged_argument<Keyword2, Arg2> >(x, empty_arg_list())
+ );
+ }
+
+ reference operator[](keyword<Keyword> const&) const
+ {
+ return value;
+ }
+
+# if defined(BOOST_NO_FUNCTION_TEMPLATE_ORDERING) || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+ template <class KW, class Default>
+ Default& get_with_default(default_<KW,Default> const& x, int) const
+ {
+ return x.value;
+ }
+
+ template <class Default>
+ reference get_with_default(default_<key_type,Default> const&, long) const
+ {
+ return value;
+ }
+
+ template <class KW, class Default>
+ typename mpl::apply_wrap3<binding, KW, Default&, mpl::true_>::type
+ operator[](default_<KW,Default> const& x) const
+ {
+ return get_with_default(x, 0L);
+ }
+
+ template <class KW, class F>
+ typename result_of0<F>::type
+ get_with_lazy_default(lazy_default<KW,F> const& x, int) const
+ {
+ return x.compute_default();
+ }
+
+ template <class F>
+ reference get_with_lazy_default(lazy_default<key_type,F> const&, long) const
+ {
+ return value;
+ }
+
+ template <class KW, class F>
+ typename mpl::apply_wrap3<
+ binding,KW
+ , typename result_of0<F>::type
+ , mpl::true_
+ >::type
+ operator[](lazy_default<KW,F> const& x) const
+ {
+ return get_with_lazy_default(x, 0L);
+ }
+# else
+ template <class Default>
+ reference operator[](default_<key_type,Default> const& x) const
+ {
+ return value;
+ }
+
+ template <class F>
+ reference operator[](lazy_default<key_type,F> const& x) const
+ {
+ return value;
+ }
+
+ template <class KW, class Default>
+ Default& operator[](default_<KW,Default> const& x) const
+ {
+ return x.value;
+ }
+
+ template <class KW, class F>
+ typename result_of0<F>::type operator[](lazy_default<KW,F> const& x) const
+ {
+ return x.compute_default();
+ }
+
+ template <class ParameterRequirements>
+ static typename ParameterRequirements::has_default
+ satisfies(ParameterRequirements*);
+
+ template <class HasDefault, class Predicate>
+ static typename mpl::apply1<Predicate, value_type>::type
+ satisfies(
+ parameter_requirements<key_type,Predicate,HasDefault>*
+ );
+# endif
+
+ reference value;
+# if BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1310))
+ // warning suppression
+ private:
+ void operator=(tagged_argument const&);
+ public:
+# endif
+ // MPL sequence support
+ typedef tagged_argument type; // Convenience for users
+ typedef empty_arg_list tail_type; // For the benefit of iterators
+ typedef arg_list_tag tag; // For dispatching to sequence intrinsics
+};
+
+// Defines a metafunction, is_tagged_argument, that identifies
+// tagged_argument specializations and their derived classes.
+template <class T>
+struct is_tagged_argument_aux
+ : is_convertible<T*,tagged_argument_base const*>
+{};
+
+template <class T>
+struct is_tagged_argument
+ : mpl::and_<
+ mpl::not_<is_reference<T> >
+ , is_tagged_argument_aux<T>
+ >
+{};
+
+}}} // namespace boost::parameter::aux
+
+#endif // BOOST_PARAMETER_TAGGED_ARGUMENT_050328_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/template_keyword.hpp b/3rdParty/Boost/src/boost/parameter/aux_/template_keyword.hpp
new file mode 100755
index 0000000..5a02f00
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/template_keyword.hpp
@@ -0,0 +1,47 @@
+// Copyright Daniel Wallin 2006. Use, modification and distribution is
+// subject to the Boost Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_PARAMETER_TEMPLATE_KEYWORD_060203_HPP
+# define BOOST_PARAMETER_TEMPLATE_KEYWORD_060203_HPP
+
+# include <boost/mpl/and.hpp>
+# include <boost/mpl/not.hpp>
+# include <boost/type_traits/is_convertible.hpp>
+# include <boost/type_traits/is_reference.hpp>
+
+namespace boost { namespace parameter {
+
+namespace aux
+{
+
+ struct template_keyword_tag {};
+
+ template <class T, class U>
+ struct is_pointer_convertible
+ : is_convertible<T*, U*>
+ {};
+
+ template <class T>
+ struct is_template_keyword
+ : mpl::and_<
+ mpl::not_<is_reference<T> >
+ , is_pointer_convertible<T, template_keyword_tag>
+ >
+ {};
+
+} // namespace aux
+
+template <class Tag, class T>
+struct template_keyword
+ : aux::template_keyword_tag
+{
+ typedef Tag key_type;
+ typedef T value_type;
+ typedef value_type reference;
+};
+
+}} // namespace boost::parameter
+
+#endif // BOOST_PARAMETER_TEMPLATE_KEYWORD_060203_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/unwrap_cv_reference.hpp b/3rdParty/Boost/src/boost/parameter/aux_/unwrap_cv_reference.hpp
new file mode 100755
index 0000000..e7aa0c1
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/unwrap_cv_reference.hpp
@@ -0,0 +1,97 @@
+// Copyright Daniel Wallin, David Abrahams 2005. Use, modification and
+// distribution is subject to the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef UNWRAP_CV_REFERENCE_050328_HPP
+#define UNWRAP_CV_REFERENCE_050328_HPP
+
+#include <boost/parameter/aux_/yesno.hpp>
+#include <boost/mpl/bool.hpp>
+#include <boost/mpl/identity.hpp>
+#include <boost/mpl/eval_if.hpp>
+
+namespace boost { template<class T> class reference_wrapper; }
+
+namespace boost { namespace parameter { namespace aux {
+
+//
+// reference_wrapper support -- because of the forwarding problem,
+// when passing arguments positionally by non-const reference, we
+// ask users of named parameter interfaces to use ref(x) to wrap
+// them.
+//
+
+// is_cv_reference_wrapper returns mpl::true_ if T is of type
+// reference_wrapper<U> cv
+template <class U>
+yes_tag is_cv_reference_wrapper_check(reference_wrapper<U> const volatile*);
+no_tag is_cv_reference_wrapper_check(...);
+
+template <class T>
+struct is_cv_reference_wrapper
+{
+ BOOST_STATIC_CONSTANT(
+ bool, value = (
+ sizeof(is_cv_reference_wrapper_check((T*)0)) == sizeof(yes_tag)
+ )
+ );
+
+ typedef mpl::bool_<
+#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+ is_cv_reference_wrapper::
+#endif
+ value> type;
+};
+
+#if BOOST_WORKAROUND(MSVC, == 1200)
+template <>
+struct is_cv_reference_wrapper<int>
+ : mpl::false_ {};
+#endif
+
+// Needed for unwrap_cv_reference below. T might be const, so
+// eval_if might fail because of deriving from T const on EDG.
+template <class T>
+struct get_type
+{
+ typedef typename T::type type;
+};
+
+#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+template <class T, class is_reference_wrapper = typename is_cv_reference_wrapper<T>::type>
+struct unwrap_cv_reference
+{
+ typedef T type;
+};
+
+template <class T>
+struct unwrap_cv_reference<T const, mpl::false_>
+{
+ typedef T const type;
+};
+
+template <class T>
+struct unwrap_cv_reference<T, mpl::true_>
+ : T
+{};
+
+#else
+// Produces the unwrapped type to hold a reference to in named<>
+// Can't use boost::unwrap_reference<> here because it
+// doesn't handle the case where T = reference_wrapper<U> cv
+template <class T>
+struct unwrap_cv_reference
+{
+ typedef typename mpl::eval_if<
+ is_cv_reference_wrapper<T>
+ , get_type<T>
+ , mpl::identity<T>
+ >::type type;
+};
+#endif
+
+}}} // namespace boost::parameter::aux
+
+#endif // UNWRAP_CV_REFERENCE_050328_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/void.hpp b/3rdParty/Boost/src/boost/parameter/aux_/void.hpp
new file mode 100755
index 0000000..7061a7d
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/void.hpp
@@ -0,0 +1,29 @@
+// Copyright Daniel Wallin, David Abrahams 2005. Use, modification and
+// distribution is subject to the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_PARAMETER_VOID_050329_HPP
+#define BOOST_PARAMETER_VOID_050329_HPP
+
+namespace boost { namespace parameter {
+
+// A placemarker for "no argument passed."
+// MAINTAINER NOTE: Do not make this into a metafunction
+struct void_ {};
+
+namespace aux
+{
+
+ inline void_& void_reference()
+ {
+ static void_ instance;
+ return instance;
+ }
+
+} // namespace aux
+
+}} // namespace boost::parameter
+
+#endif // BOOST_PARAMETER_VOID_050329_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/aux_/yesno.hpp b/3rdParty/Boost/src/boost/parameter/aux_/yesno.hpp
new file mode 100755
index 0000000..13fa545
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/aux_/yesno.hpp
@@ -0,0 +1,26 @@
+// Copyright Daniel Wallin, David Abrahams 2005. Use, modification and
+// distribution is subject to the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef YESNO_050328_HPP
+#define YESNO_050328_HPP
+
+#include <boost/mpl/bool.hpp>
+
+namespace boost { namespace parameter { namespace aux {
+
+// types used with the "sizeof trick" to capture the results of
+// overload resolution at compile-time.
+typedef char yes_tag;
+typedef char (&no_tag)[2];
+
+// mpl::true_ and mpl::false_ are not distinguishable by sizeof(),
+// so we pass them through these functions to get a type that is.
+yes_tag to_yesno(mpl::true_);
+no_tag to_yesno(mpl::false_);
+
+}}} // namespace boost::parameter::aux
+
+#endif // YESNO_050328_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/binding.hpp b/3rdParty/Boost/src/boost/parameter/binding.hpp
new file mode 100755
index 0000000..632f0fd
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/binding.hpp
@@ -0,0 +1,106 @@
+// Copyright David Abrahams 2005. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+#ifndef BOOST_PARAMETER_BINDING_DWA200558_HPP
+# define BOOST_PARAMETER_BINDING_DWA200558_HPP
+
+# include <boost/mpl/apply.hpp>
+# include <boost/mpl/assert.hpp>
+# include <boost/mpl/and.hpp>
+# include <boost/parameter/aux_/result_of0.hpp>
+# include <boost/parameter/aux_/void.hpp>
+# include <boost/type_traits/is_same.hpp>
+
+# if BOOST_WORKAROUND(BOOST_MSVC, < 1300)
+# include <boost/mpl/eval_if.hpp>
+# endif
+
+namespace boost { namespace parameter {
+
+// A metafunction that, given an argument pack, returns the type of
+// the parameter identified by the given keyword. If no such
+// parameter has been specified, returns Default
+
+# if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) \
+ || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+template <class Parameters, class Keyword, class Default>
+struct binding0
+{
+ typedef typename mpl::apply_wrap3<
+ typename Parameters::binding,Keyword,Default,mpl::true_
+ >::type type;
+
+ BOOST_MPL_ASSERT_NOT((
+ mpl::and_<
+ is_same<Default, void_>
+ , is_same<type, void_>
+ >
+ ));
+};
+# endif
+
+template <class Parameters, class Keyword, class Default = void_>
+# if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)
+struct binding
+# else
+struct binding_eti
+# endif
+{
+# if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) \
+ || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+ typedef typename mpl::eval_if<
+ mpl::is_placeholder<Parameters>
+ , mpl::identity<int>
+ , binding0<Parameters,Keyword,Default>
+ >::type type;
+# else
+ typedef typename mpl::apply_wrap3<
+ typename Parameters::binding,Keyword,Default,mpl::true_
+ >::type type;
+
+ BOOST_MPL_ASSERT_NOT((
+ mpl::and_<
+ is_same<Default, void_>
+ , is_same<type, void_>
+ >
+ ));
+# endif
+
+# if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)
+ BOOST_MPL_AUX_LAMBDA_SUPPORT(3,binding,(Parameters,Keyword,Default))
+# endif
+};
+
+# if BOOST_WORKAROUND(BOOST_MSVC, < 1300)
+template <class Parameters, class Keyword, class Default = void_>
+struct binding
+{
+ typedef typename mpl::eval_if<
+ is_same<Parameters, int>
+ , mpl::identity<int>
+ , binding_eti<Parameters, Keyword, Default>
+ >::type type;
+
+ BOOST_MPL_AUX_LAMBDA_SUPPORT(3,binding,(Parameters,Keyword,Default))
+};
+# endif
+
+// A metafunction that, given an argument pack, returns the type of
+// the parameter identified by the given keyword. If no such
+// parameter has been specified, returns the type returned by invoking
+// DefaultFn
+template <class Parameters, class Keyword, class DefaultFn>
+struct lazy_binding
+{
+ typedef typename mpl::apply_wrap3<
+ typename Parameters::binding
+ , Keyword
+ , typename aux::result_of0<DefaultFn>::type
+ , mpl::true_
+ >::type type;
+};
+
+
+}} // namespace boost::parameter
+
+#endif // BOOST_PARAMETER_BINDING_DWA200558_HPP
diff --git a/3rdParty/Boost/src/boost/parameter/config.hpp b/3rdParty/Boost/src/boost/parameter/config.hpp
new file mode 100644
index 0000000..5710c92
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/config.hpp
@@ -0,0 +1,14 @@
+// Copyright Daniel Wallin, David Abrahams 2005. Use, modification and
+// distribution is subject to the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_PARAMETER_CONFIG_050403_HPP
+#define BOOST_PARAMETER_CONFIG_050403_HPP
+
+#ifndef BOOST_PARAMETER_MAX_ARITY
+# define BOOST_PARAMETER_MAX_ARITY 8
+#endif
+
+#endif // BOOST_PARAMETER_CONFIG_050403_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/keyword.hpp b/3rdParty/Boost/src/boost/parameter/keyword.hpp
new file mode 100755
index 0000000..cfb4bfd
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/keyword.hpp
@@ -0,0 +1,152 @@
+// Copyright Daniel Wallin, David Abrahams 2005. Use, modification and
+// distribution is subject to the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef KEYWORD_050328_HPP
+#define KEYWORD_050328_HPP
+
+#include <boost/parameter/aux_/unwrap_cv_reference.hpp>
+#include <boost/parameter/aux_/tag.hpp>
+#include <boost/parameter/aux_/default.hpp>
+
+namespace boost { namespace parameter {
+
+// Instances of unique specializations of keyword<...> serve to
+// associate arguments with parameter names. For example:
+//
+// struct rate_; // parameter names
+// struct skew_;
+// namespace
+// {
+// keyword<rate_> rate; // keywords
+// keyword<skew_> skew;
+// }
+//
+// ...
+//
+// f(rate = 1, skew = 2.4);
+//
+template <class Tag>
+struct keyword
+{
+ template <class T>
+ typename aux::tag<Tag, T>::type const
+ operator=(T& x) const
+ {
+ typedef typename aux::tag<Tag, T>::type result;
+ return result(x);
+ }
+
+ template <class Default>
+ aux::default_<Tag, Default>
+ operator|(Default& default_) const
+ {
+ return aux::default_<Tag, Default>(default_);
+ }
+
+ template <class Default>
+ aux::lazy_default<Tag, Default>
+ operator||(Default& default_) const
+ {
+ return aux::lazy_default<Tag, Default>(default_);
+ }
+
+#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300) // avoid partial ordering bugs
+ template <class T>
+ typename aux::tag<Tag, T const>::type const
+ operator=(T const& x) const
+ {
+ typedef typename aux::tag<Tag, T const>::type result;
+ return result(x);
+ }
+#endif
+
+#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300) // avoid partial ordering bugs
+ template <class Default>
+ aux::default_<Tag, const Default>
+ operator|(const Default& default_) const
+#if BOOST_WORKAROUND(BOOST_MSVC, == 1300)
+ volatile
+#endif
+ {
+ return aux::default_<Tag, const Default>(default_);
+ }
+
+ template <class Default>
+ aux::lazy_default<Tag, Default>
+ operator||(Default const& default_) const
+#if BOOST_WORKAROUND(BOOST_MSVC, == 1300)
+ volatile
+#endif
+ {
+ return aux::lazy_default<Tag, Default>(default_);
+ }
+#endif
+
+ public: // Insurance against ODR violations
+
+ // People will need to define these keywords in header files. To
+ // prevent ODR violations, it's important that the keyword used in
+ // every instantiation of a function template is the same object.
+ // We provide a reference to a common instance of each keyword
+ // object and prevent construction by users.
+ static keyword<Tag> const instance;
+
+ // This interface is deprecated
+ static keyword<Tag>& get()
+ {
+ return const_cast<keyword<Tag>&>(instance);
+ }
+};
+
+template <class Tag>
+keyword<Tag> const keyword<Tag>::instance = {};
+
+// Reduces boilerplate required to declare and initialize keywords
+// without violating ODR. Declares a keyword tag type with the given
+// name in namespace tag_namespace, and declares and initializes a
+// reference in an anonymous namespace to a singleton instance of that
+// type.
+
+#if BOOST_WORKAROUND(BOOST_MSVC, < 1300)
+
+# define BOOST_PARAMETER_KEYWORD(tag_namespace,name) \
+ namespace tag_namespace \
+ { \
+ struct name \
+ { \
+ static char const* keyword_name() \
+ { \
+ return #name; \
+ } \
+ }; \
+ } \
+ static ::boost::parameter::keyword<tag_namespace::name> const& name \
+ = ::boost::parameter::keyword<tag_namespace::name>::instance;
+
+#else
+
+#define BOOST_PARAMETER_KEYWORD(tag_namespace,name) \
+ namespace tag_namespace \
+ { \
+ struct name \
+ { \
+ static char const* keyword_name() \
+ { \
+ return #name; \
+ } \
+ }; \
+ } \
+ namespace \
+ { \
+ ::boost::parameter::keyword<tag_namespace::name> const& name \
+ = ::boost::parameter::keyword<tag_namespace::name>::instance;\
+ }
+
+#endif
+
+}} // namespace boost::parameter
+
+#endif // KEYWORD_050328_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/macros.hpp b/3rdParty/Boost/src/boost/parameter/macros.hpp
new file mode 100644
index 0000000..83fbfb5
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/macros.hpp
@@ -0,0 +1,99 @@
+// Copyright David Abrahams, Daniel Wallin 2003. Use, modification and
+// distribution is subject to the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_PARAMETER_MACROS_050412_HPP
+#define BOOST_PARAMETER_MACROS_050412_HPP
+
+#include <boost/preprocessor/tuple/elem.hpp>
+#include <boost/preprocessor/repetition/repeat_from_to.hpp>
+#include <boost/preprocessor/arithmetic/inc.hpp>
+#include <boost/preprocessor/logical/bool.hpp>
+#include <boost/preprocessor/punctuation/comma_if.hpp>
+#include <boost/preprocessor/control/expr_if.hpp>
+#include <boost/preprocessor/repetition/enum_params.hpp>
+#include <boost/preprocessor/repetition/enum_binary_params.hpp>
+#include <boost/preprocessor/cat.hpp>
+#include <boost/detail/workaround.hpp>
+
+#define BOOST_PARAMETER_FUN_TEMPLATE_HEAD1(n) \
+ template<BOOST_PP_ENUM_PARAMS(n, class T)>
+
+#define BOOST_PARAMETER_FUN_TEMPLATE_HEAD0(n)
+
+#if ! defined(BOOST_NO_SFINAE) && ! BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x592))
+
+# define BOOST_PARAMETER_MATCH_TYPE(n, param) \
+ BOOST_PP_EXPR_IF(n, typename) param::match \
+ < \
+ BOOST_PP_ENUM_PARAMS(n, T) \
+ >::type
+
+#else
+
+# define BOOST_PARAMETER_MATCH_TYPE(n, param) param
+
+#endif
+
+#define BOOST_PARAMETER_FUN_DECL(z, n, params) \
+ \
+ BOOST_PP_CAT(BOOST_PARAMETER_FUN_TEMPLATE_HEAD, BOOST_PP_BOOL(n))(n) \
+ \
+ BOOST_PP_TUPLE_ELEM(3, 0, params) \
+ BOOST_PP_TUPLE_ELEM(3, 1, params)( \
+ BOOST_PP_ENUM_BINARY_PARAMS(n, T, const& p) \
+ BOOST_PP_COMMA_IF(n) \
+ BOOST_PARAMETER_MATCH_TYPE(n,BOOST_PP_TUPLE_ELEM(3, 2, params)) \
+ kw = BOOST_PP_TUPLE_ELEM(3, 2, params)() \
+ ) \
+ { \
+ return BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(3, 1, params), _with_named_params)( \
+ kw(BOOST_PP_ENUM_PARAMS(n, p)) \
+ ); \
+ }
+
+// Generates:
+//
+// template<class Params>
+// ret name ## _with_named_params(Params const&);
+//
+// template<class T0>
+// ret name(T0 const& p0, typename parameters::match<T0>::type kw = parameters())
+// {
+// return name ## _with_named_params(kw(p0));
+// }
+//
+// template<class T0, ..., class TN>
+// ret name(T0 const& p0, ..., TN const& PN
+// , typename parameters::match<T0, ..., TN>::type kw = parameters())
+// {
+// return name ## _with_named_params(kw(p0, ..., pN));
+// }
+//
+// template<class Params>
+// ret name ## _with_named_params(Params const&)
+//
+// lo and hi determines the min and max arity of the generated functions.
+
+#define BOOST_PARAMETER_FUN(ret, name, lo, hi, parameters) \
+ \
+ template<class Params> \
+ ret BOOST_PP_CAT(name, _with_named_params)(Params const& p); \
+ \
+ BOOST_PP_REPEAT_FROM_TO( \
+ lo, BOOST_PP_INC(hi), BOOST_PARAMETER_FUN_DECL, (ret, name, parameters)) \
+ \
+ template<class Params> \
+ ret BOOST_PP_CAT(name, _with_named_params)(Params const& p)
+
+#define BOOST_PARAMETER_MEMFUN(ret, name, lo, hi, parameters) \
+ \
+ BOOST_PP_REPEAT_FROM_TO( \
+ lo, BOOST_PP_INC(hi), BOOST_PARAMETER_FUN_DECL, (ret, name, parameters)) \
+ \
+ template<class Params> \
+ ret BOOST_PP_CAT(name, _with_named_params)(Params const& p)
+
+#endif // BOOST_PARAMETER_MACROS_050412_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/match.hpp b/3rdParty/Boost/src/boost/parameter/match.hpp
new file mode 100755
index 0000000..2fa3f17
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/match.hpp
@@ -0,0 +1,55 @@
+// Copyright David Abrahams 2005. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+#ifndef BOOST_PARAMETER_MATCH_DWA2005714_HPP
+# define BOOST_PARAMETER_MATCH_DWA2005714_HPP
+
+# include <boost/detail/workaround.hpp>
+# include <boost/preprocessor/seq/enum.hpp>
+
+# if BOOST_WORKAROUND(__MWERKS__, <= 0x3003)
+// Temporary version of BOOST_PP_SEQ_ENUM until Paul M. integrates the workaround.
+# define BOOST_PARAMETER_SEQ_ENUM_I(size,seq) BOOST_PP_CAT(BOOST_PP_SEQ_ENUM_, size) seq
+# define BOOST_PARAMETER_SEQ_ENUM(seq) BOOST_PARAMETER_SEQ_ENUM_I(BOOST_PP_SEQ_SIZE(seq), seq)
+# else
+# define BOOST_PARAMETER_SEQ_ENUM(seq) BOOST_PP_SEQ_ENUM(seq)
+# endif
+
+# if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+
+# include <boost/parameter/config.hpp>
+# include <boost/parameter/aux_/void.hpp>
+# include <boost/preprocessor/arithmetic/sub.hpp>
+# include <boost/preprocessor/facilities/intercept.hpp>
+# include <boost/preprocessor/repetition/enum_trailing_params.hpp>
+
+# define BOOST_PARAMETER_MATCH_DEFAULTS(ArgTypes) \
+ BOOST_PP_ENUM_TRAILING_PARAMS( \
+ BOOST_PP_SUB( \
+ BOOST_PARAMETER_MAX_ARITY \
+ , BOOST_PP_SEQ_SIZE(ArgTypes) \
+ ) \
+ , ::boost::parameter::void_ BOOST_PP_INTERCEPT \
+ )
+
+# else
+
+# define BOOST_PARAMETER_MATCH_DEFAULTS(ArgTypes)
+
+# endif
+
+//
+// Generates, e.g.
+//
+// typename dfs_params::match<A1,A2>::type name = dfs_params()
+//
+// with workarounds for Borland compatibility.
+//
+
+# define BOOST_PARAMETER_MATCH(ParameterSpec, ArgTypes, name) \
+ typename ParameterSpec ::match< \
+ BOOST_PARAMETER_SEQ_ENUM(ArgTypes) \
+ BOOST_PARAMETER_MATCH_DEFAULTS(ArgTypes) \
+ >::type name = ParameterSpec ()
+
+#endif // BOOST_PARAMETER_MATCH_DWA2005714_HPP
diff --git a/3rdParty/Boost/src/boost/parameter/name.hpp b/3rdParty/Boost/src/boost/parameter/name.hpp
new file mode 100644
index 0000000..7352616
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/name.hpp
@@ -0,0 +1,156 @@
+// Copyright Daniel Wallin 2006. Use, modification and distribution is
+// subject to the Boost Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_PARAMETER_NAME_060806_HPP
+# define BOOST_PARAMETER_NAME_060806_HPP
+
+# include <boost/parameter/keyword.hpp>
+# include <boost/parameter/value_type.hpp>
+# include <boost/detail/workaround.hpp>
+# include <boost/preprocessor/cat.hpp>
+# include <boost/preprocessor/stringize.hpp>
+# include <boost/preprocessor/control/iif.hpp>
+# include <boost/preprocessor/tuple/eat.hpp>
+# include <boost/preprocessor/tuple/elem.hpp>
+# include <boost/mpl/placeholders.hpp>
+
+# if !defined(BOOST_NO_SFINAE) \
+ && !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \
+ && !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x592))
+
+# include <boost/utility/enable_if.hpp>
+# include <boost/mpl/lambda.hpp>
+
+namespace boost { namespace parameter { namespace aux {
+
+// Tag type passed to MPL lambda.
+struct lambda_tag;
+
+struct name_tag_base
+{};
+
+template <class Tag>
+struct name_tag
+{};
+
+template <class T>
+struct is_name_tag
+ : mpl::false_
+{};
+
+}}} // namespace boost::parameter::aux
+
+namespace boost { namespace mpl {
+
+template <class T>
+struct lambda<
+ T
+ , typename boost::enable_if<
+ parameter::aux::is_name_tag<T>, parameter::aux::lambda_tag
+ >::type
+>
+{
+ typedef true_ is_le;
+ typedef bind3< quote3<parameter::value_type>, arg<2>, T, void> result_;
+ typedef result_ type;
+};
+
+}} // namespace boost::mpl
+
+# endif
+
+# if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+# include <boost/preprocessor/detail/split.hpp>
+// From Paul Mensonides
+# define BOOST_PARAMETER_IS_BINARY(x) \
+ BOOST_PP_SPLIT(1, BOOST_PARAMETER_IS_BINARY_C x BOOST_PP_COMMA() 0) \
+ /**/
+# define BOOST_PARAMETER_IS_BINARY_C(x,y) \
+ ~, 1 BOOST_PP_RPAREN() \
+ BOOST_PP_TUPLE_EAT(2) BOOST_PP_LPAREN() ~ \
+ /**/
+# else
+# include <boost/preprocessor/detail/is_binary.hpp>
+# define BOOST_PARAMETER_IS_BINARY(x) BOOST_PP_IS_BINARY(x)
+# endif
+
+# if BOOST_WORKAROUND(BOOST_MSVC, < 1300)
+# define BOOST_PARAMETER_NAME_OBJECT(tag, name) \
+ static ::boost::parameter::keyword<tag> const& name \
+ = ::boost::parameter::keyword<tag>::instance;
+# else
+# define BOOST_PARAMETER_NAME_OBJECT(tag, name) \
+ namespace \
+ { \
+ ::boost::parameter::keyword<tag> const& name \
+ = ::boost::parameter::keyword<tag>::instance; \
+ }
+# endif
+
+# define BOOST_PARAMETER_BASIC_NAME(tag_namespace, tag, name) \
+ namespace tag_namespace \
+ { \
+ struct tag \
+ { \
+ static char const* keyword_name() \
+ { \
+ return BOOST_PP_STRINGIZE(tag); \
+ } \
+ \
+ typedef boost::parameter::value_type< \
+ boost::mpl::_2, tag, boost::parameter::void_ \
+ > _; \
+ \
+ typedef boost::parameter::value_type< \
+ boost::mpl::_2, tag, boost::parameter::void_ \
+ > _1; \
+ }; \
+ } \
+ BOOST_PARAMETER_NAME_OBJECT(tag_namespace::tag, name)
+
+# define BOOST_PARAMETER_COMPLEX_NAME_TUPLE1(tag,namespace) \
+ (tag, namespace), ~
+
+# define BOOST_PARAMETER_COMPLEX_NAME_TUPLE(name) \
+ BOOST_PP_TUPLE_ELEM(2, 0, (BOOST_PARAMETER_COMPLEX_NAME_TUPLE1 name))
+
+# define BOOST_PARAMETER_COMPLEX_NAME_TAG(name) \
+ BOOST_PP_TUPLE_ELEM(2, 0, BOOST_PARAMETER_COMPLEX_NAME_TUPLE(name))
+
+# define BOOST_PARAMETER_COMPLEX_NAME_NAMESPACE(name) \
+ BOOST_PP_TUPLE_ELEM(2, 1, BOOST_PARAMETER_COMPLEX_NAME_TUPLE(name))
+
+# define BOOST_PARAMETER_COMPLEX_NAME(name) \
+ BOOST_PARAMETER_BASIC_NAME( \
+ BOOST_PARAMETER_COMPLEX_NAME_NAMESPACE(name) \
+ , BOOST_PP_TUPLE_EAT(2) name \
+ , BOOST_PARAMETER_COMPLEX_NAME_TAG(name) \
+ ) \
+/**/
+
+# define BOOST_PARAMETER_SIMPLE_NAME(name) \
+ BOOST_PARAMETER_BASIC_NAME(tag, name, BOOST_PP_CAT(_, name))
+
+# define BOOST_PARAMETER_NAME(name) \
+ BOOST_PP_IIF( \
+ BOOST_PARAMETER_IS_BINARY(name) \
+ , BOOST_PARAMETER_COMPLEX_NAME \
+ , BOOST_PARAMETER_SIMPLE_NAME \
+ )(name) \
+/**/
+
+
+# define BOOST_PARAMETER_TEMPLATE_KEYWORD(name) \
+ namespace tag \
+ { \
+ struct name; \
+ } \
+ template <class T> \
+ struct name \
+ : boost::parameter::template_keyword<tag::name, T> \
+ {}; \
+/**/
+
+#endif // BOOST_PARAMETER_NAME_060806_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/parameters.hpp b/3rdParty/Boost/src/boost/parameter/parameters.hpp
new file mode 100755
index 0000000..97e1024
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/parameters.hpp
@@ -0,0 +1,931 @@
+// Copyright David Abrahams, Daniel Wallin 2003. Use, modification and
+// distribution is subject to the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_PARAMETERS_031014_HPP
+#define BOOST_PARAMETERS_031014_HPP
+
+#include <boost/detail/is_xxx.hpp>
+
+#include <boost/type_traits/is_const.hpp>
+
+#include <boost/mpl/lambda.hpp>
+#include <boost/mpl/apply.hpp>
+#include <boost/mpl/always.hpp>
+#include <boost/mpl/and.hpp>
+#include <boost/mpl/or.hpp>
+#include <boost/mpl/if.hpp>
+#include <boost/mpl/identity.hpp>
+#include <boost/mpl/not.hpp>
+#include <boost/mpl/eval_if.hpp>
+#include <boost/mpl/pair.hpp>
+
+#include <boost/type_traits/is_same.hpp>
+#include <boost/type_traits/remove_reference.hpp>
+
+#include <boost/preprocessor/repetition/enum.hpp>
+#include <boost/preprocessor/repetition/enum_params.hpp>
+#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
+#include <boost/preprocessor/arithmetic/sub.hpp>
+#include <boost/preprocessor/repetition/repeat.hpp>
+#include <boost/preprocessor/repetition/enum_shifted.hpp>
+#include <boost/preprocessor/repetition/enum_binary_params.hpp>
+#include <boost/preprocessor/repetition/enum_shifted_params.hpp>
+#include <boost/preprocessor/seq/elem.hpp>
+#include <boost/preprocessor/iteration/iterate.hpp>
+#include <boost/preprocessor/facilities/intercept.hpp>
+#include <boost/preprocessor/cat.hpp>
+
+#include <boost/parameter/aux_/arg_list.hpp>
+#include <boost/parameter/aux_/yesno.hpp>
+#include <boost/parameter/aux_/void.hpp>
+#include <boost/parameter/aux_/default.hpp>
+#include <boost/parameter/aux_/unwrap_cv_reference.hpp>
+#include <boost/parameter/aux_/tagged_argument.hpp>
+#include <boost/parameter/aux_/tag.hpp>
+#include <boost/parameter/aux_/template_keyword.hpp>
+#include <boost/parameter/aux_/set.hpp>
+#include <boost/parameter/config.hpp>
+
+namespace parameter_
+{
+ template <class T>
+ struct unmatched_argument
+ {
+ BOOST_MPL_ASSERT((boost::is_same<T,void>));
+ typedef int type;
+ };
+} // namespace parameter_
+
+namespace boost {
+
+template<class T> class reference_wrapper;
+
+namespace parameter {
+
+namespace aux { struct use_default {}; }
+
+// These templates can be used to describe the treatment of particular
+// named parameters for the purposes of overload elimination with
+// SFINAE, by placing specializations in the parameters<...> list. In
+// order for a treated function to participate in overload resolution:
+//
+// - all keyword tags wrapped in required<...> must have a matching
+// actual argument
+//
+// - The actual argument type matched by every keyword tag
+// associated with a predicate must satisfy that predicate
+//
+// If a keyword k is specified without an optional<...> or
+// required<...>, wrapper, it is treated as though optional<k> were
+// specified.
+//
+// If a keyword k is specified with deduced<...>, that keyword
+// will be automatically deduced from the argument list.
+//
+template <class Tag, class Predicate = aux::use_default>
+struct required
+{
+ typedef Tag key_type;
+ typedef Predicate predicate;
+};
+
+template <class Tag, class Predicate = aux::use_default>
+struct optional
+{
+ typedef Tag key_type;
+ typedef Predicate predicate;
+};
+
+template <class Tag>
+struct deduced
+{
+ typedef Tag key_type;
+};
+
+namespace aux
+{
+ // Defines metafunctions, is_required and is_optional, that
+ // identify required<...>, optional<...> and deduced<...> specializations.
+ BOOST_DETAIL_IS_XXX_DEF(required, required, 2)
+ BOOST_DETAIL_IS_XXX_DEF(optional, optional, 2)
+ BOOST_DETAIL_IS_XXX_DEF(deduced_aux, deduced, 1)
+
+ template <class S>
+ struct is_deduced0
+ : is_deduced_aux<
+ typename S::key_type
+ >::type
+ {};
+
+ template <class S>
+ struct is_deduced
+ : mpl::eval_if<
+ mpl::or_<
+ is_optional<S>, is_required<S>
+ >
+ , is_deduced0<S>
+ , mpl::false_
+ >::type
+ {};
+
+ //
+ // key_type, has_default, and predicate --
+ //
+ // These metafunctions accept a ParameterSpec and extract the
+ // keyword tag, whether or not a default is supplied for the
+ // parameter, and the predicate that the corresponding actual
+ // argument type is required match.
+ //
+ // a ParameterSpec is a specialization of either keyword<...>,
+ // required<...>, optional<...>
+ //
+
+ // helper for key_type<...>, below.
+ template <class T>
+ struct get_tag_type0
+ {
+ typedef typename T::key_type type;
+ };
+
+ template <class T>
+ struct get_tag_type
+ : mpl::eval_if<
+ is_deduced_aux<typename T::key_type>
+ , get_tag_type0<typename T::key_type>
+ , mpl::identity<typename T::key_type>
+ >
+ {};
+
+ template <class T>
+ struct tag_type
+ : mpl::eval_if<
+ mpl::or_<
+ is_optional<T>
+ , is_required<T>
+ >
+ , get_tag_type<T>
+ , mpl::identity<T>
+ >
+ {};
+
+ template <class T>
+ struct has_default
+ : mpl::not_<is_required<T> >
+ {};
+
+ // helper for get_predicate<...>, below
+ template <class T>
+ struct get_predicate_or_default
+ {
+ typedef T type;
+ };
+
+ template <>
+ struct get_predicate_or_default<use_default>
+ {
+ typedef mpl::always<mpl::true_> type;
+ };
+
+ // helper for predicate<...>, below
+ template <class T>
+ struct get_predicate
+ {
+ typedef typename
+ get_predicate_or_default<typename T::predicate>::type
+ type;
+ };
+
+ template <class T>
+ struct predicate
+ : mpl::eval_if<
+ mpl::or_<
+ is_optional<T>
+ , is_required<T>
+ >
+ , get_predicate<T>
+ , mpl::identity<mpl::always<mpl::true_> >
+ >
+ {
+ };
+
+
+ // Converts a ParameterSpec into a specialization of
+ // parameter_requirements. We need to do this in order to get the
+ // tag_type into the type in a way that can be conveniently matched
+ // by a satisfies(...) member function in arg_list.
+ template <class ParameterSpec>
+ struct as_parameter_requirements
+ {
+ typedef parameter_requirements<
+ typename tag_type<ParameterSpec>::type
+ , typename predicate<ParameterSpec>::type
+ , typename has_default<ParameterSpec>::type
+ > type;
+ };
+
+ template <class T>
+ struct is_named_argument
+ : mpl::or_<
+ is_template_keyword<T>
+ , is_tagged_argument<T>
+ >
+ {};
+
+ // Returns mpl::true_ iff the given ParameterRequirements are
+ // satisfied by ArgList.
+ template <class ArgList, class ParameterRequirements>
+ struct satisfies
+ {
+#if BOOST_WORKAROUND(BOOST_MSVC, == 1310)
+ // VC7.1 can't handle the sizeof() implementation below,
+ // so we use this instead.
+ typedef typename mpl::apply_wrap3<
+ typename ArgList::binding
+ , typename ParameterRequirements::keyword
+ , void_
+ , mpl::false_
+ >::type bound;
+
+ typedef typename mpl::eval_if<
+ is_same<bound, void_>
+ , typename ParameterRequirements::has_default
+ , mpl::apply_wrap2<
+ typename mpl::lambda<
+ typename ParameterRequirements::predicate, lambda_tag
+ >::type
+ , bound
+ , ArgList
+ >
+ >::type type;
+#else
+ BOOST_STATIC_CONSTANT(
+ bool, value = (
+ sizeof(
+ aux::to_yesno(
+ ArgList::satisfies((ParameterRequirements*)0, (ArgList*)0)
+ )
+ ) == sizeof(yes_tag)
+ )
+ );
+
+ typedef mpl::bool_<satisfies::value> type;
+#endif
+ };
+
+ // Returns mpl::true_ if the requirements of the given ParameterSpec
+ // are satisfied by ArgList.
+ template <class ArgList, class ParameterSpec>
+ struct satisfies_requirements_of
+ : satisfies<
+ ArgList
+ , typename as_parameter_requirements<ParameterSpec>::type
+ >
+ {};
+
+ // Tags a deduced argument Arg with the keyword tag of Spec using TagFn.
+ // Returns the tagged argument and the mpl::set<> UsedArgs with the
+ // tag of Spec inserted.
+ template <class UsedArgs, class Spec, class Arg, class TagFn>
+ struct tag_deduced
+ {
+ typedef mpl::pair<
+ typename mpl::apply_wrap2<TagFn, typename tag_type<Spec>::type, Arg>::type
+ , typename aux::insert_<UsedArgs, typename tag_type<Spec>::type>::type
+ > type;
+ };
+
+ template <
+ class Argument
+ , class ArgumentPack
+ , class DeducedArgs
+ , class UsedArgs
+ , class TagFn
+ >
+ struct deduce_tag;
+
+ // Tag type passed to MPL lambda.
+ struct lambda_tag;
+
+ // Helper for deduce_tag<> below.
+ template <
+ class Argument
+ , class ArgumentPack
+ , class DeducedArgs
+ , class UsedArgs
+ , class TagFn
+ >
+ struct deduce_tag0
+ {
+ typedef typename DeducedArgs::spec spec;
+
+ typedef typename mpl::apply_wrap2<
+ typename mpl::lambda<
+ typename spec::predicate, lambda_tag
+ >::type
+ , Argument
+ , ArgumentPack
+ >::type condition;
+
+ // Deduced parameter matches several arguments.
+
+ BOOST_MPL_ASSERT((
+ mpl::not_<mpl::and_<
+ condition
+ , aux::has_key_<UsedArgs, typename tag_type<spec>::type>
+ > >
+ ));
+
+ typedef typename mpl::eval_if<
+ condition
+ , tag_deduced<UsedArgs, spec, Argument, TagFn>
+ , deduce_tag<Argument, ArgumentPack, typename DeducedArgs::tail, UsedArgs, TagFn>
+ >::type type;
+ };
+
+ // Tries to deduced a keyword tag for a given Argument.
+ // Returns an mpl::pair<> consisting of the tagged_argument<>,
+ // and an mpl::set<> where the new tag has been inserted.
+ //
+ // Argument: The argument type to be tagged.
+ //
+ // ArgumentPack: The ArgumentPack built so far.
+ //
+ // DeducedArgs: A specialization of deduced_item<> (see below).
+ // A list containing only the deduced ParameterSpecs.
+ //
+ // UsedArgs: An mpl::set<> containing the keyword tags used so far.
+ //
+ // TagFn: A metafunction class used to tag positional or deduced
+ // arguments with a keyword tag.
+
+ template <
+ class Argument
+ , class ArgumentPack
+ , class DeducedArgs
+ , class UsedArgs
+ , class TagFn
+ >
+ struct deduce_tag
+ {
+ typedef typename mpl::eval_if<
+ is_same<DeducedArgs, void_>
+ , mpl::pair<void_, UsedArgs>
+ , deduce_tag0<Argument, ArgumentPack, DeducedArgs, UsedArgs, TagFn>
+ >::type type;
+ };
+
+ template <
+ class List
+ , class DeducedArgs
+ , class TagFn
+ , class Positional
+ , class UsedArgs
+ , class ArgumentPack
+ , class Error
+ >
+ struct make_arg_list_aux;
+
+ // Inserts Tagged::key_type into the UserArgs set.
+ // Extra indirection to lazily evaluate Tagged::key_type.
+ template <class UsedArgs, class Tagged>
+ struct insert_tagged
+ {
+ typedef typename aux::insert_<
+ UsedArgs, typename Tagged::key_type
+ >::type type;
+ };
+
+ // Borland needs the insane extra-indirection workaround below
+ // so that it doesn't magically drop the const qualifier from
+ // the argument type.
+
+ template <
+ class List
+ , class DeducedArgs
+ , class TagFn
+ , class Positional
+ , class UsedArgs
+ , class ArgumentPack
+#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+ , class argument
+#endif
+ , class Error
+ >
+#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+ struct make_arg_list00
+#else
+ struct make_arg_list0
+#endif
+ {
+#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+ typedef typename List::arg argument;
+#endif
+ typedef typename List::spec parameter_spec;
+ typedef typename tag_type<parameter_spec>::type tag_;
+
+ typedef is_named_argument<argument> is_tagged;
+
+ // If this argument is either explicitly tagged or a deduced
+ // parameter, we turn off positional matching.
+ typedef mpl::and_<
+ mpl::not_<
+ mpl::or_<is_deduced<parameter_spec>, is_tagged>
+ >
+ , Positional
+ > positional;
+
+ // If this parameter is explicitly tagged we add it to the
+ // used-parmeters set. We only really need to add parameters
+ // that are deduced, but we would need a way to check if
+ // a given tag corresponds to a deduced parameter spec.
+ typedef typename mpl::eval_if<
+ is_tagged
+ , insert_tagged<UsedArgs, argument>
+ , mpl::identity<UsedArgs>
+ >::type used_args;
+
+ // If this parameter is neither explicitly tagged, nor
+ // positionally matched; deduce the tag from the deduced
+ // parameter specs.
+ typedef typename mpl::eval_if<
+ mpl::or_<is_tagged, positional>
+ , mpl::pair<void_, used_args>
+ , deduce_tag<argument, ArgumentPack, DeducedArgs, used_args, TagFn>
+ >::type deduced_data;
+
+ // If this parameter is explicitly tagged..
+ typedef typename mpl::eval_if<
+ is_tagged
+ , mpl::identity<argument> // .. just use it
+ , mpl::eval_if< // .. else, if positional matching is turned on..
+ positional
+ , mpl::apply_wrap2<TagFn, tag_, argument> // .. tag it positionally
+ , mpl::first<deduced_data> // .. else, use the deduced tag
+ >
+ >::type tagged;
+
+ // We build the arg_list incrementally as we go, prepending new
+ // nodes.
+
+ typedef typename mpl::if_<
+ mpl::and_<
+ is_same<Error, void_>
+ , is_same<tagged, void_>
+ >
+ , parameter_::unmatched_argument<argument>
+ , void_
+ >::type error;
+
+ typedef typename mpl::if_<
+ is_same<tagged, void_>
+ , ArgumentPack
+ , arg_list<tagged, ArgumentPack>
+ >::type argument_pack;
+
+ typedef typename make_arg_list_aux<
+ typename List::tail
+ , DeducedArgs
+ , TagFn
+ , positional
+ , typename deduced_data::second
+ , argument_pack
+ , error
+ >::type type;
+ };
+
+#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+ template <
+ class List
+ , class DeducedArgs
+ , class TagFn
+ , class Positional
+ , class UsedArgs
+ , class ArgumentPack
+ , class Error
+ >
+ struct make_arg_list0
+ {
+ typedef typename mpl::eval_if<
+ typename List::is_arg_const
+ , make_arg_list00<
+ List
+ , DeducedArgs
+ , TagFn
+ , Positional
+ , UsedArgs
+ , ArgumentPack
+ , typename List::arg const
+ , Error
+ >
+ , make_arg_list00<
+ List
+ , DeducedArgs
+ , TagFn
+ , Positional
+ , UsedArgs
+ , ArgumentPack
+ , typename List::arg
+ , Error
+ >
+ >::type type;
+ };
+#endif
+
+ // Returns an ArgumentPack where the list of arguments has
+ // been tagged with keyword tags.
+ //
+ // List: A specialization of item<> (see below). Contains
+ // both the ordered ParameterSpecs, and the given arguments.
+ //
+ // DeducedArgs: A specialization of deduced_item<> (see below).
+ // A list containing only the deduced ParameterSpecs.
+ //
+ // TagFn: A metafunction class used to tag positional or deduced
+ // arguments with a keyword tag.
+ //
+ // Position: An mpl::bool_<> specialization indicating if positional
+ // matching is to be performed.
+ //
+ // DeducedSet: An mpl::set<> containing the keyword tags used so far.
+ //
+ // ArgumentPack: The ArgumentPack built so far. This is initially an
+ // empty_arg_list and is built incrementally.
+ //
+
+ template <
+ class List
+ , class DeducedArgs
+ , class TagFn
+ , class Positional
+ , class DeducedSet
+ , class ArgumentPack
+ , class Error
+ >
+ struct make_arg_list_aux
+ {
+ typedef typename mpl::eval_if<
+ is_same<List, void_>
+ , mpl::identity<mpl::pair<ArgumentPack, Error> >
+ , make_arg_list0<List, DeducedArgs, TagFn, Positional, DeducedSet, ArgumentPack, Error>
+ >::type type;
+ };
+
+ // VC6.5 was choking on the default parameters for make_arg_list_aux, so
+ // this just forwards to that adding in the defaults.
+ template <
+ class List
+ , class DeducedArgs
+ , class TagFn
+ , class EmitErrors = mpl::true_
+ >
+ struct make_arg_list
+ {
+ typedef typename make_arg_list_aux<
+ List, DeducedArgs, TagFn, mpl::true_, aux::set0, empty_arg_list, void_
+ >::type type;
+ };
+
+ // A parameter spec item typelist.
+ template <class Spec, class Arg, class Tail = void_>
+ struct item
+ {
+ typedef Spec spec;
+
+#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+ typedef is_const<Arg> is_arg_const;
+#endif
+
+ typedef Arg arg;
+ typedef Tail tail;
+ };
+
+ template <class Spec, class Arg, class Tail>
+ struct make_item
+ {
+ typedef item<Spec, Arg, typename Tail::type> type;
+ };
+
+ // Creates a item typelist.
+ template <class Spec, class Arg, class Tail>
+ struct make_items
+ {
+ typedef typename mpl::eval_if<
+ is_same<Arg, void_>
+ , mpl::identity<void_>
+ , make_item<Spec, Arg, Tail>
+ >::type type;
+ };
+
+ // A typelist that stored deduced parameter specs.
+ template <class ParameterSpec, class Tail = void_>
+ struct deduced_item
+ {
+ typedef ParameterSpec spec;
+ typedef Tail tail;
+ };
+
+ // Evaluate Tail and construct deduced_item list.
+ template <class Spec, class Tail>
+ struct make_deduced_item
+ {
+ typedef deduced_item<Spec, typename Tail::type> type;
+ };
+
+ template <class Spec, class Tail>
+ struct make_deduced_items
+ {
+ typedef typename mpl::eval_if<
+ is_same<Spec, void_>
+ , mpl::identity<void_>
+ , mpl::eval_if<
+ is_deduced<Spec>
+ , make_deduced_item<Spec, Tail>
+ , Tail
+ >
+ >::type type;
+ };
+
+ // Generates:
+ //
+ // make<
+ // parameter_spec#0, argument_type#0
+ // , make<
+ // parameter_spec#1, argument_type#1
+ // , ... mpl::identity<aux::empty_arg_list>
+ // ...>
+ // >
+#define BOOST_PARAMETER_make_arg_list(z, n, names) \
+ BOOST_PP_SEQ_ELEM(0,names)< \
+ BOOST_PP_CAT(BOOST_PP_SEQ_ELEM(1,names), n), \
+ BOOST_PP_CAT(BOOST_PP_SEQ_ELEM(2,names), n),
+
+#define BOOST_PARAMETER_right_angle(z, n, text) >
+
+#define BOOST_PARAMETER_build_arg_list(n, make, parameter_spec, argument_type) \
+ BOOST_PP_REPEAT( \
+ n, BOOST_PARAMETER_make_arg_list, (make)(parameter_spec)(argument_type)) \
+ mpl::identity<void_> \
+ BOOST_PP_REPEAT(n, BOOST_PARAMETER_right_angle, _)
+
+#define BOOST_PARAMETER_make_deduced_list(z, n, names) \
+ BOOST_PP_SEQ_ELEM(0,names)< \
+ BOOST_PP_CAT(BOOST_PP_SEQ_ELEM(1,names), n),
+
+#define BOOST_PARAMETER_build_deduced_list(n, make, parameter_spec) \
+ BOOST_PP_REPEAT( \
+ n, BOOST_PARAMETER_make_deduced_list, (make)(parameter_spec)) \
+ mpl::identity<void_> \
+ BOOST_PP_REPEAT(n, BOOST_PARAMETER_right_angle, _)
+
+ struct tag_keyword_arg
+ {
+ template <class K, class T>
+ struct apply
+ : tag<K,T>
+ {};
+ };
+
+ struct tag_template_keyword_arg
+ {
+ template <class K, class T>
+ struct apply
+ {
+ typedef template_keyword<K,T> type;
+ };
+ };
+
+} // namespace aux
+
+#define BOOST_PARAMETER_FORWARD_TYPEDEF(z, i, names) \
+ typedef BOOST_PP_CAT(BOOST_PP_SEQ_ELEM(0,names),i) BOOST_PP_CAT(BOOST_PP_SEQ_ELEM(1,names),i);
+
+#define BOOST_PARAMETER_FORWARD_TYPEDEFS(n, src, dest) \
+ BOOST_PP_REPEAT(n, BOOST_PARAMETER_FORWARD_TYPEDEF, (src)(dest))
+
+
+#define BOOST_PARAMETER_TEMPLATE_ARGS(z, n, text) class BOOST_PP_CAT(PS, n) = void_
+
+template<
+ class PS0
+ , BOOST_PP_ENUM_SHIFTED(BOOST_PARAMETER_MAX_ARITY, BOOST_PARAMETER_TEMPLATE_ARGS, _)
+>
+struct parameters
+{
+#undef BOOST_PARAMETER_TEMPLATE_ARGS
+
+ typedef typename BOOST_PARAMETER_build_deduced_list(
+ BOOST_PARAMETER_MAX_ARITY, aux::make_deduced_items, PS
+ )::type deduced_list;
+
+ // if the elements of NamedList match the criteria of overload
+ // resolution, returns a type which can be constructed from
+ // parameters. Otherwise, this is not a valid metafunction (no nested
+ // ::type).
+
+
+#if ! defined(BOOST_NO_SFINAE) && ! BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x592))
+ // If NamedList satisfies the PS0, PS1, ..., this is a
+ // metafunction returning parameters. Otherwise it
+ // has no nested ::type.
+ template <class ArgumentPackAndError>
+ struct match_base
+ : mpl::if_<
+ // mpl::and_<
+ // aux::satisfies_requirements_of<NamedList,PS0>
+ // , mpl::and_<
+ // aux::satisfies_requirements_of<NamedList,PS1>...
+ // ..., mpl::true_
+ // ...> >
+
+# define BOOST_PARAMETER_satisfies(z, n, text) \
+ mpl::and_< \
+ aux::satisfies_requirements_of< \
+ typename mpl::first<ArgumentPackAndError>::type \
+ , BOOST_PP_CAT(PS, n)> \
+ ,
+ mpl::and_<
+ is_same<typename mpl::second<ArgumentPackAndError>::type, void_>
+ , BOOST_PP_REPEAT(BOOST_PARAMETER_MAX_ARITY, BOOST_PARAMETER_satisfies, _)
+ mpl::true_
+ BOOST_PP_REPEAT(BOOST_PARAMETER_MAX_ARITY, BOOST_PARAMETER_right_angle, _)
+ >
+
+# undef BOOST_PARAMETER_satisfies
+
+ , mpl::identity<parameters>
+ , void_
+ >
+ {};
+#endif
+
+ // Specializations are to be used as an optional argument to
+ // eliminate overloads via SFINAE
+ template<
+#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+ // Borland simply can't handle default arguments in member
+ // class templates. People wishing to write portable code can
+ // explicitly specify BOOST_PARAMETER_MAX_ARITY arguments
+ BOOST_PP_ENUM_PARAMS(BOOST_PARAMETER_MAX_ARITY, class A)
+#else
+ BOOST_PP_ENUM_BINARY_PARAMS(
+ BOOST_PARAMETER_MAX_ARITY, class A, = void_ BOOST_PP_INTERCEPT
+ )
+#endif
+ >
+ struct match
+# if ! defined(BOOST_NO_SFINAE) && ! BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x592))
+ : match_base<
+ typename aux::make_arg_list<
+ typename BOOST_PARAMETER_build_arg_list(
+ BOOST_PARAMETER_MAX_ARITY, aux::make_items, PS, A
+ )::type
+ , deduced_list
+ , aux::tag_keyword_arg
+ , mpl::false_ // Don't emit errors when doing SFINAE
+ >::type
+ >::type
+ {};
+# else
+ {
+ typedef parameters<
+ BOOST_PP_ENUM_PARAMS(BOOST_PARAMETER_MAX_ARITY, PS)
+ > type;
+ };
+# endif
+
+ // Metafunction that returns an ArgumentPack.
+
+ // TODO, bind has to instantiate the error type in the result
+ // of make_arg_list.
+
+ template <
+#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+ // Borland simply can't handle default arguments in member
+ // class templates. People wishing to write portable code can
+ // explicitly specify BOOST_PARAMETER_MAX_ARITY arguments
+ BOOST_PP_ENUM_PARAMS(BOOST_PARAMETER_MAX_ARITY, class A)
+#else
+ BOOST_PP_ENUM_BINARY_PARAMS(
+ BOOST_PARAMETER_MAX_ARITY, class A, = void_ BOOST_PP_INTERCEPT
+ )
+#endif
+ >
+ struct bind
+ {
+ typedef typename aux::make_arg_list<
+ typename BOOST_PARAMETER_build_arg_list(
+ BOOST_PARAMETER_MAX_ARITY, aux::make_items, PS, A
+ )::type
+ , deduced_list
+ , aux::tag_template_keyword_arg
+ >::type result;
+
+ typedef typename mpl::first<result>::type type;
+ };
+
+ BOOST_PARAMETER_FORWARD_TYPEDEFS(BOOST_PARAMETER_MAX_ARITY, PS, parameter_spec)
+
+ //
+ // The function call operator is used to build an arg_list that
+ // labels the positional parameters and maintains whatever other
+ // tags may have been specified by the caller.
+ //
+ // !!!NOTE!!!
+ //
+ // The make_arg_list<> produces a reversed arg_list, so
+ // we need to pass the arguments to its constructor
+ // reversed.
+ //
+ aux::empty_arg_list operator()() const
+ {
+ return aux::empty_arg_list();
+ }
+
+ template<class A0>
+ typename mpl::first<
+ typename aux::make_arg_list<
+ aux::item<
+ PS0,A0
+ >
+ , deduced_list
+ , aux::tag_keyword_arg
+ >::type
+ >::type
+ operator()(A0& a0) const
+ {
+ typedef typename aux::make_arg_list<
+ aux::item<
+ PS0,A0
+ >
+ , deduced_list
+ , aux::tag_keyword_arg
+ >::type result;
+
+ typedef typename mpl::first<result>::type result_type;
+ typedef typename mpl::second<result>::type error;
+ error();
+
+ return result_type(
+ a0
+ // , void_(), void_(), void_() ...
+ BOOST_PP_ENUM_TRAILING_PARAMS(
+ BOOST_PP_SUB(BOOST_PARAMETER_MAX_ARITY, 1)
+ , aux::void_reference() BOOST_PP_INTERCEPT)
+ );
+ }
+
+ template<class A0, class A1>
+ typename mpl::first<
+ typename aux::make_arg_list<
+ aux::item<
+ PS0,A0
+ , aux::item<
+ PS1,A1
+ >
+ >
+ , deduced_list
+ , aux::tag_keyword_arg
+ >::type
+ >::type
+ operator()(A0& a0, A1& a1) const
+ {
+ typedef typename aux::make_arg_list<
+ aux::item<
+ PS0,A0
+ , aux::item<
+ PS1,A1
+ >
+ >
+ , deduced_list
+ , aux::tag_keyword_arg
+ >::type result;
+
+ typedef typename mpl::first<result>::type result_type;
+ typedef typename mpl::second<result>::type error;
+ error();
+
+ return result_type(
+ a1,a0
+ // , void_(), void_() ...
+ BOOST_PP_ENUM_TRAILING_PARAMS(
+ BOOST_PP_SUB(BOOST_PARAMETER_MAX_ARITY, 2)
+ , aux::void_reference() BOOST_PP_INTERCEPT)
+ );
+ }
+
+ // Higher arities are handled by the preprocessor
+#define BOOST_PP_ITERATION_PARAMS_1 (3,( \
+ 3,BOOST_PARAMETER_MAX_ARITY,<boost/parameter/aux_/overloads.hpp> \
+ ))
+#include BOOST_PP_ITERATE()
+
+};
+
+} // namespace parameter
+
+} // namespace boost
+
+#endif // BOOST_PARAMETERS_031014_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/preprocessor.hpp b/3rdParty/Boost/src/boost/parameter/preprocessor.hpp
new file mode 100644
index 0000000..f1bda87
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/preprocessor.hpp
@@ -0,0 +1,1178 @@
+// Copyright Daniel Wallin 2006. Use, modification and distribution is
+// subject to the Boost Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_PARAMETER_PREPROCESSOR_060206_HPP
+# define BOOST_PARAMETER_PREPROCESSOR_060206_HPP
+
+# include <boost/parameter/parameters.hpp>
+# include <boost/parameter/binding.hpp>
+# include <boost/parameter/match.hpp>
+
+# include <boost/parameter/aux_/parenthesized_type.hpp>
+# include <boost/parameter/aux_/cast.hpp>
+# include <boost/parameter/aux_/preprocessor/flatten.hpp>
+
+# include <boost/preprocessor/repetition/repeat_from_to.hpp>
+# include <boost/preprocessor/comparison/equal.hpp>
+# include <boost/preprocessor/control/if.hpp>
+# include <boost/preprocessor/control/iif.hpp>
+# include <boost/preprocessor/control/expr_if.hpp>
+# include <boost/preprocessor/repetition/enum_params.hpp>
+# include <boost/preprocessor/repetition/enum_binary_params.hpp>
+# include <boost/preprocessor/repetition/enum_trailing.hpp>
+# include <boost/preprocessor/seq/first_n.hpp>
+# include <boost/preprocessor/seq/for_each_product.hpp>
+# include <boost/preprocessor/seq/for_each_i.hpp>
+# include <boost/preprocessor/tuple/elem.hpp>
+# include <boost/preprocessor/tuple/eat.hpp>
+# include <boost/preprocessor/seq/fold_left.hpp>
+# include <boost/preprocessor/seq/push_back.hpp>
+# include <boost/preprocessor/seq/size.hpp>
+# include <boost/preprocessor/seq/enum.hpp>
+# include <boost/preprocessor/seq/push_back.hpp>
+
+# include <boost/preprocessor/detail/is_nullary.hpp>
+
+# include <boost/mpl/always.hpp>
+# include <boost/mpl/apply_wrap.hpp>
+
+# if BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
+# include <boost/type.hpp>
+# endif
+
+namespace boost { namespace parameter { namespace aux {
+
+# if ! defined(BOOST_NO_SFINAE) && ! BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x592))
+
+// Given Match, which is "void x" where x is an argument matching
+// criterion, extract a corresponding MPL predicate.
+template <class Match>
+struct unwrap_predicate;
+
+// Match anything
+template <>
+struct unwrap_predicate<void*>
+{
+ typedef mpl::always<mpl::true_> type;
+};
+
+#if BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x580))
+
+typedef void* voidstar;
+
+// A matching predicate is explicitly specified
+template <class Predicate>
+struct unwrap_predicate<voidstar (Predicate)>
+{
+ typedef Predicate type;
+};
+
+#else
+
+// A matching predicate is explicitly specified
+template <class Predicate>
+struct unwrap_predicate<void *(Predicate)>
+{
+ typedef Predicate type;
+};
+
+#endif
+
+
+// A type to which the argument is supposed to be convertible is
+// specified
+template <class Target>
+struct unwrap_predicate<void (Target)>
+{
+ typedef is_convertible<mpl::_, Target> type;
+};
+
+// Recast the ParameterSpec's nested match metafunction as a free metafunction
+template <
+ class Parameters
+ , BOOST_PP_ENUM_BINARY_PARAMS(
+ BOOST_PARAMETER_MAX_ARITY, class A, = boost::parameter::void_ BOOST_PP_INTERCEPT
+ )
+>
+struct match
+ : Parameters::template match<
+ BOOST_PP_ENUM_PARAMS(BOOST_PARAMETER_MAX_ARITY, A)
+ >
+{};
+# endif
+
+# if BOOST_WORKAROUND(BOOST_MSVC, == 1300)
+
+// Function template argument deduction does many of the same things
+// as type matching during partial specialization, so we call a
+// function template to "store" T into the type memory addressed by
+// void(*)(T).
+template <class T>
+msvc_store_type<T,void*(*)(void**(T))>
+msvc_store_predicate_type(void*(*)(void**(T)));
+
+template <class T>
+msvc_store_type<boost::is_convertible<mpl::_,T>,void*(*)(void*(T))>
+msvc_store_predicate_type(void*(*)(void*(T)));
+
+template <class FunctionType>
+struct unwrap_predicate
+{
+ static FunctionType f;
+
+ // We don't want the function to be evaluated, just instantiated,
+ // so protect it inside of sizeof.
+ enum { dummy = sizeof(msvc_store_predicate_type(f)) };
+
+ // Now pull the type out of the instantiated base class
+ typedef typename msvc_type_memory<FunctionType>::storage::type type;
+};
+
+template <>
+struct unwrap_predicate<void*(*)(void**)>
+{
+ typedef mpl::always<mpl::true_> type;
+};
+
+# endif
+
+# undef false_
+
+template <
+ class Parameters
+ , BOOST_PP_ENUM_BINARY_PARAMS(
+ BOOST_PARAMETER_MAX_ARITY, class A, = boost::parameter::void_ BOOST_PP_INTERCEPT
+ )
+>
+struct argument_pack
+{
+ typedef typename make_arg_list<
+ typename BOOST_PARAMETER_build_arg_list(
+ BOOST_PARAMETER_MAX_ARITY, make_items, typename Parameters::parameter_spec, A
+ )::type
+ , typename Parameters::deduced_list
+ , tag_keyword_arg
+ , mpl::false_
+ >::type result;
+ typedef typename mpl::first<result>::type type;
+};
+
+# if 1 //BOOST_WORKAROUND(BOOST_MSVC, < 1300)
+// Works around VC6 problem where it won't accept rvalues.
+template <class T>
+T& as_lvalue(T& value, long)
+{
+ return value;
+}
+
+template <class T>
+T const& as_lvalue(T const& value, int)
+{
+ return value;
+}
+# endif
+
+
+# if BOOST_WORKAROUND(BOOST_MSVC, < 1300) \
+ || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+
+template <class Predicate, class T, class Args>
+struct apply_predicate
+{
+ BOOST_MPL_ASSERT((
+ mpl::and_<mpl::false_,T>
+ ));
+
+ typedef typename mpl::if_<
+ typename mpl::apply2<Predicate,T,Args>::type
+ , char
+ , int
+ >::type type;
+};
+
+template <class P>
+struct funptr_predicate
+{
+ static P p;
+
+ template <class T, class Args, class P0>
+ static typename apply_predicate<P0,T,Args>::type
+ check_predicate(type<T>, Args*, void**(*)(P0));
+
+ template <class T, class Args, class P0>
+ static typename mpl::if_<
+ is_convertible<T,P0>
+ , char
+ , int
+ >::type check_predicate(type<T>, Args*, void*(*)(P0));
+
+ template <class T, class Args>
+ struct apply
+ {
+ BOOST_STATIC_CONSTANT(bool, result =
+ sizeof(check_predicate(boost::type<T>(), (Args*)0, &p)) == 1
+ );
+
+ typedef mpl::bool_<apply<T,Args>::result> type;
+ };
+};
+
+template <>
+struct funptr_predicate<void**>
+ : mpl::always<mpl::true_>
+{};
+
+# endif
+
+}}} // namespace boost::parameter::aux
+
+# if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+// From Paul Mensonides
+# define BOOST_PARAMETER_IS_NULLARY(x) \
+ BOOST_PP_SPLIT(1, BOOST_PARAMETER_IS_NULLARY_C x BOOST_PP_COMMA() 0) \
+ /**/
+# define BOOST_PARAMETER_IS_NULLARY_C() \
+ ~, 1 BOOST_PP_RPAREN() \
+ BOOST_PP_TUPLE_EAT(2) BOOST_PP_LPAREN() ~ \
+ /**/
+# else
+# define BOOST_PARAMETER_IS_NULLARY(x) BOOST_PP_IS_NULLARY(x)
+# endif
+
+# define BOOST_PARAMETER_MEMBER_FUNCTION_CHECK_STATIC_static ()
+# define BOOST_PARAMETER_MEMBER_FUNCTION_IS_STATIC(name) \
+ BOOST_PARAMETER_IS_NULLARY( \
+ BOOST_PP_CAT(BOOST_PARAMETER_MEMBER_FUNCTION_CHECK_STATIC_,name) \
+ )
+
+# if !defined(BOOST_MSVC)
+# define BOOST_PARAMETER_MEMBER_FUNCTION_STRIP_STATIC_static
+# define BOOST_PARAMETER_MEMBER_FUNCTION_STRIP_STATIC(name) \
+ BOOST_PP_CAT(BOOST_PARAMETER_MEMBER_FUNCTION_STRIP_STATIC_, name)
+# else
+// Workaround for MSVC preprocessor.
+//
+// When stripping static from "static f", msvc will produce
+// " f". The leading whitespace doesn't go away when pasting
+// the token with something else, so this thing is a hack to
+// strip the whitespace.
+# define BOOST_PARAMETER_MEMBER_FUNCTION_STRIP_STATIC_static (
+# define BOOST_PARAMETER_MEMBER_FUNCTION_STRIP_STATIC_AUX(name) \
+ BOOST_PP_CAT(BOOST_PARAMETER_MEMBER_FUNCTION_STRIP_STATIC_, name))
+# define BOOST_PARAMETER_MEMBER_FUNCTION_STRIP_STATIC(name) \
+ BOOST_PP_SEQ_HEAD( \
+ BOOST_PARAMETER_MEMBER_FUNCTION_STRIP_STATIC_AUX(name) \
+ )
+# endif
+
+# define BOOST_PARAMETER_MEMBER_FUNCTION_STATIC(name) \
+ BOOST_PP_EXPR_IF( \
+ BOOST_PARAMETER_MEMBER_FUNCTION_IS_STATIC(name) \
+ , static \
+ )
+
+# define BOOST_PARAMETER_MEMBER_FUNCTION_NAME(name) \
+ BOOST_PP_IF( \
+ BOOST_PARAMETER_MEMBER_FUNCTION_IS_STATIC(name) \
+ , BOOST_PARAMETER_MEMBER_FUNCTION_STRIP_STATIC \
+ , name BOOST_PP_TUPLE_EAT(1) \
+ )(name)
+
+// Calculates [begin, end) arity range.
+
+# define BOOST_PARAMETER_ARITY_RANGE_M_optional(state) state
+# define BOOST_PARAMETER_ARITY_RANGE_M_deduced_optional(state) state
+# define BOOST_PARAMETER_ARITY_RANGE_M_required(state) BOOST_PP_INC(state)
+# define BOOST_PARAMETER_ARITY_RANGE_M_deduced_required(state) BOOST_PP_INC(state)
+
+# define BOOST_PARAMETER_ARITY_RANGE_M(s, state, x) \
+ BOOST_PP_CAT( \
+ BOOST_PARAMETER_ARITY_RANGE_M_ \
+ , BOOST_PARAMETER_FN_ARG_QUALIFIER(x) \
+ )(state)
+/**/
+
+# define BOOST_PARAMETER_ARITY_RANGE(args) \
+ ( \
+ BOOST_PP_SEQ_FOLD_LEFT(BOOST_PARAMETER_ARITY_RANGE_M, 0, args) \
+ , BOOST_PP_INC(BOOST_PP_SEQ_SIZE(args)) \
+ )
+/**/
+
+// Accessor macros for the argument specs tuple.
+# define BOOST_PARAMETER_FN_ARG_QUALIFIER(x) \
+ BOOST_PP_TUPLE_ELEM(4,0,x)
+/**/
+
+# define BOOST_PARAMETER_FN_ARG_NAME(x) \
+ BOOST_PP_TUPLE_ELEM(4,1,x)
+/**/
+
+# define BOOST_PARAMETER_FN_ARG_PRED(x) \
+ BOOST_PP_TUPLE_ELEM(4,2,x)
+/**/
+
+# define BOOST_PARAMETER_FN_ARG_DEFAULT(x) \
+ BOOST_PP_TUPLE_ELEM(4,3,x)
+/**/
+
+# define BOOST_PARAMETETER_FUNCTION_EAT_KEYWORD_QUALIFIER_out(x)
+# define BOOST_PARAMETETER_FUNCTION_EAT_KEYWORD_QUALIFIER_in_out(x)
+
+// Returns 1 if x is either "out(k)" or "in_out(k)".
+# define BOOST_PARAMETER_FUNCTION_IS_KEYWORD_QUALIFIER(x) \
+ BOOST_PP_IS_EMPTY( \
+ BOOST_PP_CAT(BOOST_PARAMETETER_FUNCTION_EAT_KEYWORD_QUALIFIER_, x) \
+ ) \
+/**/
+
+# define BOOST_PARAMETETER_FUNCTION_GET_KEYWORD_QUALIFIER_out(x) x
+# define BOOST_PARAMETETER_FUNCTION_GET_KEYWORD_QUALIFIER_in_out(x) x
+# define BOOST_PARAMETER_FUNCTION_KEYWORD_GET(x) \
+ BOOST_PP_CAT(BOOST_PARAMETETER_FUNCTION_GET_KEYWORD_QUALIFIER_, x)
+/**/
+
+// Returns the keyword of x, where x is either a keyword qualifier
+// or a keyword.
+//
+// k => k
+// out(k) => k
+// in_out(k) => k
+//
+# define BOOST_PARAMETER_FUNCTION_KEYWORD(x) \
+ BOOST_PP_IF( \
+ BOOST_PARAMETER_FUNCTION_IS_KEYWORD_QUALIFIER(x) \
+ , BOOST_PARAMETER_FUNCTION_KEYWORD_GET \
+ , x BOOST_PP_TUPLE_EAT(1) \
+ )(x)
+/**/
+
+# define BOOST_PARAMETER_FN_ARG_KEYWORD(x) \
+ BOOST_PARAMETER_FUNCTION_KEYWORD( \
+ BOOST_PARAMETER_FN_ARG_NAME(x) \
+ )
+
+// Builds forwarding functions.
+
+# define BOOST_PARAMETER_FUNCTION_FWD_FUNCTION_TEMPLATE_Z(z, n) \
+ template<BOOST_PP_ENUM_PARAMS_Z(z, n, class ParameterArgumentType)>
+/**/
+
+# if ! defined(BOOST_NO_SFINAE) && ! BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x592))
+# define BOOST_PARAMETER_FUNCTION_FWD_MATCH_Z(z, name, parameters, n) \
+ , typename boost::parameter::aux::match< \
+ parameters, BOOST_PP_ENUM_PARAMS(n, ParameterArgumentType) \
+ >::type = parameters()
+# else
+# define BOOST_PARAMETER_FUNCTION_FWD_MATCH_Z(z, name, parameters, n)
+# endif
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_PARAMETERS_NAME(base) \
+ BOOST_PP_CAT( \
+ boost_param_parameters_ \
+ , BOOST_PP_CAT(__LINE__, BOOST_PARAMETER_MEMBER_FUNCTION_NAME(base)) \
+ )
+
+// Produce a name for a result type metafunction for the function
+// named base
+# define BOOST_PARAMETER_FUNCTION_RESULT_NAME(base) \
+ BOOST_PP_CAT( \
+ boost_param_result_ \
+ , BOOST_PP_CAT(__LINE__,BOOST_PARAMETER_MEMBER_FUNCTION_NAME(base)) \
+ )
+
+// Can't do boost_param_impl_ ## basee because base might start with an underscore
+// daniel: what? how is that relevant? the reason for using CAT() is to make sure
+// base is expanded. i'm not sure we need to here, but it's more stable to do it.
+# define BOOST_PARAMETER_IMPL(base) \
+ BOOST_PP_CAT(boost_param_impl,BOOST_PARAMETER_MEMBER_FUNCTION_NAME(base))
+
+# define BOOST_PARAMETER_FUNCTION_FWD_FUNCTION00(z, n, r, data, elem) \
+ BOOST_PP_IF( \
+ n \
+ , BOOST_PARAMETER_FUNCTION_FWD_FUNCTION_TEMPLATE_Z, BOOST_PP_TUPLE_EAT(2) \
+ )(z,n) \
+ BOOST_PARAMETER_MEMBER_FUNCTION_STATIC(BOOST_PP_TUPLE_ELEM(7,3,data)) \
+ inline \
+ BOOST_PP_EXPR_IF(n, typename) \
+ BOOST_PARAMETER_FUNCTION_RESULT_NAME(BOOST_PP_TUPLE_ELEM(7,3,data))< \
+ BOOST_PP_EXPR_IF(n, typename) \
+ boost::parameter::aux::argument_pack< \
+ BOOST_PARAMETER_FUNCTION_PARAMETERS_NAME(BOOST_PP_TUPLE_ELEM(7,3,data)) \
+ BOOST_PP_COMMA_IF(n) \
+ BOOST_PP_IF( \
+ n, BOOST_PP_SEQ_ENUM, BOOST_PP_TUPLE_EAT(1) \
+ )(elem) \
+ >::type \
+ >::type \
+ BOOST_PARAMETER_MEMBER_FUNCTION_NAME(BOOST_PP_TUPLE_ELEM(7,3,data))( \
+ BOOST_PP_IF( \
+ n \
+ , BOOST_PP_SEQ_FOR_EACH_I_R \
+ , BOOST_PP_TUPLE_EAT(4) \
+ )( \
+ r \
+ , BOOST_PARAMETER_FUNCTION_ARGUMENT \
+ , ~ \
+ , elem \
+ ) \
+ BOOST_PP_IF(n, BOOST_PARAMETER_FUNCTION_FWD_MATCH_Z, BOOST_PP_TUPLE_EAT(4))( \
+ z \
+ , BOOST_PP_TUPLE_ELEM(7,3,data) \
+ , BOOST_PARAMETER_FUNCTION_PARAMETERS_NAME(BOOST_PP_TUPLE_ELEM(7,3,data)) \
+ , n \
+ ) \
+ ) BOOST_PP_EXPR_IF(BOOST_PP_TUPLE_ELEM(7,4,data), const) \
+ { \
+ return BOOST_PARAMETER_IMPL(BOOST_PP_TUPLE_ELEM(7,3,data))( \
+ BOOST_PARAMETER_FUNCTION_PARAMETERS_NAME(BOOST_PP_TUPLE_ELEM(7,3,data))()( \
+ BOOST_PP_ENUM_PARAMS_Z(z, n, a) \
+ ) \
+ ); \
+ }
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_FWD_FUNCTION0(r, data, elem) \
+ BOOST_PARAMETER_FUNCTION_FWD_FUNCTION00( \
+ BOOST_PP_TUPLE_ELEM(7,0,data) \
+ , BOOST_PP_TUPLE_ELEM(7,1,data) \
+ , r \
+ , data \
+ , elem \
+ )
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_FWD_FUNCTION_ARITY_0(z, n, data) \
+ BOOST_PARAMETER_FUNCTION_FWD_FUNCTION00( \
+ z, n, BOOST_PP_DEDUCE_R() \
+ , (z, n, BOOST_PP_TUPLE_REM(5) data) \
+ , ~ \
+ )
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_FWD_FUNCTION_ARITY_N(z, n, data) \
+ BOOST_PP_SEQ_FOR_EACH( \
+ BOOST_PARAMETER_FUNCTION_FWD_FUNCTION0 \
+ , (z, n, BOOST_PP_TUPLE_REM(5) data) \
+ , BOOST_PP_SEQ_FOR_EACH_PRODUCT( \
+ BOOST_PARAMETER_FUNCTION_FWD_PRODUCT \
+ , BOOST_PP_SEQ_FIRST_N( \
+ n, BOOST_PP_TUPLE_ELEM(5,3,data) \
+ ) \
+ ) \
+ )
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_FWD_FUNCTION(z, n, data) \
+ BOOST_PP_IF( \
+ n \
+ , BOOST_PARAMETER_FUNCTION_FWD_FUNCTION_ARITY_N \
+ , BOOST_PARAMETER_FUNCTION_FWD_FUNCTION_ARITY_0 \
+ )(z,n,data) \
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_FWD_FUNCTIONS0( \
+ result,name,args,const_,combinations,range \
+) \
+ BOOST_PP_REPEAT_FROM_TO( \
+ BOOST_PP_TUPLE_ELEM(2,0,range), BOOST_PP_TUPLE_ELEM(2,1,range) \
+ , BOOST_PARAMETER_FUNCTION_FWD_FUNCTION \
+ , (result,name,const_,combinations,BOOST_PP_TUPLE_ELEM(2,1,range)) \
+ )
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_FWD_FUNCTIONS(result,name,args, const_, combinations) \
+ BOOST_PARAMETER_FUNCTION_FWD_FUNCTIONS0( \
+ result, name, args, const_, combinations, BOOST_PARAMETER_ARITY_RANGE(args) \
+ )
+/**/
+
+// Builds boost::parameter::parameters<> specialization
+# define BOOST_PARAMETER_FUNCTION_PARAMETERS_QUALIFIER_optional(tag) \
+ optional<tag
+
+# define BOOST_PARAMETER_FUNCTION_PARAMETERS_QUALIFIER_required(tag) \
+ required<tag
+
+# define BOOST_PARAMETER_FUNCTION_PARAMETERS_QUALIFIER_deduced_optional(tag) \
+ optional<boost::parameter::deduced<tag>
+
+# define BOOST_PARAMETER_FUNCTION_PARAMETERS_QUALIFIER_deduced_required(tag) \
+ required<boost::parameter::deduced<tag>
+
+# if !BOOST_WORKAROUND(BOOST_MSVC, < 1300) && !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+
+# if BOOST_WORKAROUND(BOOST_MSVC, == 1300)
+# define BOOST_PARAMETER_PREDICATE_TYPE(p) void*(*) (void* p)
+# else
+# define BOOST_PARAMETER_PREDICATE_TYPE(p) void p
+# endif
+
+# define BOOST_PARAMETER_FUNCTION_PARAMETERS_M(r,tag_namespace,i,elem) \
+ BOOST_PP_COMMA_IF(i) \
+ boost::parameter::BOOST_PP_CAT( \
+ BOOST_PARAMETER_FUNCTION_PARAMETERS_QUALIFIER_ \
+ , BOOST_PARAMETER_FN_ARG_QUALIFIER(elem) \
+ )( \
+ tag_namespace::BOOST_PARAMETER_FUNCTION_KEYWORD( \
+ BOOST_PARAMETER_FN_ARG_KEYWORD(elem) \
+ ) \
+ ) \
+ , typename boost::parameter::aux::unwrap_predicate< \
+ BOOST_PARAMETER_PREDICATE_TYPE(BOOST_PARAMETER_FN_ARG_PRED(elem)) \
+ >::type \
+ >
+# elif BOOST_WORKAROUND(BOOST_MSVC, < 1300)
+# define BOOST_PARAMETER_FUNCTION_PARAMETERS_M(r,tag_namespace,i,elem) \
+ BOOST_PP_COMMA_IF(i) \
+ boost::parameter::BOOST_PP_CAT( \
+ BOOST_PARAMETER_FUNCTION_PARAMETERS_QUALIFIER_ \
+ , BOOST_PARAMETER_FN_ARG_QUALIFIER(elem) \
+ )( \
+ tag_namespace::BOOST_PARAMETER_FUNCTION_KEYWORD( \
+ BOOST_PARAMETER_FN_ARG_KEYWORD(elem) \
+ ) \
+ ) \
+ , boost::parameter::aux::funptr_predicate< \
+ void* BOOST_PARAMETER_FN_ARG_PRED(elem) \
+ > \
+ >
+# elif BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+# define BOOST_PARAMETER_FUNCTION_PARAMETERS_M(r,tag_namespace,i,elem) \
+ BOOST_PP_COMMA_IF(i) \
+ boost::parameter::BOOST_PP_CAT( \
+ BOOST_PARAMETER_FUNCTION_PARAMETERS_QUALIFIER_ \
+ , BOOST_PARAMETER_FN_ARG_QUALIFIER(elem) \
+ )( \
+ tag_namespace::BOOST_PARAMETER_FUNCTION_KEYWORD( \
+ BOOST_PARAMETER_FN_ARG_KEYWORD(elem) \
+ ) \
+ ) \
+ , boost::mpl::always<boost::mpl::true_> \
+ >
+# endif
+
+# define BOOST_PARAMETER_FUNCTION_PARAMETERS(tag_namespace, base, args) \
+ template <class BoostParameterDummy> \
+ struct BOOST_PP_CAT( \
+ BOOST_PP_CAT(boost_param_params_, __LINE__) \
+ , BOOST_PARAMETER_MEMBER_FUNCTION_NAME(base) \
+ ) : boost::parameter::parameters< \
+ BOOST_PP_SEQ_FOR_EACH_I( \
+ BOOST_PARAMETER_FUNCTION_PARAMETERS_M, tag_namespace, args \
+ ) \
+ > \
+ {}; \
+ \
+ typedef BOOST_PP_CAT( \
+ BOOST_PP_CAT(boost_param_params_, __LINE__) \
+ , BOOST_PARAMETER_MEMBER_FUNCTION_NAME(base) \
+ )<int>
+
+// Defines result type metafunction
+# define BOOST_PARAMETER_FUNCTION_RESULT_ARG(z, _, i, x) \
+ BOOST_PP_COMMA_IF(i) class BOOST_PP_TUPLE_ELEM(3,1,x)
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_RESULT_(result, name, args) \
+ template <class Args> \
+ struct BOOST_PARAMETER_FUNCTION_RESULT_NAME(name) \
+ { \
+ typedef typename BOOST_PARAMETER_PARENTHESIZED_TYPE(result) type; \
+ };
+
+# if BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
+
+# define BOOST_PARAMETER_FUNCTION_RESULT(result, name, args) \
+ BOOST_PARAMETER_FUNCTION_RESULT_(result, name, args) \
+ template <> \
+ struct BOOST_PARAMETER_FUNCTION_RESULT_NAME(name)<int> \
+ { typedef int type; };
+
+# else
+
+# define BOOST_PARAMETER_FUNCTION_RESULT(result, name, args) \
+ BOOST_PARAMETER_FUNCTION_RESULT_(result, name, args)
+
+# endif
+
+// Defines implementation function
+# define BOOST_PARAMETER_FUNCTION_IMPL_HEAD(name) \
+ template <class Args> \
+ typename BOOST_PARAMETER_FUNCTION_RESULT_NAME(name)< \
+ Args \
+ >::type BOOST_PARAMETER_IMPL(name)(Args const& args)
+
+# define BOOST_PARAMETER_FUNCTION_IMPL_FWD(name) \
+ BOOST_PARAMETER_FUNCTION_IMPL_HEAD(name);
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_SPLIT_ARG_required(state, arg) \
+ ( \
+ BOOST_PP_INC(BOOST_PP_TUPLE_ELEM(4, 0, state)) \
+ , BOOST_PP_SEQ_PUSH_BACK(BOOST_PP_TUPLE_ELEM(4, 1, state), arg) \
+ , BOOST_PP_TUPLE_ELEM(4, 2, state) \
+ , BOOST_PP_TUPLE_ELEM(4, 3, state) \
+ )
+
+# define BOOST_PARAMETER_FUNCTION_SPLIT_ARG_deduced_required(state, arg) \
+ BOOST_PARAMETER_FUNCTION_SPLIT_ARG_required(state, arg)
+
+# define BOOST_PARAMETER_FUNCTION_SPLIT_ARG_optional(state, arg) \
+ ( \
+ BOOST_PP_TUPLE_ELEM(4, 0, state) \
+ , BOOST_PP_TUPLE_ELEM(4, 1, state) \
+ , BOOST_PP_INC(BOOST_PP_TUPLE_ELEM(4, 2, state)) \
+ , BOOST_PP_SEQ_PUSH_BACK(BOOST_PP_TUPLE_ELEM(4, 3, state), arg) \
+ )
+
+# define BOOST_PARAMETER_FUNCTION_SPLIT_ARG_deduced_optional(state, arg) \
+ BOOST_PARAMETER_FUNCTION_SPLIT_ARG_optional(state, arg)
+
+# define BOOST_PARAMETER_FUNCTION_SPLIT_ARG(s, state, arg) \
+ BOOST_PP_CAT( \
+ BOOST_PARAMETER_FUNCTION_SPLIT_ARG_ \
+ , BOOST_PARAMETER_FN_ARG_QUALIFIER(arg) \
+ )(state, arg)
+
+// Returns (required_count, required, optional_count, optionals) tuple
+# define BOOST_PARAMETER_FUNCTION_SPLIT_ARGS(args) \
+ BOOST_PP_SEQ_FOLD_LEFT( \
+ BOOST_PARAMETER_FUNCTION_SPLIT_ARG \
+ , (0,BOOST_PP_SEQ_NIL, 0,BOOST_PP_SEQ_NIL) \
+ , args \
+ )
+
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_ARG_NAME(keyword) \
+ BOOST_PP_CAT(BOOST_PP_CAT(keyword,_),type)
+
+// Helpers used as parameters to BOOST_PARAMETER_FUNCTION_DEFAULT_ARGUMENTS.
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_TEMPLATE_ARG(r, _, arg) \
+ , class BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_ARG_NAME( \
+ BOOST_PARAMETER_FN_ARG_KEYWORD(arg) \
+ )
+
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_ARG(r, _, arg) \
+ , BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_ARG_NAME( \
+ BOOST_PARAMETER_FN_ARG_KEYWORD(arg) \
+ )& BOOST_PARAMETER_FN_ARG_KEYWORD(arg)
+
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_PARAMETER(r, _, arg) \
+ , BOOST_PARAMETER_FN_ARG_KEYWORD(arg)
+
+// Produces a name for the dispatch functions.
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_NAME(name) \
+ BOOST_PP_CAT( \
+ boost_param_default_ \
+ , BOOST_PP_CAT(__LINE__, BOOST_PARAMETER_MEMBER_FUNCTION_NAME(name)) \
+ )
+
+// Helper macro used below to produce lists based on the keyword argument
+// names. macro is applied to every element. n is the number of
+// optional arguments that should be included.
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_ARGUMENTS(macro, n, split_args) \
+ BOOST_PP_SEQ_FOR_EACH( \
+ macro \
+ , ~ \
+ , BOOST_PP_TUPLE_ELEM(4,1,split_args) \
+ ) \
+ BOOST_PP_SEQ_FOR_EACH( \
+ macro \
+ , ~ \
+ , BOOST_PP_SEQ_FIRST_N( \
+ BOOST_PP_SUB(BOOST_PP_TUPLE_ELEM(4,2,split_args), n) \
+ , BOOST_PP_TUPLE_ELEM(4,3,split_args) \
+ ) \
+ )
+
+// Generates a keyword | default expression.
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_EVAL_DEFAULT(arg, tag_namespace) \
+ boost::parameter::keyword< \
+ tag_namespace::BOOST_PARAMETER_FN_ARG_KEYWORD(arg) \
+ >::instance | boost::parameter::aux::use_default_tag()
+
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_GET_ARG(arg, tag_ns) \
+ BOOST_PARAMETER_FUNCTION_CAST( \
+ args[ \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_EVAL_DEFAULT( \
+ arg, tag_ns \
+ ) \
+ ] \
+ , BOOST_PARAMETER_FN_ARG_PRED(arg) \
+ , Args \
+ )
+
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_BODY(name, n, split_args, tag_namespace) \
+ { \
+ return BOOST_PARAMETER_FUNCTION_DEFAULT_NAME(name)( \
+ (ResultType(*)())0 \
+ , args \
+ , 0L \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_ARGUMENTS( \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_PARAMETER \
+ , n \
+ , split_args \
+ ) \
+ , BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_GET_ARG( \
+ BOOST_PP_SEQ_ELEM( \
+ BOOST_PP_SUB(BOOST_PP_TUPLE_ELEM(4,2,split_args), n) \
+ , BOOST_PP_TUPLE_ELEM(4,3,split_args) \
+ ) \
+ , tag_namespace \
+ ) \
+ ); \
+ }
+
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_EVAL_ACTUAL_DEFAULT(arg) \
+ BOOST_PARAMETER_FUNCTION_CAST( \
+ boost::parameter::aux::as_lvalue(BOOST_PARAMETER_FN_ARG_DEFAULT(arg), 0L) \
+ , BOOST_PARAMETER_FN_ARG_PRED(arg) \
+ , Args \
+ )
+
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_EVAL_DEFAULT_BODY(name, n, split_args, tag_ns, const_) \
+ template < \
+ class ResultType \
+ , class Args \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_ARGUMENTS( \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_TEMPLATE_ARG \
+ , BOOST_PP_INC(n) \
+ , split_args \
+ ) \
+ > \
+ BOOST_PARAMETER_MEMBER_FUNCTION_STATIC(name) \
+ ResultType BOOST_PARAMETER_FUNCTION_DEFAULT_NAME(name)( \
+ ResultType(*)() \
+ , Args const& args \
+ , long \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_ARGUMENTS( \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_ARG \
+ , BOOST_PP_INC(n) \
+ , split_args \
+ ) \
+ , boost::parameter::aux::use_default_tag \
+ ) BOOST_PP_EXPR_IF(const_, const) \
+ { \
+ return BOOST_PARAMETER_FUNCTION_DEFAULT_NAME(name)( \
+ (ResultType(*)())0 \
+ , args \
+ , 0L \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_ARGUMENTS( \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_PARAMETER \
+ , BOOST_PP_INC(n) \
+ , split_args \
+ ) \
+ , BOOST_PARAMETER_FUNCTION_DEFAULT_EVAL_ACTUAL_DEFAULT( \
+ BOOST_PP_SEQ_ELEM( \
+ BOOST_PP_SUB(BOOST_PP_TUPLE_ELEM(4,2,split_args), BOOST_PP_INC(n)) \
+ , BOOST_PP_TUPLE_ELEM(4,3,split_args) \
+ ) \
+ ) \
+ ); \
+ }
+
+// Produces a forwarding layer in the default evaluation machine.
+//
+// data is a tuple:
+//
+// (name, split_args)
+//
+// Where name is the base name of the function, and split_args is a tuple:
+//
+// (required_count, required_args, optional_count, required_args)
+//
+
+
+// defines the actual function body for BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION below.
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION0(z, n, data) \
+ template < \
+ class ResultType \
+ , class Args \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_ARGUMENTS( \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_TEMPLATE_ARG \
+ , n \
+ , BOOST_PP_TUPLE_ELEM(5,1,data) \
+ ) \
+ > \
+ BOOST_PARAMETER_MEMBER_FUNCTION_STATIC(BOOST_PP_TUPLE_ELEM(5,0,data)) \
+ ResultType BOOST_PARAMETER_FUNCTION_DEFAULT_NAME(BOOST_PP_TUPLE_ELEM(5,0,data))( \
+ ResultType(*)() \
+ , Args const& args \
+ , int \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_ARGUMENTS( \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_ARG \
+ , n \
+ , BOOST_PP_TUPLE_ELEM(5,1,data) \
+ ) \
+ ) BOOST_PP_EXPR_IF(BOOST_PP_TUPLE_ELEM(5,2,data), const) \
+ BOOST_PP_IF( \
+ n \
+ , BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_BODY \
+ , ; BOOST_PP_TUPLE_EAT(4) \
+ )( \
+ BOOST_PP_TUPLE_ELEM(5,0,data) \
+ , n \
+ , BOOST_PP_TUPLE_ELEM(5,1,data) \
+ , BOOST_PP_TUPLE_ELEM(5,3,data) \
+ )
+
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION(z, n, data) \
+ BOOST_PP_IF( \
+ BOOST_PP_AND( \
+ BOOST_PP_NOT(n) \
+ , BOOST_PP_TUPLE_ELEM(5,4,data) \
+ ) \
+ , BOOST_PP_TUPLE_EAT(3) \
+ , BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION0 \
+ )(z, n, data) \
+ BOOST_PP_IF( \
+ BOOST_PP_EQUAL(n, BOOST_PP_TUPLE_ELEM(4,2,BOOST_PP_TUPLE_ELEM(5,1,data))) \
+ , BOOST_PP_TUPLE_EAT(5) \
+ , BOOST_PARAMETER_FUNCTION_DEFAULT_EVAL_DEFAULT_BODY \
+ )( \
+ BOOST_PP_TUPLE_ELEM(5,0,data) \
+ , n \
+ , BOOST_PP_TUPLE_ELEM(5,1,data) \
+ , BOOST_PP_TUPLE_ELEM(5,3,data) \
+ , BOOST_PP_TUPLE_ELEM(5,2,data) \
+ )
+
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_GET_ARG(r, tag_ns, arg) \
+ , BOOST_PARAMETER_FUNCTION_CAST( \
+ args[ \
+ boost::parameter::keyword<tag_ns::BOOST_PARAMETER_FN_ARG_KEYWORD(arg)>::instance \
+ ] \
+ , BOOST_PARAMETER_FN_ARG_PRED(arg) \
+ , Args \
+ )
+
+// Generates the function template that recives a ArgumentPack, and then
+// goes on to call the layers of overloads generated by
+// BOOST_PARAMETER_FUNCTION_DEFAULT_LAYER.
+# define BOOST_PARAMETER_FUNCTION_INITIAL_DISPATCH_FUNCTION(name, split_args, const_, tag_ns) \
+ template <class Args> \
+ typename BOOST_PARAMETER_FUNCTION_RESULT_NAME(name)<Args>::type \
+ BOOST_PARAMETER_MEMBER_FUNCTION_STATIC(name) \
+ BOOST_PARAMETER_IMPL(name)(Args const& args) BOOST_PP_EXPR_IF(const_, const) \
+ { \
+ return BOOST_PARAMETER_FUNCTION_DEFAULT_NAME(name)( \
+ (typename BOOST_PARAMETER_FUNCTION_RESULT_NAME(name)<Args>::type(*)())0 \
+ , args \
+ , 0L \
+ \
+ BOOST_PP_SEQ_FOR_EACH( \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_GET_ARG \
+ , tag_ns \
+ , BOOST_PP_TUPLE_ELEM(4,1,split_args) \
+ ) \
+ \
+ ); \
+ }
+
+// Helper for BOOST_PARAMETER_FUNCTION_DEFAULT_LAYER below.
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_LAYER_AUX( \
+ name, split_args, skip_fwd_decl, const_, tag_namespace \
+ ) \
+ BOOST_PP_REPEAT_FROM_TO( \
+ 0 \
+ , BOOST_PP_INC(BOOST_PP_TUPLE_ELEM(4, 2, split_args)) \
+ , BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION \
+ , (name, split_args, const_, tag_namespace, skip_fwd_decl) \
+ ) \
+ \
+ BOOST_PARAMETER_FUNCTION_INITIAL_DISPATCH_FUNCTION(name, split_args, const_, tag_namespace) \
+\
+ template < \
+ class ResultType \
+ , class Args \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_ARGUMENTS( \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_TEMPLATE_ARG \
+ , 0 \
+ , split_args \
+ ) \
+ > \
+ BOOST_PARAMETER_MEMBER_FUNCTION_STATIC(name) \
+ ResultType BOOST_PARAMETER_FUNCTION_DEFAULT_NAME(name)( \
+ ResultType(*)() \
+ , Args const& args \
+ , int \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_ARGUMENTS( \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_FUNCTION_ARG \
+ , 0 \
+ , split_args \
+ ) \
+ ) BOOST_PP_EXPR_IF(const_, const)
+
+// Generates a bunch of forwarding functions that each extract
+// one more argument.
+# define BOOST_PARAMETER_FUNCTION_DEFAULT_LAYER(name, args, skip_fwd_decl, const_, tag_ns) \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_LAYER_AUX( \
+ name, BOOST_PARAMETER_FUNCTION_SPLIT_ARGS(args), skip_fwd_decl, const_, tag_ns \
+ )
+/**/
+
+// Defines the result metafunction and the parameters specialization.
+# define BOOST_PARAMETER_FUNCTION_HEAD(result, name, tag_namespace, args) \
+ BOOST_PARAMETER_FUNCTION_RESULT(result, name, args) \
+ \
+ BOOST_PARAMETER_FUNCTION_PARAMETERS(tag_namespace, name, args) \
+ BOOST_PARAMETER_FUNCTION_PARAMETERS_NAME(name); \
+
+// Helper for BOOST_PARAMETER_FUNCTION below.
+# define BOOST_PARAMETER_FUNCTION_AUX(result, name, tag_namespace, args) \
+ BOOST_PARAMETER_FUNCTION_HEAD(result, name, tag_namespace, args) \
+ BOOST_PARAMETER_FUNCTION_IMPL_HEAD(name); \
+\
+ BOOST_PARAMETER_FUNCTION_FWD_FUNCTIONS( \
+ result, name, args, 0 \
+ , BOOST_PARAMETER_FUNCTION_FWD_COMBINATIONS(args) \
+ ) \
+ \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_LAYER(name, args, 0, 0, tag_namespace)
+
+// Defines a Boost.Parameter enabled function with the new syntax.
+# define BOOST_PARAMETER_FUNCTION(result, name, tag_namespace, args) \
+ BOOST_PARAMETER_FUNCTION_AUX( \
+ result, name, tag_namespace \
+ , BOOST_PARAMETER_FLATTEN(3, 2, 3, args) \
+ ) \
+/**/
+
+// Defines a Boost.Parameter enabled function.
+# define BOOST_PARAMETER_BASIC_FUNCTION_AUX(result, name, tag_namespace, args) \
+ BOOST_PARAMETER_FUNCTION_HEAD(result, name, tag_namespace, args) \
+ \
+ BOOST_PARAMETER_FUNCTION_IMPL_FWD(name) \
+ \
+ BOOST_PARAMETER_FUNCTION_FWD_FUNCTIONS( \
+ result, name, args, 0 \
+ , BOOST_PARAMETER_FUNCTION_FWD_COMBINATIONS(args) \
+ ) \
+ \
+ BOOST_PARAMETER_FUNCTION_IMPL_HEAD(name)
+
+# define BOOST_PARAMETER_BASIC_FUNCTION(result, name, tag_namespace, args) \
+ BOOST_PARAMETER_BASIC_FUNCTION_AUX( \
+ result, name, tag_namespace \
+ , BOOST_PARAMETER_FLATTEN(2, 2, 3, args) \
+ ) \
+/**/
+
+// Defines a Boost.Parameter enabled member function.
+# define BOOST_PARAMETER_BASIC_MEMBER_FUNCTION_AUX(result, name, tag_namespace, args, const_) \
+ BOOST_PARAMETER_FUNCTION_HEAD(result, name, tag_namespace, args) \
+ \
+ BOOST_PARAMETER_FUNCTION_FWD_FUNCTIONS( \
+ result, name, args, const_ \
+ , BOOST_PARAMETER_FUNCTION_FWD_COMBINATIONS(args) \
+ ) \
+ \
+ BOOST_PARAMETER_FUNCTION_IMPL_HEAD(name) BOOST_PP_EXPR_IF(const_, const) \
+/**/
+
+# define BOOST_PARAMETER_BASIC_MEMBER_FUNCTION(result, name, tag_namespace, args) \
+ BOOST_PARAMETER_BASIC_MEMBER_FUNCTION_AUX( \
+ result, name, tag_namespace \
+ , BOOST_PARAMETER_FLATTEN(2, 2, 3, args) \
+ , 0 \
+ )
+/**/
+
+# define BOOST_PARAMETER_BASIC_CONST_MEMBER_FUNCTION(result, name, tag_namespace, args) \
+ BOOST_PARAMETER_BASIC_MEMBER_FUNCTION_AUX( \
+ result, name, tag_namespace \
+ , BOOST_PARAMETER_FLATTEN(2, 2, 3, args) \
+ , 1 \
+ )
+/**/
+
+
+
+# define BOOST_PARAMETER_MEMBER_FUNCTION_AUX(result, name, tag_namespace, const_, args) \
+ BOOST_PARAMETER_FUNCTION_HEAD(result, name, tag_namespace, args) \
+\
+ BOOST_PARAMETER_FUNCTION_FWD_FUNCTIONS( \
+ result, name, args, const_ \
+ , BOOST_PARAMETER_FUNCTION_FWD_COMBINATIONS(args) \
+ ) \
+ \
+ BOOST_PARAMETER_FUNCTION_DEFAULT_LAYER(name, args, 1, const_, tag_namespace)
+
+// Defines a Boost.Parameter enabled function with the new syntax.
+# define BOOST_PARAMETER_MEMBER_FUNCTION(result, name, tag_namespace, args) \
+ BOOST_PARAMETER_MEMBER_FUNCTION_AUX( \
+ result, name, tag_namespace, 0 \
+ , BOOST_PARAMETER_FLATTEN(3, 2, 3, args) \
+ ) \
+/**/
+
+# define BOOST_PARAMETER_CONST_MEMBER_FUNCTION(result, name, tag_namespace, args) \
+ BOOST_PARAMETER_MEMBER_FUNCTION_AUX( \
+ result, name, tag_namespace, 1 \
+ , BOOST_PARAMETER_FLATTEN(3, 2, 3, args) \
+ ) \
+/**/
+
+// Defines a Boost.Parameter enabled constructor.
+
+# define BOOST_PARAMETER_FUNCTION_ARGUMENT(r, _, i, elem) \
+ BOOST_PP_COMMA_IF(i) elem& BOOST_PP_CAT(a, i)
+/**/
+
+# if BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
+
+// Older MSVC can't do what's necessary to handle commas in base names; just
+// use a typedef instead if you have a base name that contains commas.
+# define BOOST_PARAMETER_PARENTHESIZED_BASE(x) BOOST_PP_SEQ_HEAD(x)
+
+# else
+
+# define BOOST_PARAMETER_PARENTHESIZED_BASE(x) BOOST_PARAMETER_PARENTHESIZED_TYPE(x)
+
+# endif
+
+# define BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTOR00(z, n, r, data, elem) \
+ BOOST_PP_IF( \
+ n \
+ , BOOST_PARAMETER_FUNCTION_FWD_FUNCTION_TEMPLATE_Z, BOOST_PP_TUPLE_EAT(2) \
+ )(z, n) \
+ BOOST_PP_EXPR_IF(BOOST_PP_EQUAL(n,1), explicit) \
+ BOOST_PP_TUPLE_ELEM(6,2,data)( \
+ BOOST_PP_IF( \
+ n \
+ , BOOST_PP_SEQ_FOR_EACH_I_R \
+ , BOOST_PP_TUPLE_EAT(4) \
+ )( \
+ r \
+ , BOOST_PARAMETER_FUNCTION_ARGUMENT \
+ , ~ \
+ , elem \
+ ) \
+ BOOST_PP_IF(n, BOOST_PARAMETER_FUNCTION_FWD_MATCH_Z, BOOST_PP_TUPLE_EAT(4))( \
+ z \
+ , BOOST_PP_TUPLE_ELEM(6,3,data) \
+ , BOOST_PP_CAT(constructor_parameters, __LINE__) \
+ , n \
+ ) \
+ ) \
+ : BOOST_PARAMETER_PARENTHESIZED_BASE(BOOST_PP_TUPLE_ELEM(6,3,data)) ( \
+ BOOST_PP_CAT(constructor_parameters, __LINE__)()( \
+ BOOST_PP_ENUM_PARAMS_Z(z, n, a) \
+ ) \
+ ) \
+ {}
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTOR0(r, data, elem) \
+ BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTOR00( \
+ BOOST_PP_TUPLE_ELEM(6,0,data) \
+ , BOOST_PP_TUPLE_ELEM(6,1,data) \
+ , r \
+ , data \
+ , elem \
+ )
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_FWD_PRODUCT(r, product) \
+ (product)
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTOR_ARITY_0(z, n, data) \
+ BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTOR00( \
+ z, n, BOOST_PP_DEDUCE_R() \
+ , (z, n, BOOST_PP_TUPLE_REM(4) data) \
+ , ~ \
+ )
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTOR_ARITY_N(z, n, data) \
+ BOOST_PP_SEQ_FOR_EACH( \
+ BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTOR0 \
+ , (z, n, BOOST_PP_TUPLE_REM(4) data) \
+ , BOOST_PP_SEQ_FOR_EACH_PRODUCT( \
+ BOOST_PARAMETER_FUNCTION_FWD_PRODUCT \
+ , BOOST_PP_SEQ_FIRST_N( \
+ n, BOOST_PP_TUPLE_ELEM(4,2,data) \
+ ) \
+ ) \
+ )
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTOR(z, n, data) \
+ BOOST_PP_IF( \
+ n \
+ , BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTOR_ARITY_N \
+ , BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTOR_ARITY_0 \
+ )(z,n,data) \
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTORS0(class_,base,args,combinations,range) \
+ BOOST_PP_REPEAT_FROM_TO( \
+ BOOST_PP_TUPLE_ELEM(2,0,range), BOOST_PP_TUPLE_ELEM(2,1,range) \
+ , BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTOR \
+ , (class_,base,combinations,BOOST_PP_TUPLE_ELEM(2,1,range)) \
+ )
+/**/
+
+# define BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTORS(class_,base,args,combinations) \
+ BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTORS0( \
+ class_, base, args, combinations, BOOST_PARAMETER_ARITY_RANGE(args) \
+ )
+/**/
+
+# define BOOST_PARAMETER_CONSTRUCTOR_AUX(class_, base, tag_namespace, args) \
+ BOOST_PARAMETER_FUNCTION_PARAMETERS(tag_namespace, ctor, args) \
+ BOOST_PP_CAT(constructor_parameters, __LINE__); \
+\
+ BOOST_PARAMETER_FUNCTION_FWD_CONSTRUCTORS( \
+ class_, base, args \
+ , BOOST_PARAMETER_FUNCTION_FWD_COMBINATIONS(args) \
+ ) \
+/**/
+
+# define BOOST_PARAMETER_CONSTRUCTOR(class_, base, tag_namespace, args) \
+ BOOST_PARAMETER_CONSTRUCTOR_AUX( \
+ class_, base, tag_namespace \
+ , BOOST_PARAMETER_FLATTEN(2, 2, 3, args) \
+ )
+/**/
+
+# ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
+# define BOOST_PARAMETER_FUNCTION_FWD_COMBINATION(r, _, i, elem) \
+ (BOOST_PP_IF( \
+ BOOST_PARAMETER_FUNCTION_IS_KEYWORD_QUALIFIER( \
+ BOOST_PARAMETER_FN_ARG_NAME(elem) \
+ ) \
+ , (const ParameterArgumentType ## i)(ParameterArgumentType ## i) \
+ , (const ParameterArgumentType ## i) \
+ ))
+// MSVC6.5 lets us bind rvalues to T&.
+# elif BOOST_WORKAROUND(BOOST_MSVC, < 1300)
+# define BOOST_PARAMETER_FUNCTION_FWD_COMBINATION(r, _, i, elem) \
+ (BOOST_PP_IF( \
+ BOOST_PARAMETER_FUNCTION_IS_KEYWORD_QUALIFIER( \
+ BOOST_PARAMETER_FN_ARG_NAME(elem) \
+ ) \
+ , (ParameterArgumentType ## i) \
+ , (const ParameterArgumentType ## i) \
+ ))
+// No partial ordering. This feature doesn't work.
+// This is exactly the same as for VC6.5, but we might change it later.
+# else
+# define BOOST_PARAMETER_FUNCTION_FWD_COMBINATION(r, _, i, elem) \
+ (BOOST_PP_IF( \
+ BOOST_PARAMETER_FUNCTION_IS_KEYWORD_QUALIFIER( \
+ BOOST_PARAMETER_FN_ARG_NAME(elem) \
+ ) \
+ , (ParameterArgumentType ## i) \
+ , (const ParameterArgumentType ## i) \
+ ))
+# endif
+
+# define BOOST_PARAMETER_FUNCTION_FWD_COMBINATIONS(args) \
+ BOOST_PP_SEQ_FOR_EACH_I(BOOST_PARAMETER_FUNCTION_FWD_COMBINATION, ~, args)
+
+#endif // BOOST_PARAMETER_PREPROCESSOR_060206_HPP
+
diff --git a/3rdParty/Boost/src/boost/parameter/value_type.hpp b/3rdParty/Boost/src/boost/parameter/value_type.hpp
new file mode 100755
index 0000000..7415a5c
--- /dev/null
+++ b/3rdParty/Boost/src/boost/parameter/value_type.hpp
@@ -0,0 +1,108 @@
+// Copyright Daniel Wallin 2006. Use, modification and distribution is
+// subject to the Boost Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_PARAMETER_VALUE_TYPE_060921_HPP
+# define BOOST_PARAMETER_VALUE_TYPE_060921_HPP
+
+# include <boost/mpl/apply.hpp>
+# include <boost/mpl/assert.hpp>
+# include <boost/mpl/and.hpp>
+# include <boost/parameter/aux_/result_of0.hpp>
+# include <boost/parameter/aux_/void.hpp>
+# include <boost/type_traits/is_same.hpp>
+
+# if BOOST_WORKAROUND(BOOST_MSVC, < 1300)
+# include <boost/mpl/eval_if.hpp>
+# endif
+
+namespace boost { namespace parameter {
+
+// A metafunction that, given an argument pack, returns the type of
+// the parameter identified by the given keyword. If no such
+// parameter has been specified, returns Default
+
+# if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) \
+ || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+template <class Parameters, class Keyword, class Default>
+struct value_type0
+{
+ typedef typename mpl::apply_wrap3<
+ typename Parameters::binding,Keyword,Default,mpl::false_
+ >::type type;
+
+ BOOST_MPL_ASSERT_NOT((
+ mpl::and_<
+ is_same<Default, void_>
+ , is_same<type, void_>
+ >
+ ));
+};
+# endif
+
+template <class Parameters, class Keyword, class Default = void_>
+# if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)
+struct value_type
+# else
+struct value_type_eti
+# endif
+{
+# if BOOST_WORKAROUND(BOOST_MSVC, <= 1300) \
+ || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
+ typedef typename mpl::eval_if<
+ mpl::is_placeholder<Parameters>
+ , mpl::identity<int>
+ , value_type0<Parameters,Keyword,Default>
+ >::type type;
+# else
+ typedef typename mpl::apply_wrap3<
+ typename Parameters::binding,Keyword,Default,mpl::false_
+ >::type type;
+
+ BOOST_MPL_ASSERT_NOT((
+ mpl::and_<
+ is_same<Default, void_>
+ , is_same<type, void_>
+ >
+ ));
+# endif
+
+# if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)
+ BOOST_MPL_AUX_LAMBDA_SUPPORT(3,value_type,(Parameters,Keyword,Default))
+# endif
+};
+
+# if BOOST_WORKAROUND(BOOST_MSVC, < 1300)
+template <class Parameters, class Keyword, class Default = void_>
+struct value_type
+{
+ typedef typename mpl::eval_if<
+ is_same<Parameters, int>
+ , mpl::identity<int>
+ , value_type_eti<Parameters, Keyword, Default>
+ >::type type;
+
+ BOOST_MPL_AUX_LAMBDA_SUPPORT(3,value_type,(Parameters,Keyword,Default))
+};
+# endif
+
+// A metafunction that, given an argument pack, returns the type of
+// the parameter identified by the given keyword. If no such
+// parameter has been specified, returns the type returned by invoking
+// DefaultFn
+template <class Parameters, class Keyword, class DefaultFn>
+struct lazy_value_type
+{
+ typedef typename mpl::apply_wrap3<
+ typename Parameters::binding
+ , Keyword
+ , typename aux::result_of0<DefaultFn>::type
+ , mpl::false_
+ >::type type;
+};
+
+
+}} // namespace boost::parameter
+
+#endif // BOOST_PARAMETER_VALUE_TYPE_060921_HPP
+
diff --git a/3rdParty/Boost/src/boost/preprocessor/arithmetic.hpp b/3rdParty/Boost/src/boost/preprocessor/arithmetic.hpp
new file mode 100644
index 0000000..b1be781
--- /dev/null
+++ b/3rdParty/Boost/src/boost/preprocessor/arithmetic.hpp
@@ -0,0 +1,25 @@
+# /* Copyright (C) 2001
+# * Housemarque Oy
+# * http://www.housemarque.com
+# *
+# * Distributed under the Boost Software License, Version 1.0. (See
+# * accompanying file LICENSE_1_0.txt or copy at
+# * http://www.boost.org/LICENSE_1_0.txt)
+# */
+#
+# /* Revised by Paul Mensonides (2002) */
+#
+# /* See http://www.boost.org for most recent version. */
+#
+# ifndef BOOST_PREPROCESSOR_ARITHMETIC_HPP
+# define BOOST_PREPROCESSOR_ARITHMETIC_HPP
+#
+# include <boost/preprocessor/arithmetic/add.hpp>
+# include <boost/preprocessor/arithmetic/dec.hpp>
+# include <boost/preprocessor/arithmetic/div.hpp>
+# include <boost/preprocessor/arithmetic/inc.hpp>
+# include <boost/preprocessor/arithmetic/mod.hpp>
+# include <boost/preprocessor/arithmetic/mul.hpp>
+# include <boost/preprocessor/arithmetic/sub.hpp>
+#
+# endif
diff --git a/3rdParty/Boost/src/boost/preprocessor/arithmetic/div.hpp b/3rdParty/Boost/src/boost/preprocessor/arithmetic/div.hpp
new file mode 100644
index 0000000..277596c
--- /dev/null
+++ b/3rdParty/Boost/src/boost/preprocessor/arithmetic/div.hpp
@@ -0,0 +1,39 @@
+# /* Copyright (C) 2001
+# * Housemarque Oy
+# * http://www.housemarque.com
+# *
+# * Distributed under the Boost Software License, Version 1.0. (See
+# * accompanying file LICENSE_1_0.txt or copy at
+# * http://www.boost.org/LICENSE_1_0.txt)
+# */
+#
+# /* Revised by Paul Mensonides (2002) */
+#
+# /* See http://www.boost.org for most recent version. */
+#
+# ifndef BOOST_PREPROCESSOR_ARITHMETIC_DIV_HPP
+# define BOOST_PREPROCESSOR_ARITHMETIC_DIV_HPP
+#
+# include <boost/preprocessor/arithmetic/detail/div_base.hpp>
+# include <boost/preprocessor/config/config.hpp>
+# include <boost/preprocessor/tuple/elem.hpp>
+#
+# /* BOOST_PP_DIV */
+#
+# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG()
+# define BOOST_PP_DIV(x, y) BOOST_PP_TUPLE_ELEM(3, 0, BOOST_PP_DIV_BASE(x, y))
+# else
+# define BOOST_PP_DIV(x, y) BOOST_PP_DIV_I(x, y)
+# define BOOST_PP_DIV_I(x, y) BOOST_PP_TUPLE_ELEM(3, 0, BOOST_PP_DIV_BASE(x, y))
+# endif
+#
+# /* BOOST_PP_DIV_D */
+#
+# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG()
+# define BOOST_PP_DIV_D(d, x, y) BOOST_PP_TUPLE_ELEM(3, 0, BOOST_PP_DIV_BASE_D(d, x, y))
+# else
+# define BOOST_PP_DIV_D(d, x, y) BOOST_PP_DIV_D_I(d, x, y)
+# define BOOST_PP_DIV_D_I(d, x, y) BOOST_PP_TUPLE_ELEM(3, 0, BOOST_PP_DIV_BASE_D(d, x, y))
+# endif
+#
+# endif
diff --git a/3rdParty/Boost/src/boost/preprocessor/arithmetic/mul.hpp b/3rdParty/Boost/src/boost/preprocessor/arithmetic/mul.hpp
new file mode 100644
index 0000000..f3d9ffc
--- /dev/null
+++ b/3rdParty/Boost/src/boost/preprocessor/arithmetic/mul.hpp
@@ -0,0 +1,53 @@
+# /* Copyright (C) 2001
+# * Housemarque Oy
+# * http://www.housemarque.com
+# *
+# * Distributed under the Boost Software License, Version 1.0. (See
+# * accompanying file LICENSE_1_0.txt or copy at
+# * http://www.boost.org/LICENSE_1_0.txt)
+# */
+#
+# /* Revised by Paul Mensonides (2002) */
+#
+# /* See http://www.boost.org for most recent version. */
+#
+# ifndef BOOST_PREPROCESSOR_ARITHMETIC_MUL_HPP
+# define BOOST_PREPROCESSOR_ARITHMETIC_MUL_HPP
+#
+# include <boost/preprocessor/arithmetic/add.hpp>
+# include <boost/preprocessor/arithmetic/dec.hpp>
+# include <boost/preprocessor/config/config.hpp>
+# include <boost/preprocessor/control/while.hpp>
+# include <boost/preprocessor/tuple/elem.hpp>
+# include <boost/preprocessor/tuple/rem.hpp>
+#
+# /* BOOST_PP_MUL */
+#
+# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG()
+# define BOOST_PP_MUL(x, y) BOOST_PP_TUPLE_ELEM(3, 0, BOOST_PP_WHILE(BOOST_PP_MUL_P, BOOST_PP_MUL_O, (0, x, y)))
+# else
+# define BOOST_PP_MUL(x, y) BOOST_PP_MUL_I(x, y)
+# define BOOST_PP_MUL_I(x, y) BOOST_PP_TUPLE_ELEM(3, 0, BOOST_PP_WHILE(BOOST_PP_MUL_P, BOOST_PP_MUL_O, (0, x, y)))
+# endif
+#
+# define BOOST_PP_MUL_P(d, rxy) BOOST_PP_TUPLE_ELEM(3, 2, rxy)
+#
+# if BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_STRICT()
+# define BOOST_PP_MUL_O(d, rxy) BOOST_PP_MUL_O_IM(d, BOOST_PP_TUPLE_REM_3 rxy)
+# define BOOST_PP_MUL_O_IM(d, im) BOOST_PP_MUL_O_I(d, im)
+# else
+# define BOOST_PP_MUL_O(d, rxy) BOOST_PP_MUL_O_I(d, BOOST_PP_TUPLE_ELEM(3, 0, rxy), BOOST_PP_TUPLE_ELEM(3, 1, rxy), BOOST_PP_TUPLE_ELEM(3, 2, rxy))
+# endif
+#
+# define BOOST_PP_MUL_O_I(d, r, x, y) (BOOST_PP_ADD_D(d, r, x), x, BOOST_PP_DEC(y))
+#
+# /* BOOST_PP_MUL_D */
+#
+# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG()
+# define BOOST_PP_MUL_D(d, x, y) BOOST_PP_TUPLE_ELEM(3, 0, BOOST_PP_WHILE_ ## d(BOOST_PP_MUL_P, BOOST_PP_MUL_O, (0, x, y)))
+# else
+# define BOOST_PP_MUL_D(d, x, y) BOOST_PP_MUL_D_I(d, x, y)
+# define BOOST_PP_MUL_D_I(d, x, y) BOOST_PP_TUPLE_ELEM(3, 0, BOOST_PP_WHILE_ ## d(BOOST_PP_MUL_P, BOOST_PP_MUL_O, (0, x, y)))
+# endif
+#
+# endif
diff --git a/3rdParty/Boost/src/boost/preprocessor/detail/is_nullary.hpp b/3rdParty/Boost/src/boost/preprocessor/detail/is_nullary.hpp
new file mode 100644
index 0000000..dee4075
--- /dev/null
+++ b/3rdParty/Boost/src/boost/preprocessor/detail/is_nullary.hpp
@@ -0,0 +1,30 @@
+# /* **************************************************************************
+# * *
+# * (C) Copyright Paul Mensonides 2002.
+# * Distributed under the Boost Software License, Version 1.0. (See
+# * accompanying file LICENSE_1_0.txt or copy at
+# * http://www.boost.org/LICENSE_1_0.txt)
+# * *
+# ************************************************************************** */
+#
+# /* See http://www.boost.org for most recent version. */
+#
+# ifndef BOOST_PREPROCESSOR_DETAIL_IS_NULLARY_HPP
+# define BOOST_PREPROCESSOR_DETAIL_IS_NULLARY_HPP
+#
+# include <boost/preprocessor/config/config.hpp>
+# include <boost/preprocessor/detail/check.hpp>
+#
+# /* BOOST_PP_IS_NULLARY */
+#
+# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG()
+# define BOOST_PP_IS_NULLARY(x) BOOST_PP_CHECK(x, BOOST_PP_IS_NULLARY_CHECK)
+# else
+# define BOOST_PP_IS_NULLARY(x) BOOST_PP_IS_NULLARY_I(x)
+# define BOOST_PP_IS_NULLARY_I(x) BOOST_PP_CHECK(x, BOOST_PP_IS_NULLARY_CHECK)
+# endif
+#
+# define BOOST_PP_IS_NULLARY_CHECK() 1
+# define BOOST_PP_CHECK_RESULT_BOOST_PP_IS_NULLARY_CHECK 0, BOOST_PP_NIL
+#
+# endif
diff --git a/3rdParty/Boost/src/boost/preprocessor/for.hpp b/3rdParty/Boost/src/boost/preprocessor/for.hpp
new file mode 100644
index 0000000..9ec9cee
--- /dev/null
+++ b/3rdParty/Boost/src/boost/preprocessor/for.hpp
@@ -0,0 +1,17 @@
+# /* **************************************************************************
+# * *
+# * (C) Copyright Paul Mensonides 2002.
+# * Distributed under the Boost Software License, Version 1.0. (See
+# * accompanying file LICENSE_1_0.txt or copy at
+# * http://www.boost.org/LICENSE_1_0.txt)
+# * *
+# ************************************************************************** */
+#
+# /* See http://www.boost.org for most recent version. */
+#
+# ifndef BOOST_PREPROCESSOR_FOR_HPP
+# define BOOST_PREPROCESSOR_FOR_HPP
+#
+# include <boost/preprocessor/repetition/for.hpp>
+#
+# endif
diff --git a/3rdParty/Boost/src/boost/preprocessor/iteration.hpp b/3rdParty/Boost/src/boost/preprocessor/iteration.hpp
new file mode 100644
index 0000000..1055ac0
--- /dev/null
+++ b/3rdParty/Boost/src/boost/preprocessor/iteration.hpp
@@ -0,0 +1,19 @@
+# /* **************************************************************************
+# * *
+# * (C) Copyright Paul Mensonides 2002.
+# * Distributed under the Boost Software License, Version 1.0. (See
+# * accompanying file LICENSE_1_0.txt or copy at
+# * http://www.boost.org/LICENSE_1_0.txt)
+# * *
+# ************************************************************************** */
+#
+# /* See http://www.boost.org for most recent version. */
+#
+# ifndef BOOST_PREPROCESSOR_ITERATION_HPP
+# define BOOST_PREPROCESSOR_ITERATION_HPP
+#
+# include <boost/preprocessor/iteration/iterate.hpp>
+# include <boost/preprocessor/iteration/local.hpp>
+# include <boost/preprocessor/iteration/self.hpp>
+#
+# endif
diff --git a/3rdParty/Boost/src/boost/preprocessor/repetition.hpp b/3rdParty/Boost/src/boost/preprocessor/repetition.hpp
new file mode 100644
index 0000000..efcd60a
--- /dev/null
+++ b/3rdParty/Boost/src/boost/preprocessor/repetition.hpp
@@ -0,0 +1,32 @@
+# /* **************************************************************************
+# * *
+# * (C) Copyright Paul Mensonides 2002.
+# * Distributed under the Boost Software License, Version 1.0. (See
+# * accompanying file LICENSE_1_0.txt or copy at
+# * http://www.boost.org/LICENSE_1_0.txt)
+# * *
+# ************************************************************************** */
+#
+# /* See http://www.boost.org for most recent version. */
+#
+# ifndef BOOST_PREPROCESSOR_REPETITION_HPP
+# define BOOST_PREPROCESSOR_REPETITION_HPP
+#
+# include <boost/preprocessor/repetition/deduce_r.hpp>
+# include <boost/preprocessor/repetition/deduce_z.hpp>
+# include <boost/preprocessor/repetition/enum.hpp>
+# include <boost/preprocessor/repetition/enum_binary_params.hpp>
+# include <boost/preprocessor/repetition/enum_params.hpp>
+# include <boost/preprocessor/repetition/enum_params_with_a_default.hpp>
+# include <boost/preprocessor/repetition/enum_params_with_defaults.hpp>
+# include <boost/preprocessor/repetition/enum_shifted.hpp>
+# include <boost/preprocessor/repetition/enum_shifted_binary_params.hpp>
+# include <boost/preprocessor/repetition/enum_shifted_params.hpp>
+# include <boost/preprocessor/repetition/enum_trailing.hpp>
+# include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp>
+# include <boost/preprocessor/repetition/enum_trailing_params.hpp>
+# include <boost/preprocessor/repetition/for.hpp>
+# include <boost/preprocessor/repetition/repeat.hpp>
+# include <boost/preprocessor/repetition/repeat_from_to.hpp>
+#
+# endif
diff --git a/3rdParty/Boost/src/boost/preprocessor/repetition/deduce_r.hpp b/3rdParty/Boost/src/boost/preprocessor/repetition/deduce_r.hpp
new file mode 100644
index 0000000..e49296a
--- /dev/null
+++ b/3rdParty/Boost/src/boost/preprocessor/repetition/deduce_r.hpp
@@ -0,0 +1,22 @@
+# /* **************************************************************************
+# * *
+# * (C) Copyright Paul Mensonides 2002.
+# * Distributed under the Boost Software License, Version 1.0. (See
+# * accompanying file LICENSE_1_0.txt or copy at
+# * http://www.boost.org/LICENSE_1_0.txt)
+# * *
+# ************************************************************************** */
+#
+# /* See http://www.boost.org for most recent version. */
+#
+# ifndef BOOST_PREPROCESSOR_REPETITION_DEDUCE_R_HPP
+# define BOOST_PREPROCESSOR_REPETITION_DEDUCE_R_HPP
+#
+# include <boost/preprocessor/detail/auto_rec.hpp>
+# include <boost/preprocessor/repetition/for.hpp>
+#
+# /* BOOST_PP_DEDUCE_R */
+#
+# define BOOST_PP_DEDUCE_R() BOOST_PP_AUTO_REC(BOOST_PP_FOR_P, 256)
+#
+# endif
diff --git a/3rdParty/Boost/src/boost/preprocessor/repetition/deduce_z.hpp b/3rdParty/Boost/src/boost/preprocessor/repetition/deduce_z.hpp
new file mode 100644
index 0000000..14dedc2
--- /dev/null
+++ b/3rdParty/Boost/src/boost/preprocessor/repetition/deduce_z.hpp
@@ -0,0 +1,22 @@
+# /* **************************************************************************
+# * *
+# * (C) Copyright Paul Mensonides 2002.
+# * Distributed under the Boost Software License, Version 1.0. (See
+# * accompanying file LICENSE_1_0.txt or copy at
+# * http://www.boost.org/LICENSE_1_0.txt)
+# * *
+# ************************************************************************** */
+#
+# /* See http://www.boost.org for most recent version. */
+#
+# ifndef BOOST_PREPROCESSOR_REPETITION_DEDUCE_Z_HPP
+# define BOOST_PREPROCESSOR_REPETITION_DEDUCE_Z_HPP
+#
+# include <boost/preprocessor/detail/auto_rec.hpp>
+# include <boost/preprocessor/repetition/repeat.hpp>
+#
+# /* BOOST_PP_DEDUCE_Z */
+#
+# define BOOST_PP_DEDUCE_Z() BOOST_PP_AUTO_REC(BOOST_PP_REPEAT_P, 4)
+#
+# endif
diff --git a/3rdParty/Boost/src/boost/preprocessor/repetition/enum_shifted_binary_params.hpp b/3rdParty/Boost/src/boost/preprocessor/repetition/enum_shifted_binary_params.hpp
new file mode 100644
index 0000000..f3d20fc
--- /dev/null
+++ b/3rdParty/Boost/src/boost/preprocessor/repetition/enum_shifted_binary_params.hpp
@@ -0,0 +1,51 @@
+# /* **************************************************************************
+# * *
+# * (C) Copyright Paul Mensonides 2005. *
+# * Distributed under the Boost Software License, Version 1.0. (See *
+# * accompanying file LICENSE_1_0.txt or copy at *
+# * http://www.boost.org/LICENSE_1_0.txt) *
+# * *
+# ************************************************************************** */
+#
+# /* See http://www.boost.org for most recent version. */
+#
+# ifndef BOOST_PREPROCESSOR_REPETITION_ENUM_SHIFTED_BINARY_PARAMS_HPP
+# define BOOST_PREPROCESSOR_REPETITION_ENUM_SHIFTED_BINARY_PARAMS_HPP
+#
+# include <boost/preprocessor/arithmetic/dec.hpp>
+# include <boost/preprocessor/arithmetic/inc.hpp>
+# include <boost/preprocessor/cat.hpp>
+# include <boost/preprocessor/config/config.hpp>
+# include <boost/preprocessor/punctuation/comma_if.hpp>
+# include <boost/preprocessor/repetition/repeat.hpp>
+# include <boost/preprocessor/tuple/elem.hpp>
+# include <boost/preprocessor/tuple/rem.hpp>
+#
+# /* BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS */
+#
+# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG()
+# define BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS(count, p1, p2) BOOST_PP_REPEAT(BOOST_PP_DEC(count), BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M, (p1, p2))
+# else
+# define BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS(count, p1, p2) BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_I(count, p1, p2)
+# define BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_I(count, p1, p2) BOOST_PP_REPEAT(BOOST_PP_DEC(count), BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M, (p1, p2))
+# endif
+#
+# if BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_STRICT()
+# define BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M(z, n, pp) BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M_IM(z, n, BOOST_PP_TUPLE_REM_2 pp)
+# define BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M_IM(z, n, im) BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M_I(z, n, im)
+# else
+# define BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M(z, n, pp) BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M_I(z, n, BOOST_PP_TUPLE_ELEM(2, 0, pp), BOOST_PP_TUPLE_ELEM(2, 1, pp))
+# endif
+#
+# define BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M_I(z, n, p1, p2) BOOST_PP_COMMA_IF(n) BOOST_PP_CAT(p1, BOOST_PP_INC(n)) BOOST_PP_CAT(p2, BOOST_PP_INC(n))
+#
+# /* BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_Z */
+#
+# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG()
+# define BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_Z(z, count, p1, p2) BOOST_PP_REPEAT_ ## z(BOOST_PP_DEC(count), BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M, (p1, p2))
+# else
+# define BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_Z(z, count, p1, p2) BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_Z_I(z, count, p1, p2)
+# define BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_Z_I(z, count, p1, p2) BOOST_PP_REPEAT_ ## z(BOOST_PP_DEC(count), BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS_M, (p1, p2))
+# endif
+#
+# endif
diff --git a/3rdParty/Boost/src/boost/progress.hpp b/3rdParty/Boost/src/boost/progress.hpp
new file mode 100644
index 0000000..62bece0
--- /dev/null
+++ b/3rdParty/Boost/src/boost/progress.hpp
@@ -0,0 +1,143 @@
+// boost progress.hpp header file ------------------------------------------//
+
+// Copyright Beman Dawes 1994-99. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying file
+// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org/libs/timer for documentation.
+
+// Revision History
+// 1 Dec 01 Add leading progress display strings (suggested by Toon Knapen)
+// 20 May 01 Introduce several static_casts<> to eliminate warning messages
+// (Fixed by Beman, reported by Herve Bronnimann)
+// 12 Jan 01 Change to inline implementation to allow use without library
+// builds. See docs for more rationale. (Beman Dawes)
+// 22 Jul 99 Name changed to .hpp
+// 16 Jul 99 Second beta
+// 6 Jul 99 Initial boost version
+
+#ifndef BOOST_PROGRESS_HPP
+#define BOOST_PROGRESS_HPP
+
+#include <boost/timer.hpp>
+#include <boost/noncopyable.hpp>
+#include <boost/cstdint.hpp> // for uintmax_t
+#include <iostream> // for ostream, cout, etc
+#include <string> // for string
+
+namespace boost {
+
+// progress_timer ----------------------------------------------------------//
+
+// A progress_timer behaves like a timer except that the destructor displays
+// an elapsed time message at an appropriate place in an appropriate form.
+
+class progress_timer : public timer, private noncopyable
+{
+
+ public:
+ explicit progress_timer( std::ostream & os = std::cout )
+ // os is hint; implementation may ignore, particularly in embedded systems
+ : timer(), noncopyable(), m_os(os) {}
+ ~progress_timer()
+ {
+ // A) Throwing an exception from a destructor is a Bad Thing.
+ // B) The progress_timer destructor does output which may throw.
+ // C) A progress_timer is usually not critical to the application.
+ // Therefore, wrap the I/O in a try block, catch and ignore all exceptions.
+ try
+ {
+ // use istream instead of ios_base to workaround GNU problem (Greg Chicares)
+ std::istream::fmtflags old_flags = m_os.setf( std::istream::fixed,
+ std::istream::floatfield );
+ std::streamsize old_prec = m_os.precision( 2 );
+ m_os << elapsed() << " s\n" // "s" is System International d'Unites std
+ << std::endl;
+ m_os.flags( old_flags );
+ m_os.precision( old_prec );
+ }
+
+ catch (...) {} // eat any exceptions
+ } // ~progress_timer
+
+ private:
+ std::ostream & m_os;
+};
+
+
+// progress_display --------------------------------------------------------//
+
+// progress_display displays an appropriate indication of
+// progress at an appropriate place in an appropriate form.
+
+// NOTE: (Jan 12, 2001) Tried to change unsigned long to boost::uintmax_t, but
+// found some compilers couldn't handle the required conversion to double.
+// Reverted to unsigned long until the compilers catch up.
+
+class progress_display : private noncopyable
+{
+ public:
+ explicit progress_display( unsigned long expected_count_,
+ std::ostream & os = std::cout,
+ const std::string & s1 = "\n", //leading strings
+ const std::string & s2 = "",
+ const std::string & s3 = "" )
+ // os is hint; implementation may ignore, particularly in embedded systems
+ : noncopyable(), m_os(os), m_s1(s1), m_s2(s2), m_s3(s3) { restart(expected_count_); }
+
+ void restart( unsigned long expected_count_ )
+ // Effects: display appropriate scale
+ // Postconditions: count()==0, expected_count()==expected_count_
+ {
+ _count = _next_tic_count = _tic = 0;
+ _expected_count = expected_count_;
+
+ m_os << m_s1 << "0% 10 20 30 40 50 60 70 80 90 100%\n"
+ << m_s2 << "|----|----|----|----|----|----|----|----|----|----|"
+ << std::endl // endl implies flush, which ensures display
+ << m_s3;
+ if ( !_expected_count ) _expected_count = 1; // prevent divide by zero
+ } // restart
+
+ unsigned long operator+=( unsigned long increment )
+ // Effects: Display appropriate progress tic if needed.
+ // Postconditions: count()== original count() + increment
+ // Returns: count().
+ {
+ if ( (_count += increment) >= _next_tic_count ) { display_tic(); }
+ return _count;
+ }
+
+ unsigned long operator++() { return operator+=( 1 ); }
+ unsigned long count() const { return _count; }
+ unsigned long expected_count() const { return _expected_count; }
+
+ private:
+ std::ostream & m_os; // may not be present in all imps
+ const std::string m_s1; // string is more general, safer than
+ const std::string m_s2; // const char *, and efficiency or size are
+ const std::string m_s3; // not issues
+
+ unsigned long _count, _expected_count, _next_tic_count;
+ unsigned int _tic;
+ void display_tic()
+ {
+ // use of floating point ensures that both large and small counts
+ // work correctly. static_cast<>() is also used several places
+ // to suppress spurious compiler warnings.
+ unsigned int tics_needed =
+ static_cast<unsigned int>(
+ (static_cast<double>(_count)/_expected_count)*50.0 );
+ do { m_os << '*' << std::flush; } while ( ++_tic < tics_needed );
+ _next_tic_count =
+ static_cast<unsigned long>((_tic/50.0)*_expected_count);
+ if ( _count == _expected_count ) {
+ if ( _tic < 51 ) m_os << '*';
+ m_os << std::endl;
+ }
+ } // display_tic
+};
+
+} // namespace boost
+
+#endif // BOOST_PROGRESS_HPP
diff --git a/3rdParty/Boost/src/boost/range/adaptor/reversed.hpp b/3rdParty/Boost/src/boost/range/adaptor/reversed.hpp
new file mode 100644
index 0000000..944fbff
--- /dev/null
+++ b/3rdParty/Boost/src/boost/range/adaptor/reversed.hpp
@@ -0,0 +1,103 @@
+// Boost.Range library
+//
+// Copyright Thorsten Ottosen, Neil Groves 2006 - 2008. Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// For more information, see http://www.boost.org/libs/range/
+//
+
+#ifndef BOOST_RANGE_ADAPTOR_REVERSED_HPP
+#define BOOST_RANGE_ADAPTOR_REVERSED_HPP
+
+#include <boost/range/iterator_range.hpp>
+#include <boost/range/concepts.hpp>
+#include <boost/iterator/reverse_iterator.hpp>
+
+namespace boost
+{
+ namespace range_detail
+ {
+ template< class R >
+ struct reversed_range :
+ public boost::iterator_range<
+ boost::reverse_iterator<
+ BOOST_DEDUCED_TYPENAME range_iterator<R>::type
+ >
+ >
+ {
+ private:
+ typedef boost::iterator_range<
+ boost::reverse_iterator<
+ BOOST_DEDUCED_TYPENAME range_iterator<R>::type
+ >
+ >
+ base;
+
+ public:
+ typedef boost::reverse_iterator<BOOST_DEDUCED_TYPENAME range_iterator<R>::type> iterator;
+
+ explicit reversed_range( R& r )
+ : base( iterator(boost::end(r)), iterator(boost::begin(r)) )
+ { }
+ };
+
+ struct reverse_forwarder {};
+
+ template< class BidirectionalRange >
+ inline reversed_range<BidirectionalRange>
+ operator|( BidirectionalRange& r, reverse_forwarder )
+ {
+ BOOST_RANGE_CONCEPT_ASSERT((
+ BidirectionalRangeConcept<BidirectionalRange>));
+
+ return reversed_range<BidirectionalRange>( r );
+ }
+
+ template< class BidirectionalRange >
+ inline reversed_range<const BidirectionalRange>
+ operator|( const BidirectionalRange& r, reverse_forwarder )
+ {
+ BOOST_RANGE_CONCEPT_ASSERT((
+ BidirectionalRangeConcept<const BidirectionalRange>));
+
+ return reversed_range<const BidirectionalRange>( r );
+ }
+
+ } // 'range_detail'
+
+ using range_detail::reversed_range;
+
+ namespace adaptors
+ {
+ namespace
+ {
+ const range_detail::reverse_forwarder reversed =
+ range_detail::reverse_forwarder();
+ }
+
+ template<class BidirectionalRange>
+ inline reversed_range<BidirectionalRange>
+ reverse(BidirectionalRange& rng)
+ {
+ BOOST_RANGE_CONCEPT_ASSERT((
+ BidirectionalRangeConcept<BidirectionalRange>));
+
+ return reversed_range<BidirectionalRange>(rng);
+ }
+
+ template<class BidirectionalRange>
+ inline reversed_range<const BidirectionalRange>
+ reverse(const BidirectionalRange& rng)
+ {
+ BOOST_RANGE_CONCEPT_ASSERT((
+ BidirectionalRangeConcept<const BidirectionalRange>));
+
+ return reversed_range<const BidirectionalRange>(rng);
+ }
+ } // 'adaptors'
+
+} // 'boost'
+
+#endif
diff --git a/3rdParty/Boost/src/boost/signal.hpp b/3rdParty/Boost/src/boost/signal.hpp
deleted file mode 100644
index 7b31f36..0000000
--- a/3rdParty/Boost/src/boost/signal.hpp
+++ /dev/null
@@ -1,366 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2006. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org/libs/signals
-
-#ifndef BOOST_SIGNAL_HPP
-#define BOOST_SIGNAL_HPP
-
-#ifndef BOOST_SIGNALS_NO_DEPRECATION_WARNING
-# if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__DMC__)
-# pragma message ("Warning: Boost.Signals is no longer being maintained and is now deprecated. Please switch to Boost.Signals2. To disable this warning message, define BOOST_SIGNALS_NO_DEPRECATION_WARNING.")
-# elif defined(__GNUC__) || defined(__HP_aCC) || defined(__SUNPRO_CC) || defined(__IBMCPP__)
-# warning "Boost.Signals is no longer being maintained and is now deprecated. Please switch to Boost.Signals2. To disable this warning message, define BOOST_SIGNALS_NO_DEPRECATION_WARNING."
-# endif
-#endif
-
-#ifndef BOOST_SIGNALS_MAX_ARGS
-# define BOOST_SIGNALS_MAX_ARGS 10
-#endif
-
-#include <boost/config.hpp>
-#include <boost/type_traits/function_traits.hpp>
-#include <boost/signals/signal0.hpp>
-#include <boost/signals/signal1.hpp>
-#include <boost/signals/signal2.hpp>
-#include <boost/signals/signal3.hpp>
-#include <boost/signals/signal4.hpp>
-#include <boost/signals/signal5.hpp>
-#include <boost/signals/signal6.hpp>
-#include <boost/signals/signal7.hpp>
-#include <boost/signals/signal8.hpp>
-#include <boost/signals/signal9.hpp>
-#include <boost/signals/signal10.hpp>
-#include <boost/function.hpp>
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_PREFIX
-#endif
-
-namespace boost {
-#ifndef BOOST_FUNCTION_NO_FUNCTION_TYPE_SYNTAX
- namespace BOOST_SIGNALS_NAMESPACE {
- namespace detail {
- template<int Arity,
- typename Signature,
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction>
- class real_get_signal_impl;
-
- template<typename Signature,
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction>
- class real_get_signal_impl<0, Signature, Combiner, Group, GroupCompare,
- SlotFunction>
- {
- typedef function_traits<Signature> traits;
-
- public:
- typedef signal0<typename traits::result_type,
- Combiner,
- Group,
- GroupCompare,
- SlotFunction> type;
- };
-
- template<typename Signature,
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction>
- class real_get_signal_impl<1, Signature, Combiner, Group, GroupCompare,
- SlotFunction>
- {
- typedef function_traits<Signature> traits;
-
- public:
- typedef signal1<typename traits::result_type,
- typename traits::arg1_type,
- Combiner,
- Group,
- GroupCompare,
- SlotFunction> type;
- };
-
- template<typename Signature,
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction>
- class real_get_signal_impl<2, Signature, Combiner, Group, GroupCompare,
- SlotFunction>
- {
- typedef function_traits<Signature> traits;
-
- public:
- typedef signal2<typename traits::result_type,
- typename traits::arg1_type,
- typename traits::arg2_type,
- Combiner,
- Group,
- GroupCompare,
- SlotFunction> type;
- };
-
- template<typename Signature,
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction>
- class real_get_signal_impl<3, Signature, Combiner, Group, GroupCompare,
- SlotFunction>
- {
- typedef function_traits<Signature> traits;
-
- public:
- typedef signal3<typename traits::result_type,
- typename traits::arg1_type,
- typename traits::arg2_type,
- typename traits::arg3_type,
- Combiner,
- Group,
- GroupCompare,
- SlotFunction> type;
- };
-
- template<typename Signature,
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction>
- class real_get_signal_impl<4, Signature, Combiner, Group, GroupCompare,
- SlotFunction>
- {
- typedef function_traits<Signature> traits;
-
- public:
- typedef signal4<typename traits::result_type,
- typename traits::arg1_type,
- typename traits::arg2_type,
- typename traits::arg3_type,
- typename traits::arg4_type,
- Combiner,
- Group,
- GroupCompare,
- SlotFunction> type;
- };
-
- template<typename Signature,
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction>
- class real_get_signal_impl<5, Signature, Combiner, Group, GroupCompare,
- SlotFunction>
- {
- typedef function_traits<Signature> traits;
-
- public:
- typedef signal5<typename traits::result_type,
- typename traits::arg1_type,
- typename traits::arg2_type,
- typename traits::arg3_type,
- typename traits::arg4_type,
- typename traits::arg5_type,
- Combiner,
- Group,
- GroupCompare,
- SlotFunction> type;
- };
-
- template<typename Signature,
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction>
- class real_get_signal_impl<6, Signature, Combiner, Group, GroupCompare,
- SlotFunction>
- {
- typedef function_traits<Signature> traits;
-
- public:
- typedef signal6<typename traits::result_type,
- typename traits::arg1_type,
- typename traits::arg2_type,
- typename traits::arg3_type,
- typename traits::arg4_type,
- typename traits::arg5_type,
- typename traits::arg6_type,
- Combiner,
- Group,
- GroupCompare,
- SlotFunction> type;
- };
-
- template<typename Signature,
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction>
- class real_get_signal_impl<7, Signature, Combiner, Group, GroupCompare,
- SlotFunction>
- {
- typedef function_traits<Signature> traits;
-
- public:
- typedef signal7<typename traits::result_type,
- typename traits::arg1_type,
- typename traits::arg2_type,
- typename traits::arg3_type,
- typename traits::arg4_type,
- typename traits::arg5_type,
- typename traits::arg6_type,
- typename traits::arg7_type,
- Combiner,
- Group,
- GroupCompare,
- SlotFunction> type;
- };
-
- template<typename Signature,
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction>
- class real_get_signal_impl<8, Signature, Combiner, Group, GroupCompare,
- SlotFunction>
- {
- typedef function_traits<Signature> traits;
-
- public:
- typedef signal8<typename traits::result_type,
- typename traits::arg1_type,
- typename traits::arg2_type,
- typename traits::arg3_type,
- typename traits::arg4_type,
- typename traits::arg5_type,
- typename traits::arg6_type,
- typename traits::arg7_type,
- typename traits::arg8_type,
- Combiner,
- Group,
- GroupCompare,
- SlotFunction> type;
- };
-
- template<typename Signature,
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction>
- class real_get_signal_impl<9, Signature, Combiner, Group, GroupCompare,
- SlotFunction>
- {
- typedef function_traits<Signature> traits;
-
- public:
- typedef signal9<typename traits::result_type,
- typename traits::arg1_type,
- typename traits::arg2_type,
- typename traits::arg3_type,
- typename traits::arg4_type,
- typename traits::arg5_type,
- typename traits::arg6_type,
- typename traits::arg7_type,
- typename traits::arg8_type,
- typename traits::arg9_type,
- Combiner,
- Group,
- GroupCompare,
- SlotFunction> type;
- };
-
- template<typename Signature,
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction>
- class real_get_signal_impl<10, Signature, Combiner, Group, GroupCompare,
- SlotFunction>
- {
- typedef function_traits<Signature> traits;
-
- public:
- typedef signal10<typename traits::result_type,
- typename traits::arg1_type,
- typename traits::arg2_type,
- typename traits::arg3_type,
- typename traits::arg4_type,
- typename traits::arg5_type,
- typename traits::arg6_type,
- typename traits::arg7_type,
- typename traits::arg8_type,
- typename traits::arg9_type,
- typename traits::arg10_type,
- Combiner,
- Group,
- GroupCompare,
- SlotFunction> type;
- };
-
- template<typename Signature,
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction>
- struct get_signal_impl :
- public real_get_signal_impl<(function_traits<Signature>::arity),
- Signature,
- Combiner,
- Group,
- GroupCompare,
- SlotFunction>
- {
- };
-
- } // end namespace detail
- } // end namespace BOOST_SIGNALS_NAMESPACE
-
- // Very lightweight wrapper around the signalN classes that allows signals to
- // be created where the number of arguments does not need to be part of the
- // class name.
- template<
- typename Signature, // function type R (T1, T2, ..., TN)
- typename Combiner = last_value<typename function_traits<Signature>::result_type>,
- typename Group = int,
- typename GroupCompare = std::less<Group>,
- typename SlotFunction = function<Signature>
- >
- class signal :
- public BOOST_SIGNALS_NAMESPACE::detail::get_signal_impl<Signature,
- Combiner,
- Group,
- GroupCompare,
- SlotFunction>::type
- {
- typedef typename BOOST_SIGNALS_NAMESPACE::detail::get_signal_impl<
- Signature,
- Combiner,
- Group,
- GroupCompare,
- SlotFunction>::type base_type;
-
- public:
- explicit signal(const Combiner& combiner = Combiner(),
- const GroupCompare& group_compare = GroupCompare()) :
- base_type(combiner, group_compare)
- {
- }
- };
-#endif // ndef BOOST_FUNCTION_NO_FUNCTION_TYPE_SYNTAX
-
-} // end namespace boost
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_SUFFIX
-#endif
-
-#endif // BOOST_SIGNAL_HPP
diff --git a/3rdParty/Boost/src/boost/signals.hpp b/3rdParty/Boost/src/boost/signals.hpp
deleted file mode 100644
index 7e83ed5..0000000
--- a/3rdParty/Boost/src/boost/signals.hpp
+++ /dev/null
@@ -1,10 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2003-2004. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org/libs/signals
-#include <boost/signal.hpp>
-
diff --git a/3rdParty/Boost/src/boost/signals/connection.hpp b/3rdParty/Boost/src/boost/signals/connection.hpp
deleted file mode 100644
index 1ede6be..0000000
--- a/3rdParty/Boost/src/boost/signals/connection.hpp
+++ /dev/null
@@ -1,213 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2004. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_CONNECTION_HPP
-#define BOOST_SIGNALS_CONNECTION_HPP
-
-#include <boost/signals/detail/signals_common.hpp>
-#include <boost/smart_ptr.hpp>
-#include <boost/operators.hpp>
-#include <boost/any.hpp>
-#include <list>
-#include <cassert>
-#include <utility>
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_PREFIX
-#endif
-
-namespace boost {
- namespace BOOST_SIGNALS_NAMESPACE {
- class trackable;
-
- namespace detail {
- // Represents an object that has been bound as part of a slot, and how
- // to notify that object of a disconnect
- struct bound_object {
- void* obj;
- void* data;
- void (*disconnect)(void*, void*);
-
- bool operator==(const bound_object& other) const
- { return obj == other.obj && data == other.data; }
- bool operator<(const bound_object& other) const
- { return obj < other.obj; }
-
- // To support intel 80 compiler, 2004/03/18 (Mark Rodgers)
- bool operator!=(const bound_object& other) const
- { return !(*this==other); }
- bool operator>(const bound_object& other) const
- { return !(*this < other); }
- };
-
- // Describes the connection between a signal and the objects that are
- // bound for a specific slot. Enables notification of the signal and the
- // slots when a disconnect is requested.
- struct basic_connection {
- void* signal;
- void* signal_data;
- void (*signal_disconnect)(void*, void*);
- bool blocked_;
-
- std::list<bound_object> bound_objects;
- };
- } // end namespace detail
-
- // The user may freely pass around the "connection" object and terminate
- // the connection at any time using disconnect().
- class BOOST_SIGNALS_DECL connection :
- private less_than_comparable1<connection>,
- private equality_comparable1<connection>
- {
- public:
- connection() : con(), controlling_connection(false) {}
- connection(const connection&);
- ~connection();
-
- // Block he connection: if the connection is still active, there
- // will be no notification
- void block(bool should_block = true) { con->blocked_ = should_block; }
- void unblock() { con->blocked_ = false; }
- bool blocked() const { return !connected() || con->blocked_; }
-
- // Disconnect the signal and slot, if they are connected
- void disconnect() const;
-
- // Returns true if the signal and slot are connected
- bool connected() const { return con.get() && con->signal_disconnect; }
-
- // Comparison of connections
- bool operator==(const connection& other) const;
- bool operator<(const connection& other) const;
-
- // Connection assignment
- connection& operator=(const connection& other) ;
-
- // Swap connections
- void swap(connection& other);
-
- public: // TBD: CHANGE THIS
- // Set whether this connection object is controlling or not
- void set_controlling(bool control = true)
- { controlling_connection = control; }
-
- shared_ptr<BOOST_SIGNALS_NAMESPACE::detail::basic_connection>
- get_connection() const
- { return con; }
-
- private:
- friend class detail::signal_base_impl;
- friend class detail::slot_base;
- friend class trackable;
-
- // Reset this connection to refer to a different actual connection
- void reset(BOOST_SIGNALS_NAMESPACE::detail::basic_connection*);
-
- // Add a bound object to this connection (not for users)
- void add_bound_object(const BOOST_SIGNALS_NAMESPACE::detail::bound_object& b);
-
- friend class BOOST_SIGNALS_NAMESPACE::detail::bound_objects_visitor;
-
- // Pointer to the actual contents of the connection
- shared_ptr<BOOST_SIGNALS_NAMESPACE::detail::basic_connection> con;
-
- // True if the destruction of this connection object should disconnect
- bool controlling_connection;
- };
-
- // Similar to connection, but will disconnect the connection when it is
- // destroyed unless release() has been called.
- class BOOST_SIGNALS_DECL scoped_connection : public connection {
- public:
- scoped_connection() : connection(), released(false) {}
- scoped_connection(const connection&);
- scoped_connection(const scoped_connection&);
- ~scoped_connection();
-
- connection release();
-
- void swap(scoped_connection&);
-
- scoped_connection& operator=(const connection&);
- scoped_connection& operator=(const scoped_connection&);
-
- private:
- bool released;
- };
-
- namespace detail {
- struct connection_slot_pair {
- connection first;
- any second;
-
- connection_slot_pair() {}
-
- connection_slot_pair(const connection& c, const any& a)
- : first(c), second(a)
- {
- }
-
- // Dummys to allow explicit instantiation to work
- bool operator==(const connection_slot_pair&) const { return false; }
- bool operator<(const connection_slot_pair&) const { return false;}
- };
-
- // Determines if the underlying connection is disconnected
- struct is_disconnected {
- typedef connection_slot_pair argument_type;
- typedef bool result_type;
-
- inline bool operator()(const argument_type& c) const
- {
- return !c.first.connected();
- }
- };
-
- // Determines if the underlying connection is callable, ie if
- // it is connected and not blocked
- struct is_callable {
- typedef connection_slot_pair argument_type;
- typedef bool result_type;
-
- inline bool operator()(const argument_type& c) const
- {
- return c.first.connected() && !c.first.blocked() ;
- }
- };
-
- // Autodisconnects the bound object when it is destroyed unless the
- // release method is invoked.
- class auto_disconnect_bound_object {
- public:
- auto_disconnect_bound_object(const bound_object& b) :
- binding(b), auto_disconnect(true)
- {
- }
-
- ~auto_disconnect_bound_object()
- {
- if (auto_disconnect)
- binding.disconnect(binding.obj, binding.data);
- }
-
- void release() { auto_disconnect = false; }
-
- private:
- bound_object binding;
- bool auto_disconnect;
- };
- } // end namespace detail
- } // end namespace BOOST_SIGNALS_NAMESPACE
-} // end namespace boost
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_SUFFIX
-#endif
-
-#endif // BOOST_SIGNALS_CONNECTION_HPP
diff --git a/3rdParty/Boost/src/boost/signals/detail/config.hpp b/3rdParty/Boost/src/boost/signals/detail/config.hpp
deleted file mode 100644
index bdd6d20..0000000
--- a/3rdParty/Boost/src/boost/signals/detail/config.hpp
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Copyright (c) 1998-2002
- * John Maddock
- *
- * Copyright (c) 2003-2004
- * Douglas Gregor
- *
- * Distributed under the Boost Software License, Version 1.0. (See
- * accompanying file LICENSE_1_0.txt or copy at
- * http://www.boost.org/LICENSE_1_0.txt)
- *
- */
-
-#ifndef BOOST_SIGNALS_CONFIG_HPP
-#define BOOST_SIGNALS_CONFIG_HPP
-
-#include <boost/config.hpp>
-
-#ifdef BOOST_HAS_DECLSPEC
-# if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_SIGNALS_DYN_LINK)
-# ifdef BOOST_SIGNALS_SOURCE
-# define BOOST_SIGNALS_DECL __declspec(dllexport)
-# else
-# define BOOST_SIGNALS_DECL __declspec(dllimport)
-# endif // BOOST_SIGNALS_SOURCE
-# endif // DYN_LINK
-#endif // BOOST_HAS_DECLSPEC
-
-#ifndef BOOST_SIGNALS_DECL
-# define BOOST_SIGNALS_DECL
-#endif
-
-// Setup autolinking
-#if !defined(BOOST_SIGNALS_SOURCE) && !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_SIGNALS_NO_LIB)
-# define BOOST_LIB_NAME boost_signals
-
-# if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_SIGNALS_DYN_LINK)
-# define BOOST_DYN_LINK
-# endif
-
-# include <boost/config/auto_link.hpp>
-#endif // autolinking on
-
-#endif // BOOST_SIGNALS_CONFIG_HPP
-
-
-
-
-
-
-
-
-
diff --git a/3rdParty/Boost/src/boost/signals/detail/named_slot_map.hpp b/3rdParty/Boost/src/boost/signals/detail/named_slot_map.hpp
deleted file mode 100644
index 3f7cf1c..0000000
--- a/3rdParty/Boost/src/boost/signals/detail/named_slot_map.hpp
+++ /dev/null
@@ -1,192 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2004. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_NAMED_SLOT_MAP_HPP
-#define BOOST_SIGNALS_NAMED_SLOT_MAP_HPP
-
-#include <boost/signals/detail/config.hpp>
-#include <boost/signals/detail/signals_common.hpp>
-#include <boost/signals/connection.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/function/function2.hpp>
-#include <boost/iterator/iterator_facade.hpp>
-#include <map>
-#include <memory>
-#include <utility>
-
-namespace boost { namespace BOOST_SIGNALS_NAMESPACE {
-
-enum connect_position { at_back, at_front };
-
-namespace detail {
-
-class stored_group
-{
- public:
- enum storage_kind { sk_empty, sk_front, sk_back, sk_group };
-
- stored_group(storage_kind p_kind = sk_empty) : kind(p_kind), group() { }
-
- template<typename T>
- stored_group(const T& p_group) : kind(sk_group), group(new T(p_group)) { }
-
- bool is_front() const { return kind == sk_front; }
- bool is_back() const { return kind == sk_back; }
- bool empty() const { return kind == sk_empty; }
-
- void* get() const { return group.get(); }
-
- private:
- storage_kind kind;
- shared_ptr<void> group;
-};
-
-typedef function2<bool, stored_group, stored_group> compare_type;
-
-// This function object bridges from a pair of any objects that hold
-// values of type Key to the underlying function object that compares
-// values of type Key.
-template<typename Compare, typename Key>
-class group_bridge_compare {
-public:
- typedef bool result_type;
- typedef const stored_group& first_argument_type;
- typedef const stored_group& second_argument_type;
-
- group_bridge_compare(const Compare& c) : comp(c)
- { }
-
- bool operator()(const stored_group& k1, const stored_group& k2) const
- {
- if (k1.is_front()) return !k2.is_front();
- if (k1.is_back()) return false;
- if (k2.is_front()) return false;
- if (k2.is_back()) return true;
-
- // Neither is empty, so compare their values to order them
- return comp(*static_cast<Key*>(k1.get()), *static_cast<Key*>(k2.get()));
- }
-
-private:
- Compare comp;
-};
-
-class BOOST_SIGNALS_DECL named_slot_map_iterator :
- public iterator_facade<named_slot_map_iterator,
- connection_slot_pair,
- forward_traversal_tag>
-{
- typedef std::list<connection_slot_pair> group_list;
- typedef group_list::iterator slot_pair_iterator;
- typedef std::map<stored_group, group_list, compare_type> slot_container_type;
- typedef slot_container_type::iterator group_iterator;
- typedef slot_container_type::const_iterator const_group_iterator;
-
- typedef iterator_facade<named_slot_map_iterator,
- connection_slot_pair,
- forward_traversal_tag> inherited;
-public:
- named_slot_map_iterator() : slot_assigned(false)
- { }
- named_slot_map_iterator(const named_slot_map_iterator& other)
- : group(other.group), last_group(other.last_group),
- slot_assigned(other.slot_assigned)
- {
- if (slot_assigned) slot_ = other.slot_;
- }
- named_slot_map_iterator& operator=(const named_slot_map_iterator& other)
- {
- slot_assigned = other.slot_assigned;
- group = other.group;
- last_group = other.last_group;
- if (slot_assigned) slot_ = other.slot_;
- return *this;
- }
- connection_slot_pair& dereference() const
- {
- return *slot_;
- }
- void increment()
- {
- ++slot_;
- if (slot_ == group->second.end()) {
- ++group;
- init_next_group();
- }
- }
- bool equal(const named_slot_map_iterator& other) const {
- return (group == other.group
- && (group == last_group
- || slot_ == other.slot_));
- }
-
-#if BOOST_WORKAROUND(_MSC_VER, <= 1900)
- void decrement();
- void advance(difference_type);
-#endif
-
-private:
- named_slot_map_iterator(group_iterator giter, group_iterator last) :
- group(giter), last_group(last), slot_assigned(false)
- { init_next_group(); }
- named_slot_map_iterator(group_iterator giter, group_iterator last,
- slot_pair_iterator slot) :
- group(giter), last_group(last), slot_(slot), slot_assigned(true)
- { }
-
- void init_next_group()
- {
- while (group != last_group && group->second.empty()) ++group;
- if (group != last_group) {
- slot_ = group->second.begin();
- slot_assigned = true;
- }
- }
-
- group_iterator group;
- group_iterator last_group;
- slot_pair_iterator slot_;
- bool slot_assigned;
-
- friend class named_slot_map;
-};
-
-class BOOST_SIGNALS_DECL named_slot_map
-{
-public:
- typedef named_slot_map_iterator iterator;
-
- named_slot_map(const compare_type& compare);
-
- void clear();
- iterator begin();
- iterator end();
- iterator insert(const stored_group& name, const connection& con,
- const any& slot, connect_position at);
- void disconnect(const stored_group& name);
- void erase(iterator pos);
- void remove_disconnected_slots();
-
-private:
- typedef std::list<connection_slot_pair> group_list;
- typedef std::map<stored_group, group_list, compare_type> slot_container_type;
- typedef slot_container_type::iterator group_iterator;
- typedef slot_container_type::const_iterator const_group_iterator;
-
- bool empty(const_group_iterator group) const
- {
- return (group->second.empty() && group != groups.begin() && group != back);
- }
- slot_container_type groups;
- group_iterator back;
-};
-
-} } }
-
-#endif // BOOST_SIGNALS_NAMED_SLOT_MAP_HPP
diff --git a/3rdParty/Boost/src/boost/signals/detail/signal_base.hpp b/3rdParty/Boost/src/boost/signals/detail/signal_base.hpp
deleted file mode 100644
index 991e9fc..0000000
--- a/3rdParty/Boost/src/boost/signals/detail/signal_base.hpp
+++ /dev/null
@@ -1,159 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2004. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_SIGNAL_BASE_HEADER
-#define BOOST_SIGNALS_SIGNAL_BASE_HEADER
-
-#include <boost/signals/detail/config.hpp>
-#include <boost/signals/detail/signals_common.hpp>
-#include <boost/signals/detail/named_slot_map.hpp>
-#include <boost/signals/connection.hpp>
-#include <boost/signals/trackable.hpp>
-#include <boost/signals/slot.hpp>
-#include <boost/smart_ptr.hpp>
-#include <boost/noncopyable.hpp>
-#include <boost/function/function2.hpp>
-#include <utility>
-#include <vector>
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_PREFIX
-#endif
-
-namespace boost {
- namespace BOOST_SIGNALS_NAMESPACE {
- namespace detail {
- // Must be constructed before calling the slots, because it safely
- // manages call depth
- class BOOST_SIGNALS_DECL call_notification {
- public:
- call_notification(const shared_ptr<signal_base_impl>&);
- ~call_notification();
-
- shared_ptr<signal_base_impl> impl;
- };
-
- // Implementation of base class for all signals. It handles the
- // management of the underlying slot lists.
- class BOOST_SIGNALS_DECL signal_base_impl {
- public:
- friend class call_notification;
-
- typedef function2<bool, stored_group, stored_group> compare_type;
-
- // Make sure that an exception does not cause the "clearing" flag to
- // remain set
- class temporarily_set_clearing {
- public:
- temporarily_set_clearing(signal_base_impl* b) : base(b)
- {
- base->flags.clearing = true;
- }
-
- ~temporarily_set_clearing()
- {
- base->flags.clearing = false;
- }
-
- private:
- signal_base_impl* base;
- };
-
- friend class temporarily_set_clearing;
-
- signal_base_impl(const compare_type&, const any&);
- ~signal_base_impl();
-
- // Disconnect all slots connected to this signal
- void disconnect_all_slots();
-
- // Are there any connected slots?
- bool empty() const;
-
- // The number of connected slots
- std::size_t num_slots() const;
-
- // Disconnect all slots in the given group
- void disconnect(const stored_group&);
-
- // We're being notified that a slot has disconnected
- static void slot_disconnected(void* obj, void* data);
-
- connection connect_slot(const any& slot,
- const stored_group& name,
- shared_ptr<slot_base::data_t> data,
- connect_position at);
-
- private:
- // Remove all of the slots that have been marked "disconnected"
- void remove_disconnected_slots() const;
-
- public:
- // Our call depth when invoking slots (> 1 when we have a loop)
- mutable int call_depth;
-
- struct {
- // True if some slots have disconnected, but we were not able to
- // remove them from the list of slots because there are valid
- // iterators into the slot list
- mutable bool delayed_disconnect:1;
-
- // True if we are disconnecting all disconnected slots
- bool clearing:1;
- } flags;
-
- // Slots
- mutable named_slot_map slots_;
- any combiner_;
-
- // Types
- typedef named_slot_map::iterator iterator;
- };
-
- class BOOST_SIGNALS_DECL signal_base : public noncopyable {
- public:
- typedef signal_base_impl::compare_type compare_type;
-
- friend class call_notification;
-
- signal_base(const compare_type& comp, const any& combiner);
- ~signal_base();
-
- public:
- // Disconnect all slots connected to this signal
- void disconnect_all_slots() { impl->disconnect_all_slots(); }
-
- // Are there any connected slots?
- bool empty() const { return impl->empty(); }
-
- // How many slots are connected?
- std::size_t num_slots() const { return impl->num_slots(); }
-
- protected:
- connection connect_slot(const any& slot,
- const stored_group& name,
- shared_ptr<slot_base::data_t> data,
- connect_position at)
- {
- return impl->connect_slot(slot, name, data, at);
- }
-
- typedef named_slot_map::iterator iterator;
-
- shared_ptr<signal_base_impl> impl;
- };
- } // end namespace detail
- } // end namespace BOOST_SIGNALS_NAMESPACE
-} // end namespace boost
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_SUFFIX
-#endif
-
-#endif // BOOST_SIGNALS_SIGNAL_BASE_HEADER
diff --git a/3rdParty/Boost/src/boost/signals/detail/signals_common.hpp b/3rdParty/Boost/src/boost/signals/detail/signals_common.hpp
deleted file mode 100644
index 9cf078d..0000000
--- a/3rdParty/Boost/src/boost/signals/detail/signals_common.hpp
+++ /dev/null
@@ -1,144 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2004. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_COMMON_HEADER
-#define BOOST_SIGNALS_COMMON_HEADER
-
-#ifndef BOOST_SIGNALS_NAMESPACE
-# define BOOST_SIGNALS_NAMESPACE signals
-#endif
-
-#include <boost/type_traits/conversion_traits.hpp>
-#include <boost/ref.hpp>
-#include <boost/signals/detail/config.hpp>
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_PREFIX
-#endif
-
-namespace boost {
- namespace BOOST_SIGNALS_NAMESPACE {
- namespace detail {
- // The unusable class is a placeholder for unused function arguments
- // It is also completely unusable except that it constructable from
- // anything. This helps compilers without partial specialization
- // handle slots returning void.
- struct unusable {
- unusable() {}
- };
-
- // Determine the result type of a slot call
- template<typename R>
- struct slot_result_type {
- typedef R type;
- };
-
- template<>
- struct slot_result_type<void> {
- typedef unusable type;
- };
-
- // Determine if the given type T is a signal
- class signal_base;
-
- template<typename T>
- struct is_signal {
- BOOST_STATIC_CONSTANT(bool,
- value = (is_convertible<T*, signal_base*>::value));
- };
-
- /*
- * The IF implementation is temporary code. When a Boost metaprogramming
- * library is introduced, Boost.Signals will use it instead.
- */
- namespace intimate {
- struct SelectThen
- {
- template<typename Then, typename Else>
- struct Result
- {
- typedef Then type;
- };
- };
-
- struct SelectElse
- {
- template<typename Then, typename Else>
- struct Result
- {
- typedef Else type;
- };
- };
-
- template<bool Condition>
- struct Selector
- {
- typedef SelectThen type;
- };
-
- template<>
- struct Selector<false>
- {
- typedef SelectElse type;
- };
- } // end namespace intimate
-
- template<bool Condition, typename Then, typename Else>
- struct IF
- {
- typedef typename intimate::Selector<Condition>::type select;
- typedef typename select::template Result<Then,Else>::type type;
- };
-
- // Determine if the incoming argument is a reference_wrapper
- template<typename T>
- struct is_ref
- {
- BOOST_STATIC_CONSTANT(bool, value = false);
- };
-
- template<typename T>
- struct is_ref<reference_wrapper<T> >
- {
- BOOST_STATIC_CONSTANT(bool, value = true);
- };
-
- // A slot can be a signal, a reference to a function object, or a
- // function object.
- struct signal_tag {};
- struct reference_tag {};
- struct value_tag {};
-
- // Classify the given slot as a signal, a reference-to-slot, or a
- // standard slot
- template<typename S>
- class get_slot_tag {
- typedef typename IF<(is_signal<S>::value),
- signal_tag,
- value_tag>::type signal_or_value;
-
- public:
- typedef typename IF<(is_ref<S>::value),
- reference_tag,
- signal_or_value>::type type;
- };
-
- // Forward declaration needed in lots of places
- class signal_base_impl;
- class bound_objects_visitor;
- class slot_base;
- } // end namespace detail
- } // end namespace BOOST_SIGNALS_NAMESPACE
-} // end namespace boost
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_SUFFIX
-#endif
-
-#endif // BOOST_SIGNALS_COMMON_HEADER
diff --git a/3rdParty/Boost/src/boost/signals/detail/slot_call_iterator.hpp b/3rdParty/Boost/src/boost/signals/detail/slot_call_iterator.hpp
deleted file mode 100644
index 0d6afd9..0000000
--- a/3rdParty/Boost/src/boost/signals/detail/slot_call_iterator.hpp
+++ /dev/null
@@ -1,95 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2004. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_SLOT_CALL_ITERATOR
-#define BOOST_SIGNALS_SLOT_CALL_ITERATOR
-
-#include <memory>
-#include <boost/iterator/iterator_facade.hpp>
-#include <boost/smart_ptr.hpp>
-#include <boost/signals/detail/config.hpp>
-#include <boost/signals/connection.hpp>
-#include <boost/optional.hpp>
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_PREFIX
-#endif
-
-namespace boost {
- namespace BOOST_SIGNALS_NAMESPACE {
- namespace detail {
-
- // Generates a slot call iterator. Essentially, this is an iterator that:
- // - skips over disconnected slots in the underlying list
- // - calls the connected slots when dereferenced
- // - caches the result of calling the slots
- template<typename Function, typename Iterator>
- class slot_call_iterator
- : public iterator_facade<slot_call_iterator<Function, Iterator>,
- typename Function::result_type,
- single_pass_traversal_tag,
- typename Function::result_type const&>
- {
- typedef iterator_facade<slot_call_iterator<Function, Iterator>,
- typename Function::result_type,
- single_pass_traversal_tag,
- typename Function::result_type const&>
- inherited;
-
- typedef typename Function::result_type result_type;
-
- friend class iterator_core_access;
-
- public:
- slot_call_iterator(Iterator iter_in, Iterator end_in, Function func,
- optional<result_type> &c)
- : iter(iter_in), end(end_in), f(func), cache(&c)
- {
- iter = std::find_if(iter, end, is_callable());
- }
-
- typename inherited::reference
- dereference() const
- {
- if (!cache->is_initialized()) {
- cache->reset(f(*iter));
- }
-
- return cache->get();
- }
-
- void increment()
- {
- iter = std::find_if(++iter, end, is_callable());
- cache->reset();
- }
-
- bool equal(const slot_call_iterator& other) const
- {
- iter = std::find_if(iter, end, is_callable());
- other.iter = std::find_if(other.iter, other.end,
- is_callable());
- return iter == other.iter;
- }
-
- private:
- mutable Iterator iter;
- Iterator end;
- Function f;
- optional<result_type>* cache;
- };
- } // end namespace detail
- } // end namespace BOOST_SIGNALS_NAMESPACE
-} // end namespace boost
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_SUFFIX
-#endif
-
-#endif // BOOST_SIGNALS_SLOT_CALL_ITERATOR
diff --git a/3rdParty/Boost/src/boost/signals/signal0.hpp b/3rdParty/Boost/src/boost/signals/signal0.hpp
deleted file mode 100644
index 6a6166c..0000000
--- a/3rdParty/Boost/src/boost/signals/signal0.hpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2003. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_SIGNAL0_HEADER
-#define BOOST_SIGNALS_SIGNAL0_HEADER
-
-#define BOOST_SIGNALS_NUM_ARGS 0
-#define BOOST_SIGNALS_TEMPLATE_PARMS
-#define BOOST_SIGNALS_TEMPLATE_ARGS
-#define BOOST_SIGNALS_PARMS
-#define BOOST_SIGNALS_ARGS
-#define BOOST_SIGNALS_BOUND_ARGS
-#define BOOST_SIGNALS_ARGS_AS_MEMBERS
-#define BOOST_SIGNALS_COPY_PARMS
-#define BOOST_SIGNALS_INIT_ARGS
-#define BOOST_SIGNALS_ARG_TYPES
-
-#include <boost/signals/signal_template.hpp>
-
-#undef BOOST_SIGNALS_ARG_TYPES
-#undef BOOST_SIGNALS_INIT_ARGS
-#undef BOOST_SIGNALS_COPY_PARMS
-#undef BOOST_SIGNALS_ARGS_AS_MEMBERS
-#undef BOOST_SIGNALS_BOUND_ARGS
-#undef BOOST_SIGNALS_ARGS
-#undef BOOST_SIGNALS_PARMS
-#undef BOOST_SIGNALS_TEMPLATE_ARGS
-#undef BOOST_SIGNALS_TEMPLATE_PARMS
-#undef BOOST_SIGNALS_NUM_ARGS
-
-#endif // BOOST_SIGNALS_SIGNAL0_HEADER
diff --git a/3rdParty/Boost/src/boost/signals/signal1.hpp b/3rdParty/Boost/src/boost/signals/signal1.hpp
deleted file mode 100644
index 645f7ab..0000000
--- a/3rdParty/Boost/src/boost/signals/signal1.hpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2003. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_SIGNAL1_HEADER
-#define BOOST_SIGNALS_SIGNAL1_HEADER
-
-#define BOOST_SIGNALS_NUM_ARGS 1
-#define BOOST_SIGNALS_TEMPLATE_PARMS typename T1
-#define BOOST_SIGNALS_TEMPLATE_ARGS T1
-#define BOOST_SIGNALS_PARMS T1 a1
-#define BOOST_SIGNALS_ARGS a1
-#define BOOST_SIGNALS_BOUND_ARGS args->a1
-#define BOOST_SIGNALS_ARGS_AS_MEMBERS T1 a1;
-#define BOOST_SIGNALS_COPY_PARMS T1 ia1
-#define BOOST_SIGNALS_INIT_ARGS :a1(ia1)
-#define BOOST_SIGNALS_ARG_TYPES typedef T1 arg1_type;
-
-#include <boost/signals/signal_template.hpp>
-
-#undef BOOST_SIGNALS_ARG_TYPES
-#undef BOOST_SIGNALS_INIT_ARGS
-#undef BOOST_SIGNALS_COPY_PARMS
-#undef BOOST_SIGNALS_ARGS_AS_MEMBERS
-#undef BOOST_SIGNALS_BOUND_ARGS
-#undef BOOST_SIGNALS_ARGS
-#undef BOOST_SIGNALS_PARMS
-#undef BOOST_SIGNALS_TEMPLATE_ARGS
-#undef BOOST_SIGNALS_TEMPLATE_PARMS
-#undef BOOST_SIGNALS_NUM_ARGS
-
-#endif // BOOST_SIGNALS_SIGNAL1_HEADER
diff --git a/3rdParty/Boost/src/boost/signals/signal10.hpp b/3rdParty/Boost/src/boost/signals/signal10.hpp
deleted file mode 100644
index e043563..0000000
--- a/3rdParty/Boost/src/boost/signals/signal10.hpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2003. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_SIGNAL10_HEADER
-#define BOOST_SIGNALS_SIGNAL10_HEADER
-
-#define BOOST_SIGNALS_NUM_ARGS 10
-#define BOOST_SIGNALS_TEMPLATE_PARMS typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10
-#define BOOST_SIGNALS_TEMPLATE_ARGS T1, T2, T3, T4, T5, T6, T7, T8, T9, T10
-#define BOOST_SIGNALS_PARMS T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6, T7 a7, T8 a8, T9 a9, T10 a10
-#define BOOST_SIGNALS_ARGS a1, a2, a3, a4, a5, a6, a7, a8, a9, a10
-#define BOOST_SIGNALS_BOUND_ARGS args->a1, args->a2, args->a3, args->a4, args->a5, args->a6, args->a7, args->a8, args->a9, args->a10
-#define BOOST_SIGNALS_ARGS_AS_MEMBERS T1 a1;T2 a2;T3 a3;T4 a4;T5 a5;T6 a6;T7 a7;T8 a8;T9 a9;T10 a10;
-#define BOOST_SIGNALS_COPY_PARMS T1 ia1, T2 ia2, T3 ia3, T4 ia4, T5 ia5, T6 ia6, T7 ia7, T8 ia8, T9 ia9, T10 ia10
-#define BOOST_SIGNALS_INIT_ARGS :a1(ia1), a2(ia2), a3(ia3), a4(ia4), a5(ia5), a6(ia6), a7(ia7), a8(ia8), a9(ia9), a10(ia10)
-#define BOOST_SIGNALS_ARG_TYPES typedef T1 arg1_type; typedef T2 arg2_type; typedef T3 arg3_type; typedef T4 arg4_type; typedef T5 arg5_type; typedef T6 arg6_type; typedef T7 arg7_type; typedef T8 arg8_type; typedef T9 arg9_type; typedef T10 arg10_type;
-
-#include <boost/signals/signal_template.hpp>
-
-#undef BOOST_SIGNALS_ARG_TYPES
-#undef BOOST_SIGNALS_INIT_ARGS
-#undef BOOST_SIGNALS_COPY_PARMS
-#undef BOOST_SIGNALS_ARGS_AS_MEMBERS
-#undef BOOST_SIGNALS_BOUND_ARGS
-#undef BOOST_SIGNALS_ARGS
-#undef BOOST_SIGNALS_PARMS
-#undef BOOST_SIGNALS_TEMPLATE_ARGS
-#undef BOOST_SIGNALS_TEMPLATE_PARMS
-#undef BOOST_SIGNALS_NUM_ARGS
-
-#endif // BOOST_SIGNALS_SIGNAL10_HEADER
diff --git a/3rdParty/Boost/src/boost/signals/signal2.hpp b/3rdParty/Boost/src/boost/signals/signal2.hpp
deleted file mode 100644
index e75f5e7..0000000
--- a/3rdParty/Boost/src/boost/signals/signal2.hpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2003. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_SIGNAL2_HEADER
-#define BOOST_SIGNALS_SIGNAL2_HEADER
-
-#define BOOST_SIGNALS_NUM_ARGS 2
-#define BOOST_SIGNALS_TEMPLATE_PARMS typename T1, typename T2
-#define BOOST_SIGNALS_TEMPLATE_ARGS T1, T2
-#define BOOST_SIGNALS_PARMS T1 a1, T2 a2
-#define BOOST_SIGNALS_ARGS a1, a2
-#define BOOST_SIGNALS_BOUND_ARGS args->a1, args->a2
-#define BOOST_SIGNALS_ARGS_AS_MEMBERS T1 a1;T2 a2;
-#define BOOST_SIGNALS_COPY_PARMS T1 ia1, T2 ia2
-#define BOOST_SIGNALS_INIT_ARGS :a1(ia1), a2(ia2)
-#define BOOST_SIGNALS_ARG_TYPES typedef T1 arg1_type; typedef T2 arg2_type;
-
-#include <boost/signals/signal_template.hpp>
-
-#undef BOOST_SIGNALS_ARG_TYPES
-#undef BOOST_SIGNALS_INIT_ARGS
-#undef BOOST_SIGNALS_COPY_PARMS
-#undef BOOST_SIGNALS_ARGS_AS_MEMBERS
-#undef BOOST_SIGNALS_BOUND_ARGS
-#undef BOOST_SIGNALS_ARGS
-#undef BOOST_SIGNALS_PARMS
-#undef BOOST_SIGNALS_TEMPLATE_ARGS
-#undef BOOST_SIGNALS_TEMPLATE_PARMS
-#undef BOOST_SIGNALS_NUM_ARGS
-
-#endif // BOOST_SIGNALS_SIGNAL2_HEADER
diff --git a/3rdParty/Boost/src/boost/signals/signal3.hpp b/3rdParty/Boost/src/boost/signals/signal3.hpp
deleted file mode 100644
index 0a695c5..0000000
--- a/3rdParty/Boost/src/boost/signals/signal3.hpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2003. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_SIGNAL3_HEADER
-#define BOOST_SIGNALS_SIGNAL3_HEADER
-
-#define BOOST_SIGNALS_NUM_ARGS 3
-#define BOOST_SIGNALS_TEMPLATE_PARMS typename T1, typename T2, typename T3
-#define BOOST_SIGNALS_TEMPLATE_ARGS T1, T2, T3
-#define BOOST_SIGNALS_PARMS T1 a1, T2 a2, T3 a3
-#define BOOST_SIGNALS_ARGS a1, a2, a3
-#define BOOST_SIGNALS_BOUND_ARGS args->a1, args->a2, args->a3
-#define BOOST_SIGNALS_ARGS_AS_MEMBERS T1 a1;T2 a2;T3 a3;
-#define BOOST_SIGNALS_COPY_PARMS T1 ia1, T2 ia2, T3 ia3
-#define BOOST_SIGNALS_INIT_ARGS :a1(ia1), a2(ia2), a3(ia3)
-#define BOOST_SIGNALS_ARG_TYPES typedef T1 arg1_type; typedef T2 arg2_type; typedef T3 arg3_type;
-
-#include <boost/signals/signal_template.hpp>
-
-#undef BOOST_SIGNALS_ARG_TYPES
-#undef BOOST_SIGNALS_INIT_ARGS
-#undef BOOST_SIGNALS_COPY_PARMS
-#undef BOOST_SIGNALS_ARGS_AS_MEMBERS
-#undef BOOST_SIGNALS_BOUND_ARGS
-#undef BOOST_SIGNALS_ARGS
-#undef BOOST_SIGNALS_PARMS
-#undef BOOST_SIGNALS_TEMPLATE_ARGS
-#undef BOOST_SIGNALS_TEMPLATE_PARMS
-#undef BOOST_SIGNALS_NUM_ARGS
-
-#endif // BOOST_SIGNALS_SIGNAL3_HEADER
diff --git a/3rdParty/Boost/src/boost/signals/signal4.hpp b/3rdParty/Boost/src/boost/signals/signal4.hpp
deleted file mode 100644
index 56ba360..0000000
--- a/3rdParty/Boost/src/boost/signals/signal4.hpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2003. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_SIGNAL4_HEADER
-#define BOOST_SIGNALS_SIGNAL4_HEADER
-
-#define BOOST_SIGNALS_NUM_ARGS 4
-#define BOOST_SIGNALS_TEMPLATE_PARMS typename T1, typename T2, typename T3, typename T4
-#define BOOST_SIGNALS_TEMPLATE_ARGS T1, T2, T3, T4
-#define BOOST_SIGNALS_PARMS T1 a1, T2 a2, T3 a3, T4 a4
-#define BOOST_SIGNALS_ARGS a1, a2, a3, a4
-#define BOOST_SIGNALS_BOUND_ARGS args->a1, args->a2, args->a3, args->a4
-#define BOOST_SIGNALS_ARGS_AS_MEMBERS T1 a1;T2 a2;T3 a3;T4 a4;
-#define BOOST_SIGNALS_COPY_PARMS T1 ia1, T2 ia2, T3 ia3, T4 ia4
-#define BOOST_SIGNALS_INIT_ARGS :a1(ia1), a2(ia2), a3(ia3), a4(ia4)
-#define BOOST_SIGNALS_ARG_TYPES typedef T1 arg1_type; typedef T2 arg2_type; typedef T3 arg3_type; typedef T4 arg4_type;
-
-#include <boost/signals/signal_template.hpp>
-
-#undef BOOST_SIGNALS_ARG_TYPES
-#undef BOOST_SIGNALS_INIT_ARGS
-#undef BOOST_SIGNALS_COPY_PARMS
-#undef BOOST_SIGNALS_ARGS_AS_MEMBERS
-#undef BOOST_SIGNALS_BOUND_ARGS
-#undef BOOST_SIGNALS_ARGS
-#undef BOOST_SIGNALS_PARMS
-#undef BOOST_SIGNALS_TEMPLATE_ARGS
-#undef BOOST_SIGNALS_TEMPLATE_PARMS
-#undef BOOST_SIGNALS_NUM_ARGS
-
-#endif // BOOST_SIGNALS_SIGNAL4_HEADER
diff --git a/3rdParty/Boost/src/boost/signals/signal5.hpp b/3rdParty/Boost/src/boost/signals/signal5.hpp
deleted file mode 100644
index 027cda9..0000000
--- a/3rdParty/Boost/src/boost/signals/signal5.hpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2003. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_SIGNAL5_HEADER
-#define BOOST_SIGNALS_SIGNAL5_HEADER
-
-#define BOOST_SIGNALS_NUM_ARGS 5
-#define BOOST_SIGNALS_TEMPLATE_PARMS typename T1, typename T2, typename T3, typename T4, typename T5
-#define BOOST_SIGNALS_TEMPLATE_ARGS T1, T2, T3, T4, T5
-#define BOOST_SIGNALS_PARMS T1 a1, T2 a2, T3 a3, T4 a4, T5 a5
-#define BOOST_SIGNALS_ARGS a1, a2, a3, a4, a5
-#define BOOST_SIGNALS_BOUND_ARGS args->a1, args->a2, args->a3, args->a4, args->a5
-#define BOOST_SIGNALS_ARGS_AS_MEMBERS T1 a1;T2 a2;T3 a3;T4 a4;T5 a5;
-#define BOOST_SIGNALS_COPY_PARMS T1 ia1, T2 ia2, T3 ia3, T4 ia4, T5 ia5
-#define BOOST_SIGNALS_INIT_ARGS :a1(ia1), a2(ia2), a3(ia3), a4(ia4), a5(ia5)
-#define BOOST_SIGNALS_ARG_TYPES typedef T1 arg1_type; typedef T2 arg2_type; typedef T3 arg3_type; typedef T4 arg4_type; typedef T5 arg5_type;
-
-#include <boost/signals/signal_template.hpp>
-
-#undef BOOST_SIGNALS_ARG_TYPES
-#undef BOOST_SIGNALS_INIT_ARGS
-#undef BOOST_SIGNALS_COPY_PARMS
-#undef BOOST_SIGNALS_ARGS_AS_MEMBERS
-#undef BOOST_SIGNALS_BOUND_ARGS
-#undef BOOST_SIGNALS_ARGS
-#undef BOOST_SIGNALS_PARMS
-#undef BOOST_SIGNALS_TEMPLATE_ARGS
-#undef BOOST_SIGNALS_TEMPLATE_PARMS
-#undef BOOST_SIGNALS_NUM_ARGS
-
-#endif // BOOST_SIGNALS_SIGNAL5_HEADER
diff --git a/3rdParty/Boost/src/boost/signals/signal6.hpp b/3rdParty/Boost/src/boost/signals/signal6.hpp
deleted file mode 100644
index 3955318..0000000
--- a/3rdParty/Boost/src/boost/signals/signal6.hpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2003. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_SIGNAL6_HEADER
-#define BOOST_SIGNALS_SIGNAL6_HEADER
-
-#define BOOST_SIGNALS_NUM_ARGS 6
-#define BOOST_SIGNALS_TEMPLATE_PARMS typename T1, typename T2, typename T3, typename T4, typename T5, typename T6
-#define BOOST_SIGNALS_TEMPLATE_ARGS T1, T2, T3, T4, T5, T6
-#define BOOST_SIGNALS_PARMS T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6
-#define BOOST_SIGNALS_ARGS a1, a2, a3, a4, a5, a6
-#define BOOST_SIGNALS_BOUND_ARGS args->a1, args->a2, args->a3, args->a4, args->a5, args->a6
-#define BOOST_SIGNALS_ARGS_AS_MEMBERS T1 a1;T2 a2;T3 a3;T4 a4;T5 a5;T6 a6;
-#define BOOST_SIGNALS_COPY_PARMS T1 ia1, T2 ia2, T3 ia3, T4 ia4, T5 ia5, T6 ia6
-#define BOOST_SIGNALS_INIT_ARGS :a1(ia1), a2(ia2), a3(ia3), a4(ia4), a5(ia5), a6(ia6)
-#define BOOST_SIGNALS_ARG_TYPES typedef T1 arg1_type; typedef T2 arg2_type; typedef T3 arg3_type; typedef T4 arg4_type; typedef T5 arg5_type; typedef T6 arg6_type;
-
-#include <boost/signals/signal_template.hpp>
-
-#undef BOOST_SIGNALS_ARG_TYPES
-#undef BOOST_SIGNALS_INIT_ARGS
-#undef BOOST_SIGNALS_COPY_PARMS
-#undef BOOST_SIGNALS_ARGS_AS_MEMBERS
-#undef BOOST_SIGNALS_BOUND_ARGS
-#undef BOOST_SIGNALS_ARGS
-#undef BOOST_SIGNALS_PARMS
-#undef BOOST_SIGNALS_TEMPLATE_ARGS
-#undef BOOST_SIGNALS_TEMPLATE_PARMS
-#undef BOOST_SIGNALS_NUM_ARGS
-
-#endif // BOOST_SIGNALS_SIGNAL6_HEADER
diff --git a/3rdParty/Boost/src/boost/signals/signal7.hpp b/3rdParty/Boost/src/boost/signals/signal7.hpp
deleted file mode 100644
index d4530ec..0000000
--- a/3rdParty/Boost/src/boost/signals/signal7.hpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2003. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_SIGNAL7_HEADER
-#define BOOST_SIGNALS_SIGNAL7_HEADER
-
-#define BOOST_SIGNALS_NUM_ARGS 7
-#define BOOST_SIGNALS_TEMPLATE_PARMS typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7
-#define BOOST_SIGNALS_TEMPLATE_ARGS T1, T2, T3, T4, T5, T6, T7
-#define BOOST_SIGNALS_PARMS T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6, T7 a7
-#define BOOST_SIGNALS_ARGS a1, a2, a3, a4, a5, a6, a7
-#define BOOST_SIGNALS_BOUND_ARGS args->a1, args->a2, args->a3, args->a4, args->a5, args->a6, args->a7
-#define BOOST_SIGNALS_ARGS_AS_MEMBERS T1 a1;T2 a2;T3 a3;T4 a4;T5 a5;T6 a6;T7 a7;
-#define BOOST_SIGNALS_COPY_PARMS T1 ia1, T2 ia2, T3 ia3, T4 ia4, T5 ia5, T6 ia6, T7 ia7
-#define BOOST_SIGNALS_INIT_ARGS :a1(ia1), a2(ia2), a3(ia3), a4(ia4), a5(ia5), a6(ia6), a7(ia7)
-#define BOOST_SIGNALS_ARG_TYPES typedef T1 arg1_type; typedef T2 arg2_type; typedef T3 arg3_type; typedef T4 arg4_type; typedef T5 arg5_type; typedef T6 arg6_type; typedef T7 arg7_type;
-
-#include <boost/signals/signal_template.hpp>
-
-#undef BOOST_SIGNALS_ARG_TYPES
-#undef BOOST_SIGNALS_INIT_ARGS
-#undef BOOST_SIGNALS_COPY_PARMS
-#undef BOOST_SIGNALS_ARGS_AS_MEMBERS
-#undef BOOST_SIGNALS_BOUND_ARGS
-#undef BOOST_SIGNALS_ARGS
-#undef BOOST_SIGNALS_PARMS
-#undef BOOST_SIGNALS_TEMPLATE_ARGS
-#undef BOOST_SIGNALS_TEMPLATE_PARMS
-#undef BOOST_SIGNALS_NUM_ARGS
-
-#endif // BOOST_SIGNALS_SIGNAL7_HEADER
diff --git a/3rdParty/Boost/src/boost/signals/signal8.hpp b/3rdParty/Boost/src/boost/signals/signal8.hpp
deleted file mode 100644
index 094cd97..0000000
--- a/3rdParty/Boost/src/boost/signals/signal8.hpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2003. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_SIGNAL8_HEADER
-#define BOOST_SIGNALS_SIGNAL8_HEADER
-
-#define BOOST_SIGNALS_NUM_ARGS 8
-#define BOOST_SIGNALS_TEMPLATE_PARMS typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8
-#define BOOST_SIGNALS_TEMPLATE_ARGS T1, T2, T3, T4, T5, T6, T7, T8
-#define BOOST_SIGNALS_PARMS T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6, T7 a7, T8 a8
-#define BOOST_SIGNALS_ARGS a1, a2, a3, a4, a5, a6, a7, a8
-#define BOOST_SIGNALS_BOUND_ARGS args->a1, args->a2, args->a3, args->a4, args->a5, args->a6, args->a7, args->a8
-#define BOOST_SIGNALS_ARGS_AS_MEMBERS T1 a1;T2 a2;T3 a3;T4 a4;T5 a5;T6 a6;T7 a7;T8 a8;
-#define BOOST_SIGNALS_COPY_PARMS T1 ia1, T2 ia2, T3 ia3, T4 ia4, T5 ia5, T6 ia6, T7 ia7, T8 ia8
-#define BOOST_SIGNALS_INIT_ARGS :a1(ia1), a2(ia2), a3(ia3), a4(ia4), a5(ia5), a6(ia6), a7(ia7), a8(ia8)
-#define BOOST_SIGNALS_ARG_TYPES typedef T1 arg1_type; typedef T2 arg2_type; typedef T3 arg3_type; typedef T4 arg4_type; typedef T5 arg5_type; typedef T6 arg6_type; typedef T7 arg7_type; typedef T8 arg8_type;
-
-#include <boost/signals/signal_template.hpp>
-
-#undef BOOST_SIGNALS_ARG_TYPES
-#undef BOOST_SIGNALS_INIT_ARGS
-#undef BOOST_SIGNALS_COPY_PARMS
-#undef BOOST_SIGNALS_ARGS_AS_MEMBERS
-#undef BOOST_SIGNALS_BOUND_ARGS
-#undef BOOST_SIGNALS_ARGS
-#undef BOOST_SIGNALS_PARMS
-#undef BOOST_SIGNALS_TEMPLATE_ARGS
-#undef BOOST_SIGNALS_TEMPLATE_PARMS
-#undef BOOST_SIGNALS_NUM_ARGS
-
-#endif // BOOST_SIGNALS_SIGNAL8_HEADER
diff --git a/3rdParty/Boost/src/boost/signals/signal9.hpp b/3rdParty/Boost/src/boost/signals/signal9.hpp
deleted file mode 100644
index a551c16..0000000
--- a/3rdParty/Boost/src/boost/signals/signal9.hpp
+++ /dev/null
@@ -1,37 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2003. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_SIGNAL9_HEADER
-#define BOOST_SIGNALS_SIGNAL9_HEADER
-
-#define BOOST_SIGNALS_NUM_ARGS 9
-#define BOOST_SIGNALS_TEMPLATE_PARMS typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9
-#define BOOST_SIGNALS_TEMPLATE_ARGS T1, T2, T3, T4, T5, T6, T7, T8, T9
-#define BOOST_SIGNALS_PARMS T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6, T7 a7, T8 a8, T9 a9
-#define BOOST_SIGNALS_ARGS a1, a2, a3, a4, a5, a6, a7, a8, a9
-#define BOOST_SIGNALS_BOUND_ARGS args->a1, args->a2, args->a3, args->a4, args->a5, args->a6, args->a7, args->a8, args->a9
-#define BOOST_SIGNALS_ARGS_AS_MEMBERS T1 a1;T2 a2;T3 a3;T4 a4;T5 a5;T6 a6;T7 a7;T8 a8;T9 a9;
-#define BOOST_SIGNALS_COPY_PARMS T1 ia1, T2 ia2, T3 ia3, T4 ia4, T5 ia5, T6 ia6, T7 ia7, T8 ia8, T9 ia9
-#define BOOST_SIGNALS_INIT_ARGS :a1(ia1), a2(ia2), a3(ia3), a4(ia4), a5(ia5), a6(ia6), a7(ia7), a8(ia8), a9(ia9)
-#define BOOST_SIGNALS_ARG_TYPES typedef T1 arg1_type; typedef T2 arg2_type; typedef T3 arg3_type; typedef T4 arg4_type; typedef T5 arg5_type; typedef T6 arg6_type; typedef T7 arg7_type; typedef T8 arg8_type; typedef T9 arg9_type;
-
-#include <boost/signals/signal_template.hpp>
-
-#undef BOOST_SIGNALS_ARG_TYPES
-#undef BOOST_SIGNALS_INIT_ARGS
-#undef BOOST_SIGNALS_COPY_PARMS
-#undef BOOST_SIGNALS_ARGS_AS_MEMBERS
-#undef BOOST_SIGNALS_BOUND_ARGS
-#undef BOOST_SIGNALS_ARGS
-#undef BOOST_SIGNALS_PARMS
-#undef BOOST_SIGNALS_TEMPLATE_ARGS
-#undef BOOST_SIGNALS_TEMPLATE_PARMS
-#undef BOOST_SIGNALS_NUM_ARGS
-
-#endif // BOOST_SIGNALS_SIGNAL9_HEADER
diff --git a/3rdParty/Boost/src/boost/signals/signal_template.hpp b/3rdParty/Boost/src/boost/signals/signal_template.hpp
deleted file mode 100644
index 94e1d1a..0000000
--- a/3rdParty/Boost/src/boost/signals/signal_template.hpp
+++ /dev/null
@@ -1,401 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2004. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-// This file intentionally does not have include guards, because it is meant
-// to be included multiple times (one for each signalN class). The
-// BOOST_SIGNALS_SIGNAL_TEMPLATE_HEADER_INCLUDED macro merely serves to
-// suppress reinclusion of the files that this header depends on.
-
-#ifndef BOOST_SIGNALS_SIGNAL_TEMPLATE_HEADER_INCLUDED
-#define BOOST_SIGNALS_SIGNAL_TEMPLATE_HEADER_INCLUDED
-# include <boost/config.hpp>
-# include <boost/signals/connection.hpp>
-# include <boost/ref.hpp>
-# include <boost/signals/slot.hpp>
-# include <boost/last_value.hpp>
-# include <boost/signals/detail/signal_base.hpp>
-# include <boost/signals/detail/slot_call_iterator.hpp>
-# include <boost/mpl/bool.hpp>
-# include <boost/type_traits/is_convertible.hpp>
-# include <cassert>
-# include <functional>
-# include <memory>
-#endif // !BOOST_SIGNALS_SIGNAL_TEMPLATE_HEADER_INCLUDED
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_PREFIX
-#endif
-
-// Include the appropriate functionN header
-#define BOOST_SIGNAL_FUNCTION_N_HEADER BOOST_JOIN(<boost/function/function,BOOST_SIGNALS_NUM_ARGS.hpp>)
-#include BOOST_SIGNAL_FUNCTION_N_HEADER
-
-// Determine if a comma should follow a listing of the arguments/parameters
-#if BOOST_SIGNALS_NUM_ARGS == 0
-# define BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
-#else
-# define BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS ,
-#endif // BOOST_SIGNALS_NUM_ARGS > 0
-
-// Define class names used
-#define BOOST_SIGNALS_SIGNAL BOOST_JOIN(signal,BOOST_SIGNALS_NUM_ARGS)
-#define BOOST_SIGNALS_FUNCTION BOOST_JOIN(function,BOOST_SIGNALS_NUM_ARGS)
-#define BOOST_SIGNALS_ARGS_STRUCT BOOST_JOIN(args,BOOST_SIGNALS_NUM_ARGS)
-#define BOOST_SIGNALS_CALL_BOUND BOOST_JOIN(call_bound,BOOST_SIGNALS_NUM_ARGS)
-
-// Define commonly-used instantiations
-#define BOOST_SIGNALS_ARGS_STRUCT_INST \
- BOOST_SIGNALS_NAMESPACE::detail::BOOST_SIGNALS_ARGS_STRUCT<BOOST_SIGNALS_TEMPLATE_ARGS>
-
-namespace boost {
- namespace BOOST_SIGNALS_NAMESPACE {
- namespace detail {
- // Holds the arguments for a bound slot call in a single place
- template<BOOST_SIGNALS_TEMPLATE_PARMS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- typename Dummy = int>
- struct BOOST_SIGNALS_ARGS_STRUCT {
- BOOST_SIGNALS_ARGS_STRUCT(BOOST_SIGNALS_COPY_PARMS)
- BOOST_SIGNALS_INIT_ARGS
- {
- }
-
- BOOST_SIGNALS_ARGS_AS_MEMBERS
- };
-
- // Function object that calls the function object given to it, passing
- // the bound arguments along to that underlying function object
- template<typename R>
- struct BOOST_SIGNALS_CALL_BOUND {
- template<BOOST_SIGNALS_TEMPLATE_PARMS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- typename F>
- struct caller {
- typedef BOOST_SIGNALS_ARGS_STRUCT<BOOST_SIGNALS_TEMPLATE_ARGS>*
- args_type;
-
- args_type args;
-
- typedef R result_type;
-
- caller() {}
- caller(args_type a) : args(a) {}
-
- template<typename Pair>
- R operator()(const Pair& slot) const
- {
- F* target = const_cast<F*>(unsafe_any_cast<F>(&slot.second));
- return (*target)(BOOST_SIGNALS_BOUND_ARGS);
- }
- };
- };
-
- template<>
- struct BOOST_SIGNALS_CALL_BOUND<void> {
- template<BOOST_SIGNALS_TEMPLATE_PARMS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- typename F>
- struct caller {
- typedef BOOST_SIGNALS_ARGS_STRUCT<BOOST_SIGNALS_TEMPLATE_ARGS>*
- args_type;
-
- args_type args;
-
- typedef unusable result_type;
-
- caller(args_type a) : args(a) {}
-
- template<typename Pair>
- unusable operator()(const Pair& slot) const
- {
- F* target = const_cast<F*>(unsafe_any_cast<F>(&slot.second));
- (*target)(BOOST_SIGNALS_BOUND_ARGS);
- return unusable();
- }
- };
- };
- } // namespace detail
- } // namespace BOOST_SIGNALS_NAMESPACE
-
- // The actual signalN class
- template<
- typename R,
- BOOST_SIGNALS_TEMPLATE_PARMS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- typename Combiner = last_value<R>,
- typename Group = int,
- typename GroupCompare = std::less<Group>,
- typename SlotFunction = BOOST_SIGNALS_FUNCTION<
- R BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- BOOST_SIGNALS_TEMPLATE_ARGS>
- >
- class BOOST_SIGNALS_SIGNAL :
- public BOOST_SIGNALS_NAMESPACE::detail::signal_base, // management of slot list
- public BOOST_SIGNALS_NAMESPACE::trackable // signals are trackable
- {
- public:
- // The slot function type
- typedef SlotFunction slot_function_type;
-
- // Result type of a slot
- typedef typename BOOST_SIGNALS_NAMESPACE::detail::slot_result_type<R>::type
- slot_result_type;
-
- // Argument types
- BOOST_SIGNALS_ARG_TYPES
-
-#if BOOST_SIGNALS_NUM_ARGS == 1
- typedef T1 argument_type;
-#elif BOOST_SIGNALS_NUM_ARGS == 2
- typedef T1 first_argument_type;
- typedef T2 second_argument_type;
-#endif
-
- private:
- // The real slot name comparison object type
- typedef BOOST_SIGNALS_NAMESPACE::detail::group_bridge_compare<GroupCompare, Group>
- real_group_compare_type;
-
- // The function object passed to the slot call iterator that will call
- // the underlying slot function with its arguments bound
- typedef BOOST_SIGNALS_NAMESPACE::detail::BOOST_SIGNALS_CALL_BOUND<R>
- outer_bound_slot_caller;
- typedef typename outer_bound_slot_caller::template
- caller<BOOST_SIGNALS_TEMPLATE_ARGS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- slot_function_type>
- call_bound_slot;
-
- public:
- // Combiner's result type
- typedef typename Combiner::result_type result_type;
-
- // Combiner type
- typedef Combiner combiner_type;
-
- // Slot type
- typedef slot<slot_function_type> slot_type;
-
- // Slot name type and comparison
- typedef Group group_type;
- typedef GroupCompare group_compare_type;
-
- typedef BOOST_SIGNALS_NAMESPACE::detail::slot_call_iterator<
- call_bound_slot, iterator> slot_call_iterator;
-
- explicit
- BOOST_SIGNALS_SIGNAL(const Combiner& c = Combiner(),
- const GroupCompare& comp = GroupCompare()) :
- BOOST_SIGNALS_NAMESPACE::detail::signal_base(real_group_compare_type(comp),
- c)
- {
- }
-
- // Connect a slot to this signal
- BOOST_SIGNALS_NAMESPACE::connection
- connect(const slot_type&,
- BOOST_SIGNALS_NAMESPACE::connect_position at
- = BOOST_SIGNALS_NAMESPACE::at_back);
-
-
- BOOST_SIGNALS_NAMESPACE::connection
- connect(const group_type&, const slot_type&,
- BOOST_SIGNALS_NAMESPACE::connect_position at
- = BOOST_SIGNALS_NAMESPACE::at_back);
-
- template<typename T>
- void disconnect(const T& t)
- {
- typedef mpl::bool_<(is_convertible<T, group_type>::value)> is_group;
- this->do_disconnect(t, is_group());
- }
-
- private:
- // Disconnect a named slot
- void do_disconnect(const group_type& group, mpl::bool_<true>)
- {
- impl->disconnect(group);
- }
-
- template<typename Function>
- void do_disconnect(const Function& f, mpl::bool_<false>)
- {
- // Notify the slot handling code that we are iterating through the slots
- BOOST_SIGNALS_NAMESPACE::detail::call_notification notification(this->impl);
-
- for (iterator i = impl->slots_.begin(); i != impl->slots_.end(); ++i) {
- slot_function_type& s = *unsafe_any_cast<slot_function_type>(&i->second);
- if (s == f) i->first.disconnect();
- }
- }
-
- public:
-
- // Emit the signal
- result_type operator()(BOOST_SIGNALS_PARMS);
- result_type operator()(BOOST_SIGNALS_PARMS) const;
-
- Combiner& combiner()
- { return *unsafe_any_cast<Combiner>(&impl->combiner_); }
-
- const Combiner& combiner() const
- { return *unsafe_any_cast<const Combiner>(&impl->combiner_); }
- };
-
- template<
- typename R,
- BOOST_SIGNALS_TEMPLATE_PARMS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction
- >
- BOOST_SIGNALS_NAMESPACE::connection
- BOOST_SIGNALS_SIGNAL<
- R, BOOST_SIGNALS_TEMPLATE_ARGS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- Combiner, Group, GroupCompare, SlotFunction
- >::connect(const slot_type& in_slot,
- BOOST_SIGNALS_NAMESPACE::connect_position at)
- {
- using boost::BOOST_SIGNALS_NAMESPACE::detail::stored_group;
-
- // If the slot has been disconnected, just return a disconnected
- // connection
- if (!in_slot.is_active()) {
- return BOOST_SIGNALS_NAMESPACE::connection();
- }
-
- return impl->connect_slot(in_slot.get_slot_function(), stored_group(),
- in_slot.get_data(), at);
- }
-
- template<
- typename R,
- BOOST_SIGNALS_TEMPLATE_PARMS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction
- >
- BOOST_SIGNALS_NAMESPACE::connection
- BOOST_SIGNALS_SIGNAL<
- R, BOOST_SIGNALS_TEMPLATE_ARGS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- Combiner, Group, GroupCompare, SlotFunction
- >::connect(const group_type& group,
- const slot_type& in_slot,
- BOOST_SIGNALS_NAMESPACE::connect_position at)
- {
- // If the slot has been disconnected, just return a disconnected
- // connection
- if (!in_slot.is_active()) {
- return BOOST_SIGNALS_NAMESPACE::connection();
- }
-
- return impl->connect_slot(in_slot.get_slot_function(), group,
- in_slot.get_data(), at);
- }
-
- template<
- typename R,
- BOOST_SIGNALS_TEMPLATE_PARMS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction
- >
- typename BOOST_SIGNALS_SIGNAL<
- R, BOOST_SIGNALS_TEMPLATE_ARGS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- Combiner, Group, GroupCompare, SlotFunction>::result_type
- BOOST_SIGNALS_SIGNAL<
- R, BOOST_SIGNALS_TEMPLATE_ARGS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- Combiner, Group, GroupCompare, SlotFunction
- >::operator()(BOOST_SIGNALS_PARMS)
- {
- // Notify the slot handling code that we are making a call
- BOOST_SIGNALS_NAMESPACE::detail::call_notification notification(this->impl);
-
- // Construct a function object that will call the underlying slots
- // with the given arguments.
-#if BOOST_SIGNALS_NUM_ARGS == 0
- BOOST_SIGNALS_ARGS_STRUCT_INST args;
-#else
- BOOST_SIGNALS_ARGS_STRUCT_INST args(BOOST_SIGNALS_ARGS);
-#endif // BOOST_SIGNALS_NUM_ARGS > 0
- call_bound_slot f(&args);
-
- typedef typename call_bound_slot::result_type call_result_type;
- optional<call_result_type> cache;
- // Let the combiner call the slots via a pair of input iterators
- return combiner()(slot_call_iterator(notification.impl->slots_.begin(),
- impl->slots_.end(), f, cache),
- slot_call_iterator(notification.impl->slots_.end(),
- impl->slots_.end(), f, cache));
- }
-
- template<
- typename R,
- BOOST_SIGNALS_TEMPLATE_PARMS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- typename Combiner,
- typename Group,
- typename GroupCompare,
- typename SlotFunction
- >
- typename BOOST_SIGNALS_SIGNAL<
- R, BOOST_SIGNALS_TEMPLATE_ARGS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- Combiner, Group, GroupCompare, SlotFunction>::result_type
- BOOST_SIGNALS_SIGNAL<
- R, BOOST_SIGNALS_TEMPLATE_ARGS
- BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
- Combiner, Group, GroupCompare, SlotFunction
- >::operator()(BOOST_SIGNALS_PARMS) const
- {
- // Notify the slot handling code that we are making a call
- BOOST_SIGNALS_NAMESPACE::detail::call_notification notification(this->impl);
-
- // Construct a function object that will call the underlying slots
- // with the given arguments.
-#if BOOST_SIGNALS_NUM_ARGS == 0
- BOOST_SIGNALS_ARGS_STRUCT_INST args;
-#else
- BOOST_SIGNALS_ARGS_STRUCT_INST args(BOOST_SIGNALS_ARGS);
-#endif // BOOST_SIGNALS_NUM_ARGS > 0
-
- call_bound_slot f(&args);
-
- typedef typename call_bound_slot::result_type call_result_type;
- optional<call_result_type> cache;
-
- // Let the combiner call the slots via a pair of input iterators
- return combiner()(slot_call_iterator(notification.impl->slots_.begin(),
- impl->slots_.end(), f, cache),
- slot_call_iterator(notification.impl->slots_.end(),
- impl->slots_.end(), f, cache));
- }
-} // namespace boost
-
-#undef BOOST_SIGNAL_FUNCTION_N_HEADER
-#undef BOOST_SIGNALS_ARGS_STRUCT_INST
-#undef BOOST_SIGNALS_CALL_BOUND
-#undef BOOST_SIGNALS_ARGS_STRUCT
-#undef BOOST_SIGNALS_FUNCTION
-#undef BOOST_SIGNALS_SIGNAL
-#undef BOOST_SIGNALS_COMMA_IF_NONZERO_ARGS
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_SUFFIX
-#endif
diff --git a/3rdParty/Boost/src/boost/signals/slot.hpp b/3rdParty/Boost/src/boost/signals/slot.hpp
deleted file mode 100644
index bbf1848..0000000
--- a/3rdParty/Boost/src/boost/signals/slot.hpp
+++ /dev/null
@@ -1,157 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2004. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_SLOT_HEADER
-#define BOOST_SIGNALS_SLOT_HEADER
-
-#include <boost/signals/detail/signals_common.hpp>
-#include <boost/signals/connection.hpp>
-#include <boost/signals/trackable.hpp>
-#include <boost/visit_each.hpp>
-#include <boost/shared_ptr.hpp>
-#include <cassert>
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_PREFIX
-#endif
-
-namespace boost {
- namespace BOOST_SIGNALS_NAMESPACE {
- namespace detail {
- class BOOST_SIGNALS_DECL slot_base {
- // We would have to enumerate all of the signalN classes here as
- // friends to make this private (as it otherwise should be). We can't
- // name all of them because we don't know how many there are.
- public:
- struct data_t {
- std::vector<const trackable*> bound_objects;
- connection watch_bound_objects;
- };
- shared_ptr<data_t> get_data() const { return data; }
-
- // Get the set of bound objects
- std::vector<const trackable*>& get_bound_objects() const
- { return data->bound_objects; }
-
- // Determine if this slot is still "active", i.e., all of the bound
- // objects still exist
- bool is_active() const
- { return data->watch_bound_objects.connected(); }
-
- protected:
- // Create a connection for this slot
- void create_connection();
-
- shared_ptr<data_t> data;
-
- private:
- static void bound_object_destructed(void*, void*) {}
- };
- } // end namespace detail
-
- // Get the slot so that it can be copied
- template<typename F>
- reference_wrapper<const F>
- get_invocable_slot(const F& f, BOOST_SIGNALS_NAMESPACE::detail::signal_tag)
- { return reference_wrapper<const F>(f); }
-
- template<typename F>
- const F&
- get_invocable_slot(const F& f, BOOST_SIGNALS_NAMESPACE::detail::reference_tag)
- { return f; }
-
- template<typename F>
- const F&
- get_invocable_slot(const F& f, BOOST_SIGNALS_NAMESPACE::detail::value_tag)
- { return f; }
-
- // Get the slot so that it can be inspected for trackable objects
- template<typename F>
- const F&
- get_inspectable_slot(const F& f, BOOST_SIGNALS_NAMESPACE::detail::signal_tag)
- { return f; }
-
- template<typename F>
- const F&
- get_inspectable_slot(const reference_wrapper<F>& f, BOOST_SIGNALS_NAMESPACE::detail::reference_tag)
- { return f.get(); }
-
- template<typename F>
- const F&
- get_inspectable_slot(const F& f, BOOST_SIGNALS_NAMESPACE::detail::value_tag)
- { return f; }
-
- // Determines the type of the slot - is it a signal, a reference to a
- // slot or just a normal slot.
- template<typename F>
- typename BOOST_SIGNALS_NAMESPACE::detail::get_slot_tag<F>::type
- tag_type(const F&)
- {
- typedef typename BOOST_SIGNALS_NAMESPACE::detail::get_slot_tag<F>::type
- the_tag_type;
- the_tag_type tag = the_tag_type();
- return tag;
- }
-
- } // end namespace BOOST_SIGNALS_NAMESPACE
-
- template<typename SlotFunction>
- class slot : public BOOST_SIGNALS_NAMESPACE::detail::slot_base {
- typedef BOOST_SIGNALS_NAMESPACE::detail::slot_base inherited;
- typedef typename inherited::data_t data_t;
-
- public:
- template<typename F>
- slot(const F& f) : slot_function(BOOST_SIGNALS_NAMESPACE::get_invocable_slot(f, BOOST_SIGNALS_NAMESPACE::tag_type(f)))
- {
- this->data.reset(new data_t);
-
- // Visit each of the bound objects and store them for later use
- // An exception thrown here will allow the basic_connection to be
- // destroyed when this goes out of scope, and no other connections
- // have been made.
- BOOST_SIGNALS_NAMESPACE::detail::bound_objects_visitor
- do_bind(this->data->bound_objects);
- visit_each(do_bind,
- BOOST_SIGNALS_NAMESPACE::get_inspectable_slot
- (f, BOOST_SIGNALS_NAMESPACE::tag_type(f)));
- create_connection();
- }
-
-#ifdef __BORLANDC__
- template<typename F>
- slot(F* f) : slot_function(f)
- {
- this->data.reset(new data_t);
- create_connection();
- }
-#endif // __BORLANDC__
-
- // We would have to enumerate all of the signalN classes here as friends
- // to make this private (as it otherwise should be). We can't name all of
- // them because we don't know how many there are.
- public:
- // Get the slot function to call the actual slot
- const SlotFunction& get_slot_function() const { return slot_function; }
-
- void release() const { data->watch_bound_objects.set_controlling(false); }
-
- private:
- slot(); // no default constructor
- slot& operator=(const slot&); // no assignment operator
-
- SlotFunction slot_function;
- };
-} // end namespace boost
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_SUFFIX
-#endif
-
-#endif // BOOST_SIGNALS_SLOT_HEADER
diff --git a/3rdParty/Boost/src/boost/signals/trackable.hpp b/3rdParty/Boost/src/boost/signals/trackable.hpp
deleted file mode 100644
index 047236c..0000000
--- a/3rdParty/Boost/src/boost/signals/trackable.hpp
+++ /dev/null
@@ -1,173 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2004. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#ifndef BOOST_SIGNALS_TRACKABLE_HPP
-#define BOOST_SIGNALS_TRACKABLE_HPP
-
-#include <boost/type_traits.hpp>
-#include <boost/signals/connection.hpp>
-#include <boost/ref.hpp>
-#include <boost/utility/addressof.hpp>
-#include <list>
-#include <vector>
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_PREFIX
-#endif
-
-namespace boost {
-
-namespace BOOST_SIGNALS_NAMESPACE {
- // Base class for "trackable" objects that can be tracked when they are
- // bound in slot target functions. When a trackable object is destroyed,
- // the signal/slot connections are disconnected automatically.
- class BOOST_SIGNALS_DECL trackable {
- private:
- static void signal_disconnected(void* obj, void* data);
-
- friend class detail::signal_base_impl;
- friend class detail::slot_base;
- void signal_connected(connection, BOOST_SIGNALS_NAMESPACE::detail::bound_object&) const;
-
- protected:
- trackable() : connected_signals(), dying(false) {}
- trackable(const trackable&) : connected_signals(), dying(false) {}
- ~trackable();
-
- trackable& operator=(const trackable&)
- {
- dying = true;
- connected_signals.clear();
- dying = false;
- return *this;
- }
-
- private:
- typedef std::list<connection> connection_list;
- typedef connection_list::iterator connection_iterator;
-
- // List of connections that this object is part of
- mutable connection_list connected_signals;
-
- // True when the object is being destroyed
- mutable bool dying;
- };
-
- namespace detail {
- template<bool Cond> struct truth {};
-
- // A visitor that adds each trackable object to a vector
- class bound_objects_visitor {
- public:
- bound_objects_visitor(std::vector<const trackable*>& v) :
- bound_objects(v)
- {
- }
-
- template<typename T>
- void operator()(const T& t) const
- {
- decode(t, 0);
- }
-
- private:
- // decode() decides between a reference wrapper and anything else
- template<typename T>
- void decode(const reference_wrapper<T>& t, int) const
- {
- add_if_trackable(t.get_pointer());
- }
-
- template<typename T>
- void decode(const T& t, long) const
- {
- typedef truth<(is_pointer<T>::value)> is_a_pointer;
- maybe_get_pointer(t, is_a_pointer());
- }
-
- // maybe_get_pointer() decides between a pointer and a non-pointer
- template<typename T>
- void maybe_get_pointer(const T& t, truth<true>) const
- {
- add_if_trackable(t);
- }
-
- template<typename T>
- void maybe_get_pointer(const T& t, truth<false>) const
- {
- // Take the address of this object, because the object itself may be
- // trackable
- add_if_trackable(boost::addressof(t));
- }
-
- // add_if_trackable() adds trackable objects to the list of bound objects
- inline void add_if_trackable(const trackable* b) const
- {
- if (b) {
- bound_objects.push_back(b);
- }
- }
-
- inline void add_if_trackable(const void*) const { }
-
- template<typename R>
- inline void add_if_trackable(R (*)()) const { }
-
- template<typename R, typename T1>
- inline void add_if_trackable(R (*)(T1)) const { }
-
- template<typename R, typename T1, typename T2>
- inline void add_if_trackable(R (*)(T1, T2)) const { }
-
- template<typename R, typename T1, typename T2, typename T3>
- inline void add_if_trackable(R (*)(T1, T2, T3)) const { }
-
- template<typename R, typename T1, typename T2, typename T3, typename T4>
- inline void add_if_trackable(R (*)(T1, T2, T3, T4)) const { }
-
- template<typename R, typename T1, typename T2, typename T3, typename T4,
- typename T5>
- inline void add_if_trackable(R (*)(T1, T2, T3, T4, T5)) const { }
-
- template<typename R, typename T1, typename T2, typename T3, typename T4,
- typename T5, typename T6>
- inline void add_if_trackable(R (*)(T1, T2, T3, T4, T5, T6)) const { }
-
- template<typename R, typename T1, typename T2, typename T3, typename T4,
- typename T5, typename T6, typename T7>
- inline void add_if_trackable(R (*)(T1, T2, T3, T4, T5, T6, T7)) const { }
-
- template<typename R, typename T1, typename T2, typename T3, typename T4,
- typename T5, typename T6, typename T7, typename T8>
- inline void
- add_if_trackable(R (*)(T1, T2, T3, T4, T5, T6, T7, T8)) const { }
-
- template<typename R, typename T1, typename T2, typename T3, typename T4,
- typename T5, typename T6, typename T7, typename T8, typename T9>
- inline void
- add_if_trackable(R (*)(T1, T2, T3, T4, T5, T6, T7, T8, T9)) const { }
-
- template<typename R, typename T1, typename T2, typename T3, typename T4,
- typename T5, typename T6, typename T7, typename T8, typename T9,
- typename T10>
- inline void
- add_if_trackable(R (*)(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)) const { }
-
- std::vector<const trackable*>& bound_objects;
- };
- } // end namespace detail
-} // end namespace BOOST_SIGNALS_NAMESPACE
-
-} // end namespace boost
-
-#ifdef BOOST_HAS_ABI_HEADERS
-# include BOOST_ABI_SUFFIX
-#endif
-
-#endif // BOOST_SIGNALS_TRACKABLE_HPP
diff --git a/3rdParty/Boost/src/boost/signals2.hpp b/3rdParty/Boost/src/boost/signals2.hpp
new file mode 100644
index 0000000..22b1119
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2.hpp
@@ -0,0 +1,23 @@
+// A convenience header for Boost.Signals2, should pull in everying in the library.
+
+// Copyright (c) 2008-2009 Frank Mori Hess
+
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_SIGNALS2_HPP
+#define BOOST_SIGNALS2_HPP
+
+// For documentation, see http://www.boost.org/libs/signals2/
+
+#include <boost/signals2/deconstruct.hpp>
+#include <boost/signals2/deconstruct_ptr.hpp>
+#include <boost/signals2/dummy_mutex.hpp>
+#include <boost/signals2/last_value.hpp>
+#include <boost/signals2/signal.hpp>
+#include <boost/signals2/signal_type.hpp>
+#include <boost/signals2/shared_connection_block.hpp>
+
+#endif
diff --git a/3rdParty/Boost/src/boost/signals2/connection.hpp b/3rdParty/Boost/src/boost/signals2/connection.hpp
new file mode 100644
index 0000000..0ab4dac
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/connection.hpp
@@ -0,0 +1,297 @@
+/*
+ boost::signals2::connection provides a handle to a signal/slot connection.
+
+ Author: Frank Mori Hess <fmhess@users.sourceforge.net>
+ Begin: 2007-01-23
+*/
+// Copyright Frank Mori Hess 2007-2008.
+// Distributed under the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org/libs/signals2 for library home page.
+
+#ifndef BOOST_SIGNALS2_CONNECTION_HPP
+#define BOOST_SIGNALS2_CONNECTION_HPP
+
+#include <boost/function.hpp>
+#include <boost/mpl/bool.hpp>
+#include <boost/noncopyable.hpp>
+#include <boost/shared_ptr.hpp>
+#include <boost/signals2/detail/null_output_iterator.hpp>
+#include <boost/signals2/detail/unique_lock.hpp>
+#include <boost/signals2/slot.hpp>
+#include <boost/weak_ptr.hpp>
+
+namespace boost
+{
+ namespace signals2
+ {
+ extern inline void null_deleter(const void*) {}
+ namespace detail
+ {
+ class connection_body_base
+ {
+ public:
+ connection_body_base():
+ _connected(true)
+ {
+ }
+ virtual ~connection_body_base() {}
+ void disconnect()
+ {
+ unique_lock<connection_body_base> local_lock(*this);
+ nolock_disconnect();
+ }
+ void nolock_disconnect()
+ {
+ _connected = false;
+ }
+ virtual bool connected() const = 0;
+ shared_ptr<void> get_blocker()
+ {
+ unique_lock<connection_body_base> local_lock(*this);
+ shared_ptr<void> blocker = _weak_blocker.lock();
+ if(blocker == shared_ptr<void>())
+ {
+ blocker.reset(this, &null_deleter);
+ _weak_blocker = blocker;
+ }
+ return blocker;
+ }
+ bool blocked() const
+ {
+ return !_weak_blocker.expired();
+ }
+ bool nolock_nograb_blocked() const
+ {
+ return nolock_nograb_connected() == false || blocked();
+ }
+ bool nolock_nograb_connected() const {return _connected;}
+ // expose part of Lockable concept of mutex
+ virtual void lock() = 0;
+ virtual void unlock() = 0;
+
+ protected:
+
+ mutable bool _connected;
+ weak_ptr<void> _weak_blocker;
+ };
+
+ template<typename GroupKey, typename SlotType, typename Mutex>
+ class connection_body: public connection_body_base
+ {
+ public:
+ typedef Mutex mutex_type;
+ connection_body(const SlotType &slot_in):
+ slot(slot_in)
+ {
+ }
+ virtual ~connection_body() {}
+ virtual bool connected() const
+ {
+ unique_lock<mutex_type> local_lock(_mutex);
+ nolock_grab_tracked_objects(detail::null_output_iterator());
+ return nolock_nograb_connected();
+ }
+ const GroupKey& group_key() const {return _group_key;}
+ void set_group_key(const GroupKey &key) {_group_key = key;}
+ bool nolock_slot_expired() const
+ {
+ bool expired = slot.expired();
+ if(expired == true)
+ {
+ _connected = false;
+ }
+ return expired;
+ }
+ template<typename OutputIterator>
+ void nolock_grab_tracked_objects(OutputIterator inserter) const
+ {
+ slot_base::tracked_container_type::const_iterator it;
+ for(it = slot.tracked_objects().begin();
+ it != slot.tracked_objects().end();
+ ++it)
+ {
+ void_shared_ptr_variant locked_object
+ (
+ apply_visitor
+ (
+ detail::lock_weak_ptr_visitor(),
+ *it
+ )
+ );
+ if(apply_visitor(detail::expired_weak_ptr_visitor(), *it))
+ {
+ _connected = false;
+ return;
+ }
+ *inserter++ = locked_object;
+ }
+ }
+ // expose Lockable concept of mutex
+ virtual void lock()
+ {
+ _mutex.lock();
+ }
+ virtual void unlock()
+ {
+ _mutex.unlock();
+ }
+ SlotType slot;
+ private:
+ mutable mutex_type _mutex;
+ GroupKey _group_key;
+ };
+ }
+
+ class shared_connection_block;
+
+ class connection
+ {
+ public:
+ friend class shared_connection_block;
+
+ connection() {}
+ connection(const connection &other): _weak_connection_body(other._weak_connection_body)
+ {}
+ connection(const boost::weak_ptr<detail::connection_body_base> &connectionBody):
+ _weak_connection_body(connectionBody)
+ {}
+
+ // move support
+#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
+ connection(connection && other): _weak_connection_body(std::move(other._weak_connection_body))
+ {
+ // make sure other is reset, in case it is a scoped_connection (so it
+ // won't disconnect on destruction after being moved away from).
+ other._weak_connection_body.reset();
+ }
+ connection & operator=(connection && other)
+ {
+ if(&other == this) return *this;
+ _weak_connection_body = std::move(other._weak_connection_body);
+ // make sure other is reset, in case it is a scoped_connection (so it
+ // won't disconnect on destruction after being moved away from).
+ other._weak_connection_body.reset();
+ return *this;
+ }
+#endif // !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
+ connection & operator=(const connection & other)
+ {
+ if(&other == this) return *this;
+ _weak_connection_body = other._weak_connection_body;
+ return *this;
+ }
+
+ ~connection() {}
+ void disconnect() const
+ {
+ boost::shared_ptr<detail::connection_body_base> connectionBody(_weak_connection_body.lock());
+ if(connectionBody == 0) return;
+ connectionBody->disconnect();
+ }
+ bool connected() const
+ {
+ boost::shared_ptr<detail::connection_body_base> connectionBody(_weak_connection_body.lock());
+ if(connectionBody == 0) return false;
+ return connectionBody->connected();
+ }
+ bool blocked() const
+ {
+ boost::shared_ptr<detail::connection_body_base> connectionBody(_weak_connection_body.lock());
+ if(connectionBody == 0) return true;
+ return connectionBody->blocked();
+ }
+ bool operator==(const connection& other) const
+ {
+ boost::shared_ptr<detail::connection_body_base> connectionBody(_weak_connection_body.lock());
+ boost::shared_ptr<detail::connection_body_base> otherConnectionBody(other._weak_connection_body.lock());
+ return connectionBody == otherConnectionBody;
+ }
+ bool operator!=(const connection& other) const
+ {
+ return !(*this == other);
+ }
+ bool operator<(const connection& other) const
+ {
+ boost::shared_ptr<detail::connection_body_base> connectionBody(_weak_connection_body.lock());
+ boost::shared_ptr<detail::connection_body_base> otherConnectionBody(other._weak_connection_body.lock());
+ return connectionBody < otherConnectionBody;
+ }
+ void swap(connection &other)
+ {
+ using std::swap;
+ swap(_weak_connection_body, other._weak_connection_body);
+ }
+ protected:
+
+ boost::weak_ptr<detail::connection_body_base> _weak_connection_body;
+ };
+ inline void swap(connection &conn1, connection &conn2)
+ {
+ conn1.swap(conn2);
+ }
+
+ class scoped_connection: public connection
+ {
+ public:
+ scoped_connection() {}
+ scoped_connection(const connection &other):
+ connection(other)
+ {}
+ ~scoped_connection()
+ {
+ disconnect();
+ }
+ scoped_connection& operator=(const connection &rhs)
+ {
+ disconnect();
+ connection::operator=(rhs);
+ return *this;
+ }
+
+ // move support
+#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
+ scoped_connection(scoped_connection && other): connection(std::move(other))
+ {
+ }
+ scoped_connection(connection && other): connection(std::move(other))
+ {
+ }
+ scoped_connection & operator=(scoped_connection && other)
+ {
+ if(&other == this) return *this;
+ disconnect();
+ connection::operator=(std::move(other));
+ return *this;
+ }
+ scoped_connection & operator=(connection && other)
+ {
+ if(&other == this) return *this;
+ disconnect();
+ connection::operator=(std::move(other));
+ return *this;
+ }
+#endif // !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
+
+ connection release()
+ {
+ connection conn(_weak_connection_body);
+ _weak_connection_body.reset();
+ return conn;
+ }
+ private:
+ scoped_connection(const scoped_connection &other);
+ scoped_connection& operator=(const scoped_connection &rhs);
+ };
+ // Sun 5.9 compiler doesn't find the swap for base connection class when
+ // arguments are scoped_connection, so we provide this explicitly.
+ inline void swap(scoped_connection &conn1, scoped_connection &conn2)
+ {
+ conn1.swap(conn2);
+ }
+ }
+}
+
+#endif // BOOST_SIGNALS2_CONNECTION_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/deconstruct.hpp b/3rdParty/Boost/src/boost/signals2/deconstruct.hpp
new file mode 100644
index 0000000..d3eca33
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/deconstruct.hpp
@@ -0,0 +1,547 @@
+#ifndef BOOST_SIGNALS2_DECONSTRUCT_HPP
+#define BOOST_SIGNALS2_DECONSTRUCT_HPP
+
+// deconstruct.hpp
+//
+// A factory function for creating a shared_ptr which creates
+// an object and its owning shared_ptr with one allocation, similar
+// to make_shared<T>(). It also supports postconstructors
+// and predestructors through unqualified calls of adl_postconstruct() and
+// adl_predestruct, relying on argument-dependent
+// lookup to find the appropriate postconstructor or predestructor.
+// Passing arguments to postconstructors is also supported.
+//
+// based on make_shared.hpp and make_shared_access patch from Michael Marcin
+//
+// Copyright (c) 2007, 2008 Peter Dimov
+// Copyright (c) 2008 Michael Marcin
+// Copyright (c) 2009 Frank Mori Hess
+//
+// Distributed under the Boost Software License, Version 1.0.
+// See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt
+//
+// See http://www.boost.org
+// for more information
+
+#include <boost/config.hpp>
+#include <boost/shared_ptr.hpp>
+#include <boost/signals2/deconstruct_ptr.hpp>
+#include <boost/type_traits/alignment_of.hpp>
+#include <boost/type_traits/remove_const.hpp>
+#include <boost/type_traits/type_with_alignment.hpp>
+#include <cstddef>
+#include <new>
+
+namespace boost
+{
+ template<typename T> class enable_shared_from_this;
+
+namespace signals2
+{
+ class deconstruct_access;
+
+namespace detail
+{
+ inline void adl_predestruct(...) {}
+} // namespace detail
+
+template<typename T>
+ class postconstructor_invoker
+{
+public:
+ operator const shared_ptr<T> & () const
+ {
+ return postconstruct();
+ }
+ const shared_ptr<T>& postconstruct() const
+ {
+ if(!_postconstructed)
+ {
+ adl_postconstruct(_sp, const_cast<typename boost::remove_const<T>::type *>(_sp.get()));
+ _postconstructed = true;
+ }
+ return _sp;
+ }
+#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
+ template<class... Args>
+ const shared_ptr<T>& postconstruct(Args && ... args)
+ {
+ if(!_postconstructed)
+ {
+ adl_postconstruct(_sp, const_cast<typename boost::remove_const<T>::type *>(_sp.get()),
+ std::forward<Args>(args)...);
+ _postconstructed = true;
+ }
+ return _sp;
+ }
+#else // !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
+ template<typename A1>
+ const shared_ptr<T>& postconstruct(const A1 &a1) const
+ {
+ if(!_postconstructed)
+ {
+ adl_postconstruct(_sp, const_cast<typename boost::remove_const<T>::type *>(_sp.get()),
+ a1);
+ _postconstructed = true;
+ }
+ return _sp;
+ }
+ template<typename A1, typename A2>
+ const shared_ptr<T>& postconstruct(const A1 &a1, const A2 &a2) const
+ {
+ if(!_postconstructed)
+ {
+ adl_postconstruct(_sp, const_cast<typename boost::remove_const<T>::type *>(_sp.get()),
+ a1, a2);
+ _postconstructed = true;
+ }
+ return _sp;
+ }
+ template<typename A1, typename A2, typename A3>
+ const shared_ptr<T>& postconstruct(const A1 &a1, const A2 &a2, const A3 &a3) const
+ {
+ if(!_postconstructed)
+ {
+ adl_postconstruct(_sp, const_cast<typename boost::remove_const<T>::type *>(_sp.get()),
+ a1, a2, a3);
+ _postconstructed = true;
+ }
+ return _sp;
+ }
+ template<typename A1, typename A2, typename A3, typename A4>
+ const shared_ptr<T>& postconstruct(const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4) const
+ {
+ if(!_postconstructed)
+ {
+ adl_postconstruct(_sp, const_cast<typename boost::remove_const<T>::type *>(_sp.get()),
+ a1, a2, a3, a4);
+ _postconstructed = true;
+ }
+ return _sp;
+ }
+ template<typename A1, typename A2, typename A3, typename A4, typename A5>
+ const shared_ptr<T>& postconstruct(const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5) const
+ {
+ if(!_postconstructed)
+ {
+ adl_postconstruct(_sp, const_cast<typename boost::remove_const<T>::type *>(_sp.get()),
+ a1, a2, a3, a4, a5);
+ _postconstructed = true;
+ }
+ return _sp;
+ }
+ template<typename A1, typename A2, typename A3, typename A4, typename A5,
+ typename A6>
+ const shared_ptr<T>& postconstruct(const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5,
+ const A6 &a6) const
+ {
+ if(!_postconstructed)
+ {
+ adl_postconstruct(_sp, const_cast<typename boost::remove_const<T>::type *>(_sp.get()),
+ a1, a2, a3, a4, a5, a6);
+ _postconstructed = true;
+ }
+ return _sp;
+ }
+ template<typename A1, typename A2, typename A3, typename A4, typename A5,
+ typename A6, typename A7>
+ const shared_ptr<T>& postconstruct(const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5,
+ const A6 &a6, const A7 &a7) const
+ {
+ if(!_postconstructed)
+ {
+ adl_postconstruct(_sp, const_cast<typename boost::remove_const<T>::type *>(_sp.get()),
+ a1, a2, a3, a4, a5, a6, a7);
+ _postconstructed = true;
+ }
+ return _sp;
+ }
+ template<typename A1, typename A2, typename A3, typename A4, typename A5,
+ typename A6, typename A7, typename A8>
+ const shared_ptr<T>& postconstruct(const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5,
+ const A6 &a6, const A7 &a7, const A8 &a8) const
+ {
+ if(!_postconstructed)
+ {
+ adl_postconstruct(_sp, const_cast<typename boost::remove_const<T>::type *>(_sp.get()),
+ a1, a2, a3, a4, a5, a6, a7, a8);
+ _postconstructed = true;
+ }
+ return _sp;
+ }
+ template<typename A1, typename A2, typename A3, typename A4, typename A5,
+ typename A6, typename A7, typename A8, typename A9>
+ const shared_ptr<T>& postconstruct(const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5,
+ const A6 &a6, const A7 &a7, const A8 &a8, const A9 &a9) const
+ {
+ if(!_postconstructed)
+ {
+ adl_postconstruct(_sp, const_cast<typename boost::remove_const<T>::type *>(_sp.get()),
+ a1, a2, a3, a4, a5, a6, a7, a8, a9);
+ _postconstructed = true;
+ }
+ return _sp;
+ }
+#endif // !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
+private:
+ friend class boost::signals2::deconstruct_access;
+ postconstructor_invoker(const shared_ptr<T> & sp):
+ _sp(sp), _postconstructed(false)
+ {}
+ shared_ptr<T> _sp;
+ mutable bool _postconstructed;
+};
+
+namespace detail
+{
+
+template< std::size_t N, std::size_t A > struct sp_aligned_storage
+{
+ union type
+ {
+ char data_[ N ];
+ typename boost::type_with_alignment< A >::type align_;
+ };
+};
+
+template< class T > class deconstruct_deleter
+{
+private:
+
+ typedef typename sp_aligned_storage< sizeof( T ), ::boost::alignment_of< T >::value >::type storage_type;
+
+ bool initialized_;
+ storage_type storage_;
+
+private:
+
+ void destroy()
+ {
+ if( initialized_ )
+ {
+ T* p = reinterpret_cast< T* >( storage_.data_ );
+ using boost::signals2::detail::adl_predestruct;
+ adl_predestruct(const_cast<typename boost::remove_const<T>::type *>(p));
+ p->~T();
+ initialized_ = false;
+ }
+ }
+
+public:
+
+ deconstruct_deleter(): initialized_( false )
+ {
+ }
+
+ // this copy constructor is an optimization: we don't need to copy the storage_ member,
+ // and shouldn't be copying anyways after initialized_ becomes true
+ deconstruct_deleter(const deconstruct_deleter &): initialized_( false )
+ {
+ }
+
+ ~deconstruct_deleter()
+ {
+ destroy();
+ }
+
+ void operator()( T * )
+ {
+ destroy();
+ }
+
+ void * address()
+ {
+ return storage_.data_;
+ }
+
+ void set_initialized()
+ {
+ initialized_ = true;
+ }
+};
+} // namespace detail
+
+class deconstruct_access
+{
+public:
+
+ template< class T >
+ static postconstructor_invoker<T> deconstruct()
+ {
+ boost::shared_ptr< T > pt( static_cast< T* >( 0 ), detail::deconstruct_deleter< T >() );
+
+ detail::deconstruct_deleter< T > * pd = boost::get_deleter< detail::deconstruct_deleter< T > >( pt );
+
+ void * pv = pd->address();
+
+ new( pv ) T();
+ pd->set_initialized();
+
+ boost::shared_ptr< T > retval( pt, static_cast< T* >( pv ) );
+ boost::detail::sp_enable_shared_from_this(&retval, retval.get(), retval.get());
+ return retval;
+
+ }
+
+#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
+
+ // Variadic templates, rvalue reference
+
+ template< class T, class... Args >
+ static postconstructor_invoker<T> deconstruct( Args && ... args )
+ {
+ boost::shared_ptr< T > pt( static_cast< T* >( 0 ), detail::deconstruct_deleter< T >() );
+
+ detail::deconstruct_deleter< T > * pd = boost::get_deleter< detail::deconstruct_deleter< T > >( pt );
+
+ void * pv = pd->address();
+
+ new( pv ) T( std::forward<Args>( args )... );
+ pd->set_initialized();
+
+ boost::shared_ptr< T > retval( pt, static_cast< T* >( pv ) );
+ boost::detail::sp_enable_shared_from_this(&retval, retval.get(), retval.get());
+ return retval;
+ }
+
+#else
+
+ template< class T, class A1 >
+ static postconstructor_invoker<T> deconstruct( A1 const & a1 )
+ {
+ boost::shared_ptr< T > pt( static_cast< T* >( 0 ), detail::deconstruct_deleter< T >() );
+
+ detail::deconstruct_deleter< T > * pd = boost::get_deleter< detail::deconstruct_deleter< T > >( pt );
+
+ void * pv = pd->address();
+
+ new( pv ) T( a1 );
+ pd->set_initialized();
+
+ boost::shared_ptr< T > retval( pt, static_cast< T* >( pv ) );
+ boost::detail::sp_enable_shared_from_this(&retval, retval.get(), retval.get());
+ return retval;
+ }
+
+ template< class T, class A1, class A2 >
+ static postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2 )
+ {
+ boost::shared_ptr< T > pt( static_cast< T* >( 0 ), detail::deconstruct_deleter< T >() );
+
+ detail::deconstruct_deleter< T > * pd = boost::get_deleter< detail::deconstruct_deleter< T > >( pt );
+
+ void * pv = pd->address();
+
+ new( pv ) T( a1, a2 );
+ pd->set_initialized();
+
+ boost::shared_ptr< T > retval( pt, static_cast< T* >( pv ) );
+ boost::detail::sp_enable_shared_from_this(&retval, retval.get(), retval.get());
+ return retval;
+ }
+
+ template< class T, class A1, class A2, class A3 >
+ static postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2, A3 const & a3 )
+ {
+ boost::shared_ptr< T > pt( static_cast< T* >( 0 ), detail::deconstruct_deleter< T >() );
+
+ detail::deconstruct_deleter< T > * pd = boost::get_deleter< detail::deconstruct_deleter< T > >( pt );
+
+ void * pv = pd->address();
+
+ new( pv ) T( a1, a2, a3 );
+ pd->set_initialized();
+
+ boost::shared_ptr< T > retval( pt, static_cast< T* >( pv ) );
+ boost::detail::sp_enable_shared_from_this(&retval, retval.get(), retval.get());
+ return retval;
+ }
+
+ template< class T, class A1, class A2, class A3, class A4 >
+ static postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2, A3 const & a3, A4 const & a4 )
+ {
+ boost::shared_ptr< T > pt( static_cast< T* >( 0 ), detail::deconstruct_deleter< T >() );
+
+ detail::deconstruct_deleter< T > * pd = boost::get_deleter< detail::deconstruct_deleter< T > >( pt );
+
+ void * pv = pd->address();
+
+ new( pv ) T( a1, a2, a3, a4 );
+ pd->set_initialized();
+
+ boost::shared_ptr< T > retval( pt, static_cast< T* >( pv ) );
+ boost::detail::sp_enable_shared_from_this(&retval, retval.get(), retval.get());
+ return retval;
+ }
+
+ template< class T, class A1, class A2, class A3, class A4, class A5 >
+ static postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2, A3 const & a3, A4 const & a4, A5 const & a5 )
+ {
+ boost::shared_ptr< T > pt( static_cast< T* >( 0 ), detail::deconstruct_deleter< T >() );
+
+ detail::deconstruct_deleter< T > * pd = boost::get_deleter< detail::deconstruct_deleter< T > >( pt );
+
+ void * pv = pd->address();
+
+ new( pv ) T( a1, a2, a3, a4, a5 );
+ pd->set_initialized();
+
+ boost::shared_ptr< T > retval( pt, static_cast< T* >( pv ) );
+ boost::detail::sp_enable_shared_from_this(&retval, retval.get(), retval.get());
+ return retval;
+ }
+
+ template< class T, class A1, class A2, class A3, class A4, class A5, class A6 >
+ static postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2, A3 const & a3, A4 const & a4, A5 const & a5, A6 const & a6 )
+ {
+ boost::shared_ptr< T > pt( static_cast< T* >( 0 ), detail::deconstruct_deleter< T >() );
+
+ detail::deconstruct_deleter< T > * pd = boost::get_deleter< detail::deconstruct_deleter< T > >( pt );
+
+ void * pv = pd->address();
+
+ new( pv ) T( a1, a2, a3, a4, a5, a6 );
+ pd->set_initialized();
+
+ boost::shared_ptr< T > retval( pt, static_cast< T* >( pv ) );
+ boost::detail::sp_enable_shared_from_this(&retval, retval.get(), retval.get());
+ return retval;
+ }
+
+ template< class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7 >
+ static postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2, A3 const & a3, A4 const & a4, A5 const & a5, A6 const & a6, A7 const & a7 )
+ {
+ boost::shared_ptr< T > pt( static_cast< T* >( 0 ), detail::deconstruct_deleter< T >() );
+
+ detail::deconstruct_deleter< T > * pd = boost::get_deleter< detail::deconstruct_deleter< T > >( pt );
+
+ void * pv = pd->address();
+
+ new( pv ) T( a1, a2, a3, a4, a5, a6, a7 );
+ pd->set_initialized();
+
+ boost::shared_ptr< T > retval( pt, static_cast< T* >( pv ) );
+ boost::detail::sp_enable_shared_from_this(&retval, retval.get(), retval.get());
+ return retval;
+ }
+
+ template< class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8 >
+ static postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2, A3 const & a3, A4 const & a4, A5 const & a5, A6 const & a6, A7 const & a7, A8 const & a8 )
+ {
+ boost::shared_ptr< T > pt( static_cast< T* >( 0 ), detail::deconstruct_deleter< T >() );
+
+ detail::deconstruct_deleter< T > * pd = boost::get_deleter< detail::deconstruct_deleter< T > >( pt );
+
+ void * pv = pd->address();
+
+ new( pv ) T( a1, a2, a3, a4, a5, a6, a7, a8 );
+ pd->set_initialized();
+
+ boost::shared_ptr< T > retval( pt, static_cast< T* >( pv ) );
+ boost::detail::sp_enable_shared_from_this(&retval, retval.get(), retval.get());
+ return retval;
+ }
+
+ template< class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9 >
+ static postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2, A3 const & a3, A4 const & a4, A5 const & a5, A6 const & a6, A7 const & a7, A8 const & a8, A9 const & a9 )
+ {
+ boost::shared_ptr< T > pt( static_cast< T* >( 0 ), detail::deconstruct_deleter< T >() );
+
+ detail::deconstruct_deleter< T > * pd = boost::get_deleter< detail::deconstruct_deleter< T > >( pt );
+
+ void * pv = pd->address();
+
+ new( pv ) T( a1, a2, a3, a4, a5, a6, a7, a8, a9 );
+ pd->set_initialized();
+
+ boost::shared_ptr< T > retval( pt, static_cast< T* >( pv ) );
+ boost::detail::sp_enable_shared_from_this(&retval, retval.get(), retval.get());
+ return retval;
+ }
+
+#endif
+};
+
+// Zero-argument versions
+//
+// Used even when variadic templates are available because of the new T() vs new T issue
+
+template< class T > postconstructor_invoker<T> deconstruct()
+{
+ return deconstruct_access::deconstruct<T>();
+}
+
+#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
+
+// Variadic templates, rvalue reference
+
+template< class T, class... Args > postconstructor_invoker< T > deconstruct( Args && ... args )
+{
+ return deconstruct_access::deconstruct<T>( std::forward<Args>( args )... );
+}
+
+#else
+
+// C++03 version
+
+template< class T, class A1 >
+postconstructor_invoker<T> deconstruct( A1 const & a1 )
+{
+ return deconstruct_access::deconstruct<T>(a1);
+}
+
+template< class T, class A1, class A2 >
+postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2 )
+{
+ return deconstruct_access::deconstruct<T>(a1,a2);
+}
+
+template< class T, class A1, class A2, class A3 >
+postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2, A3 const & a3 )
+{
+ return deconstruct_access::deconstruct<T>(a1,a2,a3);
+}
+
+template< class T, class A1, class A2, class A3, class A4 >
+postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2, A3 const & a3, A4 const & a4 )
+{
+ return deconstruct_access::deconstruct<T>(a1,a2,a3,a4);
+}
+
+template< class T, class A1, class A2, class A3, class A4, class A5 >
+postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2, A3 const & a3, A4 const & a4, A5 const & a5 )
+{
+ return deconstruct_access::deconstruct<T>(a1,a2,a3,a4,a5);
+}
+
+template< class T, class A1, class A2, class A3, class A4, class A5, class A6 >
+postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2, A3 const & a3, A4 const & a4, A5 const & a5, A6 const & a6 )
+{
+ return deconstruct_access::deconstruct<T>(a1,a2,a3,a4,a5,a6);
+}
+
+template< class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7 >
+postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2, A3 const & a3, A4 const & a4, A5 const & a5, A6 const & a6, A7 const & a7 )
+{
+ return deconstruct_access::deconstruct<T>(a1,a2,a3,a4,a5,a6,a7);
+}
+
+template< class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8 >
+postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2, A3 const & a3, A4 const & a4, A5 const & a5, A6 const & a6, A7 const & a7, A8 const & a8 )
+{
+ return deconstruct_access::deconstruct<T>(a1,a2,a3,a4,a5,a6,a7,a8);
+}
+
+template< class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9 >
+postconstructor_invoker<T> deconstruct( A1 const & a1, A2 const & a2, A3 const & a3, A4 const & a4, A5 const & a5, A6 const & a6, A7 const & a7, A8 const & a8, A9 const & a9 )
+{
+ return deconstruct_access::deconstruct<T>(a1,a2,a3,a4,a5,a6,a7,a8,a9);
+}
+
+#endif
+
+} // namespace signals2
+} // namespace boost
+
+#endif // #ifndef BOOST_SIGNALS2_DECONSTRUCT_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/deconstruct_ptr.hpp b/3rdParty/Boost/src/boost/signals2/deconstruct_ptr.hpp
new file mode 100644
index 0000000..841b19b
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/deconstruct_ptr.hpp
@@ -0,0 +1,84 @@
+// DEPRECATED in favor of adl_postconstruct and adl_predestruct with
+// deconstruct<T>().
+// A factory function for creating a shared_ptr that enhances the plain
+// shared_ptr constructors by adding support for postconstructors
+// and predestructors through the boost::signals2::postconstructible and
+// boost::signals2::predestructible base classes.
+//
+// Copyright Frank Mori Hess 2007-2008.
+//
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_SIGNALS2_DECONSTRUCT_PTR_HPP
+#define BOOST_SIGNALS2_DECONSTRUCT_PTR_HPP
+
+#include <boost/assert.hpp>
+#include <boost/checked_delete.hpp>
+#include <boost/signals2/postconstructible.hpp>
+#include <boost/signals2/predestructible.hpp>
+#include <boost/shared_ptr.hpp>
+
+namespace boost
+{
+ namespace signals2
+ {
+ namespace detail
+ {
+ extern inline void do_postconstruct(const postconstructible *ptr)
+ {
+ postconstructible *nonconst_ptr = const_cast<postconstructible*>(ptr);
+ nonconst_ptr->postconstruct();
+ }
+ extern inline void do_postconstruct(...)
+ {
+ }
+ extern inline void do_predestruct(...)
+ {
+ }
+ extern inline void do_predestruct(const predestructible *ptr)
+ {
+ try
+ {
+ predestructible *nonconst_ptr = const_cast<predestructible*>(ptr);
+ nonconst_ptr->predestruct();
+ }
+ catch(...)
+ {
+ BOOST_ASSERT(false);
+ }
+ }
+ }
+
+ template<typename T> class predestructing_deleter
+ {
+ public:
+ void operator()(const T *ptr) const
+ {
+ detail::do_predestruct(ptr);
+ checked_delete(ptr);
+ }
+ };
+
+ template<typename T>
+ shared_ptr<T> deconstruct_ptr(T *ptr)
+ {
+ if(ptr == 0) return shared_ptr<T>(ptr);
+ shared_ptr<T> shared(ptr, boost::signals2::predestructing_deleter<T>());
+ detail::do_postconstruct(ptr);
+ return shared;
+ }
+ template<typename T, typename D>
+ shared_ptr<T> deconstruct_ptr(T *ptr, D deleter)
+ {
+ shared_ptr<T> shared(ptr, deleter);
+ if(ptr == 0) return shared;
+ detail::do_postconstruct(ptr);
+ return shared;
+ }
+ }
+}
+
+#endif // BOOST_SIGNALS2_DECONSTRUCT_PTR_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/auto_buffer.hpp b/3rdParty/Boost/src/boost/signals2/detail/auto_buffer.hpp
new file mode 100644
index 0000000..bf12e69
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/auto_buffer.hpp
@@ -0,0 +1,1138 @@
+// Copyright Thorsten Ottosen, 2009.
+// Distributed under the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_SIGNALS2_DETAIL_AUTO_BUFFER_HPP_25_02_2009
+#define BOOST_SIGNALS2_DETAIL_AUTO_BUFFER_HPP_25_02_2009
+
+#include <boost/detail/workaround.hpp>
+
+#if defined(_MSC_VER)
+# pragma once
+#endif
+
+#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
+#pragma warning(push)
+#pragma warning(disable:4996)
+#endif
+
+#include <boost/assert.hpp>
+#include <boost/iterator/reverse_iterator.hpp>
+#include <boost/iterator/iterator_traits.hpp>
+#include <boost/mpl/if.hpp>
+#include <boost/multi_index/detail/scope_guard.hpp>
+#include <boost/swap.hpp>
+#include <boost/throw_exception.hpp>
+#include <boost/type_traits/aligned_storage.hpp>
+#include <boost/type_traits/alignment_of.hpp>
+#include <boost/type_traits/has_nothrow_copy.hpp>
+#include <boost/type_traits/has_nothrow_assign.hpp>
+#include <boost/type_traits/has_trivial_assign.hpp>
+#include <boost/type_traits/has_trivial_constructor.hpp>
+#include <boost/type_traits/has_trivial_destructor.hpp>
+#include <algorithm>
+#include <cstring>
+#include <iterator>
+#include <memory>
+#include <stdexcept>
+
+namespace boost
+{
+namespace signals2
+{
+namespace detail
+{
+ //
+ // Policies for creating the stack buffer.
+ //
+ template< unsigned N >
+ struct store_n_objects
+ {
+ BOOST_STATIC_CONSTANT( unsigned, value = N );
+ };
+
+ template< unsigned N >
+ struct store_n_bytes
+ {
+ BOOST_STATIC_CONSTANT( unsigned, value = N );
+ };
+
+ namespace auto_buffer_detail
+ {
+ template< class Policy, class T >
+ struct compute_buffer_size
+ {
+ BOOST_STATIC_CONSTANT( unsigned, value = Policy::value * sizeof(T) );
+ };
+
+ template< unsigned N, class T >
+ struct compute_buffer_size< store_n_bytes<N>, T >
+ {
+ BOOST_STATIC_CONSTANT( unsigned, value = N );
+ };
+
+ template< class Policy, class T >
+ struct compute_buffer_objects
+ {
+ BOOST_STATIC_CONSTANT( unsigned, value = Policy::value );
+ };
+
+ template< unsigned N, class T >
+ struct compute_buffer_objects< store_n_bytes<N>, T >
+ {
+ BOOST_STATIC_CONSTANT( unsigned, value = N / sizeof(T) );
+ };
+ }
+
+ struct default_grow_policy
+ {
+ template< class SizeType >
+ static SizeType new_capacity( SizeType capacity )
+ {
+ //
+ // @remark: we grow the capacity quite agressively.
+ // this is justified since we aim to minimize
+ // heap-allocations, and because we mostly use
+ // the buffer locally.
+ return capacity * 4u;
+ }
+
+ template< class SizeType >
+ static bool should_shrink( SizeType size, SizeType capacity )
+ {
+ //
+ // @remark: when defining a new grow policy, one might
+ // choose that if the waated space is less
+ // than a certain percentage, then it is of
+ // little use to shrink.
+ //
+ return true;
+ }
+ };
+
+ template< class T,
+ class StackBufferPolicy = store_n_objects<256>,
+ class GrowPolicy = default_grow_policy,
+ class Allocator = std::allocator<T> >
+ class auto_buffer;
+
+
+
+ template
+ <
+ class T,
+ class StackBufferPolicy,
+ class GrowPolicy,
+ class Allocator
+ >
+ class auto_buffer : Allocator
+ {
+ private:
+ enum { N = auto_buffer_detail::
+ compute_buffer_objects<StackBufferPolicy,T>::value };
+
+ BOOST_STATIC_CONSTANT( bool, is_stack_buffer_empty = N == 0u );
+
+ typedef auto_buffer<T, store_n_objects<0>, GrowPolicy, Allocator>
+ local_buffer;
+
+ public:
+ typedef Allocator allocator_type;
+ typedef T value_type;
+ typedef typename Allocator::size_type size_type;
+ typedef typename Allocator::difference_type difference_type;
+ typedef T* pointer;
+ typedef typename Allocator::pointer allocator_pointer;
+ typedef const T* const_pointer;
+ typedef T& reference;
+ typedef const T& const_reference;
+ typedef pointer iterator;
+ typedef const_pointer const_iterator;
+ typedef boost::reverse_iterator<iterator> reverse_iterator;
+ typedef boost::reverse_iterator<const_iterator> const_reverse_iterator;
+ typedef typename boost::mpl::if_c< boost::has_trivial_assign<T>::value
+ && sizeof(T) <= sizeof(long double),
+ const value_type,
+ const_reference >::type
+ optimized_const_reference;
+ private:
+
+ pointer allocate( size_type capacity_arg )
+ {
+ if( capacity_arg > N )
+ return &*get_allocator().allocate( capacity_arg );
+ else
+ return static_cast<T*>( members_.address() );
+ }
+
+ void deallocate( pointer where, size_type capacity_arg )
+ {
+ if( capacity_arg <= N )
+ return;
+ get_allocator().deallocate( allocator_pointer(where), capacity_arg );
+ }
+
+ template< class I >
+ static void copy_impl( I begin, I end, pointer where, std::random_access_iterator_tag )
+ {
+ copy_rai( begin, end, where, boost::has_trivial_assign<T>() );
+ }
+
+ static void copy_rai( const T* begin, const T* end,
+ pointer where, const boost::true_type& )
+ {
+ std::memcpy( where, begin, sizeof(T) * std::distance(begin,end) );
+ }
+
+ template< class I, bool b >
+ static void copy_rai( I begin, I end,
+ pointer where, const boost::integral_constant<bool, b>& )
+ {
+ std::uninitialized_copy( begin, end, where );
+ }
+
+ template< class I >
+ static void copy_impl( I begin, I end, pointer where, std::bidirectional_iterator_tag )
+ {
+ std::uninitialized_copy( begin, end, where );
+ }
+
+ template< class I >
+ static void copy_impl( I begin, I end, pointer where )
+ {
+ copy_impl( begin, end, where,
+ typename std::iterator_traits<I>::iterator_category() );
+ }
+
+ template< class I, class I2 >
+ static void assign_impl( I begin, I end, I2 where )
+ {
+ assign_impl( begin, end, where, boost::has_trivial_assign<T>() );
+ }
+
+ template< class I, class I2 >
+ static void assign_impl( I begin, I end, I2 where, const boost::true_type& )
+ {
+ std::memcpy( where, begin, sizeof(T) * std::distance(begin,end) );
+ }
+
+ template< class I, class I2 >
+ static void assign_impl( I begin, I end, I2 where, const boost::false_type& )
+ {
+ for( ; begin != end; ++begin, ++where )
+ *where = *begin;
+ }
+
+ void unchecked_push_back_n( size_type n, const boost::true_type& )
+ {
+ std::uninitialized_fill( end(), end() + n, T() );
+ size_ += n;
+ }
+
+ void unchecked_push_back_n( size_type n, const boost::false_type& )
+ {
+ for( size_type i = 0u; i < n; ++i )
+ unchecked_push_back();
+ }
+
+ void auto_buffer_destroy( pointer where, const boost::false_type& )
+ {
+ (*where).~T();
+ }
+
+ void auto_buffer_destroy( pointer, const boost::true_type& )
+ { }
+
+ void auto_buffer_destroy( pointer where )
+ {
+ auto_buffer_destroy( where, boost::has_trivial_destructor<T>() );
+ }
+
+ void destroy_back_n( size_type n, const boost::false_type& )
+ {
+ BOOST_ASSERT( n > 0 );
+ pointer buffer = buffer_ + size_ - 1u;
+ pointer new_end = buffer - n;
+ for( ; buffer > new_end; --buffer )
+ auto_buffer_destroy( buffer );
+ }
+
+ void destroy_back_n( size_type n, const boost::true_type& )
+ { }
+
+ void destroy_back_n( size_type n )
+ {
+ destroy_back_n( n, boost::has_trivial_destructor<T>() );
+ }
+
+ void auto_buffer_destroy( const boost::false_type& x )
+ {
+ if( size_ )
+ destroy_back_n( size_, x );
+ deallocate( buffer_, members_.capacity_ );
+ }
+
+ void auto_buffer_destroy( const boost::true_type& )
+ {
+ deallocate( buffer_, members_.capacity_ );
+ }
+
+ pointer move_to_new_buffer( size_type new_capacity, const boost::false_type& )
+ {
+ pointer new_buffer = allocate( new_capacity ); // strong
+ boost::multi_index::detail::scope_guard guard =
+ boost::multi_index::detail::make_obj_guard( *this,
+ &auto_buffer::deallocate,
+ new_buffer,
+ new_capacity );
+ copy_impl( begin(), end(), new_buffer ); // strong
+ guard.dismiss(); // nothrow
+ return new_buffer;
+ }
+
+ pointer move_to_new_buffer( size_type new_capacity, const boost::true_type& )
+ {
+ pointer new_buffer = allocate( new_capacity ); // strong
+ copy_impl( begin(), end(), new_buffer ); // nothrow
+ return new_buffer;
+ }
+
+ void reserve_impl( size_type new_capacity )
+ {
+ pointer new_buffer = move_to_new_buffer( new_capacity,
+ boost::has_nothrow_copy<T>() );
+ (*this).~auto_buffer();
+ buffer_ = new_buffer;
+ members_.capacity_ = new_capacity;
+ BOOST_ASSERT( size_ <= members_.capacity_ );
+ }
+
+ size_type new_capacity_impl( size_type n )
+ {
+ BOOST_ASSERT( n > members_.capacity_ );
+ size_type new_capacity = GrowPolicy::new_capacity( members_.capacity_ );
+ // @todo: consider to check for allocator.max_size()
+ return (std::max)(new_capacity,n);
+ }
+
+ static void swap_helper( auto_buffer& l, auto_buffer& r,
+ const boost::true_type& )
+ {
+ BOOST_ASSERT( l.is_on_stack() && r.is_on_stack() );
+
+ auto_buffer temp( l.begin(), l.end() );
+ assign_impl( r.begin(), r.end(), l.begin() );
+ assign_impl( temp.begin(), temp.end(), r.begin() );
+ boost::swap( l.size_, r.size_ );
+ boost::swap( l.members_.capacity_, r.members_.capacity_ );
+ }
+
+ static void swap_helper( auto_buffer& l, auto_buffer& r,
+ const boost::false_type& )
+ {
+ BOOST_ASSERT( l.is_on_stack() && r.is_on_stack() );
+ size_type min_size = (std::min)(l.size_,r.size_);
+ size_type max_size = (std::max)(l.size_,r.size_);
+ size_type diff = max_size - min_size;
+ auto_buffer* smallest = l.size_ == min_size ? &l : &r;
+ auto_buffer* largest = smallest == &l ? &r : &l;
+
+ // @remark: the implementation below is not as fast
+ // as it could be if we assumed T had a default
+ // constructor.
+
+ size_type i = 0u;
+ for( ; i < min_size; ++i )
+ boost::swap( (*smallest)[i], (*largest)[i] );
+
+ for( ; i < max_size; ++i )
+ smallest->unchecked_push_back( (*largest)[i] );
+
+ largest->pop_back_n( diff );
+ boost::swap( l.members_.capacity_, r.members_.capacity_ );
+ }
+
+ void one_sided_swap( auto_buffer& temp ) // nothrow
+ {
+ BOOST_ASSERT( !temp.is_on_stack() );
+ this->~auto_buffer();
+ // @remark: must be nothrow
+ get_allocator() = temp.get_allocator();
+ members_.capacity_ = temp.members_.capacity_;
+ buffer_ = temp.buffer_;
+ BOOST_ASSERT( temp.size_ >= size_ + 1u );
+ size_ = temp.size_;
+ temp.buffer_ = 0;
+ BOOST_ASSERT( temp.is_valid() );
+ }
+
+ template< class I >
+ void insert_impl( const_iterator before, I begin_arg, I end_arg,
+ std::input_iterator_tag )
+ {
+ for( ; begin_arg != end_arg; ++begin_arg )
+ {
+ before = insert( before, *begin_arg );
+ ++before;
+ }
+ }
+
+ void grow_back( size_type n, const boost::true_type& )
+ {
+ BOOST_ASSERT( size_ + n <= members_.capacity_ );
+ size_ += n;
+ }
+
+ void grow_back( size_type n, const boost::false_type& )
+ {
+ unchecked_push_back_n(n);
+ }
+
+ void grow_back( size_type n )
+ {
+ grow_back( n, boost::has_trivial_constructor<T>() );
+ }
+
+ void grow_back_one( const boost::true_type& )
+ {
+ BOOST_ASSERT( size_ + 1 <= members_.capacity_ );
+ size_ += 1;
+ }
+
+ void grow_back_one( const boost::false_type& )
+ {
+ unchecked_push_back();
+ }
+
+ void grow_back_one()
+ {
+ grow_back_one( boost::has_trivial_constructor<T>() );
+ }
+
+ template< class I >
+ void insert_impl( const_iterator before, I begin_arg, I end_arg,
+ std::forward_iterator_tag )
+ {
+ difference_type n = std::distance(begin_arg, end_arg);
+
+ if( size_ + n <= members_.capacity_ )
+ {
+ bool is_back_insertion = before == cend();
+ if( !is_back_insertion )
+ {
+ grow_back( n );
+ iterator where = const_cast<T*>(before);
+ std::copy( before, cend() - n, where + n );
+ assign_impl( begin_arg, end_arg, where );
+ }
+ else
+ {
+ unchecked_push_back( begin_arg, end_arg );
+ }
+ BOOST_ASSERT( is_valid() );
+ return;
+ }
+
+ auto_buffer temp( new_capacity_impl( size_ + n ) );
+ temp.unchecked_push_back( cbegin(), before );
+ temp.unchecked_push_back( begin_arg, end_arg );
+ temp.unchecked_push_back( before, cend() );
+ one_sided_swap( temp );
+ BOOST_ASSERT( is_valid() );
+ }
+
+ public:
+ bool is_valid() const // invariant
+ {
+ // @remark: allowed for N==0 and when
+ // using a locally instance
+ // in insert()/one_sided_swap()
+ if( buffer_ == 0 )
+ return true;
+
+ if( members_.capacity_ < N )
+ return false;
+
+ if( !is_on_stack() && members_.capacity_ <= N )
+ return false;
+
+ if( buffer_ == members_.address() )
+ if( members_.capacity_ > N )
+ return false;
+
+ if( size_ > members_.capacity_ )
+ return false;
+
+ return true;
+ }
+
+ auto_buffer()
+ : members_( N ),
+ buffer_( static_cast<T*>(members_.address()) ),
+ size_( 0u )
+ {
+ BOOST_ASSERT( is_valid() );
+ }
+
+ auto_buffer( const auto_buffer& r )
+ : members_( (std::max)(r.size_,size_type(N)) ),
+ buffer_( allocate( members_.capacity_ ) ),
+ size_( 0 )
+ {
+ copy_impl( r.begin(), r.end(), buffer_ );
+ size_ = r.size_;
+ BOOST_ASSERT( is_valid() );
+ }
+
+ auto_buffer& operator=( const auto_buffer& r ) // basic
+ {
+ if( this == &r )
+ return *this;
+
+ difference_type diff = size_ - r.size_;
+ if( diff >= 0 )
+ {
+ pop_back_n( static_cast<size_type>(diff) );
+ assign_impl( r.begin(), r.end(), begin() );
+ }
+ else
+ {
+ if( members_.capacity_ >= r.size() )
+ {
+ unchecked_push_back_n( static_cast<size_type>(-diff) );
+ assign_impl( r.begin(), r.end(), begin() );
+ }
+ else
+ {
+ // @remark: we release memory as early as possible
+ // since we only give the basic guarantee
+ (*this).~auto_buffer();
+ buffer_ = 0;
+ pointer new_buffer = allocate( r.size() );
+ boost::multi_index::detail::scope_guard guard =
+ boost::multi_index::detail::make_obj_guard( *this,
+ &auto_buffer::deallocate,
+ new_buffer,
+ r.size() );
+ copy_impl( r.begin(), r.end(), new_buffer );
+ guard.dismiss();
+ buffer_ = new_buffer;
+ members_.capacity_ = r.size();
+ size_ = members_.capacity_;
+ }
+ }
+
+ BOOST_ASSERT( size() == r.size() );
+ BOOST_ASSERT( is_valid() );
+ return *this;
+ }
+
+ explicit auto_buffer( size_type capacity_arg )
+ : members_( (std::max)(capacity_arg, size_type(N)) ),
+ buffer_( allocate(members_.capacity_) ),
+ size_( 0 )
+ {
+ BOOST_ASSERT( is_valid() );
+ }
+
+ auto_buffer( size_type size_arg, optimized_const_reference init_value )
+ : members_( (std::max)(size_arg, size_type(N)) ),
+ buffer_( allocate(members_.capacity_) ),
+ size_( 0 )
+ {
+ std::uninitialized_fill( buffer_, buffer_ + size_arg, init_value );
+ size_ = size_arg;
+ BOOST_ASSERT( is_valid() );
+ }
+
+ auto_buffer( size_type capacity_arg, const allocator_type& a )
+ : allocator_type( a ),
+ members_( (std::max)(capacity_arg, size_type(N)) ),
+ buffer_( allocate(members_.capacity_) ),
+ size_( 0 )
+ {
+ BOOST_ASSERT( is_valid() );
+ }
+
+ auto_buffer( size_type size_arg, optimized_const_reference init_value,
+ const allocator_type& a )
+ : allocator_type( a ),
+ members_( (std::max)(size_arg, size_type(N)) ),
+ buffer_( allocate(members_.capacity_) ),
+ size_( 0 )
+ {
+ std::uninitialized_fill( buffer_, buffer_ + size_arg, init_value );
+ size_ = size_arg;
+ BOOST_ASSERT( is_valid() );
+ }
+
+ template< class ForwardIterator >
+ auto_buffer( ForwardIterator begin_arg, ForwardIterator end_arg )
+ :
+ members_( std::distance(begin_arg, end_arg) ),
+ buffer_( allocate(members_.capacity_) ),
+ size_( 0 )
+ {
+ copy_impl( begin_arg, end_arg, buffer_ );
+ size_ = members_.capacity_;
+ if( members_.capacity_ < N )
+ members_.capacity_ = N;
+ BOOST_ASSERT( is_valid() );
+ }
+
+ template< class ForwardIterator >
+ auto_buffer( ForwardIterator begin_arg, ForwardIterator end_arg,
+ const allocator_type& a )
+ : allocator_type( a ),
+ members_( std::distance(begin_arg, end_arg) ),
+ buffer_( allocate(members_.capacity_) ),
+ size_( 0 )
+ {
+ copy_impl( begin_arg, end_arg, buffer_ );
+ size_ = members_.capacity_;
+ if( members_.capacity_ < N )
+ members_.capacity_ = N;
+ BOOST_ASSERT( is_valid() );
+ }
+
+ ~auto_buffer()
+ {
+ BOOST_ASSERT( is_valid() );
+ if( buffer_ ) // do we need this check? Yes, but only
+ // for N = 0u + local instances in one_sided_swap()
+ auto_buffer_destroy( boost::has_trivial_destructor<T>() );
+ }
+
+ public:
+ bool empty() const
+ {
+ return size_ == 0;
+ }
+
+ bool full() const
+ {
+ return size_ == members_.capacity_;
+ }
+
+ bool is_on_stack() const
+ {
+ return members_.capacity_ <= N;
+ }
+
+ size_type size() const
+ {
+ return size_;
+ }
+
+ size_type capacity() const
+ {
+ return members_.capacity_;
+ }
+
+ public:
+ pointer data()
+ {
+ return buffer_;
+ }
+
+ const_pointer data() const
+ {
+ return buffer_;
+ }
+
+ allocator_type& get_allocator()
+ {
+ return static_cast<allocator_type&>(*this);
+ }
+
+ const allocator_type& get_allocator() const
+ {
+ return static_cast<const allocator_type&>(*this);
+ }
+
+ public:
+ iterator begin()
+ {
+ return buffer_;
+ }
+
+ const_iterator begin() const
+ {
+ return buffer_;
+ }
+
+ iterator end()
+ {
+ return buffer_ + size_;
+ }
+
+ const_iterator end() const
+ {
+ return buffer_ + size_;
+ }
+
+ reverse_iterator rbegin()
+ {
+ return reverse_iterator(end());
+ }
+
+ const_reverse_iterator rbegin() const
+ {
+ return const_reverse_iterator(end());
+ }
+
+ reverse_iterator rend()
+ {
+ return reverse_iterator(begin());
+ }
+
+ const_reverse_iterator rend() const
+ {
+ return const_reverse_iterator(begin());
+ }
+
+ const_iterator cbegin() const
+ {
+ return const_cast<const auto_buffer*>(this)->begin();
+ }
+
+ const_iterator cend() const
+ {
+ return const_cast<const auto_buffer*>(this)->end();
+ }
+
+ const_reverse_iterator crbegin() const
+ {
+ return const_cast<const auto_buffer*>(this)->rbegin();
+ }
+
+ const_reverse_iterator crend() const
+ {
+ return const_cast<const auto_buffer*>(this)->rend();
+ }
+
+ public:
+ reference front()
+ {
+ return buffer_[0];
+ }
+
+ optimized_const_reference front() const
+ {
+ return buffer_[0];
+ }
+
+ reference back()
+ {
+ return buffer_[size_-1];
+ }
+
+ optimized_const_reference back() const
+ {
+ return buffer_[size_-1];
+ }
+
+ reference operator[]( size_type n )
+ {
+ BOOST_ASSERT( n < size_ );
+ return buffer_[n];
+ }
+
+ optimized_const_reference operator[]( size_type n ) const
+ {
+ BOOST_ASSERT( n < size_ );
+ return buffer_[n];
+ }
+
+ void unchecked_push_back()
+ {
+ BOOST_ASSERT( !full() );
+ new (buffer_ + size_) T;
+ ++size_;
+ }
+
+ void unchecked_push_back_n( size_type n )
+ {
+ BOOST_ASSERT( size_ + n <= members_.capacity_ );
+ unchecked_push_back_n( n, boost::has_trivial_assign<T>() );
+ }
+
+ void unchecked_push_back( optimized_const_reference x ) // non-growing
+ {
+ BOOST_ASSERT( !full() );
+ new (buffer_ + size_) T( x );
+ ++size_;
+ }
+
+ template< class ForwardIterator >
+ void unchecked_push_back( ForwardIterator begin_arg,
+ ForwardIterator end_arg ) // non-growing
+ {
+ BOOST_ASSERT( size_ + std::distance(begin_arg, end_arg) <= members_.capacity_ );
+ copy_impl( begin_arg, end_arg, buffer_ + size_ );
+ size_ += std::distance(begin_arg, end_arg);
+ }
+
+ void reserve_precisely( size_type n )
+ {
+ BOOST_ASSERT( members_.capacity_ >= N );
+
+ if( n <= members_.capacity_ )
+ return;
+ reserve_impl( n );
+ BOOST_ASSERT( members_.capacity_ == n );
+ }
+
+ void reserve( size_type n ) // strong
+ {
+ BOOST_ASSERT( members_.capacity_ >= N );
+
+ if( n <= members_.capacity_ )
+ return;
+
+ reserve_impl( new_capacity_impl( n ) );
+ BOOST_ASSERT( members_.capacity_ >= n );
+ }
+
+ void push_back()
+ {
+ if( size_ != members_.capacity_ )
+ {
+ unchecked_push_back();
+ }
+ else
+ {
+ reserve( size_ + 1u );
+ unchecked_push_back();
+ }
+ }
+
+ void push_back( optimized_const_reference x )
+ {
+ if( size_ != members_.capacity_ )
+ {
+ unchecked_push_back( x );
+ }
+ else
+ {
+ reserve( size_ + 1u );
+ unchecked_push_back( x );
+ }
+ }
+
+ template< class ForwardIterator >
+ void push_back( ForwardIterator begin_arg, ForwardIterator end_arg )
+ {
+ difference_type diff = std::distance(begin_arg, end_arg);
+ if( size_ + diff > members_.capacity_ )
+ reserve( size_ + diff );
+ unchecked_push_back( begin_arg, end_arg );
+ }
+
+ iterator insert( const_iterator before, optimized_const_reference x ) // basic
+ {
+ // @todo: consider if we want to support x in 'this'
+ if( size_ < members_.capacity_ )
+ {
+ bool is_back_insertion = before == cend();
+ iterator where = const_cast<T*>(before);
+
+ if( !is_back_insertion )
+ {
+ grow_back_one();
+ std::copy( before, cend() - 1u, where + 1u );
+ *where = x;
+ BOOST_ASSERT( is_valid() );
+ }
+ else
+ {
+ unchecked_push_back( x );
+ }
+ return where;
+ }
+
+ auto_buffer temp( new_capacity_impl( size_ + 1u ) );
+ temp.unchecked_push_back( cbegin(), before );
+ iterator result = temp.end();
+ temp.unchecked_push_back( x );
+ temp.unchecked_push_back( before, cend() );
+ one_sided_swap( temp );
+ BOOST_ASSERT( is_valid() );
+ return result;
+ }
+
+ void insert( const_iterator before, size_type n,
+ optimized_const_reference x )
+ {
+ // @todo: see problems above
+ if( size_ + n <= members_.capacity_ )
+ {
+ grow_back( n );
+ iterator where = const_cast<T*>(before);
+ std::copy( before, cend() - n, where + n );
+ std::fill( where, where + n, x );
+ BOOST_ASSERT( is_valid() );
+ return;
+ }
+
+ auto_buffer temp( new_capacity_impl( size_ + n ) );
+ temp.unchecked_push_back( cbegin(), before );
+ std::uninitialized_fill_n( temp.end(), n, x );
+ temp.size_ += n;
+ temp.unchecked_push_back( before, cend() );
+ one_sided_swap( temp );
+ BOOST_ASSERT( is_valid() );
+ }
+
+ template< class ForwardIterator >
+ void insert( const_iterator before,
+ ForwardIterator begin_arg, ForwardIterator end_arg ) // basic
+ {
+ typedef typename std::iterator_traits<ForwardIterator>
+ ::iterator_category category;
+ insert_impl( before, begin_arg, end_arg, category() );
+ }
+
+ void pop_back()
+ {
+ BOOST_ASSERT( !empty() );
+ auto_buffer_destroy( buffer_ + size_ - 1, boost::has_trivial_destructor<T>() );
+ --size_;
+ }
+
+ void pop_back_n( size_type n )
+ {
+ BOOST_ASSERT( n <= size_ );
+ if( n )
+ {
+ destroy_back_n( n );
+ size_ -= n;
+ }
+ }
+
+ void clear()
+ {
+ pop_back_n( size_ );
+ }
+
+ iterator erase( const_iterator where )
+ {
+ BOOST_ASSERT( !empty() );
+ BOOST_ASSERT( cbegin() <= where );
+ BOOST_ASSERT( cend() > where );
+
+ unsigned elements = cend() - where - 1u;
+
+ if( elements > 0u )
+ {
+ const_iterator start = where + 1u;
+ std::copy( start, start + elements,
+ const_cast<T*>(where) );
+ }
+ pop_back();
+ BOOST_ASSERT( !full() );
+ iterator result = const_cast<T*>( where );
+ BOOST_ASSERT( result <= end() );
+ return result;
+ }
+
+ iterator erase( const_iterator from, const_iterator to )
+ {
+ BOOST_ASSERT( !(std::distance(from,to)>0) ||
+ !empty() );
+ BOOST_ASSERT( cbegin() <= from );
+ BOOST_ASSERT( cend() >= to );
+
+ unsigned elements = std::distance(to,cend());
+
+ if( elements > 0u )
+ {
+ BOOST_ASSERT( elements > 0u );
+ std::copy( to, to + elements,
+ const_cast<T*>(from) );
+ }
+ pop_back_n( std::distance(from,to) );
+ BOOST_ASSERT( !full() );
+ iterator result = const_cast<T*>( from );
+ BOOST_ASSERT( result <= end() );
+ return result;
+ }
+
+ void shrink_to_fit()
+ {
+ if( is_on_stack() || !GrowPolicy::should_shrink(size_,members_.capacity_) )
+ return;
+
+ reserve_impl( size_ );
+ members_.capacity_ = (std::max)(size_type(N),members_.capacity_);
+ BOOST_ASSERT( is_on_stack() || size_ == members_.capacity_ );
+ BOOST_ASSERT( !is_on_stack() || size_ <= members_.capacity_ );
+ }
+
+ pointer uninitialized_grow( size_type n ) // strong
+ {
+ if( size_ + n <= members_.capacity_ )
+ reserve( size_ + n );
+
+ pointer res = end();
+ size_ += n;
+ return res;
+ }
+
+ void uninitialized_shrink( size_type n ) // nothrow
+ {
+ // @remark: test for wrap-around
+ BOOST_ASSERT( size_ - n <= members_.capacity_ );
+ size_ -= n;
+ }
+
+ void uninitialized_resize( size_type n )
+ {
+ if( n > size() )
+ uninitialized_grow( n - size() );
+ else if( n < size() )
+ uninitialized_shrink( size() - n );
+
+ BOOST_ASSERT( size() == n );
+ }
+
+ // nothrow - if both buffer are on the heap, or
+ // - if one buffer is on the heap and one has
+ // 'has_allocated_buffer() == false', or
+ // - if copy-construction cannot throw
+ // basic - otherwise (better guarantee impossible)
+ // requirement: the allocator must be no-throw-swappable
+ void swap( auto_buffer& r )
+ {
+ bool on_stack = is_on_stack();
+ bool r_on_stack = r.is_on_stack();
+ bool both_on_heap = !on_stack && !r_on_stack;
+ if( both_on_heap )
+ {
+ boost::swap( get_allocator(), r.get_allocator() );
+ boost::swap( members_.capacity_, r.members_.capacity_ );
+ boost::swap( buffer_, r.buffer_ );
+ boost::swap( size_, r.size_ );
+ BOOST_ASSERT( is_valid() );
+ BOOST_ASSERT( r.is_valid() );
+ return;
+ }
+
+ BOOST_ASSERT( on_stack || r_on_stack );
+ bool exactly_one_on_stack = (on_stack && !r_on_stack) ||
+ (!on_stack && r_on_stack);
+
+ //
+ // Remark: we now know that we can copy into
+ // the unused stack buffer.
+ //
+ if( exactly_one_on_stack )
+ {
+ auto_buffer* one_on_stack = on_stack ? this : &r;
+ auto_buffer* other = on_stack ? &r : this;
+ pointer new_buffer = static_cast<T*>(other->members_.address());
+ copy_impl( one_on_stack->begin(), one_on_stack->end(),
+ new_buffer ); // strong
+ one_on_stack->~auto_buffer(); // nothrow
+ boost::swap( get_allocator(), r.get_allocator() ); // assume nothrow
+ boost::swap( members_.capacity_, r.members_.capacity_ );
+ boost::swap( size_, r.size_ );
+ one_on_stack->buffer_ = other->buffer_;
+ other->buffer_ = new_buffer;
+ BOOST_ASSERT( other->is_on_stack() );
+ BOOST_ASSERT( !one_on_stack->is_on_stack() );
+ BOOST_ASSERT( is_valid() );
+ BOOST_ASSERT( r.is_valid() );
+ return;
+ }
+
+ BOOST_ASSERT( on_stack && r_on_stack );
+ swap_helper( *this, r, boost::has_trivial_assign<T>() );
+ BOOST_ASSERT( is_valid() );
+ BOOST_ASSERT( r.is_valid() );
+ }
+
+ private:
+ typedef boost::aligned_storage< N * sizeof(T),
+ boost::alignment_of<T>::value >
+ storage;
+
+ struct members_type : storage /* to enable EBO */
+ {
+ size_type capacity_;
+
+ members_type( size_type capacity )
+ : capacity_(capacity)
+ { }
+
+ void* address() const
+ { return const_cast<storage&>(static_cast<const storage&>(*this)).address(); }
+ };
+
+ members_type members_;
+ pointer buffer_;
+ size_type size_;
+
+ };
+
+ template< class T, class SBP, class GP, class A >
+ inline void swap( auto_buffer<T,SBP,GP,A>& l, auto_buffer<T,SBP,GP,A>& r )
+ {
+ l.swap( r );
+ }
+
+ template< class T, class SBP, class GP, class A >
+ inline bool operator==( const auto_buffer<T,SBP,GP,A>& l,
+ const auto_buffer<T,SBP,GP,A>& r )
+ {
+ if( l.size() != r.size() )
+ return false;
+ return std::equal( l.begin(), l.end(), r.begin() );
+ }
+
+ template< class T, class SBP, class GP, class A >
+ inline bool operator!=( const auto_buffer<T,SBP,GP,A>& l,
+ const auto_buffer<T,SBP,GP,A>& r )
+ {
+ return !(l == r);
+ }
+
+ template< class T, class SBP, class GP, class A >
+ inline bool operator<( const auto_buffer<T,SBP,GP,A>& l,
+ const auto_buffer<T,SBP,GP,A>& r )
+ {
+ return std::lexicographical_compare( l.begin(), l.end(),
+ r.begin(), r.end() );
+ }
+
+ template< class T, class SBP, class GP, class A >
+ inline bool operator>( const auto_buffer<T,SBP,GP,A>& l,
+ const auto_buffer<T,SBP,GP,A>& r )
+ {
+ return (r < l);
+ }
+
+ template< class T, class SBP, class GP, class A >
+ inline bool operator<=( const auto_buffer<T,SBP,GP,A>& l,
+ const auto_buffer<T,SBP,GP,A>& r )
+ {
+ return !(r > l);
+ }
+
+ template< class T, class SBP, class GP, class A >
+ inline bool operator>=( const auto_buffer<T,SBP,GP,A>& l,
+ const auto_buffer<T,SBP,GP,A>& r )
+ {
+ return !(l < r);
+ }
+
+} // namespace detail
+} // namespace signals2
+}
+
+#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
+#pragma warning(pop)
+#endif
+
+#endif
diff --git a/3rdParty/Boost/src/boost/signals2/detail/foreign_ptr.hpp b/3rdParty/Boost/src/boost/signals2/detail/foreign_ptr.hpp
new file mode 100644
index 0000000..4349b38
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/foreign_ptr.hpp
@@ -0,0 +1,185 @@
+
+// helper code for dealing with tracking non-boost shared_ptr/weak_ptr
+
+// Copyright Frank Mori Hess 2009.
+// Distributed under the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org/libs/signals2 for library home page.
+
+#ifndef BOOST_SIGNALS2_FOREIGN_PTR_HPP
+#define BOOST_SIGNALS2_FOREIGN_PTR_HPP
+
+#include <algorithm>
+#include <boost/config.hpp>
+#include <boost/assert.hpp>
+#include <boost/scoped_ptr.hpp>
+#include <boost/smart_ptr/bad_weak_ptr.hpp>
+#include <boost/utility/swap.hpp>
+
+#ifndef BOOST_NO_CXX11_SMART_PTR
+#include <memory>
+#endif
+
+namespace boost
+{
+ template<typename T> class shared_ptr;
+ template<typename T> class weak_ptr;
+
+ namespace signals2
+ {
+ template<typename WeakPtr> struct weak_ptr_traits
+ {};
+ template<typename T> struct weak_ptr_traits<boost::weak_ptr<T> >
+ {
+ typedef boost::shared_ptr<T> shared_type;
+ };
+#ifndef BOOST_NO_CXX11_SMART_PTR
+ template<typename T> struct weak_ptr_traits<std::weak_ptr<T> >
+ {
+ typedef std::shared_ptr<T> shared_type;
+ };
+#endif
+
+ template<typename SharedPtr> struct shared_ptr_traits
+ {};
+
+ template<typename T> struct shared_ptr_traits<boost::shared_ptr<T> >
+ {
+ typedef boost::weak_ptr<T> weak_type;
+ };
+#ifndef BOOST_NO_CXX11_SMART_PTR
+ template<typename T> struct shared_ptr_traits<std::shared_ptr<T> >
+ {
+ typedef std::weak_ptr<T> weak_type;
+ };
+#endif
+
+ namespace detail
+ {
+ struct foreign_shared_ptr_impl_base
+ {
+ virtual ~foreign_shared_ptr_impl_base() {}
+ virtual void* get() const = 0;
+ virtual foreign_shared_ptr_impl_base * clone() const = 0;
+ };
+
+ template<typename FSP>
+ class foreign_shared_ptr_impl: public foreign_shared_ptr_impl_base
+ {
+ public:
+ foreign_shared_ptr_impl(const FSP &p): _p(p)
+ {}
+ virtual void * get() const
+ {
+ return _p.get();
+ }
+ virtual foreign_shared_ptr_impl * clone() const
+ {
+ return new foreign_shared_ptr_impl(*this);
+ }
+ private:
+ FSP _p;
+ };
+
+ class foreign_void_shared_ptr
+ {
+ public:
+ foreign_void_shared_ptr():
+ _p(0)
+ {}
+ foreign_void_shared_ptr(const foreign_void_shared_ptr &other):
+ _p(other._p->clone())
+ {}
+ template<typename FSP>
+ explicit foreign_void_shared_ptr(const FSP &fsp):
+ _p(new foreign_shared_ptr_impl<FSP>(fsp))
+ {}
+ ~foreign_void_shared_ptr()
+ {
+ delete _p;
+ }
+ foreign_void_shared_ptr & operator=(const foreign_void_shared_ptr &other)
+ {
+ if(&other == this) return *this;
+ foreign_void_shared_ptr(other).swap(*this);
+ return *this;
+ }
+ void swap(foreign_void_shared_ptr &other)
+ {
+ boost::swap(_p, other._p);
+ }
+ private:
+ foreign_shared_ptr_impl_base *_p;
+ };
+
+ struct foreign_weak_ptr_impl_base
+ {
+ virtual ~foreign_weak_ptr_impl_base() {}
+ virtual foreign_void_shared_ptr lock() const = 0;
+ virtual bool expired() const = 0;
+ virtual foreign_weak_ptr_impl_base * clone() const = 0;
+ };
+
+ template<typename FWP>
+ class foreign_weak_ptr_impl: public foreign_weak_ptr_impl_base
+ {
+ public:
+ foreign_weak_ptr_impl(const FWP &p): _p(p)
+ {}
+ virtual foreign_void_shared_ptr lock() const
+ {
+ return foreign_void_shared_ptr(_p.lock());
+ }
+ virtual bool expired() const
+ {
+ return _p.expired();
+ }
+ virtual foreign_weak_ptr_impl * clone() const
+ {
+ return new foreign_weak_ptr_impl(*this);
+ }
+ private:
+ FWP _p;
+ };
+
+ class foreign_void_weak_ptr
+ {
+ public:
+ foreign_void_weak_ptr()
+ {}
+ foreign_void_weak_ptr(const foreign_void_weak_ptr &other):
+ _p(other._p->clone())
+ {}
+ template<typename FWP>
+ explicit foreign_void_weak_ptr(const FWP &fwp):
+ _p(new foreign_weak_ptr_impl<FWP>(fwp))
+ {}
+ foreign_void_weak_ptr & operator=(const foreign_void_weak_ptr &other)
+ {
+ if(&other == this) return *this;
+ foreign_void_weak_ptr(other).swap(*this);
+ return *this;
+ }
+ void swap(foreign_void_weak_ptr &other)
+ {
+ boost::swap(_p, other._p);
+ }
+ foreign_void_shared_ptr lock() const
+ {
+ return _p->lock();
+ }
+ bool expired() const
+ {
+ return _p->expired();
+ }
+ private:
+ boost::scoped_ptr<foreign_weak_ptr_impl_base> _p;
+ };
+ } // namespace detail
+
+ } // namespace signals2
+} // namespace boost
+
+#endif // BOOST_SIGNALS2_FOREIGN_PTR_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/lwm_nop.hpp b/3rdParty/Boost/src/boost/signals2/detail/lwm_nop.hpp
new file mode 100644
index 0000000..2b70544
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/lwm_nop.hpp
@@ -0,0 +1,38 @@
+//
+// boost/signals2/detail/lwm_nop.hpp
+//
+// Copyright (c) 2002 Peter Dimov and Multi Media Ltd.
+// Copyright (c) 2008 Frank Mori Hess
+//
+// Distributed under the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+
+#ifndef BOOST_SIGNALS2_LWM_NOP_HPP
+#define BOOST_SIGNALS2_LWM_NOP_HPP
+
+// MS compatible compilers support #pragma once
+
+#if defined(_MSC_VER)
+# pragma once
+#endif
+
+
+#include <boost/signals2/dummy_mutex.hpp>
+
+namespace boost
+{
+
+namespace signals2
+{
+
+class mutex: public dummy_mutex
+{
+};
+
+} // namespace signals2
+
+} // namespace boost
+
+#endif // #ifndef BOOST_SIGNALS2_LWM_NOP_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/lwm_pthreads.hpp b/3rdParty/Boost/src/boost/signals2/detail/lwm_pthreads.hpp
new file mode 100644
index 0000000..fb0dd66
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/lwm_pthreads.hpp
@@ -0,0 +1,78 @@
+//
+// boost/signals2/detail/lwm_pthreads.hpp
+//
+// Copyright (c) 2002 Peter Dimov and Multi Media Ltd.
+// Copyright (c) 2008 Frank Mori Hess
+//
+// Distributed under the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+
+#ifndef BOOST_SIGNALS2_LWM_PTHREADS_HPP
+#define BOOST_SIGNALS2_LWM_PTHREADS_HPP
+
+// MS compatible compilers support #pragma once
+
+#if defined(_MSC_VER)
+# pragma once
+#endif
+
+#include <boost/assert.hpp>
+#include <pthread.h>
+
+namespace boost
+{
+
+namespace signals2
+{
+
+class mutex
+{
+private:
+
+ pthread_mutex_t m_;
+
+ mutex(mutex const &);
+ mutex & operator=(mutex const &);
+
+public:
+
+ mutex()
+ {
+
+// HPUX 10.20 / DCE has a nonstandard pthread_mutex_init
+
+#if defined(__hpux) && defined(_DECTHREADS_)
+ BOOST_VERIFY(pthread_mutex_init(&m_, pthread_mutexattr_default) == 0);
+#else
+ BOOST_VERIFY(pthread_mutex_init(&m_, 0) == 0);
+#endif
+ }
+
+ ~mutex()
+ {
+ BOOST_VERIFY(pthread_mutex_destroy(&m_) == 0);
+ }
+
+ void lock()
+ {
+ BOOST_VERIFY(pthread_mutex_lock(&m_) == 0);
+ }
+
+ bool try_lock()
+ {
+ return pthread_mutex_trylock(&m_) == 0;
+ }
+
+ void unlock()
+ {
+ BOOST_VERIFY(pthread_mutex_unlock(&m_) == 0);
+ }
+};
+
+} // namespace signals2
+
+} // namespace boost
+
+#endif // #ifndef BOOST_SIGNALS2_LWM_PTHREADS_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/lwm_win32_cs.hpp b/3rdParty/Boost/src/boost/signals2/detail/lwm_win32_cs.hpp
new file mode 100644
index 0000000..d1c1965
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/lwm_win32_cs.hpp
@@ -0,0 +1,120 @@
+//
+// boost/signals2/detail/lwm_win32_cs.hpp
+//
+// Copyright (c) 2002, 2003 Peter Dimov
+// Copyright (c) 2008 Frank Mori Hess
+// Copyright (c) Microsoft Corporation 2014
+//
+// Distributed under the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+
+#ifndef BOOST_SIGNALS2_LWM_WIN32_CS_HPP
+#define BOOST_SIGNALS2_LWM_WIN32_CS_HPP
+
+// MS compatible compilers support #pragma once
+
+#if defined(_MSC_VER)
+# pragma once
+#endif
+
+#include <boost/assert.hpp>
+
+#ifdef BOOST_USE_WINDOWS_H
+# include <windows.h>
+#endif
+
+#include <boost/predef/platform.h>
+
+namespace boost
+{
+
+namespace signals2
+{
+
+#ifndef BOOST_USE_WINDOWS_H
+
+struct critical_section
+{
+ struct critical_section_debug * DebugInfo;
+ long LockCount;
+ long RecursionCount;
+ void * OwningThread;
+ void * LockSemaphore;
+#if defined(_WIN64)
+ unsigned __int64 SpinCount;
+#else
+ unsigned long SpinCount;
+#endif
+};
+
+#if BOOST_PLAT_WINDOWS_RUNTIME
+extern "C" __declspec(dllimport) void __stdcall InitializeCriticalSectionEx(critical_section *, unsigned long, unsigned long);
+#else
+extern "C" __declspec(dllimport) void __stdcall InitializeCriticalSection(critical_section *);
+#endif
+extern "C" __declspec(dllimport) void __stdcall EnterCriticalSection(critical_section *);
+extern "C" __declspec(dllimport) bool __stdcall TryEnterCriticalSection(critical_section *);
+extern "C" __declspec(dllimport) void __stdcall LeaveCriticalSection(critical_section *);
+extern "C" __declspec(dllimport) void __stdcall DeleteCriticalSection(critical_section *);
+
+#else
+
+typedef ::CRITICAL_SECTION critical_section;
+
+#endif // #ifndef BOOST_USE_WINDOWS_H
+
+class mutex
+{
+private:
+
+ critical_section cs_;
+
+ mutex(mutex const &);
+ mutex & operator=(mutex const &);
+
+public:
+
+ mutex()
+ {
+#if BOOST_PLAT_WINDOWS_RUNTIME
+ InitializeCriticalSectionEx(&cs_, 4000, 0);
+#else
+ InitializeCriticalSection(&cs_);
+#endif
+ }
+
+ ~mutex()
+ {
+ DeleteCriticalSection(&cs_);
+ }
+
+ void lock()
+ {
+ EnterCriticalSection(&cs_);
+ }
+// TryEnterCriticalSection only exists on Windows NT 4.0 and later
+#if (defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0400))
+ bool try_lock()
+ {
+ return TryEnterCriticalSection(&cs_) != 0;
+ }
+#else
+ bool try_lock()
+ {
+ BOOST_ASSERT(false);
+ return false;
+ }
+#endif
+ void unlock()
+ {
+ LeaveCriticalSection(&cs_);
+ }
+};
+
+} // namespace signals2
+
+} // namespace boost
+
+#endif // #ifndef BOOST_SIGNALS2_LWM_WIN32_CS_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/null_output_iterator.hpp b/3rdParty/Boost/src/boost/signals2/detail/null_output_iterator.hpp
new file mode 100644
index 0000000..9e98695
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/null_output_iterator.hpp
@@ -0,0 +1,34 @@
+/*
+ An output iterator which simply discards output.
+*/
+// Copyright Frank Mori Hess 2008.
+// Distributed under the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org/libs/signals2 for library home page.
+
+#ifndef BOOST_SIGNALS2_NULL_OUTPUT_ITERATOR_HPP
+#define BOOST_SIGNALS2_NULL_OUTPUT_ITERATOR_HPP
+
+#include <boost/function_output_iterator.hpp>
+
+namespace boost
+{
+ namespace signals2
+ {
+ namespace detail
+ {
+ class does_nothing
+ {
+ public:
+ template<typename T>
+ void operator()(const T&) const
+ {}
+ };
+ typedef boost::function_output_iterator<does_nothing> null_output_iterator;
+ } // namespace detail
+ } // namespace signals2
+} // namespace boost
+
+#endif // BOOST_SIGNALS2_NULL_OUTPUT_ITERATOR_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/preprocessed_arg_type.hpp b/3rdParty/Boost/src/boost/signals2/detail/preprocessed_arg_type.hpp
new file mode 100644
index 0000000..02717c9
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/preprocessed_arg_type.hpp
@@ -0,0 +1,34 @@
+// Boost.Signals2 library
+
+// Copyright Frank Mori Hess 2007-2009.
+// Copyright Timmo Stange 2007.
+// Copyright Douglas Gregor 2001-2004. Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_PREPROCESSED_ARG_TYPE_HPP
+#define BOOST_SIGNALS2_PREPROCESSED_ARG_TYPE_HPP
+
+#include <boost/preprocessor/repetition.hpp>
+#include <boost/signals2/detail/signals_common_macros.hpp>
+
+#define BOOST_PP_ITERATION_LIMITS (0, BOOST_PP_INC(BOOST_SIGNALS2_MAX_ARGS))
+#define BOOST_PP_FILENAME_1 <boost/signals2/detail/preprocessed_arg_type_template.hpp>
+#include BOOST_PP_ITERATE()
+
+namespace boost
+{
+ namespace signals2
+ {
+ namespace detail
+ {
+ struct std_functional_base
+ {};
+ } // namespace detail
+ } // namespace signals2
+} // namespace boost
+
+#endif // BOOST_SIGNALS2_PREPROCESSED_ARG_TYPE_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/preprocessed_arg_type_template.hpp b/3rdParty/Boost/src/boost/signals2/detail/preprocessed_arg_type_template.hpp
new file mode 100644
index 0000000..4f39433
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/preprocessed_arg_type_template.hpp
@@ -0,0 +1,39 @@
+// Copyright Frank Mori Hess 2009
+//
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+// This file is included iteratively, and should not be protected from multiple inclusion
+
+#define BOOST_SIGNALS2_NUM_ARGS BOOST_PP_ITERATION()
+
+namespace boost
+{
+ namespace signals2
+ {
+ namespace detail
+ {
+ template<unsigned n BOOST_PP_COMMA_IF(BOOST_SIGNALS2_NUM_ARGS)
+ BOOST_SIGNALS2_ARGS_TEMPLATE_DECL(BOOST_SIGNALS2_NUM_ARGS)>
+ class BOOST_SIGNALS2_PREPROCESSED_ARG_N_TYPE_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS);
+
+// template<typename T1, typename T2, ... , typename TN> class preprocessed_arg_typeN<n, T1, T2, ..., TN>{...} ...
+#define BOOST_SIGNALS2_PREPROCESSED_ARG_TYPE_CLASS_TEMPLATE_SPECIALIZATION(z, n, data) \
+ template<BOOST_SIGNALS2_ARGS_TEMPLATE_DECL(BOOST_SIGNALS2_NUM_ARGS)> \
+ class BOOST_SIGNALS2_PREPROCESSED_ARG_N_TYPE_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)<n, \
+ BOOST_SIGNALS2_ARGS_TEMPLATE_INSTANTIATION(BOOST_SIGNALS2_NUM_ARGS)> \
+ { \
+ public: \
+ typedef BOOST_PP_CAT(T, BOOST_PP_INC(n)) type; \
+ };
+ BOOST_PP_REPEAT(BOOST_SIGNALS2_NUM_ARGS, BOOST_SIGNALS2_PREPROCESSED_ARG_TYPE_CLASS_TEMPLATE_SPECIALIZATION, ~)
+
+ } // namespace detail
+ } // namespace signals2
+} // namespace boost
+
+#undef BOOST_SIGNALS2_NUM_ARGS
diff --git a/3rdParty/Boost/src/boost/signals2/detail/replace_slot_function.hpp b/3rdParty/Boost/src/boost/signals2/detail/replace_slot_function.hpp
new file mode 100644
index 0000000..de8f425
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/replace_slot_function.hpp
@@ -0,0 +1,32 @@
+// Copyright Frank Mori Hess 2007-2009
+//
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_DETAIL_REPLACE_SLOT_FUNCTION_HPP
+#define BOOST_SIGNALS2_DETAIL_REPLACE_SLOT_FUNCTION_HPP
+
+#include <boost/signals2/slot_base.hpp>
+
+namespace boost
+{
+ namespace signals2
+ {
+ namespace detail
+ {
+ template<typename ResultSlot, typename SlotIn, typename SlotFunction>
+ ResultSlot replace_slot_function(const SlotIn &slot_in, const SlotFunction &fun)
+ {
+ ResultSlot slot(fun);
+ slot.track(slot_in);
+ return slot;
+ }
+ } // namespace detail
+ } // namespace signals2
+} // namespace boost
+
+#endif // BOOST_SIGNALS2_DETAIL_REPLACE_SLOT_FUNCTION_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/result_type_wrapper.hpp b/3rdParty/Boost/src/boost/signals2/detail/result_type_wrapper.hpp
new file mode 100644
index 0000000..35dea7c
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/result_type_wrapper.hpp
@@ -0,0 +1,72 @@
+// Boost.Signals2 library
+
+// Copyright Douglas Gregor 2001-2004.
+// Copyright Frank Mori Hess 2007. Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_RESULT_TYPE_WRAPPER_HPP
+#define BOOST_SIGNALS2_RESULT_TYPE_WRAPPER_HPP
+
+#include <boost/config.hpp>
+
+namespace boost {
+ namespace signals2 {
+ namespace detail {
+ // A placeholder for void on compilers that don't support void returns
+ struct void_type {};
+
+ // Replaces void with void_type
+ template<typename R>
+ struct nonvoid {
+ typedef R type;
+ };
+ template<>
+ struct nonvoid<void> {
+ typedef void_type type;
+ };
+
+ // Replaces void with void_type only if compiler doesn't support void returns
+ template<typename R>
+ struct result_type_wrapper {
+ typedef R type;
+ };
+#ifdef BOOST_NO_VOID_RETURNS
+ template<>
+ struct result_type_wrapper<void> {
+ typedef void_type type;
+ };
+#endif
+
+ // specialization deals with possible void return from combiners
+ template<typename R> class combiner_invoker
+ {
+ public:
+ typedef R result_type;
+ template<typename Combiner, typename InputIterator>
+ result_type operator()(Combiner &combiner,
+ InputIterator first, InputIterator last) const
+ {
+ return combiner(first, last);
+ }
+ };
+ template<> class combiner_invoker<void>
+ {
+ public:
+ typedef result_type_wrapper<void>::type result_type;
+ template<typename Combiner, typename InputIterator>
+ result_type operator()(Combiner &combiner,
+ InputIterator first, InputIterator last) const
+ {
+ combiner(first, last);
+ return result_type();
+ }
+ };
+ } // end namespace detail
+ } // end namespace signals2
+} // end namespace boost
+
+#endif // BOOST_SIGNALS2_RESULT_TYPE_WRAPPER_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/signal_template.hpp b/3rdParty/Boost/src/boost/signals2/detail/signal_template.hpp
new file mode 100644
index 0000000..bb5d3a4
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/signal_template.hpp
@@ -0,0 +1,859 @@
+/*
+ Template for Signa1, Signal2, ... classes that support signals
+ with 1, 2, ... parameters
+
+ Begin: 2007-01-23
+*/
+// Copyright Frank Mori Hess 2007-2008
+//
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// This file is included iteratively, and should not be protected from multiple inclusion
+
+#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
+#define BOOST_SIGNALS2_NUM_ARGS BOOST_PP_ITERATION()
+#else
+#define BOOST_SIGNALS2_NUM_ARGS 1
+#endif
+
+// R, T1, T2, ..., TN, Combiner, Group, GroupCompare, SlotFunction, ExtendedSlotFunction, Mutex
+#define BOOST_SIGNALS2_SIGNAL_TEMPLATE_INSTANTIATION \
+ BOOST_SIGNALS2_SIGNATURE_TEMPLATE_INSTANTIATION(BOOST_SIGNALS2_NUM_ARGS), \
+ Combiner, Group, GroupCompare, SlotFunction, ExtendedSlotFunction, Mutex
+
+namespace boost
+{
+ namespace signals2
+ {
+ namespace detail
+ {
+ // helper for bound_extended_slot_function that handles specialization for void return
+ template<typename R>
+ class BOOST_SIGNALS2_BOUND_EXTENDED_SLOT_FUNCTION_INVOKER_N(BOOST_SIGNALS2_NUM_ARGS)
+ {
+ public:
+ typedef R result_type;
+ template<typename ExtendedSlotFunction BOOST_SIGNALS2_PP_COMMA_IF(BOOST_SIGNALS2_NUM_ARGS)
+ BOOST_SIGNALS2_ARGS_TEMPLATE_DECL(BOOST_SIGNALS2_NUM_ARGS)>
+ result_type operator()(ExtendedSlotFunction &func, const connection &conn
+ BOOST_SIGNALS2_PP_COMMA_IF(BOOST_SIGNALS2_NUM_ARGS)
+ BOOST_SIGNALS2_FULL_REF_ARGS(BOOST_SIGNALS2_NUM_ARGS)) const
+ {
+ return func(conn BOOST_SIGNALS2_PP_COMMA_IF(BOOST_SIGNALS2_NUM_ARGS)
+ BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(BOOST_SIGNALS2_NUM_ARGS));
+ }
+ };
+#ifdef BOOST_NO_VOID_RETURNS
+ template<>
+ class BOOST_SIGNALS2_BOUND_EXTENDED_SLOT_FUNCTION_INVOKER_N(BOOST_SIGNALS2_NUM_ARGS)<void>
+ {
+ public:
+ typedef result_type_wrapper<void>::type result_type;
+ template<typename ExtendedSlotFunction BOOST_SIGNALS2_PP_COMMA_IF(BOOST_SIGNALS2_NUM_ARGS)
+ BOOST_SIGNALS2_ARGS_TEMPLATE_DECL(BOOST_SIGNALS2_NUM_ARGS)>
+ result_type operator()(ExtendedSlotFunction &func, const connection &conn
+ BOOST_SIGNALS2_PP_COMMA_IF(BOOST_SIGNALS2_NUM_ARGS)
+ BOOST_SIGNALS2_FULL_REF_ARGS(BOOST_SIGNALS2_NUM_ARGS)) const
+ {
+ func(conn BOOST_SIGNALS2_PP_COMMA_IF(BOOST_SIGNALS2_NUM_ARGS)
+ BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(BOOST_SIGNALS2_NUM_ARGS));
+ return result_type();
+ }
+ };
+#endif
+// wrapper around an signalN::extended_slot_function which binds the
+// connection argument so it looks like a normal
+// signalN::slot_function
+
+ template<typename ExtendedSlotFunction>
+ class BOOST_SIGNALS2_BOUND_EXTENDED_SLOT_FUNCTION_N(BOOST_SIGNALS2_NUM_ARGS)
+ {
+ public:
+ typedef typename result_type_wrapper<typename ExtendedSlotFunction::result_type>::type result_type;
+ BOOST_SIGNALS2_BOUND_EXTENDED_SLOT_FUNCTION_N(BOOST_SIGNALS2_NUM_ARGS)(const ExtendedSlotFunction &fun):
+ _fun(fun), _connection(new connection)
+ {}
+ void set_connection(const connection &conn)
+ {
+ *_connection = conn;
+ }
+
+#if BOOST_SIGNALS2_NUM_ARGS > 0
+ template<BOOST_SIGNALS2_ARGS_TEMPLATE_DECL(BOOST_SIGNALS2_NUM_ARGS)>
+#endif // BOOST_SIGNALS2_NUM_ARGS > 0
+ result_type operator()(BOOST_SIGNALS2_FULL_REF_ARGS(BOOST_SIGNALS2_NUM_ARGS))
+ {
+ return BOOST_SIGNALS2_BOUND_EXTENDED_SLOT_FUNCTION_INVOKER_N(BOOST_SIGNALS2_NUM_ARGS)
+ <typename ExtendedSlotFunction::result_type>()
+ (_fun, *_connection BOOST_SIGNALS2_PP_COMMA_IF(BOOST_SIGNALS2_NUM_ARGS)
+ BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(BOOST_SIGNALS2_NUM_ARGS));
+ }
+ // const overload
+#if BOOST_SIGNALS2_NUM_ARGS > 0
+ template<BOOST_SIGNALS2_ARGS_TEMPLATE_DECL(BOOST_SIGNALS2_NUM_ARGS)>
+#endif // BOOST_SIGNALS2_NUM_ARGS > 0
+ result_type operator()(BOOST_SIGNALS2_FULL_REF_ARGS(BOOST_SIGNALS2_NUM_ARGS)) const
+ {
+ return BOOST_SIGNALS2_BOUND_EXTENDED_SLOT_FUNCTION_INVOKER_N(BOOST_SIGNALS2_NUM_ARGS)
+ <typename ExtendedSlotFunction::result_type>()
+ (_fun, *_connection BOOST_SIGNALS2_PP_COMMA_IF(BOOST_SIGNALS2_NUM_ARGS)
+ BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(BOOST_SIGNALS2_NUM_ARGS));
+ }
+ template<typename T>
+ bool operator==(const T &other) const
+ {
+ return _fun == other;
+ }
+ private:
+ BOOST_SIGNALS2_BOUND_EXTENDED_SLOT_FUNCTION_N(BOOST_SIGNALS2_NUM_ARGS)()
+ {}
+
+ ExtendedSlotFunction _fun;
+ boost::shared_ptr<connection> _connection;
+ };
+
+ template<BOOST_SIGNALS2_SIGNAL_TEMPLATE_DECL(BOOST_SIGNALS2_NUM_ARGS)>
+ class BOOST_SIGNALS2_SIGNAL_IMPL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS);
+
+ template<BOOST_SIGNALS2_SIGNAL_TEMPLATE_SPECIALIZATION_DECL(BOOST_SIGNALS2_NUM_ARGS)>
+ class BOOST_SIGNALS2_SIGNAL_IMPL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS) BOOST_SIGNALS2_SIGNAL_TEMPLATE_SPECIALIZATION
+ {
+ public:
+ typedef SlotFunction slot_function_type;
+ // typedef slotN<Signature, SlotFunction> slot_type;
+ typedef BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ <BOOST_SIGNALS2_SIGNATURE_TEMPLATE_INSTANTIATION(BOOST_SIGNALS2_NUM_ARGS),
+ slot_function_type> slot_type;
+ typedef ExtendedSlotFunction extended_slot_function_type;
+ // typedef slotN+1<R, const connection &, T1, T2, ..., TN, extended_slot_function_type> extended_slot_type;
+ typedef BOOST_SIGNALS2_EXTENDED_SLOT_TYPE(BOOST_SIGNALS2_NUM_ARGS) extended_slot_type;
+ typedef typename nonvoid<typename slot_function_type::result_type>::type nonvoid_slot_result_type;
+ private:
+#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
+ class slot_invoker;
+#else // BOOST_NO_CXX11_VARIADIC_TEMPLATES
+ typedef variadic_slot_invoker<nonvoid_slot_result_type, Args...> slot_invoker;
+#endif // BOOST_NO_CXX11_VARIADIC_TEMPLATES
+ typedef slot_call_iterator_cache<nonvoid_slot_result_type, slot_invoker> slot_call_iterator_cache_type;
+ typedef typename group_key<Group>::type group_key_type;
+ typedef shared_ptr<connection_body<group_key_type, slot_type, Mutex> > connection_body_type;
+ typedef grouped_list<Group, GroupCompare, connection_body_type> connection_list_type;
+ typedef BOOST_SIGNALS2_BOUND_EXTENDED_SLOT_FUNCTION_N(BOOST_SIGNALS2_NUM_ARGS)<extended_slot_function_type>
+ bound_extended_slot_function_type;
+ public:
+ typedef Combiner combiner_type;
+ typedef typename result_type_wrapper<typename combiner_type::result_type>::type result_type;
+ typedef Group group_type;
+ typedef GroupCompare group_compare_type;
+ typedef typename detail::slot_call_iterator_t<slot_invoker,
+ typename connection_list_type::iterator, connection_body<group_key_type, slot_type, Mutex> > slot_call_iterator;
+
+ BOOST_SIGNALS2_SIGNAL_IMPL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)(const combiner_type &combiner_arg,
+ const group_compare_type &group_compare):
+ _shared_state(new invocation_state(connection_list_type(group_compare), combiner_arg)),
+ _garbage_collector_it(_shared_state->connection_bodies().end())
+ {}
+ // connect slot
+ connection connect(const slot_type &slot, connect_position position = at_back)
+ {
+ unique_lock<mutex_type> lock(_mutex);
+ return nolock_connect(slot, position);
+ }
+ connection connect(const group_type &group,
+ const slot_type &slot, connect_position position = at_back)
+ {
+ unique_lock<Mutex> lock(_mutex);
+ return nolock_connect(group, slot, position);
+ }
+ // connect extended slot
+ connection connect_extended(const extended_slot_type &ext_slot, connect_position position = at_back)
+ {
+ unique_lock<mutex_type> lock(_mutex);
+ bound_extended_slot_function_type bound_slot(ext_slot.slot_function());
+ slot_type slot = replace_slot_function<slot_type>(ext_slot, bound_slot);
+ connection conn = nolock_connect(slot, position);
+ bound_slot.set_connection(conn);
+ return conn;
+ }
+ connection connect_extended(const group_type &group,
+ const extended_slot_type &ext_slot, connect_position position = at_back)
+ {
+ unique_lock<Mutex> lock(_mutex);
+ bound_extended_slot_function_type bound_slot(ext_slot.slot_function());
+ slot_type slot = replace_slot_function<slot_type>(ext_slot, bound_slot);
+ connection conn = nolock_connect(group, slot, position);
+ bound_slot.set_connection(conn);
+ return conn;
+ }
+ // disconnect slot(s)
+ void disconnect_all_slots()
+ {
+ shared_ptr<invocation_state> local_state =
+ get_readable_state();
+ typename connection_list_type::iterator it;
+ for(it = local_state->connection_bodies().begin();
+ it != local_state->connection_bodies().end(); ++it)
+ {
+ (*it)->disconnect();
+ }
+ }
+ void disconnect(const group_type &group)
+ {
+ shared_ptr<invocation_state> local_state =
+ get_readable_state();
+ group_key_type group_key(grouped_slots, group);
+ typename connection_list_type::iterator it;
+ typename connection_list_type::iterator end_it =
+ local_state->connection_bodies().upper_bound(group_key);
+ for(it = local_state->connection_bodies().lower_bound(group_key);
+ it != end_it; ++it)
+ {
+ (*it)->disconnect();
+ }
+ }
+ template <typename T>
+ void disconnect(const T &slot)
+ {
+ typedef mpl::bool_<(is_convertible<T, group_type>::value)> is_group;
+ do_disconnect(slot, is_group());
+ }
+ // emit signal
+ result_type operator ()(BOOST_SIGNALS2_SIGNATURE_FULL_ARGS(BOOST_SIGNALS2_NUM_ARGS))
+ {
+ shared_ptr<invocation_state> local_state;
+ typename connection_list_type::iterator it;
+ {
+ unique_lock<mutex_type> list_lock(_mutex);
+ // only clean up if it is safe to do so
+ if(_shared_state.unique())
+ nolock_cleanup_connections(false, 1);
+ /* Make a local copy of _shared_state while holding mutex, so we are
+ thread safe against the combiner or connection list getting modified
+ during invocation. */
+ local_state = _shared_state;
+ }
+ slot_invoker invoker = slot_invoker(BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(BOOST_SIGNALS2_NUM_ARGS));
+ slot_call_iterator_cache_type cache(invoker);
+ invocation_janitor janitor(cache, *this, &local_state->connection_bodies());
+ return detail::combiner_invoker<typename combiner_type::result_type>()
+ (
+ local_state->combiner(),
+ slot_call_iterator(local_state->connection_bodies().begin(), local_state->connection_bodies().end(), cache),
+ slot_call_iterator(local_state->connection_bodies().end(), local_state->connection_bodies().end(), cache)
+ );
+ }
+ result_type operator ()(BOOST_SIGNALS2_SIGNATURE_FULL_ARGS(BOOST_SIGNALS2_NUM_ARGS)) const
+ {
+ shared_ptr<invocation_state> local_state;
+ typename connection_list_type::iterator it;
+ {
+ unique_lock<mutex_type> list_lock(_mutex);
+ // only clean up if it is safe to do so
+ if(_shared_state.unique())
+ nolock_cleanup_connections(false, 1);
+ /* Make a local copy of _shared_state while holding mutex, so we are
+ thread safe against the combiner or connection list getting modified
+ during invocation. */
+ local_state = _shared_state;
+ }
+ slot_invoker invoker = slot_invoker(BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(BOOST_SIGNALS2_NUM_ARGS));
+ slot_call_iterator_cache_type cache(invoker);
+ invocation_janitor janitor(cache, *this, &local_state->connection_bodies());
+ return detail::combiner_invoker<typename combiner_type::result_type>()
+ (
+ local_state->combiner(),
+ slot_call_iterator(local_state->connection_bodies().begin(), local_state->connection_bodies().end(), cache),
+ slot_call_iterator(local_state->connection_bodies().end(), local_state->connection_bodies().end(), cache)
+ );
+ }
+ std::size_t num_slots() const
+ {
+ shared_ptr<invocation_state> local_state =
+ get_readable_state();
+ typename connection_list_type::iterator it;
+ std::size_t count = 0;
+ for(it = local_state->connection_bodies().begin();
+ it != local_state->connection_bodies().end(); ++it)
+ {
+ if((*it)->connected()) ++count;
+ }
+ return count;
+ }
+ bool empty() const
+ {
+ shared_ptr<invocation_state> local_state =
+ get_readable_state();
+ typename connection_list_type::iterator it;
+ for(it = local_state->connection_bodies().begin();
+ it != local_state->connection_bodies().end(); ++it)
+ {
+ if((*it)->connected()) return false;
+ }
+ return true;
+ }
+ combiner_type combiner() const
+ {
+ unique_lock<mutex_type> lock(_mutex);
+ return _shared_state->combiner();
+ }
+ void set_combiner(const combiner_type &combiner_arg)
+ {
+ unique_lock<mutex_type> lock(_mutex);
+ if(_shared_state.unique())
+ _shared_state->combiner() = combiner_arg;
+ else
+ _shared_state.reset(new invocation_state(*_shared_state, combiner_arg));
+ }
+ private:
+ typedef Mutex mutex_type;
+
+ // slot_invoker is passed to slot_call_iterator_t to run slots
+#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
+ class slot_invoker
+ {
+ public:
+ typedef nonvoid_slot_result_type result_type;
+// typename add_reference<Tn>::type
+#define BOOST_SIGNALS2_ADD_REF_TYPE(z, n, data) \
+ typename add_reference<BOOST_PP_CAT(T, BOOST_PP_INC(n))>::type
+// typename add_reference<Tn>::type argn
+#define BOOST_SIGNALS2_ADD_REF_ARG(z, n, data) \
+ BOOST_SIGNALS2_ADD_REF_TYPE(~, n, ~) \
+ BOOST_SIGNALS2_SIGNATURE_ARG_NAME(~, n, ~)
+// typename add_reference<T1>::type arg1, typename add_reference<T2>::type arg2, ..., typename add_reference<Tn>::type argn
+#define BOOST_SIGNALS2_ADD_REF_ARGS(arity) \
+ BOOST_PP_ENUM(arity, BOOST_SIGNALS2_ADD_REF_ARG, ~)
+ slot_invoker(BOOST_SIGNALS2_ADD_REF_ARGS(BOOST_SIGNALS2_NUM_ARGS)) BOOST_PP_EXPR_IF(BOOST_SIGNALS2_NUM_ARGS, :)
+#undef BOOST_SIGNALS2_ADD_REF_ARGS
+
+// m_argn
+#define BOOST_SIGNALS2_M_ARG_NAME(z, n, data) BOOST_PP_CAT(m_arg, BOOST_PP_INC(n))
+// m_argn ( argn )
+#define BOOST_SIGNALS2_MISC_STATEMENT(z, n, data) \
+ BOOST_SIGNALS2_M_ARG_NAME(~, n, ~) ( BOOST_SIGNALS2_SIGNATURE_ARG_NAME(~, n, ~) )
+// m_arg1(arg1), m_arg2(arg2), ..., m_argn(argn)
+ BOOST_PP_ENUM(BOOST_SIGNALS2_NUM_ARGS, BOOST_SIGNALS2_MISC_STATEMENT, ~)
+#undef BOOST_SIGNALS2_MISC_STATEMENT
+ {}
+ result_type operator ()(const connection_body_type &connectionBody) const
+ {
+ result_type *resolver = 0;
+ return m_invoke(connectionBody,
+ resolver);
+ }
+ private:
+ // declare assignment operator private since this class might have reference or const members
+ slot_invoker & operator=(const slot_invoker &);
+
+#define BOOST_SIGNALS2_ADD_REF_M_ARG_STATEMENT(z, n, data) \
+ BOOST_SIGNALS2_ADD_REF_TYPE(~, n, ~) BOOST_SIGNALS2_M_ARG_NAME(~, n, ~) ;
+ BOOST_PP_REPEAT(BOOST_SIGNALS2_NUM_ARGS, BOOST_SIGNALS2_ADD_REF_M_ARG_STATEMENT, ~)
+#undef BOOST_SIGNALS2_ADD_REF_M_ARG_STATEMENT
+#undef BOOST_SIGNALS2_ADD_REF_ARG
+#undef BOOST_SIGNALS2_ADD_REF_TYPE
+
+// m_arg1, m_arg2, ..., m_argn
+#define BOOST_SIGNALS2_M_ARG_NAMES(arity) BOOST_PP_ENUM(arity, BOOST_SIGNALS2_M_ARG_NAME, ~)
+ result_type m_invoke(const connection_body_type &connectionBody,
+ const void_type *) const
+ {
+ connectionBody->slot.slot_function()(BOOST_SIGNALS2_M_ARG_NAMES(BOOST_SIGNALS2_NUM_ARGS));
+ return void_type();
+ }
+ result_type m_invoke(const connection_body_type &connectionBody, ...) const
+ {
+ return connectionBody->slot.slot_function()(BOOST_SIGNALS2_M_ARG_NAMES(BOOST_SIGNALS2_NUM_ARGS));
+ }
+ };
+#undef BOOST_SIGNALS2_M_ARG_NAMES
+#undef BOOST_SIGNALS2_M_ARG_NAME
+
+#endif // BOOST_NO_CXX11_VARIADIC_TEMPLATES
+ // a struct used to optimize (minimize) the number of shared_ptrs that need to be created
+ // inside operator()
+ class invocation_state
+ {
+ public:
+ invocation_state(const connection_list_type &connections_in,
+ const combiner_type &combiner_in): _connection_bodies(new connection_list_type(connections_in)),
+ _combiner(new combiner_type(combiner_in))
+ {}
+ invocation_state(const invocation_state &other, const connection_list_type &connections_in):
+ _connection_bodies(new connection_list_type(connections_in)),
+ _combiner(other._combiner)
+ {}
+ invocation_state(const invocation_state &other, const combiner_type &combiner_in):
+ _connection_bodies(other._connection_bodies),
+ _combiner(new combiner_type(combiner_in))
+ {}
+ connection_list_type & connection_bodies() { return *_connection_bodies; }
+ const connection_list_type & connection_bodies() const { return *_connection_bodies; }
+ combiner_type & combiner() { return *_combiner; }
+ const combiner_type & combiner() const { return *_combiner; }
+ private:
+ invocation_state(const invocation_state &);
+
+ shared_ptr<connection_list_type> _connection_bodies;
+ shared_ptr<combiner_type> _combiner;
+ };
+ // Destructor of invocation_janitor does some cleanup when a signal invocation completes.
+ // Code can't be put directly in signal's operator() due to complications from void return types.
+ class invocation_janitor
+ {
+ public:
+ typedef BOOST_SIGNALS2_SIGNAL_IMPL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS) signal_type;
+ invocation_janitor
+ (
+ const slot_call_iterator_cache_type &cache,
+ const signal_type &sig,
+ const connection_list_type *connection_bodies
+ ):_cache(cache), _sig(sig), _connection_bodies(connection_bodies)
+ {}
+ ~invocation_janitor()
+ {
+ // force a full cleanup of disconnected slots if there are too many
+ if(_cache.disconnected_slot_count > _cache.connected_slot_count)
+ {
+ _sig.force_cleanup_connections(_connection_bodies);
+ }
+ }
+ private:
+ const slot_call_iterator_cache_type &_cache;
+ const signal_type &_sig;
+ const connection_list_type *_connection_bodies;
+ };
+
+ // clean up disconnected connections
+ void nolock_cleanup_connections_from(bool grab_tracked,
+ const typename connection_list_type::iterator &begin, unsigned count = 0) const
+ {
+ BOOST_ASSERT(_shared_state.unique());
+ typename connection_list_type::iterator it;
+ unsigned i;
+ for(it = begin, i = 0;
+ it != _shared_state->connection_bodies().end() && (count == 0 || i < count);
+ ++i)
+ {
+ bool connected;
+ {
+ unique_lock<connection_body_base> lock(**it);
+ if(grab_tracked)
+ (*it)->nolock_slot_expired();
+ connected = (*it)->nolock_nograb_connected();
+ }// scoped lock destructs here, safe to erase now
+ if(connected == false)
+ {
+ it = _shared_state->connection_bodies().erase((*it)->group_key(), it);
+ }else
+ {
+ ++it;
+ }
+ }
+ _garbage_collector_it = it;
+ }
+ // clean up a few connections in constant time
+ void nolock_cleanup_connections(bool grab_tracked, unsigned count) const
+ {
+ BOOST_ASSERT(_shared_state.unique());
+ typename connection_list_type::iterator begin;
+ if(_garbage_collector_it == _shared_state->connection_bodies().end())
+ {
+ begin = _shared_state->connection_bodies().begin();
+ }else
+ {
+ begin = _garbage_collector_it;
+ }
+ nolock_cleanup_connections_from(grab_tracked, begin, count);
+ }
+ /* Make a new copy of the slot list if it is currently being read somewhere else
+ */
+ void nolock_force_unique_connection_list()
+ {
+ if(_shared_state.unique() == false)
+ {
+ _shared_state.reset(new invocation_state(*_shared_state, _shared_state->connection_bodies()));
+ nolock_cleanup_connections_from(true, _shared_state->connection_bodies().begin());
+ }else
+ {
+ /* We need to try and check more than just 1 connection here to avoid corner
+ cases where certain repeated connect/disconnect patterns cause the slot
+ list to grow without limit. */
+ nolock_cleanup_connections(true, 2);
+ }
+ }
+ // force a full cleanup of the connection list
+ void force_cleanup_connections(const connection_list_type *connection_bodies) const
+ {
+ unique_lock<mutex_type> list_lock(_mutex);
+ // if the connection list passed in as a parameter is no longer in use,
+ // we don't need to do any cleanup.
+ if(&_shared_state->connection_bodies() != connection_bodies)
+ {
+ return;
+ }
+ if(_shared_state.unique() == false)
+ {
+ _shared_state.reset(new invocation_state(*_shared_state, _shared_state->connection_bodies()));
+ }
+ nolock_cleanup_connections_from(false, _shared_state->connection_bodies().begin());
+ }
+ shared_ptr<invocation_state> get_readable_state() const
+ {
+ unique_lock<mutex_type> list_lock(_mutex);
+ return _shared_state;
+ }
+ connection_body_type create_new_connection(const slot_type &slot)
+ {
+ nolock_force_unique_connection_list();
+ return connection_body_type(new connection_body<group_key_type, slot_type, Mutex>(slot));
+ }
+ void do_disconnect(const group_type &group, mpl::bool_<true> /* is_group */)
+ {
+ disconnect(group);
+ }
+ template<typename T>
+ void do_disconnect(const T &slot, mpl::bool_<false> /* is_group */)
+ {
+ shared_ptr<invocation_state> local_state =
+ get_readable_state();
+ typename connection_list_type::iterator it;
+ for(it = local_state->connection_bodies().begin();
+ it != local_state->connection_bodies().end(); ++it)
+ {
+ unique_lock<connection_body_base> lock(**it);
+ if((*it)->slot.slot_function() == slot)
+ {
+ (*it)->nolock_disconnect();
+ }else
+ {
+ // check for wrapped extended slot
+ bound_extended_slot_function_type *fp;
+ fp = (*it)->slot.slot_function().template target<bound_extended_slot_function_type>();
+ if(fp && *fp == slot)
+ {
+ (*it)->nolock_disconnect();
+ }
+ }
+ }
+ }
+ // connect slot
+ connection nolock_connect(const slot_type &slot, connect_position position)
+ {
+ connection_body_type newConnectionBody =
+ create_new_connection(slot);
+ group_key_type group_key;
+ if(position == at_back)
+ {
+ group_key.first = back_ungrouped_slots;
+ _shared_state->connection_bodies().push_back(group_key, newConnectionBody);
+ }else
+ {
+ group_key.first = front_ungrouped_slots;
+ _shared_state->connection_bodies().push_front(group_key, newConnectionBody);
+ }
+ newConnectionBody->set_group_key(group_key);
+ return connection(newConnectionBody);
+ }
+ connection nolock_connect(const group_type &group,
+ const slot_type &slot, connect_position position)
+ {
+ connection_body_type newConnectionBody =
+ create_new_connection(slot);
+ // update map to first connection body in group if needed
+ group_key_type group_key(grouped_slots, group);
+ newConnectionBody->set_group_key(group_key);
+ if(position == at_back)
+ {
+ _shared_state->connection_bodies().push_back(group_key, newConnectionBody);
+ }else // at_front
+ {
+ _shared_state->connection_bodies().push_front(group_key, newConnectionBody);
+ }
+ return connection(newConnectionBody);
+ }
+
+ // _shared_state is mutable so we can do force_cleanup_connections during a const invocation
+ mutable shared_ptr<invocation_state> _shared_state;
+ mutable typename connection_list_type::iterator _garbage_collector_it;
+ // connection list mutex must never be locked when attempting a blocking lock on a slot,
+ // or you could deadlock.
+ mutable mutex_type _mutex;
+ };
+
+ template<BOOST_SIGNALS2_SIGNAL_TEMPLATE_DECL(BOOST_SIGNALS2_NUM_ARGS)>
+ class BOOST_SIGNALS2_WEAK_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS);
+ }
+
+ template<BOOST_SIGNALS2_SIGNAL_TEMPLATE_DEFAULTED_DECL(BOOST_SIGNALS2_NUM_ARGS)>
+ class BOOST_SIGNALS2_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS);
+
+ template<BOOST_SIGNALS2_SIGNAL_TEMPLATE_SPECIALIZATION_DECL(BOOST_SIGNALS2_NUM_ARGS)>
+ class BOOST_SIGNALS2_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ BOOST_SIGNALS2_SIGNAL_TEMPLATE_SPECIALIZATION: public signal_base,
+ public detail::BOOST_SIGNALS2_STD_FUNCTIONAL_BASE
+ (typename detail::result_type_wrapper<typename Combiner::result_type>::type)
+ {
+ typedef detail::BOOST_SIGNALS2_SIGNAL_IMPL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ <BOOST_SIGNALS2_SIGNAL_TEMPLATE_INSTANTIATION> impl_class;
+ public:
+ typedef detail::BOOST_SIGNALS2_WEAK_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ <BOOST_SIGNALS2_SIGNAL_TEMPLATE_INSTANTIATION> weak_signal_type;
+ friend class detail::BOOST_SIGNALS2_WEAK_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ <BOOST_SIGNALS2_SIGNAL_TEMPLATE_INSTANTIATION>;
+
+ typedef SlotFunction slot_function_type;
+ // typedef slotN<Signature, SlotFunction> slot_type;
+ typedef typename impl_class::slot_type slot_type;
+ typedef typename impl_class::extended_slot_function_type extended_slot_function_type;
+ typedef typename impl_class::extended_slot_type extended_slot_type;
+ typedef typename slot_function_type::result_type slot_result_type;
+ typedef Combiner combiner_type;
+ typedef typename impl_class::result_type result_type;
+ typedef Group group_type;
+ typedef GroupCompare group_compare_type;
+ typedef typename impl_class::slot_call_iterator
+ slot_call_iterator;
+ typedef typename mpl::identity<BOOST_SIGNALS2_SIGNATURE_FUNCTION_TYPE(BOOST_SIGNALS2_NUM_ARGS)>::type signature_type;
+
+#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
+
+// typedef Tn argn_type;
+#define BOOST_SIGNALS2_MISC_STATEMENT(z, n, data) \
+ typedef BOOST_PP_CAT(T, BOOST_PP_INC(n)) BOOST_PP_CAT(BOOST_PP_CAT(arg, BOOST_PP_INC(n)), _type);
+ BOOST_PP_REPEAT(BOOST_SIGNALS2_NUM_ARGS, BOOST_SIGNALS2_MISC_STATEMENT, ~)
+#undef BOOST_SIGNALS2_MISC_STATEMENT
+#if BOOST_SIGNALS2_NUM_ARGS == 1
+ typedef arg1_type argument_type;
+#elif BOOST_SIGNALS2_NUM_ARGS == 2
+ typedef arg1_type first_argument_type;
+ typedef arg2_type second_argument_type;
+#endif
+
+ template<unsigned n> class arg : public
+ detail::BOOST_SIGNALS2_PREPROCESSED_ARG_N_TYPE_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ <n BOOST_SIGNALS2_PP_COMMA_IF(BOOST_SIGNALS2_NUM_ARGS)
+ BOOST_SIGNALS2_ARGS_TEMPLATE_INSTANTIATION(BOOST_SIGNALS2_NUM_ARGS)>
+ {};
+
+ BOOST_STATIC_CONSTANT(int, arity = BOOST_SIGNALS2_NUM_ARGS);
+
+#else // BOOST_NO_CXX11_VARIADIC_TEMPLATES
+
+ template<unsigned n> class arg
+ {
+ public:
+ typedef typename detail::variadic_arg_type<n, Args...>::type type;
+ };
+ BOOST_STATIC_CONSTANT(int, arity = sizeof...(Args));
+
+#endif // BOOST_NO_CXX11_VARIADIC_TEMPLATES
+
+ BOOST_SIGNALS2_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)(const combiner_type &combiner_arg = combiner_type(),
+ const group_compare_type &group_compare = group_compare_type()):
+ _pimpl(new impl_class(combiner_arg, group_compare))
+ {};
+ virtual ~BOOST_SIGNALS2_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)()
+ {
+ }
+
+ //move support
+#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
+ BOOST_SIGNALS2_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)(
+ BOOST_SIGNALS2_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS) && other)
+ {
+ using std::swap;
+ swap(_pimpl, other._pimpl);
+ };
+
+ BOOST_SIGNALS2_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS) &
+ operator=(BOOST_SIGNALS2_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS) && rhs)
+ {
+ if(this == &rhs)
+ {
+ return *this;
+ }
+ _pimpl.reset();
+ using std::swap;
+ swap(_pimpl, rhs._pimpl);
+ return *this;
+ }
+#endif // !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
+
+ connection connect(const slot_type &slot, connect_position position = at_back)
+ {
+ return (*_pimpl).connect(slot, position);
+ }
+ connection connect(const group_type &group,
+ const slot_type &slot, connect_position position = at_back)
+ {
+ return (*_pimpl).connect(group, slot, position);
+ }
+ connection connect_extended(const extended_slot_type &slot, connect_position position = at_back)
+ {
+ return (*_pimpl).connect_extended(slot, position);
+ }
+ connection connect_extended(const group_type &group,
+ const extended_slot_type &slot, connect_position position = at_back)
+ {
+ return (*_pimpl).connect_extended(group, slot, position);
+ }
+ void disconnect_all_slots()
+ {
+ (*_pimpl).disconnect_all_slots();
+ }
+ void disconnect(const group_type &group)
+ {
+ (*_pimpl).disconnect(group);
+ }
+ template <typename T>
+ void disconnect(const T &slot)
+ {
+ (*_pimpl).disconnect(slot);
+ }
+ result_type operator ()(BOOST_SIGNALS2_SIGNATURE_FULL_ARGS(BOOST_SIGNALS2_NUM_ARGS))
+ {
+ return (*_pimpl)(BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(BOOST_SIGNALS2_NUM_ARGS));
+ }
+ result_type operator ()(BOOST_SIGNALS2_SIGNATURE_FULL_ARGS(BOOST_SIGNALS2_NUM_ARGS)) const
+ {
+ return (*_pimpl)(BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(BOOST_SIGNALS2_NUM_ARGS));
+ }
+ std::size_t num_slots() const
+ {
+ return (*_pimpl).num_slots();
+ }
+ bool empty() const
+ {
+ return (*_pimpl).empty();
+ }
+ combiner_type combiner() const
+ {
+ return (*_pimpl).combiner();
+ }
+ void set_combiner(const combiner_type &combiner_arg)
+ {
+ return (*_pimpl).set_combiner(combiner_arg);
+ }
+ void swap(BOOST_SIGNALS2_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS) & other)
+ {
+ using std::swap;
+ swap(_pimpl, other._pimpl);
+ }
+ protected:
+ virtual shared_ptr<void> lock_pimpl() const
+ {
+ return _pimpl;
+ }
+ private:
+ shared_ptr<impl_class>
+ _pimpl;
+ };
+
+#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
+ // free swap function for signalN classes, findable by ADL
+ template<BOOST_SIGNALS2_SIGNAL_TEMPLATE_DECL(BOOST_SIGNALS2_NUM_ARGS)>
+ void swap(
+ BOOST_SIGNALS2_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS) <BOOST_SIGNALS2_SIGNAL_TEMPLATE_INSTANTIATION> &sig1,
+ BOOST_SIGNALS2_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS) <BOOST_SIGNALS2_SIGNAL_TEMPLATE_INSTANTIATION> &sig2 )
+ {
+ sig1.swap(sig2);
+ }
+#endif
+
+ namespace detail
+ {
+ // wrapper class for storing other signals as slots with automatic lifetime tracking
+ template<BOOST_SIGNALS2_SIGNAL_TEMPLATE_DECL(BOOST_SIGNALS2_NUM_ARGS)>
+ class BOOST_SIGNALS2_WEAK_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS);
+
+ template<BOOST_SIGNALS2_SIGNAL_TEMPLATE_SPECIALIZATION_DECL(BOOST_SIGNALS2_NUM_ARGS)>
+ class BOOST_SIGNALS2_WEAK_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ BOOST_SIGNALS2_SIGNAL_TEMPLATE_SPECIALIZATION
+ {
+ public:
+ typedef typename BOOST_SIGNALS2_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ <BOOST_SIGNALS2_SIGNAL_TEMPLATE_INSTANTIATION>::result_type
+ result_type;
+
+ BOOST_SIGNALS2_WEAK_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ (const BOOST_SIGNALS2_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ <BOOST_SIGNALS2_SIGNAL_TEMPLATE_INSTANTIATION>
+ &signal):
+ _weak_pimpl(signal._pimpl)
+ {}
+ result_type operator ()(BOOST_SIGNALS2_SIGNATURE_FULL_ARGS(BOOST_SIGNALS2_NUM_ARGS))
+ {
+ shared_ptr<detail::BOOST_SIGNALS2_SIGNAL_IMPL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ <BOOST_SIGNALS2_SIGNAL_TEMPLATE_INSTANTIATION> >
+ shared_pimpl(_weak_pimpl.lock());
+ if(shared_pimpl == 0) boost::throw_exception(expired_slot());
+ return (*shared_pimpl)(BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(BOOST_SIGNALS2_NUM_ARGS));
+ }
+ result_type operator ()(BOOST_SIGNALS2_SIGNATURE_FULL_ARGS(BOOST_SIGNALS2_NUM_ARGS)) const
+ {
+ shared_ptr<detail::BOOST_SIGNALS2_SIGNAL_IMPL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ <BOOST_SIGNALS2_SIGNAL_TEMPLATE_INSTANTIATION> >
+ shared_pimpl(_weak_pimpl.lock());
+ if(shared_pimpl == 0) boost::throw_exception(expired_slot());
+ return (*shared_pimpl)(BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(BOOST_SIGNALS2_NUM_ARGS));
+ }
+ private:
+ boost::weak_ptr<detail::BOOST_SIGNALS2_SIGNAL_IMPL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ <BOOST_SIGNALS2_SIGNAL_TEMPLATE_INSTANTIATION> > _weak_pimpl;
+ };
+
+#ifndef BOOST_NO_CXX11_VARIADIC_TEMPLATES
+ template<int arity, typename Signature>
+ class extended_signature: public variadic_extended_signature<Signature>
+ {};
+#else // BOOST_NO_CXX11_VARIADIC_TEMPLATES
+ template<int arity, typename Signature>
+ class extended_signature;
+ // partial template specialization
+ template<typename Signature>
+ class extended_signature<BOOST_SIGNALS2_NUM_ARGS, Signature>
+ {
+ public:
+// typename function_traits<Signature>::result_type (
+// const boost::signals2::connection &,
+// typename function_traits<Signature>::arg1_type,
+// typename function_traits<Signature>::arg2_type,
+// ...,
+// typename function_traits<Signature>::argn_type)
+#define BOOST_SIGNALS2_EXT_SIGNATURE(arity, Signature) \
+ typename function_traits<Signature>::result_type ( \
+ const boost::signals2::connection & BOOST_SIGNALS2_PP_COMMA_IF(BOOST_SIGNALS2_NUM_ARGS) \
+ BOOST_PP_ENUM(arity, BOOST_SIGNALS2_SIGNATURE_TO_ARGN_TYPE, Signature) )
+ typedef function<BOOST_SIGNALS2_EXT_SIGNATURE(BOOST_SIGNALS2_NUM_ARGS, Signature)> function_type;
+#undef BOOST_SIGNALS2_EXT_SIGNATURE
+ };
+
+ template<unsigned arity, typename Signature, typename Combiner,
+ typename Group, typename GroupCompare, typename SlotFunction,
+ typename ExtendedSlotFunction, typename Mutex>
+ class signalN;
+ // partial template specialization
+ template<typename Signature, typename Combiner, typename Group,
+ typename GroupCompare, typename SlotFunction,
+ typename ExtendedSlotFunction, typename Mutex>
+ class signalN<BOOST_SIGNALS2_NUM_ARGS, Signature, Combiner, Group,
+ GroupCompare, SlotFunction, ExtendedSlotFunction, Mutex>
+ {
+ public:
+ typedef BOOST_SIGNALS2_SIGNAL_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)<
+ BOOST_SIGNALS2_PORTABLE_SIGNATURE(BOOST_SIGNALS2_NUM_ARGS, Signature),
+ Combiner, Group,
+ GroupCompare, SlotFunction, ExtendedSlotFunction, Mutex> type;
+ };
+
+#endif // BOOST_NO_CXX11_VARIADIC_TEMPLATES
+
+ } // namespace detail
+ } // namespace signals2
+} // namespace boost
+
+#undef BOOST_SIGNALS2_NUM_ARGS
+#undef BOOST_SIGNALS2_SIGNAL_TEMPLATE_INSTANTIATION
diff --git a/3rdParty/Boost/src/boost/signals2/detail/signals_common.hpp b/3rdParty/Boost/src/boost/signals2/detail/signals_common.hpp
new file mode 100644
index 0000000..8c4baf0
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/signals_common.hpp
@@ -0,0 +1,77 @@
+// Boost.Signals library
+
+// Copyright Douglas Gregor 2001-2004.
+// Copyright Frank Mori Hess 2007. Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_SIGNALS_COMMON_HPP
+#define BOOST_SIGNALS2_SIGNALS_COMMON_HPP
+
+#include <boost/mpl/bool.hpp>
+#include <boost/mpl/if.hpp>
+#include <boost/ref.hpp>
+#include <boost/signals2/signal_base.hpp>
+#include <boost/type_traits/is_base_of.hpp>
+
+namespace boost {
+ namespace signals2 {
+ namespace detail {
+ // Determine if the given type T is a signal
+ template<typename T>
+ class is_signal: public mpl::bool_<is_base_of<signal_base, T>::value>
+ {};
+
+ // A slot can be a signal, a reference to a function object, or a
+ // function object.
+ struct signal_tag {};
+ struct reference_tag {};
+ struct value_tag {};
+
+ // Classify the given slot as a signal, a reference-to-slot, or a
+ // standard slot
+ template<typename S>
+ class get_slot_tag {
+ typedef typename mpl::if_<is_signal<S>,
+ signal_tag, value_tag>::type signal_or_value;
+ public:
+ typedef typename mpl::if_<is_reference_wrapper<S>,
+ reference_tag,
+ signal_or_value>::type type;
+ };
+
+ // Get the slot so that it can be copied
+ template<typename F>
+ typename F::weak_signal_type
+ get_invocable_slot(const F &signal, signal_tag)
+ { return typename F::weak_signal_type(signal); }
+
+ template<typename F>
+ const F&
+ get_invocable_slot(const F& f, reference_tag)
+ { return f; }
+
+ template<typename F>
+ const F&
+ get_invocable_slot(const F& f, value_tag)
+ { return f; }
+
+ // Determines the type of the slot - is it a signal, a reference to a
+ // slot or just a normal slot.
+ template<typename F>
+ typename get_slot_tag<F>::type
+ tag_type(const F&)
+ {
+ typedef typename get_slot_tag<F>::type
+ the_tag_type;
+ the_tag_type tag = the_tag_type();
+ return tag;
+ }
+ } // end namespace detail
+ } // end namespace signals2
+} // end namespace boost
+
+#endif // BOOST_SIGNALS2_SIGNALS_COMMON_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/signals_common_macros.hpp b/3rdParty/Boost/src/boost/signals2/detail/signals_common_macros.hpp
new file mode 100644
index 0000000..b149dbc
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/signals_common_macros.hpp
@@ -0,0 +1,212 @@
+/*
+ Author: Frank Mori Hess <fmhess@users.sourceforge.net>
+ Begin: 2007-01-23
+*/
+// Copyright Frank Mori Hess 2007-2008
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_SIGNALS2_SIGNALS_COMMON_MACROS_HPP
+#define BOOST_SIGNALS2_SIGNALS_COMMON_MACROS_HPP
+
+#include <boost/config.hpp>
+
+#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
+
+#ifndef BOOST_SIGNALS2_MAX_ARGS
+#define BOOST_SIGNALS2_MAX_ARGS 9
+#endif
+
+// signaln
+#define BOOST_SIGNALS2_SIGNAL_CLASS_NAME(arity) BOOST_PP_CAT(signal, arity)
+// weak_signaln
+#define BOOST_SIGNALS2_WEAK_SIGNAL_CLASS_NAME(arity) BOOST_PP_CAT(weak_, BOOST_SIGNALS2_SIGNAL_CLASS_NAME(arity))
+// signaln_impl
+#define BOOST_SIGNALS2_SIGNAL_IMPL_CLASS_NAME(arity) BOOST_PP_CAT(BOOST_SIGNALS2_SIGNAL_CLASS_NAME(arity), _impl)
+// argn
+#define BOOST_SIGNALS2_SIGNATURE_ARG_NAME(z, n, data) BOOST_PP_CAT(arg, BOOST_PP_INC(n))
+// Tn argn
+#define BOOST_SIGNALS2_SIGNATURE_FULL_ARG(z, n, data) \
+ BOOST_PP_CAT(T, BOOST_PP_INC(n)) BOOST_SIGNALS2_SIGNATURE_ARG_NAME(~, n, ~)
+// T1 arg1, T2 arg2, ..., Tn argn
+#define BOOST_SIGNALS2_SIGNATURE_FULL_ARGS(arity) \
+ BOOST_PP_ENUM(arity, BOOST_SIGNALS2_SIGNATURE_FULL_ARG, ~)
+// arg1, arg2, ..., argn
+#define BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(arity) BOOST_PP_ENUM(arity, BOOST_SIGNALS2_SIGNATURE_ARG_NAME, ~)
+// T1, T2, ..., TN
+#define BOOST_SIGNALS2_ARGS_TEMPLATE_INSTANTIATION(arity) \
+ BOOST_PP_ENUM_SHIFTED_PARAMS(BOOST_PP_INC(arity), T)
+// R (T1, T2, ..., TN)
+#define BOOST_SIGNALS2_SIGNATURE_FUNCTION_TYPE(arity) \
+ R ( BOOST_SIGNALS2_ARGS_TEMPLATE_INSTANTIATION(arity) )
+// typename prefixR, typename prefixT1, typename prefixT2, ..., typename prefixTN
+#define BOOST_SIGNALS2_PREFIXED_SIGNATURE_TEMPLATE_DECL(arity, prefix) \
+ typename BOOST_PP_CAT(prefix, R) BOOST_PP_COMMA_IF(arity) \
+ BOOST_PP_ENUM_SHIFTED_PARAMS(BOOST_PP_INC(arity), typename BOOST_PP_CAT(prefix, T))
+// typename R, typename T1, typename T2, ..., typename TN
+#define BOOST_SIGNALS2_SIGNATURE_TEMPLATE_DECL(arity) \
+ typename R BOOST_PP_COMMA_IF(arity) \
+ BOOST_PP_ENUM_SHIFTED_PARAMS(BOOST_PP_INC(arity), typename T)
+// typename prefixT1, typename prefixT2, ..., typename prefixTN
+#define BOOST_SIGNALS2_PREFIXED_ARGS_TEMPLATE_DECL(arity, prefix) \
+ BOOST_PP_ENUM_SHIFTED_PARAMS(BOOST_PP_INC(arity), typename BOOST_PP_CAT(prefix, T))
+// typename T1, typename T2, ..., typename TN
+#define BOOST_SIGNALS2_ARGS_TEMPLATE_DECL(arity) \
+ BOOST_PP_ENUM_SHIFTED_PARAMS(BOOST_PP_INC(arity), typename T)
+// prefixR, prefixT1, prefixT2, ..., prefixTN
+#define BOOST_SIGNALS2_PREFIXED_SIGNATURE_TEMPLATE_INSTANTIATION(arity, prefix) \
+ BOOST_PP_CAT(prefix, R) BOOST_PP_COMMA_IF(arity) BOOST_PP_ENUM_SHIFTED_PARAMS(BOOST_PP_INC(arity), BOOST_PP_CAT(prefix, T))
+// R, T1, T2, ..., TN
+#define BOOST_SIGNALS2_SIGNATURE_TEMPLATE_INSTANTIATION(arity) \
+ R BOOST_PP_COMMA_IF(arity) BOOST_PP_ENUM_SHIFTED_PARAMS(BOOST_PP_INC(arity), T)
+// boost::functionN<R, T1, T2, ..., TN>
+#define BOOST_SIGNALS2_FUNCTION_N_DECL(arity) BOOST_PP_CAT(boost::function, arity)<\
+ BOOST_SIGNALS2_SIGNATURE_TEMPLATE_INSTANTIATION(arity) >
+// R, const boost::signals2::connection&, T1, T2, ..., TN
+#define BOOST_SIGNALS2_EXT_SLOT_TEMPLATE_INSTANTIATION(arity) \
+ R, const boost::signals2::connection& BOOST_PP_COMMA_IF(arity) \
+ BOOST_PP_ENUM_SHIFTED_PARAMS(BOOST_PP_INC(arity), T)
+// boost::functionN<R, const boost::signals2::connection &, T1, T2, ..., TN>
+#define BOOST_SIGNALS2_EXT_FUNCTION_N_DECL(arity) BOOST_PP_CAT(boost::function, BOOST_PP_INC(arity))<\
+ BOOST_SIGNALS2_EXT_SLOT_TEMPLATE_INSTANTIATION(arity) >
+// slotN
+#define BOOST_SIGNALS2_SLOT_CLASS_NAME(arity) BOOST_PP_CAT(slot, arity)
+// slotN+1<R, const connection &, T1, T2, ..., TN, extended_slot_function_type>
+#define BOOST_SIGNALS2_EXTENDED_SLOT_TYPE(arity) \
+ BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_PP_INC(arity))< \
+ BOOST_SIGNALS2_EXT_SLOT_TEMPLATE_INSTANTIATION(arity), \
+ extended_slot_function_type>
+// bound_extended_slot_functionN
+#define BOOST_SIGNALS2_BOUND_EXTENDED_SLOT_FUNCTION_N(arity) BOOST_PP_CAT(bound_extended_slot_function, arity)
+// bound_extended_slot_function_helperN
+#define BOOST_SIGNALS2_BOUND_EXTENDED_SLOT_FUNCTION_INVOKER_N(arity) BOOST_PP_CAT(bound_extended_slot_function_invoker, arity)
+// typename function_traits<Signature>::argn_type
+#define BOOST_SIGNALS2_SIGNATURE_TO_ARGN_TYPE(z, n, Signature) \
+ BOOST_PP_CAT(BOOST_PP_CAT(typename function_traits<Signature>::arg, BOOST_PP_INC(n)), _type)
+// typename function_traits<Signature>::result_type,
+// typename function_traits<Signature>::arg1_type,
+// typename function_traits<Signature>::arg2_type,
+// ...,
+// typename function_traits<Signature>::argn_type
+#define BOOST_SIGNALS2_PORTABLE_SIGNATURE(arity, Signature) \
+ typename function_traits<Signature>::result_type \
+ BOOST_PP_COMMA_IF(arity) BOOST_PP_ENUM(arity, BOOST_SIGNALS2_SIGNATURE_TO_ARGN_TYPE, Signature)
+// prefixTn & argn
+#define BOOST_SIGNALS2_PREFIXED_FULL_REF_ARG(z, n, prefix) \
+ BOOST_PP_CAT(BOOST_PP_CAT(prefix, T), BOOST_PP_INC(n)) & BOOST_SIGNALS2_SIGNATURE_ARG_NAME(~, n, ~)
+// prefixT1 & arg1, prefixT2 & arg2, ..., prefixTn & argn
+#define BOOST_SIGNALS2_PREFIXED_FULL_REF_ARGS(arity, prefix) \
+ BOOST_PP_ENUM(arity, BOOST_SIGNALS2_PREFIXED_FULL_REF_ARG, prefix)
+// Tn & argn
+#define BOOST_SIGNALS2_FULL_REF_ARG(z, n, data) \
+ BOOST_PP_CAT(T, BOOST_PP_INC(n)) & BOOST_SIGNALS2_SIGNATURE_ARG_NAME(~, n, ~)
+// T1 & arg1, T2 & arg2, ..., Tn & argn
+#define BOOST_SIGNALS2_FULL_REF_ARGS(arity) \
+ BOOST_PP_ENUM(arity, BOOST_SIGNALS2_FULL_REF_ARG, ~)
+// preprocessed_arg_typeN
+#define BOOST_SIGNALS2_PREPROCESSED_ARG_N_TYPE_CLASS_NAME(arity) BOOST_PP_CAT(preprocessed_arg_type, arity)
+
+// typename R, typename T1, typename T2, ..., typename TN, typename SlotFunction
+#define BOOST_SIGNALS2_SLOT_TEMPLATE_SPECIALIZATION_DECL(arity) \
+ BOOST_SIGNALS2_SIGNATURE_TEMPLATE_DECL(arity), \
+ typename SlotFunction
+#define BOOST_SIGNALS2_SLOT_TEMPLATE_SPECIALIZATION
+
+// typename R, typename T1, typename T2, ..., typename TN, typename Combiner, ...
+#define BOOST_SIGNALS2_SIGNAL_TEMPLATE_DECL(arity) \
+ BOOST_SIGNALS2_SIGNATURE_TEMPLATE_DECL(arity), \
+ typename Combiner, \
+ typename Group, \
+ typename GroupCompare, \
+ typename SlotFunction, \
+ typename ExtendedSlotFunction, \
+ typename Mutex
+// typename R, typename T1, typename T2, ..., typename TN, typename Combiner = optional_last_value<R>, ...
+#define BOOST_SIGNALS2_SIGNAL_TEMPLATE_DEFAULTED_DECL(arity) \
+ BOOST_SIGNALS2_SIGNATURE_TEMPLATE_DECL(arity), \
+ typename Combiner = optional_last_value<R>, \
+ typename Group = int, \
+ typename GroupCompare = std::less<Group>, \
+ typename SlotFunction = BOOST_SIGNALS2_FUNCTION_N_DECL(arity), \
+ typename ExtendedSlotFunction = BOOST_SIGNALS2_EXT_FUNCTION_N_DECL(arity), \
+ typename Mutex = signals2::mutex
+#define BOOST_SIGNALS2_SIGNAL_TEMPLATE_SPECIALIZATION_DECL(arity) BOOST_SIGNALS2_SIGNAL_TEMPLATE_DECL(arity)
+#define BOOST_SIGNALS2_SIGNAL_TEMPLATE_SPECIALIZATION
+
+#define BOOST_SIGNALS2_STD_FUNCTIONAL_BASE(result_type) std_functional_base
+
+#define BOOST_SIGNALS2_PP_COMMA_IF(arity) BOOST_PP_COMMA_IF(arity)
+
+#else // BOOST_NO_CXX11_VARIADIC_TEMPLATES
+
+#define BOOST_SIGNALS2_SIGNAL_CLASS_NAME(arity) signal
+#define BOOST_SIGNALS2_WEAK_SIGNAL_CLASS_NAME(arity) weak_signal
+#define BOOST_SIGNALS2_SIGNAL_IMPL_CLASS_NAME(arity) signal_impl
+#define BOOST_SIGNALS2_SIGNATURE_TEMPLATE_DECL(arity) typename Signature
+#define BOOST_SIGNALS2_ARGS_TEMPLATE_INSTANTIATION(arity) Args...
+#define BOOST_SIGNALS2_SIGNATURE_TEMPLATE_INSTANTIATION(arity) R (Args...)
+#define BOOST_SIGNALS2_SIGNATURE_FUNCTION_TYPE(arity) R (Args...)
+#define BOOST_SIGNALS2_ARGS_TEMPLATE_DECL(arity) typename ... Args
+#define BOOST_SIGNALS2_FULL_REF_ARGS(arity) Args & ... args
+#define BOOST_SIGNALS2_SLOT_CLASS_NAME(arity) slot
+#define BOOST_SIGNALS2_EXTENDED_SLOT_TYPE(arity) slot<R (const connection &, Args...), extended_slot_function_type>
+#define BOOST_SIGNALS2_BOUND_EXTENDED_SLOT_FUNCTION_N(arity) bound_extended_slot_function
+#define BOOST_SIGNALS2_BOUND_EXTENDED_SLOT_FUNCTION_INVOKER_N(arity) bound_extended_slot_function_invoker
+#define BOOST_SIGNALS2_FUNCTION_N_DECL(arity) boost::function<Signature>
+#define BOOST_SIGNALS2_PREFIXED_SIGNATURE_TEMPLATE_DECL(arity, prefix) typename prefixSignature
+#define BOOST_SIGNALS2_PREFIXED_SIGNATURE_TEMPLATE_INSTANTIATION(arity, prefix) prefixSignature
+#define BOOST_SIGNALS2_SIGNATURE_FULL_ARGS(arity) Args ... args
+#define BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(arity) args...
+#define BOOST_SIGNALS2_PORTABLE_SIGNATURE(arity, Signature) Signature
+
+#define BOOST_SIGNALS2_SLOT_TEMPLATE_SPECIALIZATION_DECL(arity) \
+ typename SlotFunction, \
+ typename R, \
+ typename ... Args
+#define BOOST_SIGNALS2_SLOT_TEMPLATE_SPECIALIZATION \
+ <R (Args...), SlotFunction>
+
+#define BOOST_SIGNALS2_SIGNAL_TEMPLATE_DECL(arity) \
+ typename Signature, \
+ typename Combiner, \
+ typename Group, \
+ typename GroupCompare, \
+ typename SlotFunction, \
+ typename ExtendedSlotFunction, \
+ typename Mutex
+#define BOOST_SIGNALS2_SIGNAL_TEMPLATE_DEFAULTED_DECL(arity) \
+ typename Signature, \
+ typename Combiner = optional_last_value<typename boost::function_traits<Signature>::result_type>, \
+ typename Group = int, \
+ typename GroupCompare = std::less<Group>, \
+ typename SlotFunction = boost::function<Signature>, \
+ typename ExtendedSlotFunction = typename detail::variadic_extended_signature<Signature>::function_type, \
+ typename Mutex = signals2::mutex
+#define BOOST_SIGNALS2_SIGNAL_TEMPLATE_SPECIALIZATION_DECL(arity) \
+ typename Combiner, \
+ typename Group, \
+ typename GroupCompare, \
+ typename SlotFunction, \
+ typename ExtendedSlotFunction, \
+ typename Mutex, \
+ typename R, \
+ typename ... Args
+#define BOOST_SIGNALS2_SIGNAL_TEMPLATE_SPECIALIZATION <\
+ R (Args...), \
+ Combiner, \
+ Group, \
+ GroupCompare, \
+ SlotFunction, \
+ ExtendedSlotFunction, \
+ Mutex>
+
+#define BOOST_SIGNALS2_STD_FUNCTIONAL_BASE(result_type) \
+ std_functional_base<result_type , Args...>
+
+#define BOOST_SIGNALS2_PP_COMMA_IF(arity) ,
+
+#endif // BOOST_NO_CXX11_VARIADIC_TEMPLATES
+
+#endif // BOOST_SIGNALS2_SIGNALS_COMMON_MACROS_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/slot_call_iterator.hpp b/3rdParty/Boost/src/boost/signals2/detail/slot_call_iterator.hpp
new file mode 100644
index 0000000..99eec1d
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/slot_call_iterator.hpp
@@ -0,0 +1,147 @@
+// Boost.Signals2 library
+
+// Copyright Douglas Gregor 2001-2004.
+// Copyright Frank Mori Hess 2007-2008.
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_SLOT_CALL_ITERATOR_HPP
+#define BOOST_SIGNALS2_SLOT_CALL_ITERATOR_HPP
+
+#include <boost/assert.hpp>
+#include <boost/aligned_storage.hpp>
+#include <boost/iterator/iterator_facade.hpp>
+#include <boost/optional.hpp>
+#include <boost/scoped_ptr.hpp>
+#include <boost/signals2/connection.hpp>
+#include <boost/signals2/slot_base.hpp>
+#include <boost/signals2/detail/auto_buffer.hpp>
+#include <boost/signals2/detail/unique_lock.hpp>
+#include <boost/weak_ptr.hpp>
+
+namespace boost {
+ namespace signals2 {
+ namespace detail {
+ template<typename ResultType, typename Function>
+ class slot_call_iterator_cache
+ {
+ public:
+ slot_call_iterator_cache(const Function &f_arg):
+ f(f_arg),
+ connected_slot_count(0),
+ disconnected_slot_count(0)
+ {}
+ optional<ResultType> result;
+ typedef auto_buffer<void_shared_ptr_variant, store_n_objects<10> > tracked_ptrs_type;
+ tracked_ptrs_type tracked_ptrs;
+ Function f;
+ unsigned connected_slot_count;
+ unsigned disconnected_slot_count;
+ };
+
+ // Generates a slot call iterator. Essentially, this is an iterator that:
+ // - skips over disconnected slots in the underlying list
+ // - calls the connected slots when dereferenced
+ // - caches the result of calling the slots
+ template<typename Function, typename Iterator, typename ConnectionBody>
+ class slot_call_iterator_t
+ : public boost::iterator_facade<slot_call_iterator_t<Function, Iterator, ConnectionBody>,
+ typename Function::result_type,
+ boost::single_pass_traversal_tag,
+ typename Function::result_type const&>
+ {
+ typedef boost::iterator_facade<slot_call_iterator_t<Function, Iterator, ConnectionBody>,
+ typename Function::result_type,
+ boost::single_pass_traversal_tag,
+ typename Function::result_type const&>
+ inherited;
+
+ typedef typename Function::result_type result_type;
+
+ friend class boost::iterator_core_access;
+
+ public:
+ slot_call_iterator_t(Iterator iter_in, Iterator end_in,
+ slot_call_iterator_cache<result_type, Function> &c):
+ iter(iter_in), end(end_in),
+ cache(&c), callable_iter(end_in)
+ {
+ lock_next_callable();
+ }
+
+ typename inherited::reference
+ dereference() const
+ {
+ if (!cache->result) {
+ try
+ {
+ cache->result.reset(cache->f(*iter));
+ }
+ catch(expired_slot &)
+ {
+ (*iter)->disconnect();
+ throw;
+ }
+ }
+ return cache->result.get();
+ }
+
+ void increment()
+ {
+ ++iter;
+ lock_next_callable();
+ cache->result.reset();
+ }
+
+ bool equal(const slot_call_iterator_t& other) const
+ {
+ return iter == other.iter;
+ }
+
+ private:
+ typedef unique_lock<connection_body_base> lock_type;
+
+ void lock_next_callable() const
+ {
+ if(iter == callable_iter)
+ {
+ return;
+ }
+ for(;iter != end; ++iter)
+ {
+ lock_type lock(**iter);
+ cache->tracked_ptrs.clear();
+ (*iter)->nolock_grab_tracked_objects(std::back_inserter(cache->tracked_ptrs));
+ if((*iter)->nolock_nograb_connected())
+ {
+ ++cache->connected_slot_count;
+ }else
+ {
+ ++cache->disconnected_slot_count;
+ }
+ if((*iter)->nolock_nograb_blocked() == false)
+ {
+ callable_iter = iter;
+ break;
+ }
+ }
+ if(iter == end)
+ {
+ callable_iter = end;
+ }
+ }
+
+ mutable Iterator iter;
+ Iterator end;
+ slot_call_iterator_cache<result_type, Function> *cache;
+ mutable Iterator callable_iter;
+ };
+ } // end namespace detail
+ } // end namespace BOOST_SIGNALS_NAMESPACE
+} // end namespace boost
+
+#endif // BOOST_SIGNALS2_SLOT_CALL_ITERATOR_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/slot_groups.hpp b/3rdParty/Boost/src/boost/signals2/detail/slot_groups.hpp
new file mode 100644
index 0000000..5e1853a
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/slot_groups.hpp
@@ -0,0 +1,235 @@
+// Boost.Signals2 library
+
+// Copyright Frank Mori Hess 2007-2008.
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_SLOT_GROUPS_HPP
+#define BOOST_SIGNALS2_SLOT_GROUPS_HPP
+
+#include <boost/signals2/connection.hpp>
+#include <boost/optional.hpp>
+#include <list>
+#include <map>
+#include <utility>
+
+namespace boost {
+ namespace signals2 {
+ namespace detail {
+ enum slot_meta_group {front_ungrouped_slots, grouped_slots, back_ungrouped_slots};
+ template<typename Group>
+ struct group_key
+ {
+ typedef std::pair<enum slot_meta_group, boost::optional<Group> > type;
+ };
+ template<typename Group, typename GroupCompare>
+ class group_key_less
+ {
+ public:
+ group_key_less()
+ {}
+ group_key_less(const GroupCompare &group_compare): _group_compare(group_compare)
+ {}
+ bool operator ()(const typename group_key<Group>::type &key1, const typename group_key<Group>::type &key2) const
+ {
+ if(key1.first != key2.first) return key1.first < key2.first;
+ if(key1.first != grouped_slots) return false;
+ return _group_compare(key1.second.get(), key2.second.get());
+ }
+ private:
+ GroupCompare _group_compare;
+ };
+ template<typename Group, typename GroupCompare, typename ValueType>
+ class grouped_list
+ {
+ public:
+ typedef group_key_less<Group, GroupCompare> group_key_compare_type;
+ private:
+ typedef std::list<ValueType> list_type;
+ typedef std::map
+ <
+ typename group_key<Group>::type,
+ typename list_type::iterator,
+ group_key_compare_type
+ > map_type;
+ typedef typename map_type::iterator map_iterator;
+ typedef typename map_type::const_iterator const_map_iterator;
+ public:
+ typedef typename list_type::iterator iterator;
+ typedef typename list_type::const_iterator const_iterator;
+ typedef typename group_key<Group>::type group_key_type;
+
+ grouped_list(const group_key_compare_type &group_key_compare):
+ _group_key_compare(group_key_compare)
+ {}
+ grouped_list(const grouped_list &other): _list(other._list),
+ _group_map(other._group_map), _group_key_compare(other._group_key_compare)
+ {
+ // fix up _group_map
+ typename map_type::const_iterator other_map_it;
+ typename list_type::iterator this_list_it = _list.begin();
+ typename map_type::iterator this_map_it = _group_map.begin();
+ for(other_map_it = other._group_map.begin();
+ other_map_it != other._group_map.end();
+ ++other_map_it, ++this_map_it)
+ {
+ BOOST_ASSERT(this_map_it != _group_map.end());
+ this_map_it->second = this_list_it;
+ typename list_type::const_iterator other_list_it = other.get_list_iterator(other_map_it);
+ typename map_type::const_iterator other_next_map_it = other_map_it;
+ ++other_next_map_it;
+ typename list_type::const_iterator other_next_list_it = other.get_list_iterator(other_next_map_it);
+ while(other_list_it != other_next_list_it)
+ {
+ ++other_list_it;
+ ++this_list_it;
+ }
+ }
+ }
+ iterator begin()
+ {
+ return _list.begin();
+ }
+ iterator end()
+ {
+ return _list.end();
+ }
+ iterator lower_bound(const group_key_type &key)
+ {
+ map_iterator map_it = _group_map.lower_bound(key);
+ return get_list_iterator(map_it);
+ }
+ iterator upper_bound(const group_key_type &key)
+ {
+ map_iterator map_it = _group_map.upper_bound(key);
+ return get_list_iterator(map_it);
+ }
+ void push_front(const group_key_type &key, const ValueType &value)
+ {
+ map_iterator map_it;
+ if(key.first == front_ungrouped_slots)
+ {// optimization
+ map_it = _group_map.begin();
+ }else
+ {
+ map_it = _group_map.lower_bound(key);
+ }
+ m_insert(map_it, key, value);
+ }
+ void push_back(const group_key_type &key, const ValueType &value)
+ {
+ map_iterator map_it;
+ if(key.first == back_ungrouped_slots)
+ {// optimization
+ map_it = _group_map.end();
+ }else
+ {
+ map_it = _group_map.upper_bound(key);
+ }
+ m_insert(map_it, key, value);
+ }
+ void erase(const group_key_type &key)
+ {
+ map_iterator map_it = _group_map.lower_bound(key);
+ iterator begin_list_it = get_list_iterator(map_it);
+ iterator end_list_it = upper_bound(key);
+ if(begin_list_it != end_list_it)
+ {
+ _list.erase(begin_list_it, end_list_it);
+ _group_map.erase(map_it);
+ }
+ }
+ iterator erase(const group_key_type &key, const iterator &it)
+ {
+ BOOST_ASSERT(it != _list.end());
+ map_iterator map_it = _group_map.lower_bound(key);
+ BOOST_ASSERT(map_it != _group_map.end());
+ BOOST_ASSERT(weakly_equivalent(map_it->first, key));
+ if(map_it->second == it)
+ {
+ iterator next = it;
+ ++next;
+ // if next is in same group
+ if(next != upper_bound(key))
+ {
+ _group_map[key] = next;
+ }else
+ {
+ _group_map.erase(map_it);
+ }
+ }
+ return _list.erase(it);
+ }
+ void clear()
+ {
+ _list.clear();
+ _group_map.clear();
+ }
+ private:
+ /* Suppress default assignment operator, since it has the wrong semantics. */
+ grouped_list& operator=(const grouped_list &other);
+
+ bool weakly_equivalent(const group_key_type &arg1, const group_key_type &arg2)
+ {
+ if(_group_key_compare(arg1, arg2)) return false;
+ if(_group_key_compare(arg2, arg1)) return false;
+ return true;
+ }
+ void m_insert(const map_iterator &map_it, const group_key_type &key, const ValueType &value)
+ {
+ iterator list_it = get_list_iterator(map_it);
+ iterator new_it = _list.insert(list_it, value);
+ if(map_it != _group_map.end() && weakly_equivalent(key, map_it->first))
+ {
+ _group_map.erase(map_it);
+ }
+ map_iterator lower_bound_it = _group_map.lower_bound(key);
+ if(lower_bound_it == _group_map.end() ||
+ weakly_equivalent(lower_bound_it->first, key) == false)
+ {
+ /* doing the following instead of just
+ _group_map[key] = new_it;
+ to avoid bogus error when enabling checked iterators with g++ */
+ _group_map.insert(typename map_type::value_type(key, new_it));
+ }
+ }
+ iterator get_list_iterator(const const_map_iterator &map_it)
+ {
+ iterator list_it;
+ if(map_it == _group_map.end())
+ {
+ list_it = _list.end();
+ }else
+ {
+ list_it = map_it->second;
+ }
+ return list_it;
+ }
+ const_iterator get_list_iterator(const const_map_iterator &map_it) const
+ {
+ const_iterator list_it;
+ if(map_it == _group_map.end())
+ {
+ list_it = _list.end();
+ }else
+ {
+ list_it = map_it->second;
+ }
+ return list_it;
+ }
+
+ list_type _list;
+ // holds iterators to first list item in each group
+ map_type _group_map;
+ group_key_compare_type _group_key_compare;
+ };
+ } // end namespace detail
+ enum connect_position { at_back, at_front };
+ } // end namespace signals2
+} // end namespace boost
+
+#endif // BOOST_SIGNALS2_SLOT_GROUPS_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/slot_template.hpp b/3rdParty/Boost/src/boost/signals2/detail/slot_template.hpp
new file mode 100644
index 0000000..fc19f51
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/slot_template.hpp
@@ -0,0 +1,187 @@
+// Boost.Signals2 library
+
+// Copyright Frank Mori Hess 2007-2008.
+// Copyright Timmo Stange 2007.
+// Copyright Douglas Gregor 2001-2004. Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+// This file is included iteratively, and should not be protected from multiple inclusion
+
+#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
+#define BOOST_SIGNALS2_NUM_ARGS BOOST_PP_ITERATION()
+#else
+#define BOOST_SIGNALS2_NUM_ARGS 1
+#endif
+
+
+namespace boost
+{
+ namespace signals2
+ {
+#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
+ template<typename Signature, typename SlotFunction> class slot;
+#else
+ template<typename Signature, typename SlotFunction = boost::function<Signature> >
+ class slot;
+
+#if BOOST_WORKAROUND(BOOST_MSVC, <= 1900)
+ template<typename Signature, typename SlotFunction> class slot{};
+#endif
+#endif // BOOST_NO_CXX11_VARIADIC_TEMPLATES
+
+ template<BOOST_SIGNALS2_SLOT_TEMPLATE_SPECIALIZATION_DECL(BOOST_SIGNALS2_NUM_ARGS)>
+ class BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS) BOOST_SIGNALS2_SLOT_TEMPLATE_SPECIALIZATION
+ : public slot_base, public detail::BOOST_SIGNALS2_STD_FUNCTIONAL_BASE(R)
+
+ {
+ public:
+ template<BOOST_SIGNALS2_PREFIXED_SIGNATURE_TEMPLATE_DECL(BOOST_SIGNALS2_NUM_ARGS, Other), typename OtherSlotFunction>
+ friend class BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS);
+
+ typedef SlotFunction slot_function_type;
+ typedef R result_type;
+ typedef typename mpl::identity<BOOST_SIGNALS2_SIGNATURE_FUNCTION_TYPE(BOOST_SIGNALS2_NUM_ARGS)>::type signature_type;
+
+#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
+
+// typedef Tn argn_type;
+#define BOOST_SIGNALS2_MISC_STATEMENT(z, n, data) \
+ typedef BOOST_PP_CAT(T, BOOST_PP_INC(n)) BOOST_PP_CAT(BOOST_PP_CAT(arg, BOOST_PP_INC(n)), _type);
+ BOOST_PP_REPEAT(BOOST_SIGNALS2_NUM_ARGS, BOOST_SIGNALS2_MISC_STATEMENT, ~)
+#undef BOOST_SIGNALS2_MISC_STATEMENT
+#if BOOST_SIGNALS2_NUM_ARGS == 1
+ typedef arg1_type argument_type;
+#elif BOOST_SIGNALS2_NUM_ARGS == 2
+ typedef arg1_type first_argument_type;
+ typedef arg2_type second_argument_type;
+#endif
+
+ template<unsigned n> class arg : public
+ detail::BOOST_SIGNALS2_PREPROCESSED_ARG_N_TYPE_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ <n BOOST_SIGNALS2_PP_COMMA_IF(BOOST_SIGNALS2_NUM_ARGS)
+ BOOST_SIGNALS2_ARGS_TEMPLATE_INSTANTIATION(BOOST_SIGNALS2_NUM_ARGS)>
+ {};
+
+ BOOST_STATIC_CONSTANT(int, arity = BOOST_SIGNALS2_NUM_ARGS);
+
+#else // BOOST_NO_CXX11_VARIADIC_TEMPLATES
+
+ template<unsigned n> class arg
+ {
+ public:
+ typedef typename detail::variadic_arg_type<n, Args...>::type type;
+ };
+ BOOST_STATIC_CONSTANT(int, arity = sizeof...(Args));
+
+#endif // BOOST_NO_CXX11_VARIADIC_TEMPLATES
+
+ template<typename F>
+ BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)(const F& f)
+ {
+ init_slot_function(f);
+ }
+ // copy constructors
+#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
+ template<BOOST_SIGNALS2_PREFIXED_SIGNATURE_TEMPLATE_DECL(BOOST_SIGNALS2_NUM_ARGS, Other), typename OtherSlotFunction>
+ BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)(const BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)
+ <BOOST_SIGNALS2_PREFIXED_SIGNATURE_TEMPLATE_INSTANTIATION(BOOST_SIGNALS2_NUM_ARGS, Other), OtherSlotFunction> &other_slot):
+ slot_base(other_slot), _slot_function(other_slot._slot_function)
+ {
+ }
+#endif
+ template<typename Signature, typename OtherSlotFunction>
+ BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)(const slot<Signature, OtherSlotFunction> &other_slot):
+ slot_base(other_slot), _slot_function(other_slot._slot_function)
+ {
+ }
+ // bind syntactic sugar
+ BOOST_SIGNALS2_SLOT_N_BINDING_CONSTRUCTORS
+ // invocation
+ R operator()(BOOST_SIGNALS2_SIGNATURE_FULL_ARGS(BOOST_SIGNALS2_NUM_ARGS))
+ {
+ locked_container_type locked_objects = lock();
+ return _slot_function(BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(BOOST_SIGNALS2_NUM_ARGS));
+ }
+ R operator()(BOOST_SIGNALS2_SIGNATURE_FULL_ARGS(BOOST_SIGNALS2_NUM_ARGS)) const
+ {
+ locked_container_type locked_objects = lock();
+ return _slot_function(BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(BOOST_SIGNALS2_NUM_ARGS));
+ }
+ // tracking
+ BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)& track(const weak_ptr<void> &tracked) {
+ _tracked_objects.push_back(tracked);
+ return *this;
+ }
+ BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)& track(const signal_base &signal)
+ {
+ track_signal(signal);
+ return *this;
+ }
+ BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)& track(const slot_base &slot)
+ {
+ tracked_container_type::const_iterator it;
+ for(it = slot.tracked_objects().begin(); it != slot.tracked_objects().end(); ++it)
+ {
+ _tracked_objects.push_back(*it);
+ }
+ return *this;
+ }
+ template<typename ForeignWeakPtr>
+ BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)& track_foreign(const ForeignWeakPtr &tracked,
+ typename weak_ptr_traits<ForeignWeakPtr>::shared_type * /*SFINAE*/ = 0)
+ {
+ _tracked_objects.push_back(detail::foreign_void_weak_ptr(tracked));
+ return *this;
+ }
+ template<typename ForeignSharedPtr>
+ BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)& track_foreign(const ForeignSharedPtr &tracked,
+ typename shared_ptr_traits<ForeignSharedPtr>::weak_type * /*SFINAE*/ = 0)
+ {
+ _tracked_objects.push_back
+ (
+ detail::foreign_void_weak_ptr
+ (
+ typename shared_ptr_traits<ForeignSharedPtr>::weak_type(tracked)
+ )
+ );
+ return *this;
+ }
+
+ const slot_function_type& slot_function() const {return _slot_function;}
+ slot_function_type& slot_function() {return _slot_function;}
+ private:
+ template<typename F>
+ void init_slot_function(const F& f)
+ {
+ _slot_function = detail::get_invocable_slot(f, detail::tag_type(f));
+ signals2::detail::tracked_objects_visitor visitor(this);
+ boost::visit_each(visitor, f);
+ }
+
+ SlotFunction _slot_function;
+ };
+
+#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
+ namespace detail
+ {
+ template<unsigned arity, typename Signature, typename SlotFunction>
+ class slotN;
+ // partial template specialization
+ template<typename Signature, typename SlotFunction>
+ class slotN<BOOST_SIGNALS2_NUM_ARGS, Signature, SlotFunction>
+ {
+ public:
+ typedef BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)<
+ BOOST_SIGNALS2_PORTABLE_SIGNATURE(BOOST_SIGNALS2_NUM_ARGS, Signature),
+ SlotFunction> type;
+ };
+ }
+#endif
+ } // end namespace signals2
+} // end namespace boost
+
+#undef BOOST_SIGNALS2_NUM_ARGS
diff --git a/3rdParty/Boost/src/boost/signals2/detail/tracked_objects_visitor.hpp b/3rdParty/Boost/src/boost/signals2/detail/tracked_objects_visitor.hpp
new file mode 100644
index 0000000..71a1d50
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/tracked_objects_visitor.hpp
@@ -0,0 +1,98 @@
+// Boost.Signals2 library
+
+// Copyright Frank Mori Hess 2007-2008.
+// Copyright Timmo Stange 2007.
+// Copyright Douglas Gregor 2001-2004. Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_TRACKED_OBJECTS_VISITOR_HPP
+#define BOOST_SIGNALS2_TRACKED_OBJECTS_VISITOR_HPP
+
+#include <boost/mpl/bool.hpp>
+#include <boost/ref.hpp>
+#include <boost/signals2/detail/signals_common.hpp>
+#include <boost/signals2/slot_base.hpp>
+#include <boost/signals2/trackable.hpp>
+#include <boost/type_traits/is_function.hpp>
+#include <boost/type_traits/is_pointer.hpp>
+#include <boost/type_traits/remove_pointer.hpp>
+#include <boost/utility/addressof.hpp>
+
+namespace boost
+{
+ namespace signals2
+ {
+ namespace detail
+ {
+ // Visitor to collect tracked objects from a bound function.
+ class tracked_objects_visitor
+ {
+ public:
+ tracked_objects_visitor(slot_base *slot) : slot_(slot)
+ {}
+ template<typename T>
+ void operator()(const T& t) const
+ {
+ m_visit_reference_wrapper(t, mpl::bool_<is_reference_wrapper<T>::value>());
+ }
+ private:
+ template<typename T>
+ void m_visit_reference_wrapper(const reference_wrapper<T> &t, const mpl::bool_<true> &) const
+ {
+ m_visit_pointer(t.get_pointer(), mpl::bool_<true>());
+ }
+ template<typename T>
+ void m_visit_reference_wrapper(const T &t, const mpl::bool_<false> &) const
+ {
+ m_visit_pointer(t, mpl::bool_<is_pointer<T>::value>());
+ }
+ template<typename T>
+ void m_visit_pointer(const T &t, const mpl::bool_<true> &) const
+ {
+ m_visit_not_function_pointer(t, mpl::bool_<!is_function<typename remove_pointer<T>::type>::value>());
+ }
+ template<typename T>
+ void m_visit_pointer(const T &t, const mpl::bool_<false> &) const
+ {
+ m_visit_pointer(boost::addressof(t), mpl::bool_<true>());
+ }
+ template<typename T>
+ void m_visit_not_function_pointer(const T *t, const mpl::bool_<true> &) const
+ {
+ m_visit_signal(t, mpl::bool_<is_signal<T>::value>());
+ }
+ template<typename T>
+ void m_visit_not_function_pointer(const T &, const mpl::bool_<false> &) const
+ {}
+ template<typename T>
+ void m_visit_signal(const T *signal, const mpl::bool_<true> &) const
+ {
+ if(signal)
+ slot_->track_signal(*signal);
+ }
+ template<typename T>
+ void m_visit_signal(const T &t, const mpl::bool_<false> &) const
+ {
+ add_if_trackable(t);
+ }
+ void add_if_trackable(const trackable *trackable) const
+ {
+ if(trackable)
+ slot_->_tracked_objects.push_back(trackable->get_shared_ptr());
+ }
+ void add_if_trackable(const void *) const {}
+
+ mutable slot_base * slot_;
+ };
+
+
+ } // end namespace detail
+ } // end namespace signals2
+} // end namespace boost
+
+#endif // BOOST_SIGNALS2_TRACKED_OBJECTS_VISITOR_HPP
+
diff --git a/3rdParty/Boost/src/boost/signals2/detail/unique_lock.hpp b/3rdParty/Boost/src/boost/signals2/detail/unique_lock.hpp
new file mode 100644
index 0000000..13fecf2
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/unique_lock.hpp
@@ -0,0 +1,42 @@
+/*
+ Provides a basic subset of boost::unique_lock functionality. Provided only because
+ including boost/thread/locks.hpp requires linking to thread library
+*/
+// Copyright Frank Mori Hess 2008.
+// Distributed under the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org/libs/signals2 for library home page.
+
+#ifndef BOOST_SIGNALS2_UNIQUE_LOCK_HPP
+#define BOOST_SIGNALS2_UNIQUE_LOCK_HPP
+
+#include <boost/noncopyable.hpp>
+
+namespace boost
+{
+ namespace signals2
+ {
+ namespace detail
+ {
+ template<typename Mutex>
+ class unique_lock: public noncopyable
+ {
+ public:
+ unique_lock(Mutex &m): _mutex(m)
+ {
+ _mutex.lock();
+ }
+ ~unique_lock()
+ {
+ _mutex.unlock();
+ }
+ private:
+ Mutex &_mutex;
+ };
+ } // namespace detail
+ } // namespace signals2
+} // namespace boost
+
+#endif // BOOST_SIGNALS2_UNIQUE_LOCK_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/variadic_arg_type.hpp b/3rdParty/Boost/src/boost/signals2/detail/variadic_arg_type.hpp
new file mode 100644
index 0000000..14d54b2
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/variadic_arg_type.hpp
@@ -0,0 +1,49 @@
+// Copyright Frank Mori Hess 2009
+//
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_DETAIL_VARIADIC_ARG_TYPE_HPP
+#define BOOST_SIGNALS2_DETAIL_VARIADIC_ARG_TYPE_HPP
+
+#include <functional>
+
+namespace boost
+{
+ namespace signals2
+ {
+ namespace detail
+ {
+ template<unsigned, typename ... Args> class variadic_arg_type;
+
+ template<typename T, typename ... Args> class variadic_arg_type<0, T, Args...>
+ {
+ public:
+ typedef T type;
+ };
+
+ template<unsigned n, typename T, typename ... Args> class variadic_arg_type<n, T, Args...>
+ {
+ public:
+ typedef typename variadic_arg_type<n - 1, Args...>::type type;
+ };
+
+ template <typename R, typename ... Args>
+ struct std_functional_base
+ {};
+ template <typename R, typename T1>
+ struct std_functional_base<R, T1>: public std::unary_function<T1, R>
+ {};
+ template <typename R, typename T1, typename T2>
+ struct std_functional_base<R, T1, T2>: public std::binary_function<T1, T2, R>
+ {};
+ } // namespace detail
+ } // namespace signals2
+} // namespace boost
+
+
+#endif // BOOST_SIGNALS2_DETAIL_VARIADIC_ARG_TYPE_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/detail/variadic_slot_invoker.hpp b/3rdParty/Boost/src/boost/signals2/detail/variadic_slot_invoker.hpp
new file mode 100644
index 0000000..6d9227e
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/detail/variadic_slot_invoker.hpp
@@ -0,0 +1,139 @@
+/*
+ Helper class used by variadic implementation of variadic boost::signals2::signal.
+
+ Author: Frank Mori Hess <fmhess@users.sourceforge.net>
+ Begin: 2009-05-27
+*/
+// Copyright Frank Mori Hess 2009
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_DETAIL_VARIADIC_SLOT_INVOKER_HPP
+#define BOOST_SIGNALS2_DETAIL_VARIADIC_SLOT_INVOKER_HPP
+
+#if defined(_MSVC_VER)
+# pragma warning(push)
+# pragma warning(disable:4100) // unreferenced formal parameter
+#endif
+
+#include <boost/mpl/size_t.hpp>
+#include <boost/signals2/detail/variadic_arg_type.hpp>
+
+// if compiler has std::tuple use it instead of boost::tuple
+// because boost::tuple does not have variadic template support at present.
+#ifdef BOOST_NO_CXX11_HDR_TUPLE
+#include <boost/tuple/tuple.hpp>
+#define BOOST_SIGNALS2_TUPLE boost::tuple
+#define BOOST_SIGNALS2_GET boost::get
+#else
+#include <tuple>
+#define BOOST_SIGNALS2_TUPLE std::tuple
+#define BOOST_SIGNALS2_GET std::get
+#endif
+
+namespace boost
+{
+ namespace signals2
+ {
+ namespace detail
+ {
+ template<unsigned ... values> class unsigned_meta_array {};
+
+ template<typename UnsignedMetaArray, unsigned n> class unsigned_meta_array_appender;
+
+ template<unsigned n, unsigned ... Args>
+ class unsigned_meta_array_appender<unsigned_meta_array<Args...>, n>
+ {
+ public:
+ typedef unsigned_meta_array<Args..., n> type;
+ };
+
+ template<unsigned n> class make_unsigned_meta_array;
+
+ template<> class make_unsigned_meta_array<0>
+ {
+ public:
+ typedef unsigned_meta_array<> type;
+ };
+
+ template<> class make_unsigned_meta_array<1>
+ {
+ public:
+ typedef unsigned_meta_array<0> type;
+ };
+
+ template<unsigned n> class make_unsigned_meta_array
+ {
+ public:
+ typedef typename unsigned_meta_array_appender<typename make_unsigned_meta_array<n-1>::type, n - 1>::type type;
+ };
+
+ template<typename R>
+ class call_with_tuple_args
+ {
+ public:
+ typedef R result_type;
+
+ template<typename Func, typename ... Args, std::size_t N>
+ R operator()(Func &func, BOOST_SIGNALS2_TUPLE<Args...> args, mpl::size_t<N>) const
+ {
+ typedef typename make_unsigned_meta_array<N>::type indices_type;
+ typename Func::result_type *resolver = 0;
+ return m_invoke(resolver, func, indices_type(), args);
+ }
+ private:
+ template<typename T, typename Func, unsigned ... indices, typename ... Args>
+ R m_invoke(T *, Func &func, unsigned_meta_array<indices...>, BOOST_SIGNALS2_TUPLE<Args...> args) const
+ {
+ return func(BOOST_SIGNALS2_GET<indices>(args)...);
+ }
+ template<typename Func, unsigned ... indices, typename ... Args>
+ R m_invoke(void *, Func &func, unsigned_meta_array<indices...>, BOOST_SIGNALS2_TUPLE<Args...> args) const
+ {
+ func(BOOST_SIGNALS2_GET<indices>(args)...);
+ return R();
+ }
+ };
+
+ template<typename R, typename ... Args>
+ class variadic_slot_invoker
+ {
+ public:
+ typedef R result_type;
+
+ variadic_slot_invoker(Args & ... args): _args(args...)
+ {}
+ template<typename ConnectionBodyType>
+ result_type operator ()(const ConnectionBodyType &connectionBody) const
+ {
+ result_type *resolver = 0;
+ return m_invoke(connectionBody,
+ resolver);
+ }
+ private:
+ template<typename ConnectionBodyType>
+ result_type m_invoke(const ConnectionBodyType &connectionBody,
+ const void_type *) const
+ {
+ return call_with_tuple_args<result_type>()(connectionBody->slot.slot_function(), _args, mpl::size_t<sizeof...(Args)>());
+ }
+ template<typename ConnectionBodyType>
+ result_type m_invoke(const ConnectionBodyType &connectionBody, ...) const
+ {
+ return call_with_tuple_args<result_type>()(connectionBody->slot.slot_function(), _args, mpl::size_t<sizeof...(Args)>());
+ }
+ BOOST_SIGNALS2_TUPLE<Args& ...> _args;
+ };
+ } // namespace detail
+ } // namespace signals2
+} // namespace boost
+
+#if defined(_MSVC_VER)
+# pragma warning(pop)
+#endif
+
+#endif // BOOST_SIGNALS2_DETAIL_VARIADIC_SLOT_INVOKER_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/dummy_mutex.hpp b/3rdParty/Boost/src/boost/signals2/dummy_mutex.hpp
new file mode 100644
index 0000000..f2600f1
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/dummy_mutex.hpp
@@ -0,0 +1,28 @@
+// A model of the Lockable concept from Boost.Thread which
+// does nothing. It can be passed as the Mutex template parameter
+// for a signal, if the user wishes to disable thread-safety
+// (presumably for performance reasons).
+
+// Copyright Frank Mori Hess 2008.
+// Distributed under the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org/libs/signals2 for library home page.
+
+#ifndef BOOST_SIGNALS2_DUMMY_MUTEX_HPP
+#define BOOST_SIGNALS2_DUMMY_MUTEX_HPP
+
+namespace boost {
+ namespace signals2 {
+ class dummy_mutex
+ {
+ public:
+ void lock() {}
+ bool try_lock() {return true;}
+ void unlock() {}
+ };
+ } // end namespace signals2
+} // end namespace boost
+
+#endif // BOOST_SIGNALS2_DUMMY_MUTEX_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/expired_slot.hpp b/3rdParty/Boost/src/boost/signals2/expired_slot.hpp
new file mode 100644
index 0000000..fa6db22
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/expired_slot.hpp
@@ -0,0 +1,31 @@
+// Boost.Signals2 library
+
+// Copyright Frank Mori Hess 2007-2010.
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_EXPIRED_SLOT_HPP
+#define BOOST_SIGNALS2_EXPIRED_SLOT_HPP
+
+#include <boost/smart_ptr/bad_weak_ptr.hpp>
+
+namespace boost
+{
+ namespace signals2
+ {
+ class expired_slot: public bad_weak_ptr
+ {
+ public:
+ virtual char const * what() const throw()
+ {
+ return "boost::signals2::expired_slot";
+ }
+ };
+ }
+} // end namespace boost
+
+#endif // BOOST_SIGNALS2_EXPIRED_SLOT_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/last_value.hpp b/3rdParty/Boost/src/boost/signals2/last_value.hpp
new file mode 100644
index 0000000..51cc541
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/last_value.hpp
@@ -0,0 +1,78 @@
+// last_value function object (documented as part of Boost.Signals)
+
+// Copyright Frank Mori Hess 2007.
+// Copyright Douglas Gregor 2001-2003. Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_LAST_VALUE_HPP
+#define BOOST_SIGNALS2_LAST_VALUE_HPP
+
+#include <boost/optional.hpp>
+#include <boost/signals2/expired_slot.hpp>
+#include <boost/throw_exception.hpp>
+#include <stdexcept>
+
+namespace boost {
+ namespace signals2 {
+
+ // no_slots_error is thrown when we are unable to generate a return value
+ // due to no slots being connected to the signal.
+ class no_slots_error: public std::exception
+ {
+ public:
+ virtual const char* what() const throw() {return "boost::signals2::no_slots_error";}
+ };
+
+ template<typename T>
+ class last_value {
+ public:
+ typedef T result_type;
+
+ template<typename InputIterator>
+ T operator()(InputIterator first, InputIterator last) const
+ {
+ if(first == last)
+ {
+ boost::throw_exception(no_slots_error());
+ }
+ optional<T> value;
+ while (first != last)
+ {
+ try
+ {
+ value = *first;
+ }
+ catch(const expired_slot &) {}
+ ++first;
+ }
+ if(value) return value.get();
+ boost::throw_exception(no_slots_error());
+ }
+ };
+
+ template<>
+ class last_value<void> {
+ public:
+ typedef void result_type;
+ template<typename InputIterator>
+ result_type operator()(InputIterator first, InputIterator last) const
+ {
+ while (first != last)
+ {
+ try
+ {
+ *first;
+ }
+ catch(const expired_slot &) {}
+ ++first;
+ }
+ return;
+ }
+ };
+ } // namespace signals2
+} // namespace boost
+#endif // BOOST_SIGNALS2_LAST_VALUE_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/mutex.hpp b/3rdParty/Boost/src/boost/signals2/mutex.hpp
new file mode 100644
index 0000000..e58aca1
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/mutex.hpp
@@ -0,0 +1,38 @@
+//
+// boost/signals2/mutex.hpp - header-only mutex
+//
+// Copyright (c) 2002, 2003 Peter Dimov and Multi Media Ltd.
+// Copyright (c) 2008 Frank Mori Hess
+//
+// Distributed under the Boost Software License, Version 1.0. (See
+// accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+//
+// boost::signals2::mutex is a modification of
+// boost::detail::lightweight_mutex to follow the newer Lockable
+// concept of Boost.Thread.
+//
+
+#ifndef BOOST_SIGNALS2_MUTEX_HPP
+#define BOOST_SIGNALS2_MUTEX_HPP
+
+// MS compatible compilers support #pragma once
+
+#if defined(_MSC_VER)
+# pragma once
+#endif
+
+#include <boost/config.hpp>
+
+#if !defined(BOOST_HAS_THREADS)
+# include <boost/signals2/detail/lwm_nop.hpp>
+#elif defined(BOOST_HAS_PTHREADS)
+# include <boost/signals2/detail/lwm_pthreads.hpp>
+#elif defined(BOOST_HAS_WINTHREADS)
+# include <boost/signals2/detail/lwm_win32_cs.hpp>
+#else
+// Use #define BOOST_DISABLE_THREADS to avoid the error
+# error Unrecognized threading platform
+#endif
+
+#endif // #ifndef BOOST_SIGNALS2_MUTEX_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/optional_last_value.hpp b/3rdParty/Boost/src/boost/signals2/optional_last_value.hpp
new file mode 100644
index 0000000..766e99b
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/optional_last_value.hpp
@@ -0,0 +1,65 @@
+// optional_last_value function object (documented as part of Boost.Signals2)
+
+// Copyright Frank Mori Hess 2007-2008.
+// Copyright Douglas Gregor 2001-2003.
+// Distributed under the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org/libs/signals2 for library home page.
+
+#ifndef BOOST_SIGNALS2_OPTIONAL_LAST_VALUE_HPP
+#define BOOST_SIGNALS2_OPTIONAL_LAST_VALUE_HPP
+
+#include <boost/optional.hpp>
+#include <boost/signals2/expired_slot.hpp>
+
+namespace boost {
+ namespace signals2 {
+
+ template<typename T>
+ class optional_last_value
+ {
+ public:
+ typedef optional<T> result_type;
+
+ template<typename InputIterator>
+ optional<T> operator()(InputIterator first, InputIterator last) const
+ {
+ optional<T> value;
+ while (first != last)
+ {
+ try
+ {
+ value = *first;
+ }
+ catch(const expired_slot &) {}
+ ++first;
+ }
+ return value;
+ }
+ };
+
+ template<>
+ class optional_last_value<void>
+ {
+ public:
+ typedef void result_type;
+ template<typename InputIterator>
+ result_type operator()(InputIterator first, InputIterator last) const
+ {
+ while (first != last)
+ {
+ try
+ {
+ *first;
+ }
+ catch(const expired_slot &) {}
+ ++first;
+ }
+ return;
+ }
+ };
+ } // namespace signals2
+} // namespace boost
+#endif // BOOST_SIGNALS2_OPTIONAL_LAST_VALUE_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/postconstructible.hpp b/3rdParty/Boost/src/boost/signals2/postconstructible.hpp
new file mode 100644
index 0000000..faa1444
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/postconstructible.hpp
@@ -0,0 +1,55 @@
+// DEPRECATED in favor of adl_postconstruct with deconstruct<T>().
+// A simple framework for creating objects with postconstructors.
+// The objects must inherit from boost::signals2::postconstructible, and
+// have their lifetimes managed by
+// boost::shared_ptr created with the boost::signals2::deconstruct_ptr()
+// function.
+//
+// Copyright Frank Mori Hess 2007-2008.
+//
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_SIGNALS2_POSTCONSTRUCTIBLE_HPP
+#define BOOST_SIGNALS2_POSTCONSTRUCTIBLE_HPP
+
+namespace boost
+{
+ template<typename T> class shared_ptr;
+
+ namespace signals2
+ {
+ namespace postconstructible_adl_barrier
+ {
+ class postconstructible;
+ }
+ namespace detail
+ {
+ void do_postconstruct(const boost::signals2::postconstructible_adl_barrier::postconstructible *ptr);
+ } // namespace detail
+
+ namespace postconstructible_adl_barrier
+ {
+ class postconstructible
+ {
+ public:
+ friend void detail::do_postconstruct(const postconstructible *ptr);
+ template<typename T>
+ friend void adl_postconstruct(const shared_ptr<T> &sp, postconstructible *p)
+ {
+ p->postconstruct();
+ }
+ protected:
+ postconstructible() {}
+ virtual ~postconstructible() {}
+ virtual void postconstruct() = 0;
+ };
+ } // namespace postconstructible_adl_barrier
+ using postconstructible_adl_barrier::postconstructible;
+
+ }
+}
+
+#endif // BOOST_SIGNALS2_POSTCONSTRUCTIBLE_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/predestructible.hpp b/3rdParty/Boost/src/boost/signals2/predestructible.hpp
new file mode 100644
index 0000000..0f6806d
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/predestructible.hpp
@@ -0,0 +1,46 @@
+// DEPRECATED in favor of adl_predestruct with deconstruct<T>().
+// A simple framework for creating objects with predestructors.
+// The objects must inherit from boost::signals2::predestructible, and
+// have their lifetimes managed by
+// boost::shared_ptr created with the boost::signals2::deconstruct_ptr()
+// function.
+//
+// Copyright Frank Mori Hess 2007-2008.
+//
+//Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_SIGNALS2_PREDESTRUCTIBLE_HPP
+#define BOOST_SIGNALS2_PREDESTRUCTIBLE_HPP
+
+namespace boost
+{
+ namespace signals2
+ {
+ template<typename T> class predestructing_deleter;
+
+ namespace predestructible_adl_barrier
+ {
+ class predestructible
+ {
+ protected:
+ predestructible() {}
+ public:
+ template<typename T>
+ friend void adl_postconstruct(const shared_ptr<T> &, ...)
+ {}
+ friend void adl_predestruct(predestructible *p)
+ {
+ p->predestruct();
+ }
+ virtual ~predestructible() {}
+ virtual void predestruct() = 0;
+ };
+ } // namespace predestructible_adl_barrier
+ using predestructible_adl_barrier::predestructible;
+ }
+}
+
+#endif // BOOST_SIGNALS2_PREDESTRUCTIBLE_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/preprocessed_signal.hpp b/3rdParty/Boost/src/boost/signals2/preprocessed_signal.hpp
new file mode 100644
index 0000000..28471ba
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/preprocessed_signal.hpp
@@ -0,0 +1,59 @@
+/*
+ A thread-safe version of Boost.Signals.
+
+ Author: Frank Mori Hess <fmhess@users.sourceforge.net>
+ Begin: 2007-01-23
+*/
+// Copyright Frank Mori Hess 2007-2008
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_PREPROCESSED_SIGNAL_HPP
+#define BOOST_SIGNALS2_PREPROCESSED_SIGNAL_HPP
+
+#include <boost/preprocessor/arithmetic.hpp>
+#include <boost/preprocessor/cat.hpp>
+#include <boost/preprocessor/control/expr_if.hpp>
+#include <boost/preprocessor/iteration.hpp>
+#include <boost/preprocessor/repetition.hpp>
+#include <boost/signals2/detail/preprocessed_arg_type.hpp>
+#include <boost/type_traits/add_reference.hpp>
+
+#define BOOST_PP_ITERATION_LIMITS (0, BOOST_SIGNALS2_MAX_ARGS)
+#define BOOST_PP_FILENAME_1 <boost/signals2/detail/signal_template.hpp>
+#include BOOST_PP_ITERATE()
+
+namespace boost
+{
+ namespace signals2
+ {
+ template<typename Signature,
+ typename Combiner = optional_last_value<typename boost::function_traits<Signature>::result_type>,
+ typename Group = int,
+ typename GroupCompare = std::less<Group>,
+ typename SlotFunction = function<Signature>,
+ typename ExtendedSlotFunction = typename detail::extended_signature<function_traits<Signature>::arity, Signature>::function_type,
+ typename Mutex = mutex >
+ class signal: public detail::signalN<function_traits<Signature>::arity,
+ Signature, Combiner, Group, GroupCompare, SlotFunction, ExtendedSlotFunction, Mutex>::type
+ {
+ private:
+ typedef typename detail::signalN<boost::function_traits<Signature>::arity,
+ Signature, Combiner, Group, GroupCompare, SlotFunction, ExtendedSlotFunction, Mutex>::type base_type;
+ public:
+ signal(const Combiner &combiner_arg = Combiner(), const GroupCompare &group_compare = GroupCompare()):
+ base_type(combiner_arg, group_compare)
+ {}
+#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && BOOST_WORKAROUND(BOOST_MSVC, < 1800)
+ signal(signal && other) : base_type(std::move(other)) {}
+ signal & operator=(signal && other) { base_type::operator=(std::move(other)); return *this; }
+#endif
+ };
+ }
+}
+
+#endif // BOOST_SIGNALS2_PREPROCESSED_SIGNAL_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/preprocessed_slot.hpp b/3rdParty/Boost/src/boost/signals2/preprocessed_slot.hpp
new file mode 100644
index 0000000..322b1a1
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/preprocessed_slot.hpp
@@ -0,0 +1,72 @@
+// Boost.Signals2 library
+
+// Copyright Frank Mori Hess 2007-2009.
+// Copyright Timmo Stange 2007.
+// Copyright Douglas Gregor 2001-2004. Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_PREPROCESSED_SLOT_HPP
+#define BOOST_SIGNALS2_PREPROCESSED_SLOT_HPP
+
+#include <boost/preprocessor/repetition.hpp>
+#include <boost/signals2/detail/preprocessed_arg_type.hpp>
+#include <boost/type_traits/function_traits.hpp>
+
+#ifndef BOOST_SIGNALS2_SLOT_MAX_BINDING_ARGS
+#define BOOST_SIGNALS2_SLOT_MAX_BINDING_ARGS 10
+#endif
+
+
+// template<typename Func, typename BindArgT0, typename BindArgT1, ..., typename BindArgTN-1> slotN(...
+#define BOOST_SIGNALS2_SLOT_N_BINDING_CONSTRUCTOR(z, n, data) \
+ template<typename Func, BOOST_SIGNALS2_PREFIXED_ARGS_TEMPLATE_DECL(n, BindArg)> \
+ BOOST_SIGNALS2_SLOT_CLASS_NAME(BOOST_SIGNALS2_NUM_ARGS)( \
+ const Func &func, BOOST_SIGNALS2_PREFIXED_FULL_REF_ARGS(n, const BindArg)) \
+ { \
+ init_slot_function(boost::bind(func, BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(n))); \
+ }
+#define BOOST_SIGNALS2_SLOT_N_BINDING_CONSTRUCTORS \
+ BOOST_PP_REPEAT_FROM_TO(1, BOOST_SIGNALS2_SLOT_MAX_BINDING_ARGS, BOOST_SIGNALS2_SLOT_N_BINDING_CONSTRUCTOR, ~)
+
+
+#define BOOST_PP_ITERATION_LIMITS (0, BOOST_PP_INC(BOOST_SIGNALS2_MAX_ARGS))
+#define BOOST_PP_FILENAME_1 <boost/signals2/detail/slot_template.hpp>
+#include BOOST_PP_ITERATE()
+
+#undef BOOST_SIGNALS2_SLOT_N_BINDING_CONSTRUCTOR
+#undef BOOST_SIGNALS2_SLOT_N_BINDING_CONSTRUCTORS
+
+namespace boost
+{
+ namespace signals2
+ {
+ template<typename Signature,
+ typename SlotFunction = boost::function<Signature> >
+ class slot: public detail::slotN<function_traits<Signature>::arity,
+ Signature, SlotFunction>::type
+ {
+ private:
+ typedef typename detail::slotN<boost::function_traits<Signature>::arity,
+ Signature, SlotFunction>::type base_type;
+ public:
+ template<typename F>
+ slot(const F& f): base_type(f)
+ {}
+ // bind syntactic sugar
+// template<typename F, typename BindArgT0, typename BindArgT1, ..., typename BindArgTn-1> slot(...
+#define BOOST_SIGNALS2_SLOT_BINDING_CONSTRUCTOR(z, n, data) \
+ template<typename Func, BOOST_SIGNALS2_PREFIXED_ARGS_TEMPLATE_DECL(n, BindArg)> \
+ slot(const Func &func, BOOST_SIGNALS2_PREFIXED_FULL_REF_ARGS(n, const BindArg)): \
+ base_type(func, BOOST_SIGNALS2_SIGNATURE_ARG_NAMES(n)) \
+ {}
+ BOOST_PP_REPEAT_FROM_TO(1, BOOST_SIGNALS2_SLOT_MAX_BINDING_ARGS, BOOST_SIGNALS2_SLOT_BINDING_CONSTRUCTOR, ~)
+#undef BOOST_SIGNALS2_SLOT_BINDING_CONSTRUCTOR
+ };
+ } // namespace signals2
+}
+
+#endif // BOOST_SIGNALS2_PREPROCESSED_SLOT_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/shared_connection_block.hpp b/3rdParty/Boost/src/boost/signals2/shared_connection_block.hpp
new file mode 100644
index 0000000..c16bf9b
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/shared_connection_block.hpp
@@ -0,0 +1,64 @@
+// Boost.Signals2 library
+
+// Copyright Frank Mori Hess 2007-2008.
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_SHARED_CONNECTION_BLOCK_HPP
+#define BOOST_SIGNALS2_SHARED_CONNECTION_BLOCK_HPP
+
+#include <boost/shared_ptr.hpp>
+#include <boost/signals2/connection.hpp>
+#include <boost/weak_ptr.hpp>
+
+namespace boost
+{
+ namespace signals2
+ {
+ class shared_connection_block
+ {
+ public:
+ shared_connection_block(const signals2::connection &conn = signals2::connection(),
+ bool initially_blocked = true):
+ _weak_connection_body(conn._weak_connection_body)
+ {
+ if(initially_blocked) block();
+ }
+ void block()
+ {
+ if(blocking()) return;
+ boost::shared_ptr<detail::connection_body_base> connection_body(_weak_connection_body.lock());
+ if(connection_body == 0)
+ {
+ // Make _blocker non-empty so the blocking() method still returns the correct value
+ // after the connection has expired.
+ _blocker.reset(static_cast<int*>(0));
+ return;
+ }
+ _blocker = connection_body->get_blocker();
+ }
+ void unblock()
+ {
+ _blocker.reset();
+ }
+ bool blocking() const
+ {
+ shared_ptr<void> empty;
+ return _blocker < empty || empty < _blocker;
+ }
+ signals2::connection connection() const
+ {
+ return signals2::connection(_weak_connection_body);
+ }
+ private:
+ boost::weak_ptr<detail::connection_body_base> _weak_connection_body;
+ shared_ptr<void> _blocker;
+ };
+ }
+} // end namespace boost
+
+#endif // BOOST_SIGNALS2_SHARED_CONNECTION_BLOCK_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/signal.hpp b/3rdParty/Boost/src/boost/signals2/signal.hpp
new file mode 100644
index 0000000..c04c9e6
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/signal.hpp
@@ -0,0 +1,62 @@
+// A thread-safe version of Boost.Signals.
+
+// Copyright Frank Mori Hess 2007-2009
+//
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_SIGNAL_HPP
+#define BOOST_SIGNALS2_SIGNAL_HPP
+
+#include <algorithm>
+#include <boost/assert.hpp>
+#include <boost/config.hpp>
+#include <boost/function.hpp>
+#include <boost/mpl/identity.hpp>
+#include <boost/shared_ptr.hpp>
+#include <boost/signals2/connection.hpp>
+#include <boost/signals2/detail/unique_lock.hpp>
+#include <boost/signals2/detail/replace_slot_function.hpp>
+#include <boost/signals2/detail/result_type_wrapper.hpp>
+#include <boost/signals2/detail/signals_common.hpp>
+#include <boost/signals2/detail/signals_common_macros.hpp>
+#include <boost/signals2/detail/slot_groups.hpp>
+#include <boost/signals2/detail/slot_call_iterator.hpp>
+#include <boost/signals2/optional_last_value.hpp>
+#include <boost/signals2/mutex.hpp>
+#include <boost/signals2/slot.hpp>
+#include <boost/throw_exception.hpp>
+#include <functional>
+
+#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
+#include <boost/signals2/preprocessed_signal.hpp>
+#else
+#include <boost/signals2/variadic_signal.hpp>
+#endif
+
+namespace boost
+{
+ namespace signals2
+ {
+ // free swap function, findable by ADL
+ template<typename Signature,
+ typename Combiner,
+ typename Group,
+ typename GroupCompare,
+ typename SlotFunction,
+ typename ExtendedSlotFunction,
+ typename Mutex>
+ void swap(
+ signal<Signature, Combiner, Group, GroupCompare, SlotFunction, ExtendedSlotFunction, Mutex> &sig1,
+ signal<Signature, Combiner, Group, GroupCompare, SlotFunction, ExtendedSlotFunction, Mutex> &sig2)
+ {
+ sig1.swap(sig2);
+ }
+ }
+}
+
+#endif // BOOST_SIGNALS2_SIGNAL_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/signal_base.hpp b/3rdParty/Boost/src/boost/signals2/signal_base.hpp
new file mode 100644
index 0000000..05b6b5f
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/signal_base.hpp
@@ -0,0 +1,33 @@
+// Boost.Signals2 library
+
+// Copyright Frank Mori Hess 2007-2008.
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_SIGNAL_BASE_HPP
+#define BOOST_SIGNALS2_SIGNAL_BASE_HPP
+
+#include <boost/noncopyable.hpp>
+#include <boost/shared_ptr.hpp>
+
+namespace boost {
+ namespace signals2 {
+ class slot_base;
+
+ class signal_base : public noncopyable
+ {
+ public:
+ friend class slot_base;
+
+ virtual ~signal_base() {}
+ protected:
+ virtual shared_ptr<void> lock_pimpl() const = 0;
+ };
+ } // end namespace signals2
+} // end namespace boost
+
+#endif // BOOST_SIGNALS2_SIGNAL_BASE_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/signal_type.hpp b/3rdParty/Boost/src/boost/signals2/signal_type.hpp
new file mode 100644
index 0000000..4de5396
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/signal_type.hpp
@@ -0,0 +1,144 @@
+/*
+ A meta function which supports using named template type parameters
+ via Boost.Parameter to specify the template type parameters for
+ the boost::signals2::signal class.
+
+ Author: Frank Mori Hess <fmhess@users.sourceforge.net>
+ Begin: 2009-01-22
+*/
+// Copyright Frank Mori Hess 2009
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_SIGNAL_TYPE_HPP
+#define BOOST_SIGNALS2_SIGNAL_TYPE_HPP
+
+// support for function types is currently broken in Boost.Parameter
+// #define BOOST_SIGNALS2_NAMED_SIGNATURE_PARAMETER
+
+#include <boost/signals2/signal.hpp>
+
+#if !defined(BOOST_PARAMETER_MAX_ARITY)
+#define BOOST_PARAMETER_MAX_ARITY 7
+#else
+#if BOOST_PARAMETER_MAX_ARITY < 7
+#error This header requires BOOST_PARAMETER_MAX_ARITY to be defined as 7 or greater prior to including Boost.Parameter headers
+#endif // BOOST_PARAMETER_MAX_ARITY < 7
+#endif // !defined(BOOST_PARAMETER_MAX_ARITY)
+#include <boost/parameter.hpp>
+
+#include <boost/type_traits/is_function.hpp>
+
+namespace boost
+{
+ namespace signals2
+ {
+ namespace keywords
+ {
+#ifdef BOOST_SIGNALS2_NAMED_SIGNATURE_PARAMETER
+ BOOST_PARAMETER_TEMPLATE_KEYWORD(signature_type)
+#endif
+ BOOST_PARAMETER_TEMPLATE_KEYWORD(combiner_type)
+ BOOST_PARAMETER_TEMPLATE_KEYWORD(group_type)
+ BOOST_PARAMETER_TEMPLATE_KEYWORD(group_compare_type)
+ BOOST_PARAMETER_TEMPLATE_KEYWORD(slot_function_type)
+ BOOST_PARAMETER_TEMPLATE_KEYWORD(extended_slot_function_type)
+ BOOST_PARAMETER_TEMPLATE_KEYWORD(mutex_type)
+ } // namespace keywords
+
+ template <
+#ifdef BOOST_SIGNALS2_NAMED_SIGNATURE_PARAMETER
+ typename A0,
+#else
+ typename Signature,
+#endif
+ typename A1 = parameter::void_,
+ typename A2 = parameter::void_,
+ typename A3 = parameter::void_,
+ typename A4 = parameter::void_,
+ typename A5 = parameter::void_,
+ typename A6 = parameter::void_
+ >
+ class signal_type
+ {
+ typedef parameter::parameters<
+#ifdef BOOST_SIGNALS2_NAMED_SIGNATURE_PARAMETER
+ parameter::required<keywords::tag::signature_type, is_function<boost::mpl::_> >,
+#endif
+ parameter::optional<keywords::tag::combiner_type>,
+ parameter::optional<keywords::tag::group_type>,
+ parameter::optional<keywords::tag::group_compare_type>,
+ parameter::optional<keywords::tag::slot_function_type>,
+ parameter::optional<keywords::tag::extended_slot_function_type>,
+ parameter::optional<keywords::tag::mutex_type>
+ > parameter_spec;
+
+ public:
+ // ArgumentPack
+ typedef typename
+ parameter_spec::bind<
+#ifdef BOOST_SIGNALS2_NAMED_SIGNATURE_PARAMETER
+ A0,
+#endif
+ A1, A2, A3, A4, A5, A6>::type
+ args;
+
+#ifdef BOOST_SIGNALS2_NAMED_SIGNATURE_PARAMETER
+ typedef typename parameter::value_type<args, keywords::tag::signature_type>::type
+ signature_type;
+#else
+ typedef Signature signature_type;
+#endif
+
+ typedef typename parameter::value_type
+ <
+ args,
+ keywords::tag::combiner_type,
+ optional_last_value
+ <
+ typename boost::function_traits<signature_type>::result_type
+ >
+ >::type combiner_type;
+
+ typedef typename
+ parameter::value_type<args, keywords::tag::group_type, int>::type group_type;
+
+ typedef typename
+ parameter::value_type<args, keywords::tag::group_compare_type, std::less<group_type> >::type
+ group_compare_type;
+
+ typedef typename
+ parameter::value_type<args, keywords::tag::slot_function_type, function<signature_type> >::type
+ slot_function_type;
+
+ typedef typename
+ parameter::value_type
+ <
+ args,
+ keywords::tag::extended_slot_function_type,
+ typename detail::extended_signature<function_traits<signature_type>::arity, signature_type>::function_type
+ >::type
+ extended_slot_function_type;
+
+ typedef typename
+ parameter::value_type<args, keywords::tag::mutex_type, mutex>::type mutex_type;
+
+ typedef signal
+ <
+ signature_type,
+ combiner_type,
+ group_type,
+ group_compare_type,
+ slot_function_type,
+ extended_slot_function_type,
+ mutex_type
+ > type;
+ };
+ } // namespace signals2
+} // namespace boost
+
+#endif // BOOST_SIGNALS2_SIGNAL_TYPE_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/slot.hpp b/3rdParty/Boost/src/boost/signals2/slot.hpp
new file mode 100644
index 0000000..b6ec4d7
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/slot.hpp
@@ -0,0 +1,33 @@
+// Boost.Signals2 library
+
+// Copyright Frank Mori Hess 2009.
+//
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_SLOT_HPP
+#define BOOST_SIGNALS2_SLOT_HPP
+
+#include <boost/bind.hpp>
+#include <boost/config.hpp>
+#include <boost/function.hpp>
+#include <boost/mpl/identity.hpp>
+#include <boost/ref.hpp>
+#include <boost/signals2/detail/signals_common.hpp>
+#include <boost/signals2/detail/signals_common_macros.hpp>
+#include <boost/signals2/detail/tracked_objects_visitor.hpp>
+#include <boost/signals2/slot_base.hpp>
+#include <boost/visit_each.hpp>
+#include <boost/weak_ptr.hpp>
+
+#ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
+#include <boost/signals2/preprocessed_slot.hpp>
+#else
+#include <boost/signals2/variadic_slot.hpp>
+#endif
+
+#endif // BOOST_SIGNALS2_SLOT_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/slot_base.hpp b/3rdParty/Boost/src/boost/signals2/slot_base.hpp
new file mode 100644
index 0000000..d2dd946
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/slot_base.hpp
@@ -0,0 +1,100 @@
+// Boost.Signals2 library
+
+// Copyright Frank Mori Hess 2007-2008.
+// Copyright Timmo Stange 2007.
+// Copyright Douglas Gregor 2001-2004. Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_SLOT_BASE_HPP
+#define BOOST_SIGNALS2_SLOT_BASE_HPP
+
+#include <boost/shared_ptr.hpp>
+#include <boost/weak_ptr.hpp>
+#include <boost/signals2/detail/foreign_ptr.hpp>
+#include <boost/signals2/expired_slot.hpp>
+#include <boost/signals2/signal_base.hpp>
+#include <boost/throw_exception.hpp>
+#include <boost/variant/apply_visitor.hpp>
+#include <boost/variant/variant.hpp>
+#include <vector>
+
+namespace boost
+{
+ namespace signals2
+ {
+ namespace detail
+ {
+ class tracked_objects_visitor;
+
+ typedef boost::variant<boost::weak_ptr<void>, detail::foreign_void_weak_ptr > void_weak_ptr_variant;
+ typedef boost::variant<boost::shared_ptr<void>, detail::foreign_void_shared_ptr > void_shared_ptr_variant;
+ class lock_weak_ptr_visitor
+ {
+ public:
+ typedef void_shared_ptr_variant result_type;
+ template<typename WeakPtr>
+ result_type operator()(const WeakPtr &wp) const
+ {
+ return wp.lock();
+ }
+ };
+ class expired_weak_ptr_visitor
+ {
+ public:
+ typedef bool result_type;
+ template<typename WeakPtr>
+ bool operator()(const WeakPtr &wp) const
+ {
+ return wp.expired();
+ }
+ };
+ }
+
+ class slot_base
+ {
+ public:
+ typedef std::vector<detail::void_weak_ptr_variant> tracked_container_type;
+ typedef std::vector<detail::void_shared_ptr_variant> locked_container_type;
+
+ const tracked_container_type& tracked_objects() const {return _tracked_objects;}
+ locked_container_type lock() const
+ {
+ locked_container_type locked_objects;
+ tracked_container_type::const_iterator it;
+ for(it = tracked_objects().begin(); it != tracked_objects().end(); ++it)
+ {
+ locked_objects.push_back(apply_visitor(detail::lock_weak_ptr_visitor(), *it));
+ if(apply_visitor(detail::expired_weak_ptr_visitor(), *it))
+ {
+ boost::throw_exception(expired_slot());
+ }
+ }
+ return locked_objects;
+ }
+ bool expired() const
+ {
+ tracked_container_type::const_iterator it;
+ for(it = tracked_objects().begin(); it != tracked_objects().end(); ++it)
+ {
+ if(apply_visitor(detail::expired_weak_ptr_visitor(), *it)) return true;
+ }
+ return false;
+ }
+ protected:
+ friend class detail::tracked_objects_visitor;
+
+ void track_signal(const signal_base &signal)
+ {
+ _tracked_objects.push_back(signal.lock_pimpl());
+ }
+
+ tracked_container_type _tracked_objects;
+ };
+ }
+} // end namespace boost
+
+#endif // BOOST_SIGNALS2_SLOT_BASE_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/trackable.hpp b/3rdParty/Boost/src/boost/signals2/trackable.hpp
new file mode 100644
index 0000000..d6a6014
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/trackable.hpp
@@ -0,0 +1,49 @@
+// Boost.Signals2 library
+
+// Copyright Frank Mori Hess 2007,2009.
+// Copyright Timmo Stange 2007.
+// Copyright Douglas Gregor 2001-2004. Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// Compatibility class to ease porting from the original
+// Boost.Signals library. However,
+// boost::signals2::trackable is NOT thread-safe.
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_TRACKABLE_HPP
+#define BOOST_SIGNALS2_TRACKABLE_HPP
+
+#include <boost/assert.hpp>
+#include <boost/shared_ptr.hpp>
+
+namespace boost {
+ namespace signals2 {
+ namespace detail
+ {
+ class tracked_objects_visitor;
+ }
+ class trackable {
+ protected:
+ trackable(): _tracked_ptr(static_cast<int*>(0)) {}
+ trackable(const trackable &): _tracked_ptr(static_cast<int*>(0)) {}
+ trackable& operator=(const trackable &)
+ {
+ return *this;
+ }
+ ~trackable() {}
+ private:
+ friend class detail::tracked_objects_visitor;
+ const shared_ptr<void>& get_shared_ptr() const
+ {
+ return _tracked_ptr;
+ }
+
+ shared_ptr<void> _tracked_ptr;
+ };
+ } // end namespace signals2
+} // end namespace boost
+
+#endif // BOOST_SIGNALS2_TRACKABLE_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/variadic_signal.hpp b/3rdParty/Boost/src/boost/signals2/variadic_signal.hpp
new file mode 100644
index 0000000..d7d2619
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/variadic_signal.hpp
@@ -0,0 +1,44 @@
+/*
+ A variadic implementation of variadic boost::signals2::signal, used when variadic
+ template support is detected in the compiler.
+
+ Author: Frank Mori Hess <fmhess@users.sourceforge.net>
+ Begin: 2009-05-26
+*/
+// Copyright Frank Mori Hess 2009
+// Use, modification and
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_VARIADIC_SIGNAL_HPP
+#define BOOST_SIGNALS2_VARIADIC_SIGNAL_HPP
+
+#include <boost/preprocessor/control/expr_if.hpp>
+#include <boost/signals2/detail/variadic_arg_type.hpp>
+#include <boost/signals2/detail/variadic_slot_invoker.hpp>
+#include <boost/type_traits/function_traits.hpp>
+
+namespace boost
+{
+ namespace signals2
+ {
+ namespace detail
+ {
+ template<typename Signature> class variadic_extended_signature;
+ // partial template specialization
+ template<typename R, typename ... Args>
+ class variadic_extended_signature<R (Args...)>
+ {
+ public:
+ typedef boost::function<R (const boost::signals2::connection &, Args...)> function_type;
+ };
+ } // namespace detail
+ } // namespace signals2
+} // namespace boost
+
+#include <boost/signals2/detail/signal_template.hpp>
+
+#endif // BOOST_SIGNALS2_VARIADIC_SIGNAL_HPP
diff --git a/3rdParty/Boost/src/boost/signals2/variadic_slot.hpp b/3rdParty/Boost/src/boost/signals2/variadic_slot.hpp
new file mode 100644
index 0000000..59ae176
--- /dev/null
+++ b/3rdParty/Boost/src/boost/signals2/variadic_slot.hpp
@@ -0,0 +1,25 @@
+// Boost.Signals2 library
+
+// Copyright Frank Mori Hess 2009.
+//
+// distribution is subject to the Boost Software License, Version
+// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+// For more information, see http://www.boost.org
+
+#ifndef BOOST_SIGNALS2_VARIADIC_SLOT_HPP
+#define BOOST_SIGNALS2_VARIADIC_SLOT_HPP
+
+#include <boost/signals2/detail/variadic_arg_type.hpp>
+
+#define BOOST_SIGNALS2_SLOT_N_BINDING_CONSTRUCTORS \
+ template<typename A1, typename A2, typename ... BindArgs> \
+ slot(const A1 &arg1, const A2 &arg2, const BindArgs & ... args) \
+ { \
+ init_slot_function(boost::bind(arg1, arg2, args...)); \
+ }
+
+
+#include <boost/signals2/detail/slot_template.hpp>
+#endif // BOOST_SIGNALS2_VARIADIC_SLOT_HPP
diff --git a/3rdParty/Boost/src/boost/smart_ptr.hpp b/3rdParty/Boost/src/boost/smart_ptr.hpp
deleted file mode 100644
index b5e569d..0000000
--- a/3rdParty/Boost/src/boost/smart_ptr.hpp
+++ /dev/null
@@ -1,31 +0,0 @@
-#ifndef BOOST_SMART_PTR_HPP_INCLUDED
-#define BOOST_SMART_PTR_HPP_INCLUDED
-
-//
-// smart_ptr.hpp
-//
-// For convenience, this header includes the rest of the smart
-// pointer library headers.
-//
-// Copyright (c) 2003 Peter Dimov Distributed under the Boost
-// Software License, Version 1.0. (See accompanying file
-// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
-//
-// http://www.boost.org/libs/smart_ptr/smart_ptr.htm
-//
-
-#include <boost/config.hpp>
-
-#include <boost/scoped_ptr.hpp>
-#include <boost/scoped_array.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/shared_array.hpp>
-
-#if !defined(BOOST_NO_MEMBER_TEMPLATES) || defined(BOOST_MSVC6_MEMBER_TEMPLATES)
-# include <boost/weak_ptr.hpp>
-# include <boost/intrusive_ptr.hpp>
-# include <boost/enable_shared_from_this.hpp>
-# include <boost/make_shared.hpp>
-#endif
-
-#endif // #ifndef BOOST_SMART_PTR_HPP_INCLUDED
diff --git a/3rdParty/Boost/src/boost/timer.hpp b/3rdParty/Boost/src/boost/timer.hpp
new file mode 100644
index 0000000..1e3571e
--- /dev/null
+++ b/3rdParty/Boost/src/boost/timer.hpp
@@ -0,0 +1,72 @@
+// boost timer.hpp header file ---------------------------------------------//
+
+// Copyright Beman Dawes 1994-99. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying file
+// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org/libs/timer for documentation.
+
+// Revision History
+// 01 Apr 01 Modified to use new <boost/limits.hpp> header. (JMaddock)
+// 12 Jan 01 Change to inline implementation to allow use without library
+// builds. See docs for more rationale. (Beman Dawes)
+// 25 Sep 99 elapsed_max() and elapsed_min() added (John Maddock)
+// 16 Jul 99 Second beta
+// 6 Jul 99 Initial boost version
+
+#ifndef BOOST_TIMER_HPP
+#define BOOST_TIMER_HPP
+
+#include <boost/config.hpp>
+#include <ctime>
+#include <boost/limits.hpp>
+
+# ifdef BOOST_NO_STDC_NAMESPACE
+ namespace std { using ::clock_t; using ::clock; }
+# endif
+
+
+namespace boost {
+
+// timer -------------------------------------------------------------------//
+
+// A timer object measures elapsed time.
+
+// It is recommended that implementations measure wall clock rather than CPU
+// time since the intended use is performance measurement on systems where
+// total elapsed time is more important than just process or CPU time.
+
+// Warnings: The maximum measurable elapsed time may well be only 596.5+ hours
+// due to implementation limitations. The accuracy of timings depends on the
+// accuracy of timing information provided by the underlying platform, and
+// this varies a great deal from platform to platform.
+
+class timer
+{
+ public:
+ timer() { _start_time = std::clock(); } // postcondition: elapsed()==0
+// timer( const timer& src ); // post: elapsed()==src.elapsed()
+// ~timer(){}
+// timer& operator=( const timer& src ); // post: elapsed()==src.elapsed()
+ void restart() { _start_time = std::clock(); } // post: elapsed()==0
+ double elapsed() const // return elapsed time in seconds
+ { return double(std::clock() - _start_time) / CLOCKS_PER_SEC; }
+
+ double elapsed_max() const // return estimated maximum value for elapsed()
+ // Portability warning: elapsed_max() may return too high a value on systems
+ // where std::clock_t overflows or resets at surprising values.
+ {
+ return (double((std::numeric_limits<std::clock_t>::max)())
+ - double(_start_time)) / double(CLOCKS_PER_SEC);
+ }
+
+ double elapsed_min() const // return minimum value for elapsed()
+ { return double(1)/double(CLOCKS_PER_SEC); }
+
+ private:
+ std::clock_t _start_time;
+}; // timer
+
+} // namespace boost
+
+#endif // BOOST_TIMER_HPP
diff --git a/3rdParty/Boost/src/libs/atomic/README.md b/3rdParty/Boost/src/libs/atomic/README.md
new file mode 100644
index 0000000..9c82949
--- /dev/null
+++ b/3rdParty/Boost/src/libs/atomic/README.md
@@ -0,0 +1,19 @@
+#![Boost.Atomic](doc/logo.png)
+
+Boost.Atomic, part of collection of the [Boost C++ Libraries](http://github.com/boostorg), implements atomic operations for various CPU architectures, reflecting the standard interface defined in C++11.
+
+### Directories
+
+* **build** - Boost.Atomic build scripts
+* **doc** - QuickBook documentation sources
+* **include** - Interface headers of Boost.Atomic
+* **src** - Compilable source code of Boost.Atomic
+* **test** - Boost.Atomic unit tests
+
+### More information
+
+* [Documentation](http://boost.org/libs/atomic)
+
+### License
+
+Distributed under the [Boost Software License, Version 1.0](http://www.boost.org/LICENSE_1_0.txt).
diff --git a/3rdParty/Boost/src/libs/atomic/doc/Jamfile.v2 b/3rdParty/Boost/src/libs/atomic/doc/Jamfile.v2
new file mode 100644
index 0000000..c293a66
--- /dev/null
+++ b/3rdParty/Boost/src/libs/atomic/doc/Jamfile.v2
@@ -0,0 +1,26 @@
+# Boost.Atomic library documentation Jamfile
+#
+# Copyright Helge Bahmann 2011.
+# Copyright Tim Blechmann 2012.
+# Distributed under the Boost Software License, Version 1.0.
+# (See accompanying file LICENSE_1_0.txt or copy at
+# http://www.boost.org/LICENSE_1_0.txt)
+
+import quickbook ;
+import boostbook : boostbook ;
+
+xml atomic : atomic.qbk ;
+
+boostbook standalone
+ : atomic
+ : <xsl:param>boost.root=../../../..
+ <xsl:param>boost.libraries=../../../libraries.htm
+ <format>pdf:<xsl:param>boost.url.prefix=http://www.boost.org/doc/libs/release/libs/atomic/doc/html
+ ;
+
+install css : [ glob $(BOOST_ROOT)/doc/src/*.css ]
+ : <location>html ;
+install images : [ glob $(BOOST_ROOT)/doc/src/images/*.png ]
+ : <location>html/images ;
+explicit css ;
+explicit images ;
diff --git a/3rdParty/Boost/src/libs/atomic/doc/atomic.hpp b/3rdParty/Boost/src/libs/atomic/doc/atomic.hpp
new file mode 100644
index 0000000..60e61c2
--- /dev/null
+++ b/3rdParty/Boost/src/libs/atomic/doc/atomic.hpp
@@ -0,0 +1,547 @@
+/** \file boost/atomic.hpp */
+
+// Copyright (c) 2009 Helge Bahmann
+//
+// Distributed under the Boost Software License, Version 1.0.
+// See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+/* this is just a pseudo-header file fed to doxygen
+to more easily generate the class documentation; will
+be replaced by proper documentation down the road */
+
+namespace boost {
+
+/**
+ \brief Memory ordering constraints
+
+ This defines the relative order of one atomic operation
+ and other memory operations (loads, stores, other atomic operations)
+ executed by the same thread.
+
+ The order of operations specified by the programmer in the
+ source code ("program order") does not necessarily match
+ the order in which they are actually executed on the target system:
+ Both compiler as well as processor may reorder operations
+ quite arbitrarily. <B>Specifying the wrong ordering
+ constraint will therefore generally result in an incorrect program.</B>
+*/
+enum memory_order {
+ /**
+ \brief No constraint
+ Atomic operation and other memory operations may be reordered freely.
+ */
+ memory_order_relaxed,
+ /**
+ \brief Data dependence constraint
+ Atomic operation must strictly precede any memory operation that
+ computationally depends on the outcome of the atomic operation.
+ */
+ memory_order_consume,
+ /**
+ \brief Acquire memory
+ Atomic operation must strictly precede all memory operations that
+ follow in program order.
+ */
+ memory_order_acquire,
+ /**
+ \brief Release memory
+ Atomic operation must strictly follow all memory operations that precede
+ in program order.
+ */
+ memory_order_release,
+ /**
+ \brief Acquire and release memory
+ Combines the effects of \ref memory_order_acquire and \ref memory_order_release
+ */
+ memory_order_acq_rel,
+ /**
+ \brief Sequentially consistent
+ Produces the same result \ref memory_order_acq_rel, but additionally
+ enforces globally sequential consistent execution
+ */
+ memory_order_seq_cst
+};
+
+/**
+ \brief Atomic datatype
+
+ An atomic variable. Provides methods to modify this variable atomically.
+ Valid template parameters are:
+
+ - integral data types (char, short, int, ...)
+ - pointer data types
+ - any other data type that has a non-throwing default
+ constructor and that can be copied via <TT>memcpy</TT>
+
+ Unless specified otherwise, any memory ordering constraint can be used
+ with any of the atomic operations.
+*/
+template<typename Type>
+class atomic {
+public:
+ /**
+ \brief Create uninitialized atomic variable
+ Creates an atomic variable. Its initial value is undefined.
+ */
+ atomic();
+ /**
+ \brief Create an initialize atomic variable
+ \param value Initial value
+ Creates and initializes an atomic variable.
+ */
+ explicit atomic(Type value);
+
+ /**
+ \brief Read the current value of the atomic variable
+ \param order Memory ordering constraint, see \ref memory_order
+ \return Current value of the variable
+
+ Valid memory ordering constraints are:
+ - @c memory_order_relaxed
+ - @c memory_order_consume
+ - @c memory_order_acquire
+ - @c memory_order_seq_cst
+ */
+ Type load(memory_order order=memory_order_seq_cst) const;
+
+ /**
+ \brief Write new value to atomic variable
+ \param value New value
+ \param order Memory ordering constraint, see \ref memory_order
+
+ Valid memory ordering constraints are:
+ - @c memory_order_relaxed
+ - @c memory_order_release
+ - @c memory_order_seq_cst
+ */
+ void store(Type value, memory_order order=memory_order_seq_cst);
+
+ /**
+ \brief Atomically compare and exchange variable
+ \param expected Expected old value
+ \param desired Desired new value
+ \param order Memory ordering constraint, see \ref memory_order
+ \return @c true if value was changed
+
+ Atomically performs the following operation
+
+ \code
+ if (variable==expected) {
+ variable=desired;
+ return true;
+ } else {
+ expected=variable;
+ return false;
+ }
+ \endcode
+
+ This operation may fail "spuriously", i.e. the state of the variable
+ is unchanged even though the expected value was found (this is the
+ case on architectures using "load-linked"/"store conditional" to
+ implement the operation).
+
+ The established memory order will be @c order if the operation
+ is successful. If the operation is unsuccessful, the
+ memory order will be
+
+ - @c memory_order_relaxed if @c order is @c memory_order_acquire ,
+ @c memory_order_relaxed or @c memory_order_consume
+ - @c memory_order_release if @c order is @c memory_order_acq_release
+ or @c memory_order_release
+ - @c memory_order_seq_cst if @c order is @c memory_order_seq_cst
+ */
+ bool compare_exchange_weak(
+ Type &expected,
+ Type desired,
+ memory_order order=memory_order_seq_cst);
+
+ /**
+ \brief Atomically compare and exchange variable
+ \param expected Expected old value
+ \param desired Desired new value
+ \param success_order Memory ordering constraint if operation
+ is successful
+ \param failure_order Memory ordering constraint if operation is unsuccessful
+ \return @c true if value was changed
+
+ Atomically performs the following operation
+
+ \code
+ if (variable==expected) {
+ variable=desired;
+ return true;
+ } else {
+ expected=variable;
+ return false;
+ }
+ \endcode
+
+ This operation may fail "spuriously", i.e. the state of the variable
+ is unchanged even though the expected value was found (this is the
+ case on architectures using "load-linked"/"store conditional" to
+ implement the operation).
+
+ The constraint imposed by @c success_order may not be
+ weaker than the constraint imposed by @c failure_order.
+ */
+ bool compare_exchange_weak(
+ Type &expected,
+ Type desired,
+ memory_order success_order,
+ memory_order failure_order);
+ /**
+ \brief Atomically compare and exchange variable
+ \param expected Expected old value
+ \param desired Desired new value
+ \param order Memory ordering constraint, see \ref memory_order
+ \return @c true if value was changed
+
+ Atomically performs the following operation
+
+ \code
+ if (variable==expected) {
+ variable=desired;
+ return true;
+ } else {
+ expected=variable;
+ return false;
+ }
+ \endcode
+
+ In contrast to \ref compare_exchange_weak, this operation will never
+ fail spuriously. Since compare-and-swap must generally be retried
+ in a loop, implementors are advised to prefer \ref compare_exchange_weak
+ where feasible.
+
+ The established memory order will be @c order if the operation
+ is successful. If the operation is unsuccessful, the
+ memory order will be
+
+ - @c memory_order_relaxed if @c order is @c memory_order_acquire ,
+ @c memory_order_relaxed or @c memory_order_consume
+ - @c memory_order_release if @c order is @c memory_order_acq_release
+ or @c memory_order_release
+ - @c memory_order_seq_cst if @c order is @c memory_order_seq_cst
+ */
+ bool compare_exchange_strong(
+ Type &expected,
+ Type desired,
+ memory_order order=memory_order_seq_cst);
+
+ /**
+ \brief Atomically compare and exchange variable
+ \param expected Expected old value
+ \param desired Desired new value
+ \param success_order Memory ordering constraint if operation
+ is successful
+ \param failure_order Memory ordering constraint if operation is unsuccessful
+ \return @c true if value was changed
+
+ Atomically performs the following operation
+
+ \code
+ if (variable==expected) {
+ variable=desired;
+ return true;
+ } else {
+ expected=variable;
+ return false;
+ }
+ \endcode
+
+ In contrast to \ref compare_exchange_weak, this operation will never
+ fail spuriously. Since compare-and-swap must generally be retried
+ in a loop, implementors are advised to prefer \ref compare_exchange_weak
+ where feasible.
+
+ The constraint imposed by @c success_order may not be
+ weaker than the constraint imposed by @c failure_order.
+ */
+ bool compare_exchange_strong(
+ Type &expected,
+ Type desired,
+ memory_order success_order,
+ memory_order failure_order);
+ /**
+ \brief Atomically exchange variable
+ \param value New value
+ \param order Memory ordering constraint, see \ref memory_order
+ \return Old value of the variable
+
+ Atomically exchanges the value of the variable with the new
+ value and returns its old value.
+ */
+ Type exchange(Type value, memory_order order=memory_order_seq_cst);
+
+ /**
+ \brief Atomically add and return old value
+ \param operand Operand
+ \param order Memory ordering constraint, see \ref memory_order
+ \return Old value of the variable
+
+ Atomically adds operand to the variable and returns its
+ old value.
+ */
+ Type fetch_add(Type operand, memory_order order=memory_order_seq_cst);
+ /**
+ \brief Atomically subtract and return old value
+ \param operand Operand
+ \param order Memory ordering constraint, see \ref memory_order
+ \return Old value of the variable
+
+ Atomically subtracts operand from the variable and returns its
+ old value.
+
+ This method is available only if \c Type is an integral type
+ or a non-void pointer type. If it is a pointer type,
+ @c operand is of type @c ptrdiff_t and the operation
+ is performed following the rules for pointer arithmetic
+ in C++.
+ */
+ Type fetch_sub(Type operand, memory_order order=memory_order_seq_cst);
+
+ /**
+ \brief Atomically perform bitwise "AND" and return old value
+ \param operand Operand
+ \param order Memory ordering constraint, see \ref memory_order
+ \return Old value of the variable
+
+ Atomically performs bitwise "AND" with the variable and returns its
+ old value.
+
+ This method is available only if \c Type is an integral type
+ or a non-void pointer type. If it is a pointer type,
+ @c operand is of type @c ptrdiff_t and the operation
+ is performed following the rules for pointer arithmetic
+ in C++.
+ */
+ Type fetch_and(Type operand, memory_order order=memory_order_seq_cst);
+
+ /**
+ \brief Atomically perform bitwise "OR" and return old value
+ \param operand Operand
+ \param order Memory ordering constraint, see \ref memory_order
+ \return Old value of the variable
+
+ Atomically performs bitwise "OR" with the variable and returns its
+ old value.
+
+ This method is available only if \c Type is an integral type.
+ */
+ Type fetch_or(Type operand, memory_order order=memory_order_seq_cst);
+
+ /**
+ \brief Atomically perform bitwise "XOR" and return old value
+ \param operand Operand
+ \param order Memory ordering constraint, see \ref memory_order
+ \return Old value of the variable
+
+ Atomically performs bitwise "XOR" with the variable and returns its
+ old value.
+
+ This method is available only if \c Type is an integral type.
+ */
+ Type fetch_xor(Type operand, memory_order order=memory_order_seq_cst);
+
+ /**
+ \brief Implicit load
+ \return Current value of the variable
+
+ The same as <tt>load(memory_order_seq_cst)</tt>. Avoid using
+ the implicit conversion operator, use \ref load with
+ an explicit memory ordering constraint.
+ */
+ operator Type(void) const;
+ /**
+ \brief Implicit store
+ \param value New value
+ \return Copy of @c value
+
+ The same as <tt>store(value, memory_order_seq_cst)</tt>. Avoid using
+ the implicit conversion operator, use \ref store with
+ an explicit memory ordering constraint.
+ */
+ Type operator=(Type v);
+
+ /**
+ \brief Atomically perform bitwise "AND" and return new value
+ \param operand Operand
+ \return New value of the variable
+
+ The same as <tt>fetch_and(operand, memory_order_seq_cst)&operand</tt>.
+ Avoid using the implicit bitwise "AND" operator, use \ref fetch_and
+ with an explicit memory ordering constraint.
+ */
+ Type operator&=(Type operand);
+
+ /**
+ \brief Atomically perform bitwise "OR" and return new value
+ \param operand Operand
+ \return New value of the variable
+
+ The same as <tt>fetch_or(operand, memory_order_seq_cst)|operand</tt>.
+ Avoid using the implicit bitwise "OR" operator, use \ref fetch_or
+ with an explicit memory ordering constraint.
+
+ This method is available only if \c Type is an integral type.
+ */
+ Type operator|=(Type operand);
+
+ /**
+ \brief Atomically perform bitwise "XOR" and return new value
+ \param operand Operand
+ \return New value of the variable
+
+ The same as <tt>fetch_xor(operand, memory_order_seq_cst)^operand</tt>.
+ Avoid using the implicit bitwise "XOR" operator, use \ref fetch_xor
+ with an explicit memory ordering constraint.
+
+ This method is available only if \c Type is an integral type.
+ */
+ Type operator^=(Type operand);
+
+ /**
+ \brief Atomically add and return new value
+ \param operand Operand
+ \return New value of the variable
+
+ The same as <tt>fetch_add(operand, memory_order_seq_cst)+operand</tt>.
+ Avoid using the implicit add operator, use \ref fetch_add
+ with an explicit memory ordering constraint.
+
+ This method is available only if \c Type is an integral type
+ or a non-void pointer type. If it is a pointer type,
+ @c operand is of type @c ptrdiff_t and the operation
+ is performed following the rules for pointer arithmetic
+ in C++.
+ */
+ Type operator+=(Type operand);
+
+ /**
+ \brief Atomically subtract and return new value
+ \param operand Operand
+ \return New value of the variable
+
+ The same as <tt>fetch_sub(operand, memory_order_seq_cst)-operand</tt>.
+ Avoid using the implicit subtract operator, use \ref fetch_sub
+ with an explicit memory ordering constraint.
+
+ This method is available only if \c Type is an integral type
+ or a non-void pointer type. If it is a pointer type,
+ @c operand is of type @c ptrdiff_t and the operation
+ is performed following the rules for pointer arithmetic
+ in C++.
+ */
+ Type operator-=(Type operand);
+
+ /**
+ \brief Atomically increment and return new value
+ \return New value of the variable
+
+ The same as <tt>fetch_add(1, memory_order_seq_cst)+1</tt>.
+ Avoid using the implicit increment operator, use \ref fetch_add
+ with an explicit memory ordering constraint.
+
+ This method is available only if \c Type is an integral type
+ or a non-void pointer type. If it is a pointer type,
+ the operation
+ is performed following the rules for pointer arithmetic
+ in C++.
+ */
+ Type operator++(void);
+ /**
+ \brief Atomically increment and return old value
+ \return Old value of the variable
+
+ The same as <tt>fetch_add(1, memory_order_seq_cst)</tt>.
+ Avoid using the implicit increment operator, use \ref fetch_add
+ with an explicit memory ordering constraint.
+
+ This method is available only if \c Type is an integral type
+ or a non-void pointer type. If it is a pointer type,
+ the operation
+ is performed following the rules for pointer arithmetic
+ in C++.
+ */
+ Type operator++(int);
+ /**
+ \brief Atomically subtract and return new value
+ \return New value of the variable
+
+ The same as <tt>fetch_sub(1, memory_order_seq_cst)-1</tt>.
+ Avoid using the implicit increment operator, use \ref fetch_sub
+ with an explicit memory ordering constraint.
+
+ This method is available only if \c Type is an integral type
+ or a non-void pointer type. If it is a pointer type,
+ the operation
+ is performed following the rules for pointer arithmetic
+ in C++.
+ */
+ Type operator--(void);
+ /**
+ \brief Atomically subtract and return old value
+ \return Old value of the variable
+
+ The same as <tt>fetch_sub(1, memory_order_seq_cst)</tt>.
+ Avoid using the implicit increment operator, use \ref fetch_sub
+ with an explicit memory ordering constraint.
+
+ This method is available only if \c Type is an integral type
+ or a non-void pointer type. If it is a pointer type,
+ the operation
+ is performed following the rules for pointer arithmetic
+ in C++.
+ */
+ Type operator--(int);
+
+ /** \brief Deleted copy constructor */
+ atomic(const atomic &) = delete;
+ /** \brief Deleted copy assignment */
+ const atomic & operator=(const atomic &) = delete;
+};
+
+/**
+ \brief Insert explicit fence for thread synchronization
+ \param order Memory ordering constraint
+
+ Inserts an explicit fence. The exact semantic depends on the
+ type of fence inserted:
+
+ - \c memory_order_relaxed: No operation
+ - \c memory_order_release: Performs a "release" operation
+ - \c memory_order_acquire or \c memory_order_consume: Performs an
+ "acquire" operation
+ - \c memory_order_acq_rel: Performs both an "acquire" and a "release"
+ operation
+ - \c memory_order_seq_cst: Performs both an "acquire" and a "release"
+ operation and in addition there exists a global total order of
+ all \c memory_order_seq_cst operations
+
+*/
+void atomic_thread_fence(memory_order order);
+
+/**
+ \brief Insert explicit fence for synchronization with a signal handler
+ \param order Memory ordering constraint
+
+ Inserts an explicit fence to synchronize with a signal handler called within
+ the context of the same thread. The fence ensures the corresponding operations
+ around it are complete and/or not started. The exact semantic depends on the
+ type of fence inserted:
+
+ - \c memory_order_relaxed: No operation
+ - \c memory_order_release: Ensures the operations before the fence are complete
+ - \c memory_order_acquire or \c memory_order_consume: Ensures the operations
+ after the fence are not started.
+ - \c memory_order_acq_rel or \c memory_order_seq_cst: Ensures the operations
+ around the fence do not cross it.
+
+ Note that this call does not affect visibility order of the memory operations
+ to other threads. It is functionally similar to \c atomic_thread_fence, only
+ it does not generate any instructions to synchronize hardware threads.
+*/
+void atomic_signal_fence(memory_order order);
+
+}
diff --git a/3rdParty/Boost/src/libs/atomic/doc/atomic.qbk b/3rdParty/Boost/src/libs/atomic/doc/atomic.qbk
new file mode 100644
index 0000000..880fab5
--- /dev/null
+++ b/3rdParty/Boost/src/libs/atomic/doc/atomic.qbk
@@ -0,0 +1,828 @@
+[/
+ / Copyright (c) 2009 Helge Bahmann
+ / Copyright (c) 2014 Andrey Semashev
+ /
+ / Distributed under the Boost Software License, Version 1.0. (See accompanying
+ / file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+ /]
+
+[library Boost.Atomic
+ [quickbook 1.4]
+ [authors [Bahmann, Helge][Semashev, Andrey]]
+ [copyright 2011 Helge Bahmann]
+ [copyright 2012 Tim Blechmann]
+ [copyright 2013 Andrey Semashev]
+ [id atomic]
+ [dirname atomic]
+ [purpose Atomic operations]
+ [license
+ Distributed under the Boost Software License, Version 1.0.
+ (See accompanying file LICENSE_1_0.txt or copy at
+ [@http://www.boost.org/LICENSE_1_0.txt])
+ ]
+]
+
+[section:introduction Introduction]
+
+[section:introduction_presenting Presenting Boost.Atomic]
+
+[*Boost.Atomic] is a library that provides [^atomic]
+data types and operations on these data types, as well as memory
+ordering constraints required for coordinating multiple threads through
+atomic variables. It implements the interface as defined by the C++11
+standard, but makes this feature available for platforms lacking
+system/compiler support for this particular C++11 feature.
+
+Users of this library should already be familiar with concurrency
+in general, as well as elementary concepts such as "mutual exclusion".
+
+The implementation makes use of processor-specific instructions where
+possible (via inline assembler, platform libraries or compiler
+intrinsics), and falls back to "emulating" atomic operations through
+locking.
+
+[endsect]
+
+[section:introduction_purpose Purpose]
+
+Operations on "ordinary" variables are not guaranteed to be atomic.
+This means that with [^int n=0] initially, two threads concurrently
+executing
+
+[c++]
+
+ void function()
+ {
+ n ++;
+ }
+
+might result in [^n==1] instead of 2: Each thread will read the
+old value into a processor register, increment it and write the result
+back. Both threads may therefore write [^1], unaware that the other thread
+is doing likewise.
+
+Declaring [^atomic<int> n=0] instead, the same operation on
+this variable will always result in [^n==2] as each operation on this
+variable is ['atomic]: This means that each operation behaves as if it
+were strictly sequentialized with respect to the other.
+
+Atomic variables are useful for two purposes:
+
+* as a means for coordinating multiple threads via custom
+ coordination protocols
+* as faster alternatives to "locked" access to simple variables
+
+Take a look at the [link atomic.usage_examples examples] section
+for common patterns.
+
+[endsect]
+
+[endsect]
+
+[section:thread_coordination Thread coordination using Boost.Atomic]
+
+The most common use of [*Boost.Atomic] is to realize custom
+thread synchronization protocols: The goal is to coordinate
+accesses of threads to shared variables in order to avoid
+"conflicts". The
+programmer must be aware of the fact that
+compilers, CPUs and the cache
+hierarchies may generally reorder memory references at will.
+As a consequence a program such as:
+
+[c++]
+
+ int x = 0, int y = 0;
+
+ thread1:
+ x = 1;
+ y = 1;
+
+ thread2
+ if (y == 1) {
+ assert(x == 1);
+ }
+
+might indeed fail as there is no guarantee that the read of `x`
+by thread2 "sees" the write by thread1.
+
+[*Boost.Atomic] uses a synchronisation concept based on the
+['happens-before] relation to describe the guarantees under
+which situations such as the above one cannot occur.
+
+The remainder of this section will discuss ['happens-before] in
+a "hands-on" way instead of giving a fully formalized definition.
+The reader is encouraged to additionally have a
+look at the discussion of the correctness of a few of the
+[link atomic.usage_examples examples] afterwards.
+
+[section:mutex Enforcing ['happens-before] through mutual exclusion]
+
+As an introductory example to understand how arguing using
+['happens-before] works, consider two threads synchronizing
+using a common mutex:
+
+[c++]
+
+ mutex m;
+
+ thread1:
+ m.lock();
+ ... /* A */
+ m.unlock();
+
+ thread2:
+ m.lock();
+ ... /* B */
+ m.unlock();
+
+The "lockset-based intuition" would be to argue that A and B
+cannot be executed concurrently as the code paths require a
+common lock to be held.
+
+One can however also arrive at the same conclusion using
+['happens-before]: Either thread1 or thread2 will succeed first
+at [^m.lock()]. If this is be thread1, then as a consequence,
+thread2 cannot succeed at [^m.lock()] before thread1 has executed
+[^m.unlock()], consequently A ['happens-before] B in this case.
+By symmetry, if thread2 succeeds at [^m.lock()] first, we can
+conclude B ['happens-before] A.
+
+Since this already exhausts all options, we can conclude that
+either A ['happens-before] B or B ['happens-before] A must
+always hold. Obviously cannot state ['which] of the two relationships
+holds, but either one is sufficient to conclude that A and B
+cannot conflict.
+
+Compare the [link boost_atomic.usage_examples.example_spinlock spinlock]
+implementation to see how the mutual exclusion concept can be
+mapped to [*Boost.Atomic].
+
+[endsect]
+
+[section:release_acquire ['happens-before] through [^release] and [^acquire]]
+
+The most basic pattern for coordinating threads via [*Boost.Atomic]
+uses [^release] and [^acquire] on an atomic variable for coordination: If ...
+
+* ... thread1 performs an operation A,
+* ... thread1 subsequently writes (or atomically
+ modifies) an atomic variable with [^release] semantic,
+* ... thread2 reads (or atomically reads-and-modifies)
+ the value this value from the same atomic variable with
+ [^acquire] semantic and
+* ... thread2 subsequently performs an operation B,
+
+... then A ['happens-before] B.
+
+Consider the following example
+
+[c++]
+
+ atomic<int> a(0);
+
+ thread1:
+ ... /* A */
+ a.fetch_add(1, memory_order_release);
+
+ thread2:
+ int tmp = a.load(memory_order_acquire);
+ if (tmp == 1) {
+ ... /* B */
+ } else {
+ ... /* C */
+ }
+
+In this example, two avenues for execution are possible:
+
+* The [^store] operation by thread1 precedes the [^load] by thread2:
+ In this case thread2 will execute B and "A ['happens-before] B"
+ holds as all of the criteria above are satisfied.
+* The [^load] operation by thread2 precedes the [^store] by thread1:
+ In this case, thread2 will execute C, but "A ['happens-before] C"
+ does ['not] hold: thread2 does not read the value written by
+ thread1 through [^a].
+
+Therefore, A and B cannot conflict, but A and C ['can] conflict.
+
+[endsect]
+
+[section:fences Fences]
+
+Ordering constraints are generally specified together with an access to
+an atomic variable. It is however also possible to issue "fence"
+operations in isolation, in this case the fence operates in
+conjunction with preceding (for `acquire`, `consume` or `seq_cst`
+operations) or succeeding (for `release` or `seq_cst`) atomic
+operations.
+
+The example from the previous section could also be written in
+the following way:
+
+[c++]
+
+ atomic<int> a(0);
+
+ thread1:
+ ... /* A */
+ atomic_thread_fence(memory_order_release);
+ a.fetch_add(1, memory_order_relaxed);
+
+ thread2:
+ int tmp = a.load(memory_order_relaxed);
+ if (tmp == 1) {
+ atomic_thread_fence(memory_order_acquire);
+ ... /* B */
+ } else {
+ ... /* C */
+ }
+
+This provides the same ordering guarantees as previously, but
+elides a (possibly expensive) memory ordering operation in
+the case C is executed.
+
+[endsect]
+
+[section:release_consume ['happens-before] through [^release] and [^consume]]
+
+The second pattern for coordinating threads via [*Boost.Atomic]
+uses [^release] and [^consume] on an atomic variable for coordination: If ...
+
+* ... thread1 performs an operation A,
+* ... thread1 subsequently writes (or atomically modifies) an
+ atomic variable with [^release] semantic,
+* ... thread2 reads (or atomically reads-and-modifies)
+ the value this value from the same atomic variable with [^consume] semantic and
+* ... thread2 subsequently performs an operation B that is ['computationally
+ dependent on the value of the atomic variable],
+
+... then A ['happens-before] B.
+
+Consider the following example
+
+[c++]
+
+ atomic<int> a(0);
+ complex_data_structure data[2];
+
+ thread1:
+ data[1] = ...; /* A */
+ a.store(1, memory_order_release);
+
+ thread2:
+ int index = a.load(memory_order_consume);
+ complex_data_structure tmp = data[index]; /* B */
+
+In this example, two avenues for execution are possible:
+
+* The [^store] operation by thread1 precedes the [^load] by thread2:
+ In this case thread2 will read [^data\[1\]] and "A ['happens-before] B"
+ holds as all of the criteria above are satisfied.
+* The [^load] operation by thread2 precedes the [^store] by thread1:
+ In this case thread2 will read [^data\[0\]] and "A ['happens-before] B"
+ does ['not] hold: thread2 does not read the value written by
+ thread1 through [^a].
+
+Here, the ['happens-before] relationship helps ensure that any
+accesses (presumable writes) to [^data\[1\]] by thread1 happen before
+before the accesses (presumably reads) to [^data\[1\]] by thread2:
+Lacking this relationship, thread2 might see stale/inconsistent
+data.
+
+Note that in this example, the fact that operation B is computationally
+dependent on the atomic variable, therefore the following program would
+be erroneous:
+
+[c++]
+
+ atomic<int> a(0);
+ complex_data_structure data[2];
+
+ thread1:
+ data[1] = ...; /* A */
+ a.store(1, memory_order_release);
+
+ thread2:
+ int index = a.load(memory_order_consume);
+ complex_data_structure tmp;
+ if (index == 0)
+ tmp = data[0];
+ else
+ tmp = data[1];
+
+[^consume] is most commonly (and most safely! see
+[link atomic.limitations limitations]) used with
+pointers, compare for example the
+[link boost_atomic.usage_examples.singleton singleton with double-checked locking].
+
+[endsect]
+
+[section:seq_cst Sequential consistency]
+
+The third pattern for coordinating threads via [*Boost.Atomic]
+uses [^seq_cst] for coordination: If ...
+
+* ... thread1 performs an operation A,
+* ... thread1 subsequently performs any operation with [^seq_cst],
+* ... thread1 subsequently performs an operation B,
+* ... thread2 performs an operation C,
+* ... thread2 subsequently performs any operation with [^seq_cst],
+* ... thread2 subsequently performs an operation D,
+
+then either "A ['happens-before] D" or "C ['happens-before] B" holds.
+
+In this case it does not matter whether thread1 and thread2 operate
+on the same or different atomic variables, or use a "stand-alone"
+[^atomic_thread_fence] operation.
+
+[endsect]
+
+[endsect]
+
+[section:interface Programming interfaces]
+
+[section:configuration Configuration and building]
+
+The library contains header-only and compiled parts. The library is
+header-only for lock-free cases but requires a separate binary to
+implement the lock-based emulation. Users are able to detect whether
+linking to the compiled part is required by checking the
+[link atomic.interface.feature_macros feature macros].
+
+The following macros affect library behavior:
+
+[table
+ [[Macro] [Description]]
+ [[`BOOST_ATOMIC_NO_CMPXCHG16B`] [Affects 64-bit x86 MSVC builds. When defined,
+ the library assumes the target CPU does not support `cmpxchg16b` instruction used
+ to support 128-bit atomic operations. This is the case with some early 64-bit AMD CPUs,
+ all Intel CPUs and current AMD CPUs support this instruction. The library does not
+ perform runtime detection of this instruction, so running the code that uses 128-bit
+ atomics on such CPUs will result in crashes, unless this macro is defined. Note that
+ the macro does not affect GCC and compatible compilers because the library infers
+ this information from the compiler-defined macros.]]
+ [[`BOOST_ATOMIC_FORCE_FALLBACK`] [When defined, all operations are implemented with locks.
+ This is mostly used for testing and should not be used in real world projects.]]
+ [[`BOOST_ATOMIC_DYN_LINK` and `BOOST_ALL_DYN_LINK`] [Control library linking. If defined,
+ the library assumes dynamic linking, otherwise static. The latter macro affects all Boost
+ libraries, not just [*Boost.Atomic].]]
+ [[`BOOST_ATOMIC_NO_LIB` and `BOOST_ALL_NO_LIB`] [Control library auto-linking on Windows.
+ When defined, disables auto-linking. The latter macro affects all Boost libraries,
+ not just [*Boost.Atomic].]]
+]
+
+Besides macros, it is important to specify the correct compiler options for the target CPU.
+With GCC and compatible compilers this affects whether particular atomic operations are
+lock-free or not.
+
+Boost building process is described in the [@http://www.boost.org/doc/libs/release/more/getting_started/ Getting Started guide].
+For example, you can build [*Boost.Atomic] with the following command line:
+
+[pre
+ bjam --with-atomic variant=release instruction-set=core2 stage
+]
+
+[endsect]
+
+[section:interface_memory_order Memory order]
+
+ #include <boost/memory_order.hpp>
+
+The enumeration [^boost::memory_order] defines the following
+values to represent memory ordering constraints:
+
+[table
+ [[Constant] [Description]]
+ [[`memory_order_relaxed`] [No ordering constraint.
+ Informally speaking, following operations may be reordered before,
+ preceding operations may be reordered after the atomic
+ operation. This constraint is suitable only when
+ either a) further operations do not depend on the outcome
+ of the atomic operation or b) ordering is enforced through
+ stand-alone `atomic_thread_fence` operations. The operation on
+ the atomic value itself is still atomic though.
+ ]]
+ [[`memory_order_release`] [
+ Perform `release` operation. Informally speaking,
+ prevents all preceding memory operations to be reordered
+ past this point.
+ ]]
+ [[`memory_order_acquire`] [
+ Perform `acquire` operation. Informally speaking,
+ prevents succeeding memory operations to be reordered
+ before this point.
+ ]]
+ [[`memory_order_consume`] [
+ Perform `consume` operation. More relaxed (and
+ on some architectures more efficient) than `memory_order_acquire`
+ as it only affects succeeding operations that are
+ computationally-dependent on the value retrieved from
+ an atomic variable.
+ ]]
+ [[`memory_order_acq_rel`] [Perform both `release` and `acquire` operation]]
+ [[`memory_order_seq_cst`] [
+ Enforce sequential consistency. Implies `memory_order_acq_rel`, but
+ additionally enforces total order for all operations such qualified.
+ ]]
+]
+
+See section [link atomic.thread_coordination ['happens-before]] for explanation
+of the various ordering constraints.
+
+[endsect]
+
+[section:interface_atomic_object Atomic objects]
+
+ #include <boost/atomic/atomic.hpp>
+
+[^boost::atomic<['T]>] provides methods for atomically accessing
+variables of a suitable type [^['T]]. The type is suitable if
+it is /trivially copyable/ (3.9/9 \[basic.types\]). Following are
+examples of the types compatible with this requirement:
+
+* a scalar type (e.g. integer, boolean, enum or pointer type)
+* a [^class] or [^struct] that has no non-trivial copy or move
+ constructors or assignment operators, has a trivial destructor,
+ and that is comparable via [^memcmp].
+
+Note that classes with virtual functions or virtual base classes
+do not satisfy the requirements. Also be warned
+that structures with "padding" between data members may compare
+non-equal via [^memcmp] even though all members are equal.
+
+[section:interface_atomic_generic [^boost::atomic<['T]>] template class]
+
+All atomic objects supports the following operations:
+
+[table
+ [[Syntax] [Description]]
+ [
+ [`atomic()`]
+ [Initialize to an unspecified value]
+ ]
+ [
+ [`atomic(T initial_value)`]
+ [Initialize to [^initial_value]]
+ ]
+ [
+ [`bool is_lock_free()`]
+ [Checks if the atomic object is lock-free]
+ ]
+ [
+ [`T load(memory_order order)`]
+ [Return current value]
+ ]
+ [
+ [`void store(T value, memory_order order)`]
+ [Write new value to atomic variable]
+ ]
+ [
+ [`T exchange(T new_value, memory_order order)`]
+ [Exchange current value with `new_value`, returning current value]
+ ]
+ [
+ [`bool compare_exchange_weak(T & expected, T desired, memory_order order)`]
+ [Compare current value with `expected`, change it to `desired` if matches.
+ Returns `true` if an exchange has been performed, and always writes the
+ previous value back in `expected`. May fail spuriously, so must generally be
+ retried in a loop.]
+ ]
+ [
+ [`bool compare_exchange_weak(T & expected, T desired, memory_order success_order, memory_order failure_order)`]
+ [Compare current value with `expected`, change it to `desired` if matches.
+ Returns `true` if an exchange has been performed, and always writes the
+ previous value back in `expected`. May fail spuriously, so must generally be
+ retried in a loop.]
+ ]
+ [
+ [`bool compare_exchange_strong(T & expected, T desired, memory_order order)`]
+ [Compare current value with `expected`, change it to `desired` if matches.
+ Returns `true` if an exchange has been performed, and always writes the
+ previous value back in `expected`.]
+ ]
+ [
+ [`bool compare_exchange_strong(T & expected, T desired, memory_order success_order, memory_order failure_order))`]
+ [Compare current value with `expected`, change it to `desired` if matches.
+ Returns `true` if an exchange has been performed, and always writes the
+ previous value back in `expected`.]
+ ]
+]
+
+`order` always has `memory_order_seq_cst` as default parameter.
+
+The `compare_exchange_weak`/`compare_exchange_strong` variants
+taking four parameters differ from the three parameter variants
+in that they allow a different memory ordering constraint to
+be specified in case the operation fails.
+
+In addition to these explicit operations, each
+[^atomic<['T]>] object also supports
+implicit [^store] and [^load] through the use of "assignment"
+and "conversion to [^T]" operators. Avoid using these operators,
+as they do not allow explicit specification of a memory ordering
+constraint.
+
+[endsect]
+
+[section:interface_atomic_integral [^boost::atomic<['integral]>] template class]
+
+In addition to the operations listed in the previous section,
+[^boost::atomic<['I]>] for integral
+types [^['I]] supports the following operations:
+
+[table
+ [[Syntax] [Description]]
+ [
+ [`T fetch_add(T v, memory_order order)`]
+ [Add `v` to variable, returning previous value]
+ ]
+ [
+ [`T fetch_sub(T v, memory_order order)`]
+ [Subtract `v` from variable, returning previous value]
+ ]
+ [
+ [`T fetch_and(T v, memory_order order)`]
+ [Apply bit-wise "and" with `v` to variable, returning previous value]
+ ]
+ [
+ [`T fetch_or(T v, memory_order order)`]
+ [Apply bit-wise "or" with `v` to variable, returning previous value]
+ ]
+ [
+ [`T fetch_xor(T v, memory_order order)`]
+ [Apply bit-wise "xor" with `v` to variable, returning previous value]
+ ]
+]
+
+`order` always has `memory_order_seq_cst` as default parameter.
+
+In addition to these explicit operations, each
+[^boost::atomic<['I]>] object also
+supports implicit pre-/post- increment/decrement, as well
+as the operators `+=`, `-=`, `&=`, `|=` and `^=`.
+Avoid using these operators,
+as they do not allow explicit specification of a memory ordering
+constraint.
+
+[endsect]
+
+[section:interface_atomic_pointer [^boost::atomic<['pointer]>] template class]
+
+In addition to the operations applicable to all atomic object,
+[^boost::atomic<['P]>] for pointer
+types [^['P]] (other than [^void] pointers) support the following operations:
+
+[table
+ [[Syntax] [Description]]
+ [
+ [`T fetch_add(ptrdiff_t v, memory_order order)`]
+ [Add `v` to variable, returning previous value]
+ ]
+ [
+ [`T fetch_sub(ptrdiff_t v, memory_order order)`]
+ [Subtract `v` from variable, returning previous value]
+ ]
+]
+
+`order` always has `memory_order_seq_cst` as default parameter.
+
+In addition to these explicit operations, each
+[^boost::atomic<['P]>] object also
+supports implicit pre-/post- increment/decrement, as well
+as the operators `+=`, `-=`. Avoid using these operators,
+as they do not allow explicit specification of a memory ordering
+constraint.
+
+[endsect]
+
+[endsect]
+
+[section:interface_fences Fences]
+
+ #include <boost/atomic/fences.hpp>
+
+[table
+ [[Syntax] [Description]]
+ [
+ [`void atomic_thread_fence(memory_order order)`]
+ [Issue fence for coordination with other threads.]
+ ]
+ [
+ [`void atomic_signal_fence(memory_order order)`]
+ [Issue fence for coordination with signal handler (only in same thread).]
+ ]
+]
+
+[endsect]
+
+[section:feature_macros Feature testing macros]
+
+ #include <boost/atomic/capabilities.hpp>
+
+[*Boost.Atomic] defines a number of macros to allow compile-time
+detection whether an atomic data type is implemented using
+"true" atomic operations, or whether an internal "lock" is
+used to provide atomicity. The following macros will be
+defined to `0` if operations on the data type always
+require a lock, to `1` if operations on the data type may
+sometimes require a lock, and to `2` if they are always lock-free:
+
+[table
+ [[Macro] [Description]]
+ [
+ [`BOOST_ATOMIC_FLAG_LOCK_FREE`]
+ [Indicate whether `atomic_flag` is lock-free]
+ ]
+ [
+ [`BOOST_ATOMIC_BOOL_LOCK_FREE`]
+ [Indicate whether `atomic<bool>` is lock-free]
+ ]
+ [
+ [`BOOST_ATOMIC_CHAR_LOCK_FREE`]
+ [Indicate whether `atomic<char>` (including signed/unsigned variants) is lock-free]
+ ]
+ [
+ [`BOOST_ATOMIC_CHAR16_T_LOCK_FREE`]
+ [Indicate whether `atomic<char16_t>` (including signed/unsigned variants) is lock-free]
+ ]
+ [
+ [`BOOST_ATOMIC_CHAR32_T_LOCK_FREE`]
+ [Indicate whether `atomic<char32_t>` (including signed/unsigned variants) is lock-free]
+ ]
+ [
+ [`BOOST_ATOMIC_WCHAR_T_LOCK_FREE`]
+ [Indicate whether `atomic<wchar_t>` (including signed/unsigned variants) is lock-free]
+ ]
+ [
+ [`BOOST_ATOMIC_SHORT_LOCK_FREE`]
+ [Indicate whether `atomic<short>` (including signed/unsigned variants) is lock-free]
+ ]
+ [
+ [`BOOST_ATOMIC_INT_LOCK_FREE`]
+ [Indicate whether `atomic<int>` (including signed/unsigned variants) is lock-free]
+ ]
+ [
+ [`BOOST_ATOMIC_LONG_LOCK_FREE`]
+ [Indicate whether `atomic<long>` (including signed/unsigned variants) is lock-free]
+ ]
+ [
+ [`BOOST_ATOMIC_LLONG_LOCK_FREE`]
+ [Indicate whether `atomic<long long>` (including signed/unsigned variants) is lock-free]
+ ]
+ [
+ [`BOOST_ATOMIC_ADDRESS_LOCK_FREE` or `BOOST_ATOMIC_POINTER_LOCK_FREE`]
+ [Indicate whether `atomic<T *>` is lock-free]
+ ]
+ [
+ [`BOOST_ATOMIC_THREAD_FENCE`]
+ [Indicate whether `atomic_thread_fence` function is lock-free]
+ ]
+ [
+ [`BOOST_ATOMIC_SIGNAL_FENCE`]
+ [Indicate whether `atomic_signal_fence` function is lock-free]
+ ]
+]
+
+In addition to these standard macros, [*Boost.Atomic] also defines a number of extension macros,
+which can also be useful. Like the standard ones, these macros are defined to values `0`, `1` and `2`
+to indicate whether the corresponding operations are lock-free or not.
+
+[table
+ [[Macro] [Description]]
+ [
+ [`BOOST_ATOMIC_INT8_LOCK_FREE`]
+ [Indicate whether `atomic<int8_type>` is lock-free.]
+ ]
+ [
+ [`BOOST_ATOMIC_INT16_LOCK_FREE`]
+ [Indicate whether `atomic<int16_type>` is lock-free.]
+ ]
+ [
+ [`BOOST_ATOMIC_INT32_LOCK_FREE`]
+ [Indicate whether `atomic<int32_type>` is lock-free.]
+ ]
+ [
+ [`BOOST_ATOMIC_INT64_LOCK_FREE`]
+ [Indicate whether `atomic<int64_type>` is lock-free.]
+ ]
+ [
+ [`BOOST_ATOMIC_INT128_LOCK_FREE`]
+ [Indicate whether `atomic<int128_type>` is lock-free.]
+ ]
+ [
+ [`BOOST_ATOMIC_NO_ATOMIC_FLAG_INIT`]
+ [Defined after including `atomic_flag.hpp`, if the implementation
+ does not support the `BOOST_ATOMIC_FLAG_INIT` macro for static
+ initialization of `atomic_flag`. This macro is typically defined
+ for pre-C++11 compilers.]
+ ]
+]
+
+In the table above, `intN_type` is a type that fits storage of contiguous `N` bits, suitably aligned for atomic operations.
+
+[endsect]
+
+[endsect]
+
+[section:usage_examples Usage examples]
+
+[include examples.qbk]
+
+[endsect]
+
+[/
+[section:platform_support Implementing support for additional platforms]
+
+[include platform.qbk]
+
+[endsect]
+]
+
+[/ [xinclude autodoc.xml] ]
+
+[section:limitations Limitations]
+
+While [*Boost.Atomic] strives to implement the atomic operations
+from C++11 as faithfully as possible, there are a few
+limitations that cannot be lifted without compiler support:
+
+* [*Using non-POD-classes as template parameter to `atomic<T>` results
+ in undefined behavior]: This means that any class containing a
+ constructor, destructor, virtual methods or access control
+ specifications is not a valid argument in C++98. C++11 relaxes
+ this slightly by allowing "trivial" classes containing only
+ empty constructors. [*Advise]: Use only POD types.
+* [*C++98 compilers may transform computation- to control-dependency]:
+ Crucially, `memory_order_consume` only affects computationally-dependent
+ operations, but in general there is nothing preventing a compiler
+ from transforming a computation dependency into a control dependency.
+ A C++11 compiler would be forbidden from such a transformation.
+ [*Advise]: Use `memory_order_consume` only in conjunction with
+ pointer values, as the compiler cannot speculate and transform
+ these into control dependencies.
+* [*Fence operations enforce "too strong" compiler ordering]:
+ Semantically, `memory_order_acquire`/`memory_order_consume`
+ and `memory_order_release` need to restrain reordering of
+ memory operations only in one direction. Since there is no
+ way to express this constraint to the compiler, these act
+ as "full compiler barriers" in this implementation. In corner
+ cases this may result in a less efficient code than a C++11 compiler
+ could generate.
+* [*No interprocess fallback]: using `atomic<T>` in shared memory only works
+ correctly, if `atomic<T>::is_lock_free() == true`.
+
+[endsect]
+
+[section:porting Porting]
+
+[section:unit_tests Unit tests]
+
+[*Boost.Atomic] provides a unit test suite to verify that the
+implementation behaves as expected:
+
+* [*fallback_api.cpp] verifies that the fallback-to-locking aspect
+ of [*Boost.Atomic] compiles and has correct value semantics.
+* [*native_api.cpp] verifies that all atomic operations have correct
+ value semantics (e.g. "fetch_add" really adds the desired value,
+ returning the previous). It is a rough "smoke-test" to help weed
+ out the most obvious mistakes (for example width overflow,
+ signed/unsigned extension, ...).
+* [*lockfree.cpp] verifies that the [*BOOST_ATOMIC_*_LOCKFREE] macros
+ are set properly according to the expectations for a given
+ platform, and that they match up with the [*is_lock_free] member
+ functions of the [*atomic] object instances.
+* [*atomicity.cpp] lets two threads race against each other modifying
+ a shared variable, verifying that the operations behave atomic
+ as appropriate. By nature, this test is necessarily stochastic, and
+ the test self-calibrates to yield 99% confidence that a
+ positive result indicates absence of an error. This test is
+ very useful on uni-processor systems with preemption already.
+* [*ordering.cpp] lets two threads race against each other accessing
+ multiple shared variables, verifying that the operations
+ exhibit the expected ordering behavior. By nature, this test is
+ necessarily stochastic, and the test attempts to self-calibrate to
+ yield 99% confidence that a positive result indicates absence
+ of an error. This only works on true multi-processor (or multi-core)
+ systems. It does not yield any result on uni-processor systems
+ or emulators (due to there being no observable reordering even
+ the order=relaxed case) and will report that fact.
+
+[endsect]
+
+[section:tested_compilers Tested compilers]
+
+[*Boost.Atomic] has been tested on and is known to work on
+the following compilers/platforms:
+
+* gcc 4.x: i386, x86_64, ppc32, ppc64, sparcv9, armv6, alpha
+* Visual Studio Express 2008/Windows XP, x86, x64, ARM
+
+[endsect]
+
+[section:acknowledgements Acknowledgements]
+
+* Adam Wulkiewicz created the logo used on the [@https://github.com/boostorg/atomic GitHub project page]. The logo was taken from his [@https://github.com/awulkiew/boost-logos collection] of Boost logos.
+
+[endsect]
+
+[endsect]
diff --git a/3rdParty/Boost/src/libs/atomic/doc/examples.qbk b/3rdParty/Boost/src/libs/atomic/doc/examples.qbk
new file mode 100644
index 0000000..e34c402
--- /dev/null
+++ b/3rdParty/Boost/src/libs/atomic/doc/examples.qbk
@@ -0,0 +1,398 @@
+[/
+ / Copyright (c) 2009 Helge Bahmann
+ /
+ / Distributed under the Boost Software License, Version 1.0. (See accompanying
+ / file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+ /]
+
+[section:example_reference_counters Reference counting]
+
+The purpose of a ['reference counter] is to count the number
+of pointers to an object. The object can be destroyed as
+soon as the reference counter reaches zero.
+
+[section Implementation]
+
+[c++]
+
+ #include <boost/intrusive_ptr.hpp>
+ #include <boost/atomic.hpp>
+
+ class X {
+ public:
+ typedef boost::intrusive_ptr<X> pointer;
+ X() : refcount_(0) {}
+
+ private:
+ mutable boost::atomic<int> refcount_;
+ friend void intrusive_ptr_add_ref(const X * x)
+ {
+ x->refcount_.fetch_add(1, boost::memory_order_relaxed);
+ }
+ friend void intrusive_ptr_release(const X * x)
+ {
+ if (x->refcount_.fetch_sub(1, boost::memory_order_release) == 1) {
+ boost::atomic_thread_fence(boost::memory_order_acquire);
+ delete x;
+ }
+ }
+ };
+
+[endsect]
+
+[section Usage]
+
+[c++]
+
+ X::pointer x = new X;
+
+[endsect]
+
+[section Discussion]
+
+Increasing the reference counter can always be done with
+[^memory_order_relaxed]: New references to an object can only
+be formed from an existing reference, and passing an existing
+reference from one thread to another must already provide any
+required synchronization.
+
+It is important to enforce any possible access to the object in
+one thread (through an existing reference) to ['happen before]
+deleting the object in a different thread. This is achieved
+by a "release" operation after dropping a reference (any
+access to the object through this reference must obviously
+happened before), and an "acquire" operation before
+deleting the object.
+
+It would be possible to use [^memory_order_acq_rel] for the
+[^fetch_sub] operation, but this results in unneeded "acquire"
+operations when the reference counter does not yet reach zero
+and may impose a performance penalty.
+
+[endsect]
+
+[endsect]
+
+[section:example_spinlock Spinlock]
+
+The purpose of a ['spin lock] is to prevent multiple threads
+from concurrently accessing a shared data structure. In contrast
+to a mutex, threads will busy-wait and waste CPU cycles instead
+of yielding the CPU to another thread. ['Do not use spinlocks
+unless you are certain that you understand the consequences.]
+
+[section Implementation]
+
+[c++]
+
+ #include <boost/atomic.hpp>
+
+ class spinlock {
+ private:
+ typedef enum {Locked, Unlocked} LockState;
+ boost::atomic<LockState> state_;
+
+ public:
+ spinlock() : state_(Unlocked) {}
+
+ void lock()
+ {
+ while (state_.exchange(Locked, boost::memory_order_acquire) == Locked) {
+ /* busy-wait */
+ }
+ }
+ void unlock()
+ {
+ state_.store(Unlocked, boost::memory_order_release);
+ }
+ };
+
+[endsect]
+
+[section Usage]
+
+[c++]
+
+ spinlock s;
+
+ s.lock();
+ // access data structure here
+ s.unlock();
+
+[endsect]
+
+[section Discussion]
+
+The purpose of the spinlock is to make sure that one access
+to the shared data structure always strictly "happens before"
+another. The usage of acquire/release in lock/unlock is required
+and sufficient to guarantee this ordering.
+
+It would be correct to write the "lock" operation in the following
+way:
+
+[c++]
+
+ lock()
+ {
+ while (state_.exchange(Locked, boost::memory_order_relaxed) == Locked) {
+ /* busy-wait */
+ }
+ atomic_thread_fence(boost::memory_order_acquire);
+ }
+
+This "optimization" is however a) useless and b) may in fact hurt:
+a) Since the thread will be busily spinning on a blocked spinlock,
+it does not matter if it will waste the CPU cycles with just
+"exchange" operations or with both useless "exchange" and "acquire"
+operations. b) A tight "exchange" loop without any
+memory-synchronizing instruction introduced through an "acquire"
+operation will on some systems monopolize the memory subsystem
+and degrade the performance of other system components.
+
+[endsect]
+
+[endsect]
+
+[section:singleton Singleton with double-checked locking pattern]
+
+The purpose of the ['Singleton with double-checked locking pattern] is to ensure
+that at most one instance of a particular object is created.
+If one instance has been created already, access to the existing
+object should be as light-weight as possible.
+
+[section Implementation]
+
+[c++]
+
+ #include <boost/atomic.hpp>
+ #include <boost/thread/mutex.hpp>
+
+ class X {
+ public:
+ static X * instance()
+ {
+ X * tmp = instance_.load(boost::memory_order_consume);
+ if (!tmp) {
+ boost::mutex::scoped_lock guard(instantiation_mutex);
+ tmp = instance_.load(boost::memory_order_consume);
+ if (!tmp) {
+ tmp = new X;
+ instance_.store(tmp, boost::memory_order_release);
+ }
+ }
+ return tmp;
+ }
+ private:
+ static boost::atomic<X *> instance_;
+ static boost::mutex instantiation_mutex;
+ };
+
+ boost::atomic<X *> X::instance_(0);
+
+[endsect]
+
+[section Usage]
+
+[c++]
+
+ X * x = X::instance();
+ // dereference x
+
+[endsect]
+
+[section Discussion]
+
+The mutex makes sure that only one instance of the object is
+ever created. The [^instance] method must make sure that any
+dereference of the object strictly "happens after" creating
+the instance in another thread. The use of [^memory_order_release]
+after creating and initializing the object and [^memory_order_consume]
+before dereferencing the object provides this guarantee.
+
+It would be permissible to use [^memory_order_acquire] instead of
+[^memory_order_consume], but this provides a stronger guarantee
+than is required since only operations depending on the value of
+the pointer need to be ordered.
+
+[endsect]
+
+[endsect]
+
+[section:example_ringbuffer Wait-free ring buffer]
+
+A ['wait-free ring buffer] provides a mechanism for relaying objects
+from one single "producer" thread to one single "consumer" thread without
+any locks. The operations on this data structure are "wait-free" which
+means that each operation finishes within a constant number of steps.
+This makes this data structure suitable for use in hard real-time systems
+or for communication with interrupt/signal handlers.
+
+[section Implementation]
+
+[c++]
+
+ #include <boost/atomic.hpp>
+
+ template<typename T, size_t Size>
+ class ringbuffer {
+ public:
+ ringbuffer() : head_(0), tail_(0) {}
+
+ bool push(const T & value)
+ {
+ size_t head = head_.load(boost::memory_order_relaxed);
+ size_t next_head = next(head);
+ if (next_head == tail_.load(boost::memory_order_acquire))
+ return false;
+ ring_[head] = value;
+ head_.store(next_head, boost::memory_order_release);
+ return true;
+ }
+ bool pop(T & value)
+ {
+ size_t tail = tail_.load(boost::memory_order_relaxed);
+ if (tail == head_.load(boost::memory_order_acquire))
+ return false;
+ value = ring_[tail];
+ tail_.store(next(tail), boost::memory_order_release);
+ return true;
+ }
+ private:
+ size_t next(size_t current)
+ {
+ return (current + 1) % Size;
+ }
+ T ring_[Size];
+ boost::atomic<size_t> head_, tail_;
+ };
+
+[endsect]
+
+[section Usage]
+
+[c++]
+
+ ringbuffer<int, 32> r;
+
+ // try to insert an element
+ if (r.push(42)) { /* succeeded */ }
+ else { /* buffer full */ }
+
+ // try to retrieve an element
+ int value;
+ if (r.pop(value)) { /* succeeded */ }
+ else { /* buffer empty */ }
+
+[endsect]
+
+[section Discussion]
+
+The implementation makes sure that the ring indices do
+not "lap-around" each other to ensure that no elements
+are either lost or read twice.
+
+Furthermore it must guarantee that read-access to a
+particular object in [^pop] "happens after" it has been
+written in [^push]. This is achieved by writing [^head_ ]
+with "release" and reading it with "acquire". Conversely
+the implementation also ensures that read access to
+a particular ring element "happens before" before
+rewriting this element with a new value by accessing [^tail_]
+with appropriate ordering constraints.
+
+[endsect]
+
+[endsect]
+
+[section:mp_queue Wait-free multi-producer queue]
+
+The purpose of the ['wait-free multi-producer queue] is to allow
+an arbitrary number of producers to enqueue objects which are
+retrieved and processed in FIFO order by a single consumer.
+
+[section Implementation]
+
+[c++]
+
+ template<typename T>
+ class waitfree_queue {
+ public:
+ struct node {
+ T data;
+ node * next;
+ };
+ void push(const T &data)
+ {
+ node * n = new node;
+ n->data = data;
+ node * stale_head = head_.load(boost::memory_order_relaxed);
+ do {
+ n->next = stale_head;
+ } while (!head_.compare_exchange_weak(stale_head, n, boost::memory_order_release));
+ }
+
+ node * pop_all(void)
+ {
+ T * last = pop_all_reverse(), * first = 0;
+ while(last) {
+ T * tmp = last;
+ last = last->next;
+ tmp->next = first;
+ first = tmp;
+ }
+ return first;
+ }
+
+ waitfree_queue() : head_(0) {}
+
+ // alternative interface if ordering is of no importance
+ node * pop_all_reverse(void)
+ {
+ return head_.exchange(0, boost::memory_order_consume);
+ }
+ private:
+ boost::atomic<node *> head_;
+ };
+
+[endsect]
+
+[section Usage]
+
+[c++]
+
+ waitfree_queue<int> q;
+
+ // insert elements
+ q.push(42);
+ q.push(2);
+
+ // pop elements
+ waitfree_queue<int>::node * x = q.pop_all()
+ while(x) {
+ X * tmp = x;
+ x = x->next;
+ // process tmp->data, probably delete it afterwards
+ delete tmp;
+ }
+
+[endsect]
+
+[section Discussion]
+
+The implementation guarantees that all objects enqueued are
+processed in the order they were enqueued by building a singly-linked
+list of object in reverse processing order. The queue is atomically
+emptied by the consumer and brought into correct order.
+
+It must be guaranteed that any access to an object to be enqueued
+by the producer "happens before" any access by the consumer. This
+is assured by inserting objects into the list with ['release] and
+dequeuing them with ['consume] memory order. It is not
+necessary to use ['acquire] memory order in [^waitfree_queue::pop_all]
+because all operations involved depend on the value of
+the atomic pointer through dereference
+
+[endsect]
+
+[endsect]
diff --git a/3rdParty/Boost/src/libs/atomic/doc/logo.png b/3rdParty/Boost/src/libs/atomic/doc/logo.png
new file mode 100644
index 0000000..8b12104
--- /dev/null
+++ b/3rdParty/Boost/src/libs/atomic/doc/logo.png
Binary files differ
diff --git a/3rdParty/Boost/src/libs/atomic/doc/logo.svg b/3rdParty/Boost/src/libs/atomic/doc/logo.svg
new file mode 100644
index 0000000..50d078e
--- /dev/null
+++ b/3rdParty/Boost/src/libs/atomic/doc/logo.svg
@@ -0,0 +1,1053 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Created with Inkscape (http://www.inkscape.org/) -->
+
+<svg
+ xmlns:dc="http://purl.org/dc/elements/1.1/"
+ xmlns:cc="http://creativecommons.org/ns#"
+ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:svg="http://www.w3.org/2000/svg"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:xlink="http://www.w3.org/1999/xlink"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ width="744.09448819"
+ height="1052.3622047"
+ id="svg7933"
+ version="1.1"
+ inkscape:version="0.48.4 r9939"
+ sodipodi:docname="atomic.svg">
+ <defs
+ id="defs7935">
+ <linearGradient
+ inkscape:collect="always"
+ xlink:href="#linearGradient4453-7-8-6-7-87"
+ id="linearGradient10687-9"
+ gradientUnits="userSpaceOnUse"
+ x1="753.02301"
+ y1="3132.0801"
+ x2="1146.25"
+ y2="3132.0801" />
+ <linearGradient
+ id="linearGradient4453-7-8-6-7-87">
+ <stop
+ style="stop-color:#aac4dd;stop-opacity:1;"
+ offset="0"
+ id="stop4455-61-8-7-1-8" />
+ <stop
+ style="stop-color:#c2dbe9;stop-opacity:1;"
+ offset="1"
+ id="stop4457-4-1-9-1-4" />
+ </linearGradient>
+ <linearGradient
+ inkscape:collect="always"
+ xlink:href="#linearGradient4453-7-8-6-7-87"
+ id="linearGradient10685-44"
+ gradientUnits="userSpaceOnUse"
+ x1="753.02301"
+ y1="3132.0801"
+ x2="1146.25"
+ y2="3132.0801" />
+ <linearGradient
+ id="linearGradient7822">
+ <stop
+ style="stop-color:#aac4dd;stop-opacity:1;"
+ offset="0"
+ id="stop7824" />
+ <stop
+ style="stop-color:#c2dbe9;stop-opacity:1;"
+ offset="1"
+ id="stop7826" />
+ </linearGradient>
+ <clipPath
+ clipPathUnits="userSpaceOnUse"
+ id="clipPath3387-3-6-4-2-3">
+ <path
+ inkscape:connector-curvature="0"
+ d="m 862.109,3289.75 -109.086,-190.45 69.122,-124.42 164.511,-0.47 c 0,0 111.044,188.28 116.564,197.63 7.66,0 43.03,0 43.03,0 l -67.03,117.71 -217.111,0 z"
+ id="path3389-2-0-7-7-58" />
+ </clipPath>
+ <linearGradient
+ y2="3132.0801"
+ x2="1146.25"
+ y1="3132.0801"
+ x1="753.02301"
+ gradientUnits="userSpaceOnUse"
+ id="linearGradient4492-0"
+ xlink:href="#linearGradient4453-7-8-6-7-87"
+ inkscape:collect="always" />
+ <linearGradient
+ id="linearGradient7831">
+ <stop
+ style="stop-color:#aac4dd;stop-opacity:1;"
+ offset="0"
+ id="stop7833" />
+ <stop
+ style="stop-color:#c2dbe9;stop-opacity:1;"
+ offset="1"
+ id="stop7835" />
+ </linearGradient>
+ <linearGradient
+ inkscape:collect="always"
+ xlink:href="#linearGradient4453-7-8-6-7-87"
+ id="linearGradient10691-2"
+ gradientUnits="userSpaceOnUse"
+ x1="1026.6899"
+ y1="2937.73"
+ x2="1463.14"
+ y2="2937.73" />
+ <linearGradient
+ id="linearGradient7838">
+ <stop
+ style="stop-color:#aac4dd;stop-opacity:1;"
+ offset="0"
+ id="stop7840" />
+ <stop
+ style="stop-color:#c2dbe9;stop-opacity:1;"
+ offset="1"
+ id="stop7842" />
+ </linearGradient>
+ <linearGradient
+ inkscape:collect="always"
+ xlink:href="#linearGradient4453-7-8-6-7-87"
+ id="linearGradient10689-9"
+ gradientUnits="userSpaceOnUse"
+ x1="1026.6899"
+ y1="2937.73"
+ x2="1463.14"
+ y2="2937.73" />
+ <linearGradient
+ id="linearGradient7845">
+ <stop
+ style="stop-color:#aac4dd;stop-opacity:1;"
+ offset="0"
+ id="stop7847" />
+ <stop
+ style="stop-color:#c2dbe9;stop-opacity:1;"
+ offset="1"
+ id="stop7849" />
+ </linearGradient>
+ <clipPath
+ clipPathUnits="userSpaceOnUse"
+ id="clipPath3369-1-5-6-1-49">
+ <path
+ inkscape:connector-curvature="0"
+ d="m 1131.64,3128.5 -104.95,-181.12 116.38,-200.42 208.05,0.94 112.02,191.63 -112.08,188.97 -219.42,0 z"
+ id="path3371-89-4-1-6-8" />
+ </clipPath>
+ <linearGradient
+ y2="2937.73"
+ x2="1463.14"
+ y1="2937.73"
+ x1="1026.6899"
+ gradientUnits="userSpaceOnUse"
+ id="linearGradient4498-3"
+ xlink:href="#linearGradient4453-7-8-6-7-87"
+ inkscape:collect="always" />
+ <linearGradient
+ id="linearGradient7854">
+ <stop
+ style="stop-color:#aac4dd;stop-opacity:1;"
+ offset="0"
+ id="stop7856" />
+ <stop
+ style="stop-color:#c2dbe9;stop-opacity:1;"
+ offset="1"
+ id="stop7858" />
+ </linearGradient>
+ <linearGradient
+ inkscape:collect="always"
+ xlink:href="#linearGradient4459-1-2-8-9-0"
+ id="linearGradient10695-5"
+ gradientUnits="userSpaceOnUse"
+ x1="646.55499"
+ y1="2736.25"
+ x2="1088.27"
+ y2="2736.25" />
+ <linearGradient
+ id="linearGradient4459-1-2-8-9-0">
+ <stop
+ id="stop4461-2-1-5-2-43"
+ offset="0"
+ style="stop-color:#839bc2;stop-opacity:1;" />
+ <stop
+ id="stop4463-3-2-8-7-5"
+ offset="1"
+ style="stop-color:#9fb6d4;stop-opacity:1;" />
+ </linearGradient>
+ <linearGradient
+ inkscape:collect="always"
+ xlink:href="#linearGradient4459-1-2-8-9-0"
+ id="linearGradient10693-2"
+ gradientUnits="userSpaceOnUse"
+ x1="646.55499"
+ y1="2736.25"
+ x2="1088.27"
+ y2="2736.25" />
+ <linearGradient
+ id="linearGradient7865">
+ <stop
+ id="stop7867"
+ offset="0"
+ style="stop-color:#839bc2;stop-opacity:1;" />
+ <stop
+ id="stop7869"
+ offset="1"
+ style="stop-color:#9fb6d4;stop-opacity:1;" />
+ </linearGradient>
+ <clipPath
+ clipPathUnits="userSpaceOnUse"
+ id="clipPath3351-4-7-3-5-57">
+ <path
+ inkscape:connector-curvature="0"
+ d="m 757.242,2926.25 -110.687,-189.11 110.656,-190.89 219.437,0 111.622,189.1 -111.59,190.9 -219.438,0 z"
+ id="path3353-1-9-3-4-77" />
+ </clipPath>
+ <linearGradient
+ y2="2736.25"
+ x2="1088.27"
+ y1="2736.25"
+ x1="646.55499"
+ gradientUnits="userSpaceOnUse"
+ id="linearGradient4510-4"
+ xlink:href="#linearGradient4459-1-2-8-9-0"
+ inkscape:collect="always" />
+ <linearGradient
+ id="linearGradient7874">
+ <stop
+ id="stop7876"
+ offset="0"
+ style="stop-color:#839bc2;stop-opacity:1;" />
+ <stop
+ id="stop7878"
+ offset="1"
+ style="stop-color:#9fb6d4;stop-opacity:1;" />
+ </linearGradient>
+ <radialGradient
+ inkscape:collect="always"
+ xlink:href="#radialGradient3327-8-4-8-0-0"
+ id="radialGradient10699-4"
+ gradientUnits="userSpaceOnUse"
+ cx="997.46997"
+ cy="2896.25"
+ fx="997.46997"
+ fy="2896.25"
+ r="583.73999" />
+ <radialGradient
+ fx="0"
+ fy="0"
+ cx="0"
+ cy="0"
+ r="1"
+ gradientUnits="userSpaceOnUse"
+ gradientTransform="matrix(58.375,0,0,-58.375,99.75,289.625)"
+ spreadMethod="pad"
+ id="radialGradient3327-8-4-8-0-0">
+ <stop
+ style="stop-opacity:1;stop-color:#aeaeb3"
+ offset="0"
+ id="stop3329-7-0-1-0-4" />
+ <stop
+ style="stop-opacity:1;stop-color:#ffffff"
+ offset="0.949438"
+ id="stop3331-4-3-0-0-11" />
+ <stop
+ style="stop-opacity:1;stop-color:#ffffff"
+ offset="1"
+ id="stop3333-2-4-9-7-54" />
+ </radialGradient>
+ <radialGradient
+ r="583.73999"
+ fy="2896.25"
+ fx="997.46997"
+ cy="2896.25"
+ cx="997.46997"
+ gradientUnits="userSpaceOnUse"
+ id="radialGradient15837"
+ xlink:href="#radialGradient3327-8-4-8-0-0"
+ inkscape:collect="always" />
+ <radialGradient
+ fx="0"
+ fy="0"
+ cx="0"
+ cy="0"
+ r="1"
+ gradientUnits="userSpaceOnUse"
+ gradientTransform="matrix(58.375,0,0,-58.375,99.75,289.625)"
+ spreadMethod="pad"
+ id="radialGradient7886">
+ <stop
+ style="stop-opacity:1;stop-color:#aeaeb3"
+ offset="0"
+ id="stop7888" />
+ <stop
+ style="stop-opacity:1;stop-color:#ffffff"
+ offset="0.949438"
+ id="stop7890" />
+ <stop
+ style="stop-opacity:1;stop-color:#ffffff"
+ offset="1"
+ id="stop7892" />
+ </radialGradient>
+ <clipPath
+ clipPathUnits="userSpaceOnUse"
+ id="clipPath3323-7-2-4-5-2">
+ <path
+ inkscape:connector-curvature="0"
+ d="m 997.469,2312.51 c -322.379,0 -583.739,261.36 -583.739,583.74 0,322.38 261.36,583.74 583.739,583.74 322.381,0 583.741,-261.36 583.741,-583.74 0,-322.38 -261.36,-583.74 -583.741,-583.74"
+ id="path3325-9-2-9-5-8" />
+ </clipPath>
+ <radialGradient
+ r="583.73999"
+ fy="2896.25"
+ fx="997.46997"
+ cy="2896.25"
+ cx="997.46997"
+ gradientUnits="userSpaceOnUse"
+ id="radialGradient4516-6"
+ xlink:href="#radialGradient3327-8-4-8-0-0"
+ inkscape:collect="always" />
+ <radialGradient
+ fx="0"
+ fy="0"
+ cx="0"
+ cy="0"
+ r="1"
+ gradientUnits="userSpaceOnUse"
+ gradientTransform="matrix(58.375,0,0,-58.375,99.75,289.625)"
+ spreadMethod="pad"
+ id="radialGradient7897">
+ <stop
+ style="stop-opacity:1;stop-color:#aeaeb3"
+ offset="0"
+ id="stop7899" />
+ <stop
+ style="stop-opacity:1;stop-color:#ffffff"
+ offset="0.949438"
+ id="stop7901" />
+ <stop
+ style="stop-opacity:1;stop-color:#ffffff"
+ offset="1"
+ id="stop7903" />
+ </radialGradient>
+ <radialGradient
+ r="583.73999"
+ fy="2896.25"
+ fx="997.46997"
+ cy="2896.25"
+ cx="997.46997"
+ gradientUnits="userSpaceOnUse"
+ id="radialGradient7931"
+ xlink:href="#radialGradient3327-8-4-8-0-0"
+ inkscape:collect="always" />
+ <linearGradient
+ inkscape:collect="always"
+ xlink:href="#linearGradient4453-7-8-6-7-87-7"
+ id="linearGradient10687-9-1"
+ gradientUnits="userSpaceOnUse"
+ x1="753.02301"
+ y1="3132.0801"
+ x2="1146.25"
+ y2="3132.0801" />
+ <linearGradient
+ id="linearGradient4453-7-8-6-7-87-7">
+ <stop
+ style="stop-color:#aac4dd;stop-opacity:1;"
+ offset="0"
+ id="stop4455-61-8-7-1-8-4" />
+ <stop
+ style="stop-color:#c2dbe9;stop-opacity:1;"
+ offset="1"
+ id="stop4457-4-1-9-1-4-0" />
+ </linearGradient>
+ <linearGradient
+ inkscape:collect="always"
+ xlink:href="#linearGradient4453-7-8-6-7-87-7"
+ id="linearGradient10685-44-9"
+ gradientUnits="userSpaceOnUse"
+ x1="753.02301"
+ y1="3132.0801"
+ x2="1146.25"
+ y2="3132.0801" />
+ <linearGradient
+ id="linearGradient3083">
+ <stop
+ style="stop-color:#aac4dd;stop-opacity:1;"
+ offset="0"
+ id="stop3085" />
+ <stop
+ style="stop-color:#c2dbe9;stop-opacity:1;"
+ offset="1"
+ id="stop3087" />
+ </linearGradient>
+ <clipPath
+ clipPathUnits="userSpaceOnUse"
+ id="clipPath3387-3-6-4-2-3-4">
+ <path
+ inkscape:connector-curvature="0"
+ d="m 862.109,3289.75 -109.086,-190.45 69.122,-124.42 164.511,-0.47 c 0,0 111.044,188.28 116.564,197.63 7.66,0 43.03,0 43.03,0 l -67.03,117.71 -217.111,0 z"
+ id="path3389-2-0-7-7-58-8" />
+ </clipPath>
+ <linearGradient
+ y2="3132.0801"
+ x2="1146.25"
+ y1="3132.0801"
+ x1="753.02301"
+ gradientUnits="userSpaceOnUse"
+ id="linearGradient4492-0-8"
+ xlink:href="#linearGradient4453-7-8-6-7-87-7"
+ inkscape:collect="always" />
+ <linearGradient
+ id="linearGradient3092">
+ <stop
+ style="stop-color:#aac4dd;stop-opacity:1;"
+ offset="0"
+ id="stop3094" />
+ <stop
+ style="stop-color:#c2dbe9;stop-opacity:1;"
+ offset="1"
+ id="stop3096" />
+ </linearGradient>
+ <linearGradient
+ inkscape:collect="always"
+ xlink:href="#linearGradient4453-7-8-6-7-87-7"
+ id="linearGradient10691-2-2"
+ gradientUnits="userSpaceOnUse"
+ x1="1026.6899"
+ y1="2937.73"
+ x2="1463.14"
+ y2="2937.73" />
+ <linearGradient
+ id="linearGradient3099">
+ <stop
+ style="stop-color:#aac4dd;stop-opacity:1;"
+ offset="0"
+ id="stop3101" />
+ <stop
+ style="stop-color:#c2dbe9;stop-opacity:1;"
+ offset="1"
+ id="stop3103" />
+ </linearGradient>
+ <linearGradient
+ inkscape:collect="always"
+ xlink:href="#linearGradient4453-7-8-6-7-87-7"
+ id="linearGradient10689-9-4"
+ gradientUnits="userSpaceOnUse"
+ x1="1026.6899"
+ y1="2937.73"
+ x2="1463.14"
+ y2="2937.73" />
+ <linearGradient
+ id="linearGradient3106">
+ <stop
+ style="stop-color:#aac4dd;stop-opacity:1;"
+ offset="0"
+ id="stop3108" />
+ <stop
+ style="stop-color:#c2dbe9;stop-opacity:1;"
+ offset="1"
+ id="stop3110" />
+ </linearGradient>
+ <clipPath
+ clipPathUnits="userSpaceOnUse"
+ id="clipPath3369-1-5-6-1-49-5">
+ <path
+ inkscape:connector-curvature="0"
+ d="m 1131.64,3128.5 -104.95,-181.12 116.38,-200.42 208.05,0.94 112.02,191.63 -112.08,188.97 -219.42,0 z"
+ id="path3371-89-4-1-6-8-5" />
+ </clipPath>
+ <linearGradient
+ y2="2937.73"
+ x2="1463.14"
+ y1="2937.73"
+ x1="1026.6899"
+ gradientUnits="userSpaceOnUse"
+ id="linearGradient4498-3-1"
+ xlink:href="#linearGradient4453-7-8-6-7-87-7"
+ inkscape:collect="always" />
+ <linearGradient
+ id="linearGradient3115">
+ <stop
+ style="stop-color:#aac4dd;stop-opacity:1;"
+ offset="0"
+ id="stop3117" />
+ <stop
+ style="stop-color:#c2dbe9;stop-opacity:1;"
+ offset="1"
+ id="stop3119" />
+ </linearGradient>
+ <linearGradient
+ inkscape:collect="always"
+ xlink:href="#linearGradient4459-1-2-8-9-0-1"
+ id="linearGradient10695-5-7"
+ gradientUnits="userSpaceOnUse"
+ x1="646.55499"
+ y1="2736.25"
+ x2="1088.27"
+ y2="2736.25" />
+ <linearGradient
+ id="linearGradient4459-1-2-8-9-0-1">
+ <stop
+ id="stop4461-2-1-5-2-43-1"
+ offset="0"
+ style="stop-color:#839bc2;stop-opacity:1;" />
+ <stop
+ id="stop4463-3-2-8-7-5-5"
+ offset="1"
+ style="stop-color:#9fb6d4;stop-opacity:1;" />
+ </linearGradient>
+ <linearGradient
+ inkscape:collect="always"
+ xlink:href="#linearGradient4459-1-2-8-9-0-1"
+ id="linearGradient10693-2-2"
+ gradientUnits="userSpaceOnUse"
+ x1="646.55499"
+ y1="2736.25"
+ x2="1088.27"
+ y2="2736.25" />
+ <linearGradient
+ id="linearGradient3126">
+ <stop
+ id="stop3128"
+ offset="0"
+ style="stop-color:#839bc2;stop-opacity:1;" />
+ <stop
+ id="stop3130"
+ offset="1"
+ style="stop-color:#9fb6d4;stop-opacity:1;" />
+ </linearGradient>
+ <clipPath
+ clipPathUnits="userSpaceOnUse"
+ id="clipPath3351-4-7-3-5-57-7">
+ <path
+ inkscape:connector-curvature="0"
+ d="m 757.242,2926.25 -110.687,-189.11 110.656,-190.89 219.437,0 111.622,189.1 -111.59,190.9 -219.438,0 z"
+ id="path3353-1-9-3-4-77-6" />
+ </clipPath>
+ <linearGradient
+ y2="2736.25"
+ x2="1088.27"
+ y1="2736.25"
+ x1="646.55499"
+ gradientUnits="userSpaceOnUse"
+ id="linearGradient4510-4-1"
+ xlink:href="#linearGradient4459-1-2-8-9-0-1"
+ inkscape:collect="always" />
+ <linearGradient
+ id="linearGradient3135">
+ <stop
+ id="stop3137"
+ offset="0"
+ style="stop-color:#839bc2;stop-opacity:1;" />
+ <stop
+ id="stop3139"
+ offset="1"
+ style="stop-color:#9fb6d4;stop-opacity:1;" />
+ </linearGradient>
+ <radialGradient
+ inkscape:collect="always"
+ xlink:href="#radialGradient3327-8-4-8-0-0-2"
+ id="radialGradient10699-4-4"
+ gradientUnits="userSpaceOnUse"
+ cx="997.46997"
+ cy="2896.25"
+ fx="997.46997"
+ fy="2896.25"
+ r="583.73999" />
+ <radialGradient
+ fx="0"
+ fy="0"
+ cx="0"
+ cy="0"
+ r="1"
+ gradientUnits="userSpaceOnUse"
+ gradientTransform="matrix(58.375,0,0,-58.375,99.75,289.625)"
+ spreadMethod="pad"
+ id="radialGradient3327-8-4-8-0-0-2">
+ <stop
+ style="stop-opacity:1;stop-color:#aeaeb3"
+ offset="0"
+ id="stop3329-7-0-1-0-4-3" />
+ <stop
+ style="stop-opacity:1;stop-color:#ffffff"
+ offset="0.949438"
+ id="stop3331-4-3-0-0-11-2" />
+ <stop
+ style="stop-opacity:1;stop-color:#ffffff"
+ offset="1"
+ id="stop3333-2-4-9-7-54-2" />
+ </radialGradient>
+ <radialGradient
+ r="583.73999"
+ fy="2896.25"
+ fx="997.46997"
+ cy="2896.25"
+ cx="997.46997"
+ gradientUnits="userSpaceOnUse"
+ id="radialGradient7931-1"
+ xlink:href="#radialGradient3327-8-4-8-0-0-2"
+ inkscape:collect="always" />
+ <radialGradient
+ fx="0"
+ fy="0"
+ cx="0"
+ cy="0"
+ r="1"
+ gradientUnits="userSpaceOnUse"
+ gradientTransform="matrix(58.375,0,0,-58.375,99.75,289.625)"
+ spreadMethod="pad"
+ id="radialGradient3147">
+ <stop
+ style="stop-opacity:1;stop-color:#aeaeb3"
+ offset="0"
+ id="stop3149" />
+ <stop
+ style="stop-opacity:1;stop-color:#ffffff"
+ offset="0.949438"
+ id="stop3151" />
+ <stop
+ style="stop-opacity:1;stop-color:#ffffff"
+ offset="1"
+ id="stop3153" />
+ </radialGradient>
+ <clipPath
+ clipPathUnits="userSpaceOnUse"
+ id="clipPath3323-7-2-4-5-2-6">
+ <path
+ inkscape:connector-curvature="0"
+ d="m 997.469,2312.51 c -322.379,0 -583.739,261.36 -583.739,583.74 0,322.38 261.36,583.74 583.739,583.74 322.381,0 583.741,-261.36 583.741,-583.74 0,-322.38 -261.36,-583.74 -583.741,-583.74"
+ id="path3325-9-2-9-5-8-8" />
+ </clipPath>
+ <radialGradient
+ r="583.73999"
+ fy="2896.25"
+ fx="997.46997"
+ cy="2896.25"
+ cx="997.46997"
+ gradientUnits="userSpaceOnUse"
+ id="radialGradient4516-6-5"
+ xlink:href="#radialGradient3327-8-4-8-0-0-2"
+ inkscape:collect="always" />
+ <radialGradient
+ fx="0"
+ fy="0"
+ cx="0"
+ cy="0"
+ r="1"
+ gradientUnits="userSpaceOnUse"
+ gradientTransform="matrix(58.375,0,0,-58.375,99.75,289.625)"
+ spreadMethod="pad"
+ id="radialGradient3158">
+ <stop
+ style="stop-opacity:1;stop-color:#aeaeb3"
+ offset="0"
+ id="stop3160" />
+ <stop
+ style="stop-opacity:1;stop-color:#ffffff"
+ offset="0.949438"
+ id="stop3162" />
+ <stop
+ style="stop-opacity:1;stop-color:#ffffff"
+ offset="1"
+ id="stop3164" />
+ </radialGradient>
+ <radialGradient
+ r="583.73999"
+ fy="2896.25"
+ fx="997.46997"
+ cy="2896.25"
+ cx="997.46997"
+ gradientUnits="userSpaceOnUse"
+ id="radialGradient3192"
+ xlink:href="#radialGradient3327-8-4-8-0-0-2"
+ inkscape:collect="always" />
+ </defs>
+ <sodipodi:namedview
+ id="base"
+ pagecolor="#ffffff"
+ bordercolor="#666666"
+ borderopacity="1.0"
+ inkscape:pageopacity="0.0"
+ inkscape:pageshadow="2"
+ inkscape:zoom="0.98994949"
+ inkscape:cx="194.37763"
+ inkscape:cy="577.68232"
+ inkscape:document-units="px"
+ inkscape:current-layer="layer1"
+ showgrid="false"
+ inkscape:window-width="1680"
+ inkscape:window-height="982"
+ inkscape:window-x="-8"
+ inkscape:window-y="-8"
+ inkscape:window-maximized="1" />
+ <metadata
+ id="metadata7938">
+ <rdf:RDF>
+ <cc:Work
+ rdf:about="">
+ <dc:format>image/svg+xml</dc:format>
+ <dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+ <dc:title />
+ </cc:Work>
+ </rdf:RDF>
+ </metadata>
+ <g
+ inkscape:label="Layer 1"
+ inkscape:groupmode="layer"
+ id="layer1">
+ <g
+ id="g3319-1-2-5-1-8"
+ transform="matrix(0.10419818,0,0,-0.10419818,149.49392,819.86044)"
+ style="fill:url(#radialGradient10699-4);fill-opacity:1"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523">
+ <g
+ clip-path="url(#clipPath3323-7-2-4-5-2)"
+ id="g3321-9-2-7-4-14"
+ style="fill:url(#radialGradient7931);fill-opacity:1">
+ <path
+ id="path3335-8-7-3-8-7"
+ style="fill:url(#radialGradient4516-6);fill-opacity:1;fill-rule:nonzero;stroke:none"
+ d="m 997.469,2312.51 c -322.379,0 -583.739,261.36 -583.739,583.74 0,322.38 261.36,583.74 583.739,583.74 322.381,0 583.741,-261.36 583.741,-583.74 0,-322.38 -261.36,-583.74 -583.741,-583.74"
+ inkscape:connector-curvature="0" />
+ </g>
+ </g>
+ <g
+ id="g3347-6-8-3-7-64"
+ transform="matrix(0.125,0,0,-0.125,124.46742,882.67914)"
+ style="fill:url(#linearGradient10695-5);fill-opacity:1"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523">
+ <g
+ clip-path="url(#clipPath3351-4-7-3-5-57)"
+ id="g3349-5-5-4-7-98"
+ style="fill:url(#linearGradient10693-2);fill-opacity:1">
+ <path
+ id="path3361-0-8-2-9-7"
+ style="fill:url(#linearGradient4510-4);fill-opacity:1;fill-rule:nonzero;stroke:none"
+ d="m 757.242,2926.25 -110.687,-189.11 110.656,-190.89 219.437,0 111.622,189.1 -111.59,190.9 -219.438,0"
+ inkscape:connector-curvature="0" />
+ </g>
+ </g>
+ <path
+ id="path3363-6-9-0-1-3"
+ style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
+ d="m 206.73253,540.54045 13.106,-22.3925 25.99649,0 13.21487,22.6087 -13.21487,22.39129 -25.99649,0 -13.106,-22.60749 z m 40.53761,-24.8925 -28.86524,0 -0.72412,1.2375 -13.106,22.3925 -0.73575,1.2563 0.73087,1.26 13.106,22.60739 0.72263,1.2464 28.86374,0 0.72512,-1.2289 13.215,-22.39119 0.74625,-1.265 -0.74,-1.2675 -13.21537,-22.6088 -0.72313,-1.2387"
+ inkscape:connector-curvature="0"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523" />
+ <g
+ id="g3365-0-4-1-9-8"
+ transform="matrix(0.125,0,0,-0.125,124.46742,882.67914)"
+ style="fill:url(#linearGradient10691-2);fill-opacity:1"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523">
+ <g
+ clip-path="url(#clipPath3369-1-5-6-1-49)"
+ id="g3367-2-4-2-8-6"
+ style="fill:url(#linearGradient10689-9);fill-opacity:1">
+ <path
+ id="path3379-4-6-7-6-2"
+ style="fill:url(#linearGradient4498-3);fill-opacity:1;fill-rule:nonzero;stroke:none"
+ d="m 1131.64,3128.5 -104.95,-181.12 116.38,-200.42 208.05,0.94 112.02,191.63 -112.08,188.97 -219.42,0"
+ inkscape:connector-curvature="0" />
+ </g>
+ </g>
+ <path
+ id="path3381-6-8-0-0-8"
+ style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
+ d="m 254.24864,514.25665 12.3925,-21.3899 25.99625,0 13.27125,22.3762 -13.27125,22.7025 -24.56875,0.11 -13.82,-23.7988 z m 39.8125,-23.8899 -28.86125,0 -0.7225,1.2462 -12.3925,21.39 -0.72625,1.255 0.7275,1.2537 13.82,23.7988 0.7275,1.2513 1.44625,-0.01 24.56875,-0.11 1.4275,-0.01 0.72,-1.2325 13.27125,-22.7025 0.7425,-1.27 -0.75125,-1.2663 -13.27125,-22.3762 -0.72625,-1.225"
+ inkscape:connector-curvature="0"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523" />
+ <g
+ id="g3383-5-5-2-2-0"
+ transform="matrix(0.125,0,0,-0.125,124.46742,882.67914)"
+ style="fill:url(#linearGradient10687-9);fill-opacity:1"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523">
+ <g
+ clip-path="url(#clipPath3387-3-6-4-2-3)"
+ id="g3385-0-6-4-8-9"
+ style="fill:url(#linearGradient10685-44);fill-opacity:1">
+ <path
+ id="path3397-9-6-1-6-8"
+ style="fill:url(#linearGradient4492-0);fill-opacity:1;fill-rule:nonzero;stroke:none"
+ d="m 862.109,3289.75 -109.086,-190.45 69.122,-124.42 164.511,-0.47 c 0,0 111.044,188.28 116.564,197.63 7.66,0 43.03,0 43.03,0 l -67.03,117.71 -217.111,0"
+ inkscape:connector-curvature="0" />
+ </g>
+ </g>
+ <path
+ id="path3399-6-7-3-2-04"
+ style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
+ d="m 220.0304,495.27665 12.92424,-22.5662 25.68775,0 6.95625,12.2138 -3.94375,0 -14.56837,24.7025 -19.11525,-0.055 -7.94087,-14.295 z m 40.06574,-25.0662 -28.59012,0 -0.71975,1.2575 -12.92537,22.5663 -0.70112,1.2237 0.68512,1.2325 7.94137,14.295 0.71087,1.2825 1.46638,0 19.11525,0.055 1.43212,0 0.729,-1.2338 13.84375,-23.4724 6.81625,0 -2.12875,-3.7375 -6.95625,-12.2138 -0.71875,-1.2625"
+ inkscape:connector-curvature="0"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523" />
+ <g
+ transform="matrix(1.25,0,0,-1.25,117.405,895.69964)"
+ id="g3465-0-9"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523">
+ <text
+ id="text3467-9-6"
+ transform="matrix(1,0,-0.17627963,-1,0,0)"
+ x="116.98372"
+ y="-267.77499"
+ style="font-size:11.81779194px">
+ <tspan
+ id="tspan3469-0-8"
+ sodipodi:role="line"
+ style="font-size:46.39999771px;font-variant:normal;font-weight:normal;writing-mode:lr-tb;fill:#49608a;fill-opacity:1;fill-rule:nonzero;stroke:none;font-family:Denmark;-inkscape-font-specification:Denmark"
+ x="116.98372"
+ y="-267.77499">ATOMIC</tspan>
+ </text>
+ <text
+ id="text3471-0-2"
+ transform="matrix(0.99235617,0,-0.17763746,-1.0077027,0,0)"
+ style="font-size:38.40000153px"
+ x="112.74373"
+ y="-306.75479">
+ <tspan
+ id="tspan3473-6-8"
+ sodipodi:role="line"
+ style="font-size:38.40000153px;font-variant:normal;font-weight:normal;writing-mode:lr-tb;fill:#49608a;fill-opacity:1;fill-rule:nonzero;stroke:none;font-family:Denmark;-inkscape-font-specification:Denmark"
+ x="112.74373"
+ y="-306.75479">boost</tspan>
+ </text>
+ </g>
+ <path
+ sodipodi:type="arc"
+ style="fill:#0000a7;fill-opacity:1;stroke:#ffffff;stroke-width:2;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+ id="path4821-47"
+ sodipodi:cx="160.35715"
+ sodipodi:cy="240.93361"
+ sodipodi:rx="10.114144"
+ sodipodi:ry="10.114144"
+ d="m 170.47129,240.93361 a 10.114144,10.114144 0 1 1 -20.22829,0 10.114144,10.114144 0 1 1 20.22829,0 z"
+ transform="translate(73.021973,299.26676)" />
+ <path
+ transform="matrix(0.74292732,0,0,0.74292732,160.9833,334.95876)"
+ sodipodi:type="arc"
+ style="fill:#00b000;fill-opacity:1;stroke:#ffffff;stroke-width:2.69205332;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+ id="path4821-4-9"
+ sodipodi:cx="160.35715"
+ sodipodi:cy="240.93361"
+ sodipodi:rx="10.114144"
+ sodipodi:ry="10.114144"
+ d="m 170.47129,240.93361 a 10.114144,10.114144 0 1 1 -20.22829,0 10.114144,10.114144 0 1 1 20.22829,0 z" />
+ <path
+ transform="matrix(0.51798873,0,0,0.51798873,159.28596,366.74327)"
+ sodipodi:type="arc"
+ style="fill:#cb0000;fill-opacity:1;stroke:#ffffff;stroke-width:3.8610878;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+ id="path4821-4-8-4"
+ sodipodi:cx="160.35715"
+ sodipodi:cy="240.93361"
+ sodipodi:rx="10.114144"
+ sodipodi:ry="10.114144"
+ d="m 170.47129,240.93361 a 10.114144,10.114144 0 1 1 -20.22829,0 10.114144,10.114144 0 1 1 20.22829,0 z" />
+ <path
+ style="fill:none;stroke:#808080;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+ d="m 250.05288,487.74985 c 12.11436,-0.8226 21.99257,5.106 28.337,15.9431"
+ id="path16018"
+ inkscape:connector-curvature="0"
+ sodipodi:nodetypes="cc" />
+ <path
+ style="fill:none;stroke:#808080;stroke-width:2;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+ d="m 279.75705,526.03685 c -5.64547,24.9935 -31.79301,20.1257 -32.06907,20.0828"
+ id="path16020"
+ inkscape:connector-curvature="0"
+ sodipodi:nodetypes="cc" />
+ <path
+ style="fill:none;stroke:#808080;stroke-width:1.70000005;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+ d="m 233.21476,494.63695 c -16.70632,11.7511 -8.41283,33.4381 -8.77494,33.2356"
+ id="path16022"
+ inkscape:connector-curvature="0"
+ sodipodi:nodetypes="cc" />
+ <g
+ id="g3319-1-2-5-1-8-7"
+ transform="matrix(0.10419818,0,0,-0.10419818,147.29097,965.23744)"
+ style="fill:url(#radialGradient10699-4-4);fill-opacity:1"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523">
+ <g
+ clip-path="url(#clipPath3323-7-2-4-5-2-6)"
+ id="g3321-9-2-7-4-14-6"
+ style="fill:url(#radialGradient3192);fill-opacity:1">
+ <path
+ id="path3335-8-7-3-8-7-1"
+ style="fill:url(#radialGradient4516-6-5);fill-opacity:1;fill-rule:nonzero;stroke:none"
+ d="m 997.469,2312.51 c -322.379,0 -583.739,261.36 -583.739,583.74 0,322.38 261.36,583.74 583.739,583.74 322.381,0 583.741,-261.36 583.741,-583.74 0,-322.38 -261.36,-583.74 -583.741,-583.74"
+ inkscape:connector-curvature="0" />
+ </g>
+ </g>
+ <g
+ id="g3347-6-8-3-7-64-8"
+ transform="matrix(0.125,0,0,-0.125,122.26447,1028.0561)"
+ style="fill:url(#linearGradient10695-5-7);fill-opacity:1"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523">
+ <g
+ clip-path="url(#clipPath3351-4-7-3-5-57-7)"
+ id="g3349-5-5-4-7-98-9"
+ style="fill:url(#linearGradient10693-2-2);fill-opacity:1">
+ <path
+ id="path3361-0-8-2-9-7-2"
+ style="fill:url(#linearGradient4510-4-1);fill-opacity:1;fill-rule:nonzero;stroke:none"
+ d="m 757.242,2926.25 -110.687,-189.11 110.656,-190.89 219.437,0 111.622,189.1 -111.59,190.9 -219.438,0"
+ inkscape:connector-curvature="0" />
+ </g>
+ </g>
+ <path
+ id="path3363-6-9-0-1-3-7"
+ style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
+ d="m 204.52958,685.91745 13.106,-22.3925 25.99649,0 13.21487,22.6087 -13.21487,22.39129 -25.99649,0 -13.106,-22.60749 z m 40.53761,-24.8925 -28.86524,0 -0.72412,1.2375 -13.106,22.3925 -0.73575,1.2563 0.73087,1.26 13.106,22.60739 0.72263,1.2464 28.86374,0 0.72512,-1.2289 13.215,-22.39119 0.74625,-1.265 -0.74,-1.2675 -13.21537,-22.6088 -0.72313,-1.2387"
+ inkscape:connector-curvature="0"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523" />
+ <g
+ id="g3365-0-4-1-9-8-9"
+ transform="matrix(0.125,0,0,-0.125,122.26447,1028.0561)"
+ style="fill:url(#linearGradient10691-2-2);fill-opacity:1"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523">
+ <g
+ clip-path="url(#clipPath3369-1-5-6-1-49-5)"
+ id="g3367-2-4-2-8-6-5"
+ style="fill:url(#linearGradient10689-9-4);fill-opacity:1">
+ <path
+ id="path3379-4-6-7-6-2-4"
+ style="fill:url(#linearGradient4498-3-1);fill-opacity:1;fill-rule:nonzero;stroke:none"
+ d="m 1131.64,3128.5 -104.95,-181.12 116.38,-200.42 208.05,0.94 112.02,191.63 -112.08,188.97 -219.42,0"
+ inkscape:connector-curvature="0" />
+ </g>
+ </g>
+ <path
+ id="path3381-6-8-0-0-8-3"
+ style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
+ d="m 252.04569,659.63365 12.3925,-21.3899 25.99625,0 13.27125,22.3762 -13.27125,22.7025 -24.56875,0.11 -13.82,-23.7988 z m 39.8125,-23.8899 -28.86125,0 -0.7225,1.2462 -12.3925,21.39 -0.72625,1.255 0.7275,1.2537 13.82,23.7988 0.7275,1.2513 1.44625,-0.01 24.56875,-0.11 1.4275,-0.01 0.72,-1.2325 13.27125,-22.7025 0.7425,-1.27 -0.75125,-1.2663 -13.27125,-22.3762 -0.72625,-1.225"
+ inkscape:connector-curvature="0"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523" />
+ <g
+ id="g3383-5-5-2-2-0-1"
+ transform="matrix(0.125,0,0,-0.125,122.26447,1028.0561)"
+ style="fill:url(#linearGradient10687-9-1);fill-opacity:1"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523">
+ <g
+ clip-path="url(#clipPath3387-3-6-4-2-3-4)"
+ id="g3385-0-6-4-8-9-2"
+ style="fill:url(#linearGradient10685-44-9);fill-opacity:1">
+ <path
+ id="path3397-9-6-1-6-8-3"
+ style="fill:url(#linearGradient4492-0-8);fill-opacity:1;fill-rule:nonzero;stroke:none"
+ d="m 862.109,3289.75 -109.086,-190.45 69.122,-124.42 164.511,-0.47 c 0,0 111.044,188.28 116.564,197.63 7.66,0 43.03,0 43.03,0 l -67.03,117.71 -217.111,0"
+ inkscape:connector-curvature="0" />
+ </g>
+ </g>
+ <path
+ id="path3399-6-7-3-2-04-3"
+ style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
+ d="m 217.82745,640.65365 12.92424,-22.5662 25.68775,0 6.95625,12.2138 -3.94375,0 -14.56837,24.7025 -19.11525,-0.055 -7.94087,-14.295 z m 40.06574,-25.0662 -28.59012,0 -0.71975,1.2575 -12.92537,22.5663 -0.70112,1.2237 0.68512,1.2325 7.94137,14.295 0.71087,1.2825 1.46638,0 19.11525,0.055 1.43212,0 0.729,-1.2338 13.84375,-23.4724 6.81625,0 -2.12875,-3.7375 -6.95625,-12.2138 -0.71875,-1.2625"
+ inkscape:connector-curvature="0"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523" />
+ <g
+ transform="matrix(1.25,0,0,-1.25,115.20205,1041.0766)"
+ id="g3465-0-9-4"
+ inkscape:export-filename="C:\Users\Adam\Desktop\bg_logo1.png"
+ inkscape:export-xdpi="63.625523"
+ inkscape:export-ydpi="63.625523">
+ <text
+ id="text3467-9-6-1"
+ transform="matrix(1,0,-0.17627963,-1,0,0)"
+ x="116.98372"
+ y="-267.77499"
+ style="font-size:11.81779194px">
+ <tspan
+ id="tspan3469-0-8-1"
+ sodipodi:role="line"
+ style="font-size:46.39999771px;font-variant:normal;font-weight:normal;writing-mode:lr-tb;fill:#49608a;fill-opacity:1;fill-rule:nonzero;stroke:none;font-family:Denmark;-inkscape-font-specification:Denmark"
+ x="116.98372"
+ y="-267.77499">Atomic</tspan>
+ </text>
+ <text
+ id="text3471-0-2-3"
+ transform="matrix(0.99235617,0,-0.17763746,-1.0077027,0,0)"
+ style="font-size:38.40000153px"
+ x="112.74373"
+ y="-306.75479">
+ <tspan
+ id="tspan3473-6-8-8"
+ sodipodi:role="line"
+ style="font-size:38.40000153px;font-variant:normal;font-weight:normal;writing-mode:lr-tb;fill:#49608a;fill-opacity:1;fill-rule:nonzero;stroke:none;font-family:Denmark;-inkscape-font-specification:Denmark"
+ x="112.74373"
+ y="-306.75479">Boost</tspan>
+ </text>
+ </g>
+ <path
+ sodipodi:type="arc"
+ style="fill:#ffffff;fill-opacity:1;stroke:#ffffff;stroke-width:2;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+ id="path4821-47-7"
+ sodipodi:cx="160.35715"
+ sodipodi:cy="240.93361"
+ sodipodi:rx="10.114144"
+ sodipodi:ry="10.114144"
+ d="m 170.47129,240.93361 a 10.114144,10.114144 0 1 1 -20.22829,0 10.114144,10.114144 0 1 1 20.22829,0 z"
+ transform="matrix(0.53649776,0,0,0.53649776,136.31572,567.15057)" />
+ <path
+ transform="matrix(0.45553914,0,0,0.45553914,171.71781,574.06648)"
+ sodipodi:type="arc"
+ style="fill:#ffffff;fill-opacity:1;stroke:#ffffff;stroke-width:2.69205331999999990;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+ id="path4821-4-9-4"
+ sodipodi:cx="160.35715"
+ sodipodi:cy="240.93361"
+ sodipodi:rx="10.114144"
+ sodipodi:ry="10.114144"
+ d="m 170.47129,240.93361 a 10.114144,10.114144 0 1 1 -20.22829,0 10.114144,10.114144 0 1 1 20.22829,0 z" />
+ <path
+ transform="matrix(0.33234221,0,0,0.33234221,173.35638,592.9985)"
+ sodipodi:type="arc"
+ style="fill:#ffffff;fill-opacity:1;stroke:#ffffff;stroke-width:3.86108780000000000;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+ id="path4821-4-8-4-2"
+ sodipodi:cx="160.35715"
+ sodipodi:cy="240.93361"
+ sodipodi:rx="10.114144"
+ sodipodi:ry="10.114144"
+ d="m 170.47129,240.93361 a 10.114144,10.114144 0 1 1 -20.22829,0 10.114144,10.114144 0 1 1 20.22829,0 z" />
+ <path
+ style="fill:none;stroke:#ffffff;stroke-width:1;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+ d="m 231.48167,671.25081 c 5.6438,-0.15431 8.79799,1.45226 12.0778,6.25882"
+ id="path16018-7"
+ inkscape:connector-curvature="0"
+ sodipodi:nodetypes="cc" />
+ <path
+ style="fill:none;stroke:#ffffff;stroke-width:2;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+ d="m 244.5941,690.50066 c -4.06373,10.90468 -15.39442,8.6554 -15.38328,8.74968"
+ id="path16020-7"
+ inkscape:connector-curvature="0"
+ sodipodi:nodetypes="cc" />
+ <path
+ style="fill:none;stroke:#ffffff;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+ d="m 221.63678,674.9333 c -7.09591,5.63691 -3.2412,15.66119 -3.57792,15.56405"
+ id="path16022-9"
+ inkscape:connector-curvature="0"
+ sodipodi:nodetypes="cc" />
+ </g>
+</svg>
diff --git a/3rdParty/Boost/src/libs/atomic/doc/platform.qbk b/3rdParty/Boost/src/libs/atomic/doc/platform.qbk
new file mode 100644
index 0000000..6b9a9ec
--- /dev/null
+++ b/3rdParty/Boost/src/libs/atomic/doc/platform.qbk
@@ -0,0 +1,312 @@
+[/
+ / Copyright (c) 2009 Helge Bahmann
+ /
+ / Distributed under the Boost Software License, Version 1.0. (See accompanying
+ / file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+ /]
+
+[section:template_organization Organization of class template layers]
+
+The implementation uses multiple layers of template classes that
+inherit from the next lower level each and refine or adapt the respective
+underlying class:
+
+* [^boost::atomic<T>] is the topmost-level, providing
+ the external interface. Implementation-wise, it does not add anything
+ (except for hiding copy constructor and assignment operator).
+
+* [^boost::detail::atomic::internal_atomic&<T,S=sizeof(T),I=is_integral_type<T> >]:
+ This layer is mainly responsible for providing the overloaded operators
+ mapping to API member functions (e.g. [^+=] to [^fetch_add]).
+ The defaulted template parameter [^I] allows
+ to expose the correct API functions (via partial template
+ specialization): For non-integral types, it only
+ publishes the various [^exchange] functions
+ as well as load and store, for integral types it
+ additionally exports arithmetic and logic operations.
+ [br]
+ Depending on whether the given type is integral, it
+ inherits from either [^boost::detail::atomic::platform_atomic<T,S=sizeof(T)>]
+ or [^boost::detail::atomic::platform_atomic_integral<T,S=sizeof(T)>].
+ There is however some special-casing: for non-integral types
+ of size 1, 2, 4 or 8, it will coerce the datatype into an integer representation
+ and delegate to [^boost::detail::atomic::platform_atomic_integral<T,S=sizeof(T)>]
+ -- the rationale is that platform implementors only need to provide
+ integer-type operations.
+
+* [^boost::detail::atomic::platform_atomic_integral<T,S=sizeof(T)>]
+ must provide the full set of operations for an integral type T
+ (i.e. [^load], [^store], [^exchange],
+ [^compare_exchange_weak], [^compare_exchange_strong],
+ [^fetch_add], [^fetch_sub], [^fetch_and],
+ [^fetch_or], [^fetch_xor], [^is_lock_free]).
+ The default implementation uses locking to emulate atomic operations, so
+ this is the level at which implementors should provide template specializations
+ to add support for platform-specific atomic operations.
+ [br]
+ The two separate template parameters allow separate specialization
+ on size and type (which, with fixed size, cannot
+ specify more than signedness/unsignedness). The rationale is that
+ most platform-specific atomic operations usually depend only on the
+ operand size, so that common implementations for signed/unsigned
+ types are possible. Signedness allows to properly to choose sign-extending
+ instructions for the [^load] operation, avoiding later
+ conversion. The expectation is that in most implementations this will
+ be a normal assignment in C, possibly accompanied by memory
+ fences, so that the compiler can automatically choose the correct
+ instruction.
+
+* At the lowest level, [^boost::detail::atomic::platform_atomic<T,S=sizeof(T)>]
+ provides the most basic atomic operations ([^load], [^store],
+ [^exchange], [^compare_exchange_weak],
+ [^compare_exchange_strong]) for arbitrarily generic data types.
+ The default implementation uses locking as a fallback mechanism.
+ Implementors generally do not have to specialize at this level
+ (since these will not be used for the common integral type sizes
+ of 1, 2, 4 and 8 bytes), but if s/he can if s/he so wishes to
+ provide truly atomic operations for "odd" data type sizes.
+ Some amount of care must be taken as the "raw" data type
+ passed in from the user through [^boost::atomic<T>]
+ is visible here -- it thus needs to be type-punned or otherwise
+ manipulated byte-by-byte to avoid using overloaded assignment,
+ comparison operators and copy constructors.
+
+[endsect]
+
+
+[section:platform_atomic_implementation Implementing platform-specific atomic operations]
+
+In principle implementors are responsible for providing the
+full range of named member functions of an atomic object
+(i.e. [^load], [^store], [^exchange],
+[^compare_exchange_weak], [^compare_exchange_strong],
+[^fetch_add], [^fetch_sub], [^fetch_and],
+[^fetch_or], [^fetch_xor], [^is_lock_free]).
+These must be implemented as partial template specializations for
+[^boost::detail::atomic::platform_atomic_integral<T,S=sizeof(T)>]:
+
+[c++]
+
+ template<typename T>
+ class platform_atomic_integral<T, 4>
+ {
+ public:
+ explicit platform_atomic_integral(T v) : i(v) {}
+ platform_atomic_integral(void) {}
+
+ T load(memory_order order=memory_order_seq_cst) const volatile
+ {
+ // platform-specific code
+ }
+ void store(T v, memory_order order=memory_order_seq_cst) volatile
+ {
+ // platform-specific code
+ }
+
+ private:
+ volatile T i;
+ };
+
+As noted above, it will usually suffice to specialize on the second
+template argument, indicating the size of the data type in bytes.
+
+[section:automatic_buildup Templates for automatic build-up]
+
+Often only a portion of the required operations can be
+usefully mapped to machine instructions. Several helper template
+classes are provided that can automatically synthesize missing methods to
+complete an implementation.
+
+At the minimum, an implementor must provide the
+[^load], [^store],
+[^compare_exchange_weak] and
+[^is_lock_free] methods:
+
+[c++]
+
+ template<typename T>
+ class my_atomic_32 {
+ public:
+ my_atomic_32() {}
+ my_atomic_32(T initial_value) : value(initial_value) {}
+
+ T load(memory_order order=memory_order_seq_cst) volatile const
+ {
+ // platform-specific code
+ }
+ void store(T new_value, memory_order order=memory_order_seq_cst) volatile
+ {
+ // platform-specific code
+ }
+ bool compare_exchange_weak(T &expected, T desired,
+ memory_order success_order,
+ memory_order_failure_order) volatile
+ {
+ // platform-specific code
+ }
+ bool is_lock_free() const volatile {return true;}
+ protected:
+ // typedef is required for classes inheriting from this
+ typedef T integral_type;
+ private:
+ T value;
+ };
+
+The template [^boost::detail::atomic::build_atomic_from_minimal]
+can then take care of the rest:
+
+[c++]
+
+ template<typename T>
+ class platform_atomic_integral<T, 4>
+ : public boost::detail::atomic::build_atomic_from_minimal<my_atomic_32<T> >
+ {
+ public:
+ typedef build_atomic_from_minimal<my_atomic_32<T> > super;
+
+ explicit platform_atomic_integral(T v) : super(v) {}
+ platform_atomic_integral(void) {}
+ };
+
+There are several helper classes to assist in building "complete"
+atomic implementations from different starting points:
+
+* [^build_atomic_from_minimal] requires
+ * [^load]
+ * [^store]
+ * [^compare_exchange_weak] (4-operand version)
+
+* [^build_atomic_from_exchange] requires
+ * [^load]
+ * [^store]
+ * [^compare_exchange_weak] (4-operand version)
+ * [^compare_exchange_strong] (4-operand version)
+ * [^exchange]
+
+* [^build_atomic_from_add] requires
+ * [^load]
+ * [^store]
+ * [^compare_exchange_weak] (4-operand version)
+ * [^compare_exchange_strong] (4-operand version)
+ * [^exchange]
+ * [^fetch_add]
+
+* [^build_atomic_from_typical] (<I>supported on gcc only</I>) requires
+ * [^load]
+ * [^store]
+ * [^compare_exchange_weak] (4-operand version)
+ * [^compare_exchange_strong] (4-operand version)
+ * [^exchange]
+ * [^fetch_add_var] (protected method)
+ * [^fetch_inc] (protected method)
+ * [^fetch_dec] (protected method)
+
+ This will generate a [^fetch_add] method
+ that calls [^fetch_inc]/[^fetch_dec]
+ when the given parameter is a compile-time constant
+ equal to +1 or -1 respectively, and [^fetch_add_var]
+ in all other cases. This provides a mechanism for
+ optimizing the extremely common case of an atomic
+ variable being used as a counter.
+
+ The prototypes for these methods to be implemented is:
+ [c++]
+
+ template<typename T>
+ class my_atomic {
+ public:
+ T fetch_inc(memory_order order) volatile;
+ T fetch_dec(memory_order order) volatile;
+ T fetch_add_var(T counter, memory_order order) volatile;
+ };
+
+These helper templates are defined in [^boost/atomic/detail/builder.hpp].
+
+[endsect]
+
+[section:automatic_buildup_small Build sub-word-sized atomic data types]
+
+There is one other helper template that can build sub-word-sized
+atomic data types even though the underlying architecture allows
+only word-sized atomic operations:
+
+[c++]
+
+ template<typename T>
+ class platform_atomic_integral<T, 1> :
+ public build_atomic_from_larger_type<my_atomic_32<uint32_t>, T>
+ {
+ public:
+ typedef build_atomic_from_larger_type<my_atomic_32<uint32_t>, T> super;
+
+ explicit platform_atomic_integral(T v) : super(v) {}
+ platform_atomic_integral(void) {}
+ };
+
+The above would create an atomic data type of 1 byte size, and
+use masking and shifts to map it to 32-bit atomic operations.
+The base type must implement [^load], [^store]
+and [^compare_exchange_weak] for this to work.
+
+[endsect]
+
+[section:other_sizes Atomic data types for unusual object sizes]
+
+In unusual circumstances, an implementor may also opt to specialize
+[^public boost::detail::atomic::platform_atomic<T,S=sizeof(T)>]
+to provide support for atomic objects not fitting an integral size.
+If you do that, keep the following things in mind:
+
+* There is no reason to ever do this for object sizes
+ of 1, 2, 4 and 8
+* Only the following methods need to be implemented:
+ * [^load]
+ * [^store]
+ * [^compare_exchange_weak] (4-operand version)
+ * [^compare_exchange_strong] (4-operand version)
+ * [^exchange]
+
+The type of the data to be stored in the atomic
+variable (template parameter [^T])
+is exposed to this class, and the type may have
+overloaded assignment and comparison operators --
+using these overloaded operators however will result
+in an error. The implementor is responsible for
+accessing the objects in a way that does not
+invoke either of these operators (using e.g.
+[^memcpy] or type-casts).
+
+[endsect]
+
+[endsect]
+
+[section:platform_atomic_fences Fences]
+
+Platform implementors need to provide a function performing
+the action required for [funcref boost::atomic_thread_fence atomic_thread_fence]
+(the fallback implementation will just perform an atomic operation
+on an integer object). This is achieved by specializing the
+[^boost::detail::atomic::platform_atomic_thread_fence] template
+function in the following way:
+
+[c++]
+
+ template<>
+ void platform_atomic_thread_fence(memory_order order)
+ {
+ // platform-specific code here
+ }
+
+[endsect]
+
+[section:platform_atomic_puttogether Putting it altogether]
+
+The template specializations should be put into a header file
+in the [^boost/atomic/detail] directory, preferably
+specifying supported compiler and architecture in its name.
+
+The file [^boost/atomic/detail/platform.hpp] must
+subsequently be modified to conditionally include the new
+header.
+
+[endsect]
diff --git a/3rdParty/Boost/src/libs/atomic/index.html b/3rdParty/Boost/src/libs/atomic/index.html
new file mode 100644
index 0000000..62a6c59
--- /dev/null
+++ b/3rdParty/Boost/src/libs/atomic/index.html
@@ -0,0 +1,13 @@
+<html>
+<head>
+<meta http-equiv="refresh" content="0; URL=../../doc/html/atomic.html">
+</head>
+<body>
+Automatic redirection failed, please go to
+<a href="../../doc/html/atomic.html">../../doc/html/atomic.html</a> &nbsp;<hr>
+<p>&copy; Copyright Beman Dawes, 2001</p>
+<p>Distributed under the Boost Software License, Version 1.0. (See accompanying
+file <a href="../../LICENSE_1_0.txt">LICENSE_1_0.txt</a> or copy
+at <a href="http://www.boost.org/LICENSE_1_0.txt">www.boost.org/LICENSE_1_0.txt</a>)</p>
+</body>
+</html>
diff --git a/3rdParty/Boost/src/libs/signals/src/connection.cpp b/3rdParty/Boost/src/libs/signals/src/connection.cpp
deleted file mode 100644
index b4ed8b4..0000000
--- a/3rdParty/Boost/src/libs/signals/src/connection.cpp
+++ /dev/null
@@ -1,155 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2004. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#define BOOST_SIGNALS_SOURCE
-
-#include <boost/signals/connection.hpp>
-#include <cassert>
-
-namespace boost {
- namespace BOOST_SIGNALS_NAMESPACE {
-
- connection::connection(const connection& other) :
- con(other.con), controlling_connection(other.controlling_connection)
- {
- }
-
- connection::~connection()
- {
- if (controlling_connection) {
- disconnect();
- }
- }
-
- void
- connection::reset(BOOST_SIGNALS_NAMESPACE::detail::basic_connection* new_con)
- {
- con.reset(new_con);
- }
-
- bool connection::operator==(const connection& other) const
- {
- return con.get() == other.con.get();
- }
-
- bool connection::operator<(const connection& other) const
- {
- return con.get() < other.con.get();
- }
-
- connection& connection::operator=(const connection& other)
- {
- connection(other).swap(*this);
- return *this;
- }
-
- void connection::swap(connection& other)
- {
- this->con.swap(other.con);
- std::swap(this->controlling_connection, other.controlling_connection);
- }
-
- void swap(connection& c1, connection& c2)
- {
- c1.swap(c2);
- }
-
- scoped_connection::scoped_connection(const connection& other) :
- connection(other),
- released(false)
- {
- }
-
- scoped_connection::scoped_connection(const scoped_connection& other) :
- connection(other),
- released(other.released)
- {
- }
-
- scoped_connection::~scoped_connection()
- {
- if (!released) {
- this->disconnect();
- }
- }
-
- connection scoped_connection::release()
- {
- released = true;
- return *this;
- }
-
- void scoped_connection::swap(scoped_connection& other)
- {
- this->connection::swap(other);
- bool other_released = other.released;
- other.released = this->released;
- this->released = other_released;
- }
-
- void swap(scoped_connection& c1, scoped_connection& c2)
- {
- c1.swap(c2);
- }
-
- scoped_connection&
- scoped_connection::operator=(const connection& other)
- {
- scoped_connection(other).swap(*this);
- return *this;
- }
-
- scoped_connection&
- scoped_connection::operator=(const scoped_connection& other)
- {
- scoped_connection(other).swap(*this);
- return *this;
- }
-
- void
- connection::add_bound_object(const BOOST_SIGNALS_NAMESPACE::detail::bound_object& b)
- {
- assert(con.get() != 0);
- con->bound_objects.push_back(b);
- }
-
-
- void connection::disconnect() const
- {
- if (this->connected()) {
- // Make sure we have a reference to the basic_connection object,
- // because 'this' may disappear
- shared_ptr<detail::basic_connection> local_con = con;
-
- void (*signal_disconnect)(void*, void*) = local_con->signal_disconnect;
-
- // Note that this connection no longer exists
- // Order is important here: we could get into an infinite loop if this
- // isn't cleared before we try the disconnect.
- local_con->signal_disconnect = 0;
-
- // Disconnect signal
- signal_disconnect(local_con->signal, local_con->signal_data);
-
- // Disconnect all bound objects
- typedef std::list<BOOST_SIGNALS_NAMESPACE::detail::bound_object>::iterator iterator;
- for (iterator i = local_con->bound_objects.begin();
- i != local_con->bound_objects.end(); ++i) {
- assert(i->disconnect != 0);
- i->disconnect(i->obj, i->data);
- }
- }
- }
- } // end namespace boost
-} // end namespace boost
-
-#ifndef BOOST_MSVC
-// Explicit instantiations to keep everything in the library
-template class std::list<boost::BOOST_SIGNALS_NAMESPACE::detail::bound_object>;
-#endif
diff --git a/3rdParty/Boost/src/libs/signals/src/named_slot_map.cpp b/3rdParty/Boost/src/libs/signals/src/named_slot_map.cpp
deleted file mode 100644
index 2fe2790..0000000
--- a/3rdParty/Boost/src/libs/signals/src/named_slot_map.cpp
+++ /dev/null
@@ -1,134 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2004. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#define BOOST_SIGNALS_SOURCE
-
-#include <boost/signals/detail/named_slot_map.hpp>
-#include <cassert>
-#include <map>
-#include <list>
-#include <typeinfo>
-
-namespace boost { namespace BOOST_SIGNALS_NAMESPACE { namespace detail {
-
-typedef std::list<connection_slot_pair> group_list;
-typedef group_list::iterator slot_pair_iterator;
-typedef std::map<stored_group, group_list, compare_type> slot_container_type;
-typedef slot_container_type::iterator group_iterator;
-typedef slot_container_type::const_iterator const_group_iterator;
-
-
-#if BOOST_WORKAROUND(_MSC_VER, <= 1900)
-void named_slot_map_iterator::decrement() { assert(false); }
-void named_slot_map_iterator::advance(difference_type) { assert(false); }
-#endif
-
-named_slot_map::named_slot_map(const compare_type& compare) : groups(compare)
-{
- clear();
-}
-
-void named_slot_map::clear()
-{
- groups.clear();
- groups[stored_group(stored_group::sk_front)];
- groups[stored_group(stored_group::sk_back)];
- back = groups.end();
- --back;
-}
-
-named_slot_map::iterator named_slot_map::begin()
-{
- return named_slot_map::iterator(groups.begin(), groups.end());
-}
-
-named_slot_map::iterator named_slot_map::end()
-{
- return named_slot_map::iterator(groups.end(), groups.end());
-}
-
-named_slot_map::iterator
-named_slot_map::insert(const stored_group& name, const connection& con,
- const any& slot, connect_position at)
-{
- group_iterator group;
- if (name.empty()) {
- switch (at) {
- case at_front: group = groups.begin(); break;
- case at_back: group = back; break;
- }
- } else {
- group = groups.find(name);
- if (group == groups.end()) {
- slot_container_type::value_type v(name, group_list());
- group = groups.insert(v).first;
- }
- }
- iterator it;
- it.group = group;
- it.last_group = groups.end();
-
- switch (at) {
- case at_back:
- group->second.push_back(connection_slot_pair(con, slot));
- it.slot_ = group->second.end();
- it.slot_assigned = true;
- --(it.slot_);
- break;
-
- case at_front:
- group->second.push_front(connection_slot_pair(con, slot));
- it.slot_ = group->second.begin();
- it.slot_assigned = true;
- break;
- }
- return it;
-}
-
-void named_slot_map::disconnect(const stored_group& name)
-{
- group_iterator group = groups.find(name);
- if (group != groups.end()) {
- slot_pair_iterator i = group->second.begin();
- while (i != group->second.end()) {
- slot_pair_iterator next = i;
- ++next;
- i->first.disconnect();
- i = next;
- }
- groups.erase((const_group_iterator) group);
- }
-}
-
-void named_slot_map::erase(iterator pos)
-{
- // Erase the slot
- pos.slot_->first.disconnect();
- pos.group->second.erase(pos.slot_);
-}
-
-void named_slot_map::remove_disconnected_slots()
-{
- // Remove any disconnected slots
- group_iterator g = groups.begin();
- while (g != groups.end()) {
- slot_pair_iterator s = g->second.begin();
- while (s != g->second.end()) {
- if (s->first.connected()) ++s;
- else g->second.erase(s++);
- }
-
- // Clear out empty groups
- if (empty(g)) groups.erase((const_group_iterator) g++);
- else ++g;
- }
-}
-
-
-} } }
diff --git a/3rdParty/Boost/src/libs/signals/src/signal_base.cpp b/3rdParty/Boost/src/libs/signals/src/signal_base.cpp
deleted file mode 100644
index 759672d..0000000
--- a/3rdParty/Boost/src/libs/signals/src/signal_base.cpp
+++ /dev/null
@@ -1,189 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2004. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#define BOOST_SIGNALS_SOURCE
-
-#include <boost/signals/detail/signal_base.hpp>
-#include <cassert>
-
-namespace boost {
- namespace BOOST_SIGNALS_NAMESPACE {
- namespace detail {
- signal_base_impl::signal_base_impl(const compare_type& comp,
- const any& combiner)
- : call_depth(0),
- slots_(comp),
- combiner_(combiner)
- {
- flags.delayed_disconnect = false;
- flags.clearing = false;
- }
-
- signal_base_impl::~signal_base_impl()
- {
- // Set the "clearing" flag to ignore extraneous disconnect requests,
- // because all slots will be disconnected on destruction anyway.
- flags.clearing = true;
- }
-
- void signal_base_impl::disconnect_all_slots()
- {
- // Do nothing if we're already clearing the slot list
- if (flags.clearing)
- return;
-
- if (call_depth == 0) {
- // Clearing the slot list will disconnect all slots automatically
- temporarily_set_clearing set_clearing(this);
- slots_.clear();
- }
- else {
- // We can't actually remove elements from the slot list because there
- // are still iterators into the slot list that must not be
- // invalidated by this operation. So just disconnect each slot
- // without removing it from the slot list. When the call depth does
- // reach zero, the call list will be cleared.
- flags.delayed_disconnect = true;
- temporarily_set_clearing set_clearing(this);
- for (iterator i = slots_.begin(); i != slots_.end(); ++i) {
- i->first.disconnect();
- }
- }
- }
-
- connection
- signal_base_impl::
- connect_slot(const any& slot_,
- const stored_group& name,
- shared_ptr<slot_base::data_t> data,
- connect_position at)
- {
- // Transfer the burden of ownership to a local, scoped
- // connection.
- data->watch_bound_objects.set_controlling(false);
- scoped_connection safe_connection(data->watch_bound_objects);
-
- // Allocate storage for an iterator that will hold the point of
- // insertion of the slot into the list. This is used to later remove
- // the slot when it is disconnected.
- std::auto_ptr<iterator> saved_iter(new iterator);
-
- // Add the slot to the list.
- iterator pos =
- slots_.insert(name, data->watch_bound_objects, slot_, at);
-
- // The assignment operation here absolutely must not throw, which
- // intuitively makes sense (because any container's insert method
- // becomes impossible to use in an exception-safe manner without this
- // assumption), but doesn't appear to be mentioned in the standard.
- *saved_iter = pos;
-
- // Fill out the connection object appropriately. None of these
- // operations can throw
- data->watch_bound_objects.get_connection()->signal = this;
- data->watch_bound_objects.get_connection()->signal_data =
- saved_iter.release();
- data->watch_bound_objects.get_connection()->signal_disconnect =
- &signal_base_impl::slot_disconnected;
-
- // Make the copy of the connection in the list disconnect when it is
- // destroyed. The local, scoped connection is then released
- // because ownership has been transferred.
- pos->first.set_controlling();
- return safe_connection.release();
- }
-
- bool signal_base_impl::empty() const
- {
- // Disconnected slots may still be in the list of slots if
- // a) this is called while slots are being invoked (call_depth > 0)
- // b) an exception was thrown in remove_disconnected_slots
- for (iterator i = slots_.begin(); i != slots_.end(); ++i) {
- if (i->first.connected())
- return false;
- }
-
- return true;
- }
-
- std::size_t signal_base_impl::num_slots() const
- {
- // Disconnected slots may still be in the list of slots if
- // a) this is called while slots are being invoked (call_depth > 0)
- // b) an exception was thrown in remove_disconnected_slots
- std::size_t count = 0;
- for (iterator i = slots_.begin(); i != slots_.end(); ++i) {
- if (i->first.connected())
- ++count;
- }
- return count;
- }
-
- void signal_base_impl::disconnect(const stored_group& group)
- { slots_.disconnect(group); }
-
- void signal_base_impl::slot_disconnected(void* obj, void* data)
- {
- signal_base_impl* self = reinterpret_cast<signal_base_impl*>(obj);
-
- // We won't need the slot iterator after this
- std::auto_ptr<iterator> slot(reinterpret_cast<iterator*>(data));
-
- // If we're flags.clearing, we don't bother updating the list of slots
- if (!self->flags.clearing) {
- // If we're in a call, note the fact that a slot has been deleted so
- // we can come back later to remove the iterator
- if (self->call_depth > 0) {
- self->flags.delayed_disconnect = true;
- }
- else {
- // Just remove the slot now, it's safe
- self->slots_.erase(*slot);
- }
- }
- }
-
- void signal_base_impl::remove_disconnected_slots() const
- { slots_.remove_disconnected_slots(); }
-
- call_notification::
- call_notification(const shared_ptr<signal_base_impl>& b) :
- impl(b)
- {
- // A call will be made, so increment the call depth as a notification
- impl->call_depth++;
- }
-
- call_notification::~call_notification()
- {
- impl->call_depth--;
-
- // If the call depth is zero and we have some slots that have been
- // disconnected during the calls, remove those slots from the list
- if (impl->call_depth == 0 &&
- impl->flags.delayed_disconnect) {
- impl->remove_disconnected_slots();
- impl->flags.delayed_disconnect = false;
- }
- }
-
- signal_base::signal_base(const compare_type& comp, const any& combiner)
- : impl()
- {
- impl.reset(new signal_base_impl(comp, combiner));
- }
-
- signal_base::~signal_base()
- {
- }
-
- } // namespace detail
- } // namespace BOOST_SIGNALS_NAMESPACE
-} // namespace boost
-
diff --git a/3rdParty/Boost/src/libs/signals/src/slot.cpp b/3rdParty/Boost/src/libs/signals/src/slot.cpp
deleted file mode 100644
index 7c296d6..0000000
--- a/3rdParty/Boost/src/libs/signals/src/slot.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2004. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#define BOOST_SIGNALS_SOURCE
-
-#include <boost/signals/slot.hpp>
-
-namespace boost {
- namespace BOOST_SIGNALS_NAMESPACE {
- namespace detail {
- void slot_base::create_connection()
- {
- // Create a new connection object
- basic_connection* con = new basic_connection();
-
- /* nothrow */ {
- // The signal portion isn't really necessary, except that we need a
- // signal for the connection to be connected.
- con->signal = static_cast<void*>(this);
- con->signal_data = 0;
- con->blocked_ = false ;
- con->signal_disconnect = &bound_object_destructed;
- }
-
- // This connection watches for destruction of bound objects. Note
- // that the reset routine will delete con if an allocation throws
- data->watch_bound_objects.reset(con);
-
- // We create a scoped connection, so that exceptions thrown while
- // adding bound objects will cause a cleanup of the bound objects
- // already connected.
- scoped_connection safe_connection(data->watch_bound_objects);
-
- // Now notify each of the bound objects that they are connected to this
- // slot.
- for(std::vector<const trackable*>::iterator i =
- data->bound_objects.begin();
- i != data->bound_objects.end(); ++i) {
- // Notify the object that the slot is connecting to it
- BOOST_SIGNALS_NAMESPACE::detail::bound_object binding;
- (*i)->signal_connected(data->watch_bound_objects, binding);
-
- // This will notify the bound object that the connection just made
- // should be disconnected if an exception is thrown before the
- // end of this iteration
- BOOST_SIGNALS_NAMESPACE::detail::auto_disconnect_bound_object
- disconnector(binding);
-
- // Add the binding to the list of bindings for the connection
- con->bound_objects.push_back(binding);
-
- // The connection object now knows about the bound object, so if an
- // exception is thrown later the connection object will notify the
- // bound object of the disconnection automatically
- disconnector.release();
- }
-
- // No exceptions will be thrown past this point.
- safe_connection.release();
-
- data->watch_bound_objects.set_controlling(true);
- }
- } // end namespace detail
- } // end namespace BOOST_SIGNALS_NAMESPACE
-} // end namespace boost
diff --git a/3rdParty/Boost/src/libs/signals/src/trackable.cpp b/3rdParty/Boost/src/libs/signals/src/trackable.cpp
deleted file mode 100644
index 4f63586..0000000
--- a/3rdParty/Boost/src/libs/signals/src/trackable.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-// Boost.Signals library
-
-// Copyright Douglas Gregor 2001-2004. Use, modification and
-// distribution is subject to the Boost Software License, Version
-// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
-// http://www.boost.org/LICENSE_1_0.txt)
-
-// For more information, see http://www.boost.org
-
-#define BOOST_SIGNALS_SOURCE
-
-#include <boost/signals/trackable.hpp>
-#include <algorithm>
-
-namespace boost {
- namespace BOOST_SIGNALS_NAMESPACE {
- void trackable::signal_disconnected(void* obj, void* data)
- {
- trackable* self = reinterpret_cast<trackable*>(obj);
- connection_iterator* signal =
- reinterpret_cast<connection_iterator*>(data);
-
- // If we're dying, don't bother erasing the connection from the list;
- // it'll be gone anyway
- if (!self->dying) {
- self->connected_signals.erase(*signal);
- }
-
- // This iterator pointer won't ever be used again
- delete signal;
- }
-
- void
- trackable::signal_connected(connection c,
- BOOST_SIGNALS_NAMESPACE::detail::bound_object& binding) const
- {
- // Insert the connection
- connection_iterator pos =
- connected_signals.insert(connected_signals.end(), c);
-
- // Make this copy of the object disconnect when destroyed
- pos->set_controlling();
-
- binding.obj = const_cast<void*>(reinterpret_cast<const void*>(this));
- binding.data = reinterpret_cast<void*>(new connection_iterator(pos));
- binding.disconnect = &signal_disconnected;
- }
-
- trackable::~trackable()
- {
- dying = true;
- }
- } // end namespace BOOST_SIGNALS_NAMESPACE
-}
-
-#ifndef BOOST_MSVC
-// Explicit instantiations to keep in the library
-template class std::list<boost::BOOST_SIGNALS_NAMESPACE::connection>;
-#endif
diff --git a/3rdParty/Boost/update.sh b/3rdParty/Boost/update.sh
index 99e6479..afa7722 100755
--- a/3rdParty/Boost/update.sh
+++ b/3rdParty/Boost/update.sh
@@ -25,7 +25,6 @@ fi
date_time/local_time/local_time.hpp \
date_time/c_local_time_adjustor.hpp \
date_time/gregorian/gregorian_types.hpp \
- foreach.hpp \
filesystem.hpp \
filesystem/fstream.hpp \
format.hpp \
@@ -41,8 +40,6 @@ fi
random/uniform_int.hpp \
regex.hpp \
scope_exit.hpp \
- shared_ptr.hpp \
- smart_ptr/make_shared.hpp \
serialization/serialization.hpp \
serialization/vector.hpp \
serialization/list.hpp \
@@ -53,7 +50,7 @@ fi
serialization/version.hpp \
serialization/split_member.hpp \
serialization/optional.hpp \
- signals.hpp \
+ signals2.hpp \
thread.hpp \
unordered_map.hpp \
uuid/uuid.hpp \
@@ -62,13 +59,18 @@ fi
variant.hpp \
spirit/include/lex_lexertl.hpp \
typeof/incr_registration_group.hpp \
+ atomic \
+ system/src/error_code.cpp \
+ phoenix/support/detail/iterate.hpp \
+ type_traits.hpp \
+ range/adaptor/reversed.hpp \
$TARGET_DIR
cp $1/LICENSE_1_0.txt $TARGET_DIR
rm -rf $TARGET_DIR/libs/config
rm -rf $TARGET_DIR/libs/smart_ptr
-LIBS="date_time regex system thread signals filesystem program_options serialization archive"
+LIBS="date_time regex system thread signals2 filesystem program_options serialization archive atomic"
for lib in $LIBS; do
rm -rf $TARGET_DIR/libs/$lib/build $TARGET_DIR/libs/$lib/*.doc $TARGET_DIR/libs/$lib/src/*.doc $TARGET_DIR/libs/$lib/src/CMakeLists.txt $TARGET_DIR/libs/$lib/test
done
diff --git a/3rdParty/Breakpad/01_breakpad_filename_prefix.diff b/3rdParty/Breakpad/01_breakpad_filename_prefix.diff
new file mode 100644
index 0000000..b63180d
--- /dev/null
+++ b/3rdParty/Breakpad/01_breakpad_filename_prefix.diff
@@ -0,0 +1,66 @@
+diff --git a/3rdParty/Breakpad/src/client/windows/handler/exception_handler.cc b/3rdParty/Breakpad/src/client/windows/handler/exception_handler.cc
+index 6e5b724..272ca5f 100644
+--- a/3rdParty/Breakpad/src/client/windows/handler/exception_handler.cc
++++ b/3rdParty/Breakpad/src/client/windows/handler/exception_handler.cc
+@@ -124,6 +124,7 @@ void ExceptionHandler::Initialize(const wstring& dump_path,
+ callback_ = callback;
+ callback_context_ = callback_context;
+ dump_path_c_ = NULL;
++ dump_filename_prefix_c_ = NULL;
+ next_minidump_id_c_ = NULL;
+ next_minidump_path_c_ = NULL;
+ dbghelp_module_ = NULL;
+@@ -217,6 +218,7 @@ void ExceptionHandler::Initialize(const wstring& dump_path,
+
+ // set_dump_path calls UpdateNextID. This sets up all of the path and id
+ // strings, and their equivalent c_str pointers.
++ set_dump_filename_prefix(wstring());
+ set_dump_path(dump_path);
+ }
+
+@@ -914,8 +916,8 @@ void ExceptionHandler::UpdateNextID() {
+ next_minidump_id_c_ = next_minidump_id_.c_str();
+
+ wchar_t minidump_path[MAX_PATH];
+- swprintf(minidump_path, MAX_PATH, L"%s\\%s.dmp",
+- dump_path_c_, next_minidump_id_c_);
++ swprintf(minidump_path, MAX_PATH, L"%s\\%s%s.dmp",
++ dump_path_c_, dump_filename_prefix_c_, next_minidump_id_c_);
+
+ // remove when VC++7.1 is no longer supported
+ minidump_path[MAX_PATH - 1] = L'\0';
+diff --git a/3rdParty/Breakpad/src/client/windows/handler/exception_handler.h b/3rdParty/Breakpad/src/client/windows/handler/exception_handler.h
+index 09f5177..6f59348 100644
+--- a/3rdParty/Breakpad/src/client/windows/handler/exception_handler.h
++++ b/3rdParty/Breakpad/src/client/windows/handler/exception_handler.h
+@@ -188,6 +188,12 @@ class ExceptionHandler {
+ UpdateNextID(); // Necessary to put dump_path_ in next_minidump_path_.
+ }
+
++ void set_dump_filename_prefix(const wstring& dump_prefix) {
++ dump_filename_prefix_ = dump_prefix;
++ dump_filename_prefix_c_ = dump_filename_prefix_.c_str();
++ UpdateNextID();
++ }
++
+ // Requests that a previously reported crash be uploaded.
+ bool RequestUpload(DWORD crash_id);
+
+@@ -313,6 +319,9 @@ class ExceptionHandler {
+ // argument to the constructor, or set_dump_path.
+ wstring dump_path_;
+
++ // The filename prefix used for the minidump files.
++ wstring dump_filename_prefix_;
++
+ // The basename of the next minidump to be written, without the extension.
+ wstring next_minidump_id_;
+
+@@ -327,6 +336,7 @@ class ExceptionHandler {
+ // should be equivalent to the lifetimes of the associated wstring, provided
+ // that the wstrings are not altered.
+ const wchar_t* dump_path_c_;
++ const wchar_t* dump_filename_prefix_c_;
+ const wchar_t* next_minidump_id_c_;
+ const wchar_t* next_minidump_path_c_;
+
diff --git a/3rdParty/Breakpad/SConscript b/3rdParty/Breakpad/SConscript
index 142634b..3b9447d 100644
--- a/3rdParty/Breakpad/SConscript
+++ b/3rdParty/Breakpad/SConscript
@@ -7,91 +7,91 @@ if env["PLATFORM"] == "win32" :
# Module flags
################################################################################
- if env["SCONS_STAGE"] == "flags" :
- env["HAVE_BREAKPAD"] = True
- env["BREAKPAD_FLAGS"] = {
- "CPPPATH": [env.Dir("src")],
- "CPPFLAGS": [],
- "LIBPATH": [env.Dir(".")],
- "LIBS": ["Swift_BreakPad"]
- }
+ if env["SCONS_STAGE"] == "flags" :
+ env["HAVE_BREAKPAD"] = True
+ env["BREAKPAD_FLAGS"] = {
+ "CPPPATH": [env.Dir("src")],
+ "CPPFLAGS": [],
+ "LIBPATH": [env.Dir(".")],
+ "LIBS": ["Swift_BreakPad"]
+ }
################################################################################
# Build
################################################################################
- if env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
- myenv.Replace(CXXFLAGS = [flag for flag in env["CXXFLAGS"] if not flag.startswith("-W")])
- myenv.Append(CPPPATH = ["src"])
+ if env["SCONS_STAGE"] == "build" :
+ myenv = env.Clone()
+ myenv.Replace(CXXFLAGS = [flag for flag in env["CXXFLAGS"] if not flag.startswith("-W")])
+ myenv.Append(CPPPATH = ["src"])
- lib_sources = []
- dumpsyms_sources = []
- common_sources = []
- if myenv["PLATFORM"] == "win32" :
- myenv.Append(CPPDEFINES = ["UNICODE"])
- lib_sources += [
- "src/client/windows/handler/exception_handler.cc",
- "src/client/windows/crash_generation/crash_generation_client.cc",
- "src/common/windows/guid_string.cc",
- ]
+ lib_sources = []
+ dumpsyms_sources = []
+ common_sources = []
+ if myenv["PLATFORM"] == "win32" :
+ myenv.Append(CPPDEFINES = ["UNICODE"])
+ lib_sources += [
+ "src/client/windows/handler/exception_handler.cc",
+ "src/client/windows/crash_generation/crash_generation_client.cc",
+ "src/common/windows/guid_string.cc",
+ ]
- if myenv["PLATFORM"] == "darwin" or myenv["PLATFORM"] == "linux" :
- lib_sources += [
- ]
- common_sources += [
- "src/common/md5.cc",
- ]
-
- if myenv["PLATFORM"] == "darwin" :
- myenv.Append(CPPDEFINES = ["HAVE_MACH_O_NLIST_H"])
- lib_sources += [
- "src/client/mac/handler/exception_handler.cc",
- "src/client/mac/handler/minidump_generator.cc",
- "src/client/mac/handler/dynamic_images.cc",
- "src/client/mac/handler/breakpad_nlist_64.cc",
- "src/client/mac/crash_generation/crash_generation_client.cc",
- "src/common/mac/MachIPC.mm",
- "src/common/mac/string_utilities.cc",
- "src/common/mac/bootstrap_compat.cc",
- "src/client/minidump_file_writer.cc",
- "src/common/string_conversion.cc",
- "src/common/convert_UTF.c",
- ]
- common_sources += [
- "src/common/mac/macho_id.cc",
- "src/common/mac/macho_walker.cc",
- "src/common/mac/file_id.cc",
- "src/common/mac/macho_utilities.cc",
- ]
- dumpsyms_sources += [
- "src/tools/mac/dump_syms/dump_syms_tool.mm",
- "src/common/mac/dump_syms.mm",
- "src/common/mac/macho_reader.cc",
- "src/common/dwarf/bytereader.cc",
- "src/common/dwarf/dwarf2reader.cc",
- "src/common/dwarf/dwarf2diehandler.cc",
- "src/common/dwarf_line_to_module.cc",
- "src/common/dwarf_cfi_to_module.cc",
- "src/common/dwarf_cu_to_module.cc",
- "src/common/stabs_to_module.cc",
- "src/common/stabs_reader.cc",
- "src/common/module.cc",
- "src/common/language.cc",
- ]
+ if myenv["PLATFORM"] == "darwin" or myenv["PLATFORM"] == "linux" :
+ lib_sources += [
+ ]
+ common_sources += [
+ "src/common/md5.cc",
+ ]
+
+ if myenv["PLATFORM"] == "darwin" :
+ myenv.Append(CPPDEFINES = ["HAVE_MACH_O_NLIST_H"])
+ lib_sources += [
+ "src/client/mac/handler/exception_handler.cc",
+ "src/client/mac/handler/minidump_generator.cc",
+ "src/client/mac/handler/dynamic_images.cc",
+ "src/client/mac/handler/breakpad_nlist_64.cc",
+ "src/client/mac/crash_generation/crash_generation_client.cc",
+ "src/common/mac/MachIPC.mm",
+ "src/common/mac/string_utilities.cc",
+ "src/common/mac/bootstrap_compat.cc",
+ "src/client/minidump_file_writer.cc",
+ "src/common/string_conversion.cc",
+ "src/common/convert_UTF.c",
+ ]
+ common_sources += [
+ "src/common/mac/macho_id.cc",
+ "src/common/mac/macho_walker.cc",
+ "src/common/mac/file_id.cc",
+ "src/common/mac/macho_utilities.cc",
+ ]
+ dumpsyms_sources += [
+ "src/tools/mac/dump_syms/dump_syms_tool.mm",
+ "src/common/mac/dump_syms.mm",
+ "src/common/mac/macho_reader.cc",
+ "src/common/dwarf/bytereader.cc",
+ "src/common/dwarf/dwarf2reader.cc",
+ "src/common/dwarf/dwarf2diehandler.cc",
+ "src/common/dwarf_line_to_module.cc",
+ "src/common/dwarf_cfi_to_module.cc",
+ "src/common/dwarf_cu_to_module.cc",
+ "src/common/stabs_to_module.cc",
+ "src/common/stabs_reader.cc",
+ "src/common/module.cc",
+ "src/common/language.cc",
+ ]
- if myenv["PLATFORM"] == "linux" :
- dumpsyms_sources += ["src/tools/linux/dump_syms/dump_syms.cc"]
+ if myenv["PLATFORM"] == "linux" :
+ dumpsyms_sources += ["src/tools/linux/dump_syms/dump_syms.cc"]
- common_objects = myenv.StaticObject(common_sources)
+ common_objects = myenv.StaticObject(common_sources)
- myenv.StaticLibrary("Swift_BreakPad", lib_sources + common_objects)
+ myenv.StaticLibrary("Swift_BreakPad", lib_sources + common_objects)
- #if myenv["PLATFORM"] == "darwin" or myenv["PLATFORM"] == "linux" :
- # myenv.Program("dump_syms", dumpsyms_sources + common_objects)
+ #if myenv["PLATFORM"] == "darwin" or myenv["PLATFORM"] == "linux" :
+ # myenv.Program("dump_syms", dumpsyms_sources + common_objects)
else :
- if env["SCONS_STAGE"] == "flags" :
- env["HAVE_BREAKPAD"] = False
- env["BREAKPAD_FLAGS"] = {}
+ if env["SCONS_STAGE"] == "flags" :
+ env["HAVE_BREAKPAD"] = False
+ env["BREAKPAD_FLAGS"] = {}
diff --git a/3rdParty/Breakpad/src/client/windows/handler/exception_handler.cc b/3rdParty/Breakpad/src/client/windows/handler/exception_handler.cc
index 6e5b724..272ca5f 100644
--- a/3rdParty/Breakpad/src/client/windows/handler/exception_handler.cc
+++ b/3rdParty/Breakpad/src/client/windows/handler/exception_handler.cc
@@ -124,6 +124,7 @@ void ExceptionHandler::Initialize(const wstring& dump_path,
callback_ = callback;
callback_context_ = callback_context;
dump_path_c_ = NULL;
+ dump_filename_prefix_c_ = NULL;
next_minidump_id_c_ = NULL;
next_minidump_path_c_ = NULL;
dbghelp_module_ = NULL;
@@ -217,6 +218,7 @@ void ExceptionHandler::Initialize(const wstring& dump_path,
// set_dump_path calls UpdateNextID. This sets up all of the path and id
// strings, and their equivalent c_str pointers.
+ set_dump_filename_prefix(wstring());
set_dump_path(dump_path);
}
@@ -914,8 +916,8 @@ void ExceptionHandler::UpdateNextID() {
next_minidump_id_c_ = next_minidump_id_.c_str();
wchar_t minidump_path[MAX_PATH];
- swprintf(minidump_path, MAX_PATH, L"%s\\%s.dmp",
- dump_path_c_, next_minidump_id_c_);
+ swprintf(minidump_path, MAX_PATH, L"%s\\%s%s.dmp",
+ dump_path_c_, dump_filename_prefix_c_, next_minidump_id_c_);
// remove when VC++7.1 is no longer supported
minidump_path[MAX_PATH - 1] = L'\0';
diff --git a/3rdParty/Breakpad/src/client/windows/handler/exception_handler.h b/3rdParty/Breakpad/src/client/windows/handler/exception_handler.h
index 09f5177..6f59348 100644
--- a/3rdParty/Breakpad/src/client/windows/handler/exception_handler.h
+++ b/3rdParty/Breakpad/src/client/windows/handler/exception_handler.h
@@ -188,6 +188,12 @@ class ExceptionHandler {
UpdateNextID(); // Necessary to put dump_path_ in next_minidump_path_.
}
+ void set_dump_filename_prefix(const wstring& dump_prefix) {
+ dump_filename_prefix_ = dump_prefix;
+ dump_filename_prefix_c_ = dump_filename_prefix_.c_str();
+ UpdateNextID();
+ }
+
// Requests that a previously reported crash be uploaded.
bool RequestUpload(DWORD crash_id);
@@ -313,6 +319,9 @@ class ExceptionHandler {
// argument to the constructor, or set_dump_path.
wstring dump_path_;
+ // The filename prefix used for the minidump files.
+ wstring dump_filename_prefix_;
+
// The basename of the next minidump to be written, without the extension.
wstring next_minidump_id_;
@@ -327,6 +336,7 @@ class ExceptionHandler {
// should be equivalent to the lifetimes of the associated wstring, provided
// that the wstrings are not altered.
const wchar_t* dump_path_c_;
+ const wchar_t* dump_filename_prefix_c_;
const wchar_t* next_minidump_id_c_;
const wchar_t* next_minidump_path_c_;
diff --git a/3rdParty/CppUnit/SConscript b/3rdParty/CppUnit/SConscript
index addc8ab..0b97289 100644
--- a/3rdParty/CppUnit/SConscript
+++ b/3rdParty/CppUnit/SConscript
@@ -2,65 +2,65 @@ Import("env")
if env["TEST"] :
- if env["PLATFORM"] == "win32" :
- cppflags = ["/I" + Dir("src/include").abspath]
- elif env["PLATFORM"] == "sunos" :
- cppflags = [("-I" + Dir("src/include").abspath)]
- else :
- cppflags = [("-isystem", Dir("src/include").abspath)]
+ if env["PLATFORM"] == "win32" :
+ cppflags = ["/I" + Dir("src/include").abspath]
+ elif env["PLATFORM"] == "sunos" :
+ cppflags = [("-I" + Dir("src/include").abspath)]
+ else :
+ cppflags = [("-isystem", Dir("src/include").abspath)]
################################################################################
# Module flags
################################################################################
- if env["SCONS_STAGE"] == "flags" :
- env["CPPUNIT_FLAGS"] = {
- "CPPPATH": [env.Dir(".")],
- "CPPFLAGS": cppflags,
- "LIBPATH": [env.Dir(".")],
- "LIBS": ["Swiften_CppUnit"]
- }
+ if env["SCONS_STAGE"] == "flags" :
+ env["CPPUNIT_FLAGS"] = {
+ "CPPPATH": [env.Dir(".")],
+ "CPPFLAGS": cppflags,
+ "LIBPATH": [env.Dir(".")],
+ "LIBS": ["Swiften_CppUnit"]
+ }
################################################################################
# Build
################################################################################
- if env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
- myenv.Replace(CXXFLAGS = [flag for flag in env["CXXFLAGS"] if not flag.startswith("-W")])
- myenv.Append(CPPPATH = ["src/include", "."])
- sources = [
- "src/src/cppunit/TextTestRunner.cpp",
- "src/src/cppunit/TextTestProgressListener.cpp",
- "src/src/cppunit/BriefTestProgressListener.cpp",
- "src/src/cppunit/TextOutputter.cpp",
- "src/src/cppunit/XmlOutputter.cpp",
- "src/src/cppunit/XmlElement.cpp",
- "src/src/cppunit/XmlDocument.cpp",
- "src/src/cppunit/StringTools.cpp",
- "src/src/cppunit/DefaultProtector.cpp",
- "src/src/cppunit/Protector.cpp",
- "src/src/cppunit/ProtectorChain.cpp",
- "src/src/cppunit/SynchronizedObject.cpp",
- "src/src/cppunit/SourceLine.cpp",
- "src/src/cppunit/TestRunner.cpp",
- "src/src/cppunit/TestFactoryRegistry.cpp",
- "src/src/cppunit/TestSuite.cpp",
- "src/src/cppunit/TestSuiteBuilderContext.cpp",
- "src/src/cppunit/TestResult.cpp",
- "src/src/cppunit/TestResultCollector.cpp",
- "src/src/cppunit/TestSuccessListener.cpp",
- "src/src/cppunit/TestComposite.cpp",
- "src/src/cppunit/TestCase.cpp",
- "src/src/cppunit/TestFailure.cpp",
- "src/src/cppunit/TestLeaf.cpp",
- "src/src/cppunit/TestNamer.cpp",
- "src/src/cppunit/Asserter.cpp",
- "src/src/cppunit/TypeInfoHelper.cpp",
- "src/src/cppunit/Exception.cpp",
- "src/src/cppunit/Message.cpp",
- "src/src/cppunit/AdditionalMessage.cpp",
- "src/src/cppunit/Test.cpp",
- "src/src/cppunit/TestPath.cpp"
- ]
- myenv.StaticLibrary("Swiften_CppUnit", sources)
+ if env["SCONS_STAGE"] == "build" :
+ myenv = env.Clone()
+ myenv.Replace(CXXFLAGS = [flag for flag in env["CXXFLAGS"] if not flag.startswith("-W")])
+ myenv.Append(CPPPATH = ["src/include", "."])
+ sources = [
+ "src/src/cppunit/TextTestRunner.cpp",
+ "src/src/cppunit/TextTestProgressListener.cpp",
+ "src/src/cppunit/BriefTestProgressListener.cpp",
+ "src/src/cppunit/TextOutputter.cpp",
+ "src/src/cppunit/XmlOutputter.cpp",
+ "src/src/cppunit/XmlElement.cpp",
+ "src/src/cppunit/XmlDocument.cpp",
+ "src/src/cppunit/StringTools.cpp",
+ "src/src/cppunit/DefaultProtector.cpp",
+ "src/src/cppunit/Protector.cpp",
+ "src/src/cppunit/ProtectorChain.cpp",
+ "src/src/cppunit/SynchronizedObject.cpp",
+ "src/src/cppunit/SourceLine.cpp",
+ "src/src/cppunit/TestRunner.cpp",
+ "src/src/cppunit/TestFactoryRegistry.cpp",
+ "src/src/cppunit/TestSuite.cpp",
+ "src/src/cppunit/TestSuiteBuilderContext.cpp",
+ "src/src/cppunit/TestResult.cpp",
+ "src/src/cppunit/TestResultCollector.cpp",
+ "src/src/cppunit/TestSuccessListener.cpp",
+ "src/src/cppunit/TestComposite.cpp",
+ "src/src/cppunit/TestCase.cpp",
+ "src/src/cppunit/TestFailure.cpp",
+ "src/src/cppunit/TestLeaf.cpp",
+ "src/src/cppunit/TestNamer.cpp",
+ "src/src/cppunit/Asserter.cpp",
+ "src/src/cppunit/TypeInfoHelper.cpp",
+ "src/src/cppunit/Exception.cpp",
+ "src/src/cppunit/Message.cpp",
+ "src/src/cppunit/AdditionalMessage.cpp",
+ "src/src/cppunit/Test.cpp",
+ "src/src/cppunit/TestPath.cpp"
+ ]
+ myenv.StaticLibrary("Swiften_CppUnit", sources)
diff --git a/3rdParty/Expat/SConscript b/3rdParty/Expat/SConscript
index c961483..56949aa 100644
--- a/3rdParty/Expat/SConscript
+++ b/3rdParty/Expat/SConscript
@@ -1,29 +1,29 @@
Import(["env", "conf_env"])
if env.get("EXPAT_BUNDLED", False) :
- if env["SCONS_STAGE"] == "flags" :
- env["EXPAT_FLAGS"] = {
- "CPPDEFINES": ["XML_STATIC"],
- "CPPPATH": [Dir("src")],
- "LIBPATH": [Dir(".")],
- }
+ if env["SCONS_STAGE"] == "flags" :
+ env["EXPAT_FLAGS"] = {
+ "CPPDEFINES": ["XML_STATIC"],
+ "CPPPATH": [Dir("src")],
+ "LIBPATH": [Dir(".")],
+ }
- if env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
- myenv.Append(CPPDEFINES = ["XML_STATIC", "HAVE_EXPAT_CONFIG_H"])
- if env.get("BOOST_BUNDLED", False) :
- myenv.Append(CPPPATH = [".", "src", "../Boost/src"])
- else :
- myenv.Append(CPPPATH = [".", "src"])
- myenv.MergeFlags(env["BOOST_FLAGS"])
+ if env["SCONS_STAGE"] == "build" :
+ myenv = env.Clone()
+ myenv.Append(CPPDEFINES = ["XML_STATIC", "HAVE_EXPAT_CONFIG_H"])
+ if env.get("BOOST_BUNDLED", False) :
+ myenv.Append(CPPPATH = [".", "src", "../Boost/src"])
+ else :
+ myenv.Append(CPPPATH = [".", "src"])
+ myenv.MergeFlags(env["BOOST_FLAGS"])
- conf = Configure(conf_env)
- if conf.CheckFunc('memmove') :
- myenv.Append(CPPDEFINES = ["HAVE_MEMMOVE"])
- conf.Finish()
+ conf = Configure(conf_env)
+ if conf.CheckFunc('memmove') :
+ myenv.Append(CPPDEFINES = ["HAVE_MEMMOVE"])
+ conf.Finish()
- env["EXPAT_OBJECTS"] = myenv.SwiftenObject([
- "src/xmltok.c",
- "src/xmlparse.c",
- "src/xmlrole.c"
- ])
+ env["EXPAT_OBJECTS"] = myenv.SwiftenObject([
+ "src/xmltok.c",
+ "src/xmlparse.c",
+ "src/xmlrole.c"
+ ])
diff --git a/3rdParty/LCov/gendesc b/3rdParty/LCov/gendesc
index 522ef69..7287c83 100755
--- a/3rdParty/LCov/gendesc
+++ b/3rdParty/LCov/gendesc
@@ -38,10 +38,12 @@
use strict;
use File::Basename;
use Getopt::Long;
+use Cwd qw/abs_path/;
# Constants
-our $lcov_version = 'LCOV version 1.9';
+our $tool_dir = abs_path(dirname($0));
+our $lcov_version = "LCOV version 1.12";
our $lcov_url = "http://ltp.sourceforge.net/coverage/lcov.php";
our $tool_name = basename($0);
@@ -67,9 +69,6 @@ our $input_filename;
$SIG{__WARN__} = \&warn_handler;
$SIG{__DIE__} = \&die_handler;
-# Prettify version string
-$lcov_version =~ s/\$\s*Revision\s*:?\s*(\S+)\s*\$/$1/;
-
# Parse command line options
if (!GetOptions("output-filename=s" => \$output_filename,
"version" =>\$version,
@@ -153,13 +152,13 @@ sub gen_desc()
local *OUTPUT_HANDLE;
my $empty_line = "ignore";
- open(INPUT_HANDLE, $input_filename)
+ open(INPUT_HANDLE, "<", $input_filename)
or die("ERROR: cannot open $input_filename!\n");
# Open output file for writing
if ($output_filename)
{
- open(OUTPUT_HANDLE, ">$output_filename")
+ open(OUTPUT_HANDLE, ">", $output_filename)
or die("ERROR: cannot create $output_filename!\n");
}
else
diff --git a/3rdParty/LCov/genhtml b/3rdParty/LCov/genhtml
index d74063a..cf1b7f5 100755
--- a/3rdParty/LCov/genhtml
+++ b/3rdParty/LCov/genhtml
@@ -1,6 +1,6 @@
#!/usr/bin/perl -w
#
-# Copyright (c) International Business Machines Corp., 2002,2010
+# Copyright (c) International Business Machines Corp., 2002,2012
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -65,17 +65,23 @@
#
use strict;
-use File::Basename;
+use File::Basename;
+use File::Temp qw(tempfile);
use Getopt::Long;
use Digest::MD5 qw(md5_base64);
+use Cwd qw/abs_path/;
# Global constants
our $title = "LCOV - code coverage report";
-our $lcov_version = 'LCOV version 1.9';
+our $tool_dir = abs_path(dirname($0));
+our $lcov_version = "LCOV version 1.12";
our $lcov_url = "http://ltp.sourceforge.net/coverage/lcov.php";
our $tool_name = basename($0);
+# Specify coverage rate default precision
+our $default_precision = 1;
+
# Specify coverage rate limits (in %) for classifying file entries
# HI: $hi_limit <= rate <= 100 graph color: green
# MED: $med_limit <= rate < $hi_limit graph color: orange
@@ -145,6 +151,7 @@ our $BR_BRANCH = 1;
our $BR_TAKEN = 2;
our $BR_VEC_ENTRIES = 3;
our $BR_VEC_WIDTH = 32;
+our $BR_VEC_MAX = vec(pack('b*', 1 x $BR_VEC_WIDTH), 0, $BR_VEC_WIDTH);
# Additional offsets used when converting branch coverage data to HTML
our $BR_LEN = 3;
@@ -155,6 +162,12 @@ our $BR_CLOSE = 5;
our $BR_SUB = 0;
our $BR_ADD = 1;
+# Error classes which users may specify to ignore during processing
+our $ERROR_SOURCE = 0;
+our %ERROR_ID = (
+ "source" => $ERROR_SOURCE,
+);
+
# Data related prototypes
sub print_usage(*);
sub gen_html();
@@ -165,7 +178,7 @@ sub info(@);
sub read_info_file($);
sub get_info_entry($);
sub set_info_entry($$$$$$$$$;$$$$$$);
-sub get_prefix(@);
+sub get_prefix($@);
sub shorten_prefix($);
sub get_dir_list(@);
sub get_relative_base_path($);
@@ -181,7 +194,7 @@ sub get_affecting_tests($$$);
sub combine_info_files($$);
sub merge_checksums($$$);
sub combine_info_entries($$$);
-sub apply_prefix($$);
+sub apply_prefix($@);
sub system_no_output($@);
sub read_config($);
sub apply_config($);
@@ -198,6 +211,9 @@ sub combine_brcount($$$);
sub get_br_found_and_hit($);
sub warn_handler($);
sub die_handler($);
+sub parse_ignore_errors(@);
+sub parse_dir_prefix(@);
+sub rate($$;$$$);
# HTML related prototypes
@@ -244,7 +260,8 @@ sub gen_png($$$@);
# Global variables & initialization
our %info_data; # Hash containing all data from .info file
-our $dir_prefix; # Prefix to remove from all sub directories
+our @opt_dir_prefix; # Array of prefixes to remove from all sub directories
+our @dir_prefix;
our %test_description; # Hash containing test descriptions if available
our $date = get_date_string();
@@ -259,9 +276,9 @@ our $help; # Help option flag
our $version; # Version option flag
our $show_details; # If set, generate detailed directory view
our $no_prefix; # If set, do not remove filename prefix
-our $func_coverage = 1; # If set, generate function coverage statistics
+our $func_coverage; # If set, generate function coverage statistics
our $no_func_coverage; # Disable func_coverage
-our $br_coverage = 1; # If set, generate branch coverage statistics
+our $br_coverage; # If set, generate branch coverage statistics
our $no_br_coverage; # Disable br_coverage
our $sort = 1; # If set, provide directory listings with sorted entries
our $no_sort; # Disable sort
@@ -279,15 +296,22 @@ our $html_epilog; # Actual HTML epilog
our $html_ext = "html"; # Extension for generated HTML files
our $html_gzip = 0; # Compress with gzip
our $demangle_cpp = 0; # Demangle C++ function names
+our @opt_ignore_errors; # Ignore certain error classes during processing
+our @ignore;
+our $opt_config_file; # User-specified configuration file location
+our %opt_rc;
+our $charset = "UTF-8"; # Default charset for HTML pages
our @fileview_sortlist;
our @fileview_sortname = ("", "-sort-l", "-sort-f", "-sort-b");
our @funcview_sortlist;
our @rate_name = ("Lo", "Med", "Hi");
our @rate_png = ("ruby.png", "amber.png", "emerald.png");
+our $lcov_func_coverage = 1;
+our $lcov_branch_coverage = 0;
+our $rc_desc_html = 0; # lcovrc: genhtml_desc_html
our $cwd = `pwd`; # Current working directory
chomp($cwd);
-our $tool_dir = dirname($0); # Directory where genhtml tool is installed
#
@@ -297,17 +321,29 @@ our $tool_dir = dirname($0); # Directory where genhtml tool is installed
$SIG{__WARN__} = \&warn_handler;
$SIG{__DIE__} = \&die_handler;
-# Prettify version string
-$lcov_version =~ s/\$\s*Revision\s*:?\s*(\S+)\s*\$/$1/;
+# Check command line for a configuration file name
+Getopt::Long::Configure("pass_through", "no_auto_abbrev");
+GetOptions("config-file=s" => \$opt_config_file,
+ "rc=s%" => \%opt_rc);
+Getopt::Long::Configure("default");
-# Add current working directory if $tool_dir is not already an absolute path
-if (! ($tool_dir =~ /^\/(.*)$/))
{
- $tool_dir = "$cwd/$tool_dir";
+ # Remove spaces around rc options
+ my %new_opt_rc;
+
+ while (my ($key, $value) = each(%opt_rc)) {
+ $key =~ s/^\s+|\s+$//g;
+ $value =~ s/^\s+|\s+$//g;
+
+ $new_opt_rc{$key} = $value;
+ }
+ %opt_rc = %new_opt_rc;
}
# Read configuration file if available
-if (defined($ENV{"HOME"}) && (-r $ENV{"HOME"}."/.lcovrc"))
+if (defined($opt_config_file)) {
+ $config = read_config($opt_config_file);
+} elsif (defined($ENV{"HOME"}) && (-r $ENV{"HOME"}."/.lcovrc"))
{
$config = read_config($ENV{"HOME"}."/.lcovrc");
}
@@ -316,9 +352,9 @@ elsif (-r "/etc/lcovrc")
$config = read_config("/etc/lcovrc");
}
-if ($config)
+if ($config || %opt_rc)
{
- # Copy configuration file values to variables
+ # Copy configuration file and --rc values to variables
apply_config({
"genhtml_css_file" => \$css_filename,
"genhtml_hi_limit" => \$hi_limit,
@@ -337,6 +373,7 @@ if ($config)
"genhtml_html_epilog" => \$html_epilog_file,
"genhtml_html_extension" => \$html_ext,
"genhtml_html_gzip" => \$html_gzip,
+ "genhtml_precision" => \$default_precision,
"genhtml_function_hi_limit" => \$fn_hi_limit,
"genhtml_function_med_limit" => \$fn_med_limit,
"genhtml_function_coverage" => \$func_coverage,
@@ -345,14 +382,20 @@ if ($config)
"genhtml_branch_coverage" => \$br_coverage,
"genhtml_branch_field_width" => \$br_field_width,
"genhtml_sort" => \$sort,
+ "genhtml_charset" => \$charset,
+ "genhtml_desc_html" => \$rc_desc_html,
+ "lcov_function_coverage" => \$lcov_func_coverage,
+ "lcov_branch_coverage" => \$lcov_branch_coverage,
});
}
-# Copy limit values if not specified
+# Copy related values if not specified
$fn_hi_limit = $hi_limit if (!defined($fn_hi_limit));
$fn_med_limit = $med_limit if (!defined($fn_med_limit));
$br_hi_limit = $hi_limit if (!defined($br_hi_limit));
$br_med_limit = $med_limit if (!defined($br_med_limit));
+$func_coverage = $lcov_func_coverage if (!defined($func_coverage));
+$br_coverage = $lcov_branch_coverage if (!defined($br_coverage));
# Parse command line options
if (!GetOptions("output-directory|o=s" => \$output_directory,
@@ -361,7 +404,7 @@ if (!GetOptions("output-directory|o=s" => \$output_directory,
"keep-descriptions|k" => \$keep_descriptions,
"css-file|c=s" => \$css_filename,
"baseline-file|b=s" => \$base_filename,
- "prefix|p=s" => \$dir_prefix,
+ "prefix|p=s" => \@opt_dir_prefix,
"num-spaces=i" => \$tab_size,
"no-prefix" => \$no_prefix,
"no-sourceview" => \$no_sourceview,
@@ -383,6 +426,10 @@ if (!GetOptions("output-directory|o=s" => \$output_directory,
"sort" => \$sort,
"no-sort" => \$no_sort,
"demangle-cpp" => \$demangle_cpp,
+ "ignore-errors=s" => \@opt_ignore_errors,
+ "config-file=s" => \$opt_config_file,
+ "rc=s%" => \%opt_rc,
+ "precision=i" => \$default_precision,
))
{
print(STDERR "Use $tool_name --help to get usage information\n");
@@ -418,6 +465,12 @@ if ($version)
exit(0);
}
+# Determine which errors the user wants us to ignore
+parse_ignore_errors(@opt_ignore_errors);
+
+# Split the list of prefixes if needed
+parse_dir_prefix(@opt_dir_prefix);
+
# Check for info filename
if (!@info_filenames)
{
@@ -471,11 +524,11 @@ if ($no_sourceview && defined($frames))
}
# Issue a warning if --no-prefix is enabled together with --prefix
-if ($no_prefix && defined($dir_prefix))
+if ($no_prefix && @dir_prefix)
{
warn("WARNING: option --prefix disabled because --no-prefix was ".
"specified!\n");
- $dir_prefix = undef;
+ @dir_prefix = undef;
}
@fileview_sortlist = ($SORT_FILE);
@@ -503,6 +556,13 @@ if ($demangle_cpp)
}
}
+# Make sure precision is within valid range
+if ($default_precision < 1 || $default_precision > 4)
+{
+ die("ERROR: specified precision is out of range (1 to 4)\n");
+}
+
+
# Make sure output_directory exists, create it if necessary
if ($output_directory)
{
@@ -541,6 +601,9 @@ Misc:
-h, --help Print this help, then exit
-v, --version Print version number, then exit
-q, --quiet Do not print progress messages
+ --config-file FILENAME Specify configuration file location
+ --rc SETTING=VALUE Override configuration file setting
+ --ignore-errors ERRORS Continue after ERRORS (source)
Operation:
-o, --output-directory OUTDIR Write HTML output to OUTDIR
@@ -567,6 +630,7 @@ HTML output:
--html-gzip Use gzip to compress HTML
--(no-)sort Enable (disable) sorted coverage views
--demangle-cpp Demangle C++ function names
+ --precision NUM Set precision of coverage rate
For more information see: $lcov_url
END_OF_USAGE
@@ -607,8 +671,7 @@ sub get_overall_line($$$$)
return "no data found" if (!defined($found) || $found == 0);
$name = ($found == 1) ? $name_sn : $name_pl;
- return sprintf("%.1f%% (%d of %d %s)", $hit * 100 / $found, $hit,
- $found, $name);
+ return rate($hit, $found, "% ($hit of $found $name)");
}
@@ -636,6 +699,116 @@ sub print_overall_rate($$$$$$$$$)
if ($br_do);
}
+sub get_fn_list($)
+{
+ my ($info) = @_;
+ my %fns;
+ my @result;
+
+ foreach my $filename (keys(%{$info})) {
+ my $data = $info->{$filename};
+ my $funcdata = $data->{"func"};
+ my $sumfnccount = $data->{"sumfnc"};
+
+ if (defined($funcdata)) {
+ foreach my $func_name (keys(%{$funcdata})) {
+ $fns{$func_name} = 1;
+ }
+ }
+
+ if (defined($sumfnccount)) {
+ foreach my $func_name (keys(%{$sumfnccount})) {
+ $fns{$func_name} = 1;
+ }
+ }
+ }
+
+ @result = keys(%fns);
+
+ return \@result;
+}
+
+#
+# rename_functions(info, conv)
+#
+# Rename all function names in INFO according to CONV: OLD_NAME -> NEW_NAME.
+# In case two functions demangle to the same name, assume that they are
+# different object code implementations for the same source function.
+#
+
+sub rename_functions($$)
+{
+ my ($info, $conv) = @_;
+
+ foreach my $filename (keys(%{$info})) {
+ my $data = $info->{$filename};
+ my $funcdata;
+ my $testfncdata;
+ my $sumfnccount;
+ my %newfuncdata;
+ my %newsumfnccount;
+ my $f_found;
+ my $f_hit;
+
+ # funcdata: function name -> line number
+ $funcdata = $data->{"func"};
+ foreach my $fn (keys(%{$funcdata})) {
+ my $cn = $conv->{$fn};
+
+ # Abort if two functions on different lines map to the
+ # same demangled name.
+ if (defined($newfuncdata{$cn}) &&
+ $newfuncdata{$cn} != $funcdata->{$fn}) {
+ die("ERROR: Demangled function name $cn ".
+ "maps to different lines (".
+ $newfuncdata{$cn}." vs ".
+ $funcdata->{$fn}.") in $filename\n");
+ }
+ $newfuncdata{$cn} = $funcdata->{$fn};
+ }
+ $data->{"func"} = \%newfuncdata;
+
+ # testfncdata: test name -> testfnccount
+ # testfnccount: function name -> execution count
+ $testfncdata = $data->{"testfnc"};
+ foreach my $tn (keys(%{$testfncdata})) {
+ my $testfnccount = $testfncdata->{$tn};
+ my %newtestfnccount;
+
+ foreach my $fn (keys(%{$testfnccount})) {
+ my $cn = $conv->{$fn};
+
+ # Add counts for different functions that map
+ # to the same name.
+ $newtestfnccount{$cn} +=
+ $testfnccount->{$fn};
+ }
+ $testfncdata->{$tn} = \%newtestfnccount;
+ }
+
+ # sumfnccount: function name -> execution count
+ $sumfnccount = $data->{"sumfnc"};
+ foreach my $fn (keys(%{$sumfnccount})) {
+ my $cn = $conv->{$fn};
+
+ # Add counts for different functions that map
+ # to the same name.
+ $newsumfnccount{$cn} += $sumfnccount->{$fn};
+ }
+ $data->{"sumfnc"} = \%newsumfnccount;
+
+ # Update function found and hit counts since they may have
+ # changed
+ $f_found = 0;
+ $f_hit = 0;
+ foreach my $fn (keys(%newsumfnccount)) {
+ $f_found++;
+ $f_hit++ if ($newsumfnccount{$fn} > 0);
+ }
+ $data->{"f_found"} = $f_found;
+ $data->{"f_hit"} = $f_hit;
+ }
+}
#
# gen_html()
@@ -701,14 +874,16 @@ sub gen_html()
# User requested that we leave filenames alone
info("User asked not to remove filename prefix\n");
}
- elsif (!defined($dir_prefix))
+ elsif (! @dir_prefix)
{
# Get prefix common to most directories in list
- $dir_prefix = get_prefix(@dir_list);
+ my $prefix = get_prefix(1, keys(%info_data));
- if ($dir_prefix)
+ if ($prefix)
{
- info("Found common filename prefix \"$dir_prefix\"\n");
+ info("Found common filename prefix \"$prefix\"\n");
+ $dir_prefix[0] = $prefix;
+
}
else
{
@@ -718,10 +893,17 @@ sub gen_html()
}
else
{
- info("Using user-specified filename prefix \"".
- "$dir_prefix\"\n");
+ my $msg = "Using user-specified filename prefix ";
+ for my $i (0 .. $#dir_prefix)
+ {
+ $dir_prefix[$i] =~ s/\/+$//;
+ $msg .= ", " unless 0 == $i;
+ $msg .= "\"" . $dir_prefix[$i] . "\"";
+ }
+ info($msg . "\n");
}
+
# Read in test description file if specified
if ($desc_filename)
{
@@ -763,11 +945,14 @@ sub gen_html()
$br_found, $br_hit)
= process_dir($dir_name);
+ # Handle files in root directory gracefully
+ $dir_name = "root" if ($dir_name eq "");
+
# Remove prefix if applicable
- if (!$no_prefix && $dir_prefix)
+ if (!$no_prefix && @dir_prefix)
{
- # Match directory names beginning with $dir_prefix
- $dir_name = apply_prefix($dir_name, $dir_prefix);
+ # Match directory names beginning with one of @dir_prefix
+ $dir_name = apply_prefix($dir_name,@dir_prefix);
}
# Generate name for directory overview HTML page
@@ -832,13 +1017,13 @@ sub html_create($$)
if ($html_gzip)
{
- open($handle, "|gzip -c >$filename")
+ open($handle, "|-", "gzip -c >'$filename'")
or die("ERROR: cannot open $filename for writing ".
"(gzip)!\n");
}
else
{
- open($handle, ">$filename")
+ open($handle, ">", $filename)
or die("ERROR: cannot open $filename for writing!\n");
}
}
@@ -855,6 +1040,7 @@ sub write_dir_page($$$$$$$$$$$$$$$$$)
if (!defined($trunc_dir)) {
$trunc_dir = "";
}
+ $title .= " - " if ($trunc_dir ne "");
write_html_prolog(*HTML_HANDLE, $base_dir, "LCOV - $title$trunc_dir");
write_header(*HTML_HANDLE, $view_type, $trunc_dir, $rel_dir,
$overall_found, $overall_hit, $total_fn_found,
@@ -904,8 +1090,8 @@ sub process_dir($)
# Remove prefix if applicable
if (!$no_prefix)
{
- # Match directory name beginning with $dir_prefix
- $rel_dir = apply_prefix($rel_dir, $dir_prefix);
+ # Match directory name beginning with one of @dir_prefix
+ $rel_dir = apply_prefix($rel_dir,@dir_prefix);
}
$trunc_dir = $rel_dir;
@@ -916,6 +1102,10 @@ sub process_dir($)
$rel_dir = substr($rel_dir, 1);
}
+ # Handle files in root directory gracefully
+ $rel_dir = "root" if ($rel_dir eq "");
+ $trunc_dir = "root" if ($trunc_dir eq "");
+
$base_dir = get_relative_base_path($rel_dir);
create_sub_dir($rel_dir);
@@ -1083,7 +1273,7 @@ sub write_function_page($$$$$$$$$$$$$$$$$$)
sub process_file($$$)
{
- info("Processing file ".apply_prefix($_[2], $dir_prefix)."\n");
+ info("Processing file ".apply_prefix($_[2], @dir_prefix)."\n");
my $trunc_dir = $_[0];
my $rel_dir = $_[1];
@@ -1195,6 +1385,10 @@ sub process_file($$$)
# "func" -> \%funcdata
# "found" -> $lines_found (number of instrumented lines found in file)
# "hit" -> $lines_hit (number of executed lines in file)
+# "f_found" -> $fn_found (number of instrumented functions found in file)
+# "f_hit" -> $fn_hit (number of executed functions in file)
+# "b_found" -> $br_found (number of instrumented branches found in file)
+# "b_hit" -> $br_hit (number of executed branches in file)
# "check" -> \%checkdata
# "testfnc" -> \%testfncdata
# "sumfnc" -> \%sumfnccount
@@ -1251,6 +1445,7 @@ sub read_info_file($)
my $line_checksum; # Checksum of current line
my $br_found;
my $br_hit;
+ my $notified_about_relative_paths;
local *INFO_HANDLE; # Filehandle for .info file
info("Reading data file $tracefile\n");
@@ -1281,14 +1476,14 @@ sub read_info_file($)
"compressed file $_[0]!\n");
# Open compressed file
- open(INFO_HANDLE, "gunzip -c $_[0]|")
+ open(INFO_HANDLE, "-|", "gunzip -c '$_[0]'")
or die("ERROR: cannot start gunzip to decompress ".
"file $_[0]!\n");
}
else
{
# Open decompressed file
- open(INFO_HANDLE, $_[0])
+ open(INFO_HANDLE, "<", $_[0])
or die("ERROR: cannot read file $_[0]!\n");
}
@@ -1317,7 +1512,16 @@ sub read_info_file($)
{
# Filename information found
# Retrieve data for new entry
- $filename = $1;
+ $filename = File::Spec->rel2abs($1, Cwd::cwd());
+
+ if (!File::Spec->file_name_is_absolute($1) &&
+ !$notified_about_relative_paths)
+ {
+ info("Resolved relative source file ".
+ "path \"$1\" with CWD to ".
+ "\"$filename\".\n");
+ $notified_about_relative_paths = 1;
+ }
$data = $result{$filename};
($testdata, $sumcount, $funcdata, $checkdata,
@@ -1379,6 +1583,8 @@ sub read_info_file($)
/^FN:(\d+),([^,]+)/ && do
{
+ last if (!$func_coverage);
+
# Function data found, add to structure
$funcdata->{$2} = $1;
@@ -1397,6 +1603,7 @@ sub read_info_file($)
/^FNDA:(\d+),([^,]+)/ && do
{
+ last if (!$func_coverage);
# Function call count found, add to structure
# Add summary counts
$sumfnccount->{$2} += $1;
@@ -1414,6 +1621,7 @@ sub read_info_file($)
my ($line, $block, $branch, $taken) =
($1, $2, $3, $4);
+ last if (!$br_coverage);
$sumbrcount->{$line} =
br_ivec_push($sumbrcount->{$line},
$block, $branch, $taken);
@@ -1614,8 +1822,8 @@ sub set_info_entry($$$$$$$$$;$$$$$$)
sub add_counts($$)
{
- my %data1 = %{$_[0]}; # Hash 1
- my %data2 = %{$_[1]}; # Hash 2
+ my $data1_ref = $_[0]; # Hash 1
+ my $data2_ref = $_[1]; # Hash 2
my %result; # Resulting hash
my $line; # Current line iteration scalar
my $data1_count; # Count of line in hash1
@@ -1623,10 +1831,10 @@ sub add_counts($$)
my $found = 0; # Total number of lines found
my $hit = 0; # Number of lines with a count > 0
- foreach $line (keys(%data1))
+ foreach $line (keys(%$data1_ref))
{
- $data1_count = $data1{$line};
- $data2_count = $data2{$line};
+ $data1_count = $data1_ref->{$line};
+ $data2_count = $data2_ref->{$line};
# Add counts if present in both hashes
if (defined($data2_count)) { $data1_count += $data2_count; }
@@ -1638,14 +1846,14 @@ sub add_counts($$)
if ($data1_count > 0) { $hit++; }
}
- # Add lines unique to data2
- foreach $line (keys(%data2))
+ # Add lines unique to data2_ref
+ foreach $line (keys(%$data2_ref))
{
- # Skip lines already in data1
- if (defined($data1{$line})) { next; }
+ # Skip lines already in data1_ref
+ if (defined($data1_ref->{$line})) { next; }
- # Copy count from data2
- $result{$line} = $data2{$line};
+ # Copy count from data2_ref
+ $result{$line} = $data2_ref->{$line};
$found++;
if ($result{$line} > 0) { $hit++; }
@@ -2110,16 +2318,17 @@ sub combine_info_files($$)
#
-# get_prefix(filename_list)
+# get_prefix(min_dir, filename_list)
#
# Search FILENAME_LIST for a directory prefix which is common to as many
# list entries as possible, so that removing this prefix will minimize the
-# sum of the lengths of all resulting shortened filenames.
+# sum of the lengths of all resulting shortened filenames while observing
+# that no filename has less than MIN_DIR parent directories.
#
-sub get_prefix(@)
+sub get_prefix($@)
{
- my @filename_list = @_; # provided list of filenames
+ my ($min_dir, @filename_list) = @_;
my %prefix; # mapping: prefix -> sum of lengths
my $current; # Temporary iteration variable
@@ -2128,12 +2337,14 @@ sub get_prefix(@)
{
# Need explicit assignment to get a copy of $_ so that
# shortening the contained prefix does not affect the list
- $current = shorten_prefix($_);
+ $current = $_;
while ($current = shorten_prefix($current))
{
+ $current .= "/";
+
# Skip rest if the remaining prefix has already been
# added to hash
- if ($prefix{$current}) { last; }
+ if (exists($prefix{$current})) { last; }
# Initialize with 0
$prefix{$current}="0";
@@ -2141,6 +2352,20 @@ sub get_prefix(@)
}
+ # Remove all prefixes that would cause filenames to have less than
+ # the minimum number of parent directories
+ foreach my $filename (@filename_list) {
+ my $dir = dirname($filename);
+
+ for (my $i = 0; $i < $min_dir; $i++) {
+ delete($prefix{$dir."/"});
+ $dir = shorten_prefix($dir);
+ }
+ }
+
+ # Check if any prefix remains
+ return undef if (!%prefix);
+
# Calculate sum of lengths for all prefixes
foreach $current (keys(%prefix))
{
@@ -2169,6 +2394,8 @@ sub get_prefix(@)
}
}
+ $current =~ s/\/$//;
+
return($current);
}
@@ -2260,7 +2487,7 @@ sub read_testfile($)
my $changed_testname;
local *TEST_HANDLE;
- open(TEST_HANDLE, "<".$_[0])
+ open(TEST_HANDLE, "<", $_[0])
or die("ERROR: cannot open $_[0]!\n");
while (<TEST_HANDLE>)
@@ -2281,6 +2508,9 @@ sub read_testfile($)
# Match lines beginning with TD:<whitespace(s)>
if (/^TD:\s+(.*?)\s*$/)
{
+ if (!defined($test_name)) {
+ die("ERROR: Found test description without prior test name in $_[0]:$.\n");
+ }
# Check for empty line
if ($1)
{
@@ -2348,10 +2578,15 @@ sub get_date_string()
my $year;
my $month;
my $day;
+ my $hour;
+ my $min;
+ my $sec;
- ($year, $month, $day) = (localtime())[5, 4, 3];
+ ($year, $month, $day, $hour, $min, $sec) =
+ (localtime())[5, 4, 3, 2, 1, 0];
- return sprintf("%d-%02d-%02d", $year+1900, $month+1, $day);
+ return sprintf("%d-%02d-%02d %02d:%02d:%02d", $year+1900, $month+1,
+ $day, $hour, $min, $sec);
}
@@ -2408,8 +2643,10 @@ sub write_description_file($$$$$$$)
foreach $test_name (sort(keys(%description)))
{
- write_test_table_entry(*HTML_HANDLE, $test_name,
- escape_html($description{$test_name}));
+ my $desc = $description{$test_name};
+
+ $desc = escape_html($desc) if (!$rc_desc_html);
+ write_test_table_entry(*HTML_HANDLE, $test_name, $desc);
}
write_test_table_epilog(*HTML_HANDLE);
@@ -2531,7 +2768,7 @@ sub write_png_files()
0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82] if ($sort);
foreach (keys(%data))
{
- open(PNG_HANDLE, ">".$_)
+ open(PNG_HANDLE, ">", $_)
or die("ERROR: cannot create $_!\n");
binmode(PNG_HANDLE);
print(PNG_HANDLE map(chr,@{$data{$_}}));
@@ -2549,7 +2786,7 @@ sub write_htaccess_file()
local *HTACCESS_HANDLE;
my $htaccess_data;
- open(*HTACCESS_HANDLE, ">.htaccess")
+ open(*HTACCESS_HANDLE, ">", ".htaccess")
or die("ERROR: cannot open .htaccess for writing!\n");
$htaccess_data = (<<"END_OF_HTACCESS")
@@ -2582,7 +2819,7 @@ sub write_css_file()
return;
}
- open(CSS_HANDLE, ">gcov.css")
+ open(CSS_HANDLE, ">", "gcov.css")
or die ("ERROR: cannot open gcov.css for writing!\n");
@@ -3132,6 +3369,7 @@ END_OF_CSS
sub get_bar_graph_code($$$)
{
+ my ($base_dir, $found, $hit) = @_;
my $rate;
my $alt;
my $width;
@@ -3142,13 +3380,12 @@ sub get_bar_graph_code($$$)
# Check number of instrumented lines
if ($_[1] == 0) { return ""; }
- $rate = $_[2] * 100 / $_[1];
- $alt = sprintf("%.1f", $rate)."%";
- $width = sprintf("%.0f", $rate);
- $remainder = sprintf("%d", 100-$width);
+ $alt = rate($hit, $found, "%");
+ $width = rate($hit, $found, undef, 0);
+ $remainder = 100 - $width;
# Decide which .png file to use
- $png_name = $rate_png[classify_rate($_[1], $_[2], $med_limit,
+ $png_name = $rate_png[classify_rate($found, $hit, $med_limit,
$hi_limit)];
if ($width == 0)
@@ -3197,7 +3434,7 @@ sub classify_rate($$$$)
if ($found == 0) {
return 2;
}
- $rate = $hit * 100 / $found;
+ $rate = rate($hit, $found);
if ($rate < $med) {
return 0;
} elsif ($rate < $hi) {
@@ -3415,12 +3652,13 @@ sub write_file_table_entry(*$$$@)
my ($handle, $base_dir, $filename, $page_link, @entries) = @_;
my $file_code;
my $entry;
+ my $esc_filename = escape_html($filename);
# Add link to source if provided
if (defined($page_link) && $page_link ne "") {
- $file_code = "<a href=\"$page_link\">$filename</a>";
+ $file_code = "<a href=\"$page_link\">$esc_filename</a>";
} else {
- $file_code = $filename;
+ $file_code = $esc_filename;
}
# First column: filename
@@ -3450,7 +3688,7 @@ END_OF_HTML
$rate = "-";
$class = "Hi";
} else {
- $rate = sprintf("%.1f&nbsp;%%", $hit * 100 / $found);
+ $rate = rate($hit, $found, "&nbsp;%");
$class = $rate_name[classify_rate($found, $hit,
$med, $hi)];
}
@@ -3490,11 +3728,8 @@ END_OF_HTML
# Test data
foreach $entry (@entries) {
my ($found, $hit) = @{$entry};
- my $rate = "-";
+ my $rate = rate($hit, $found, "&nbsp;%");
- if ($found > 0) {
- $rate = sprintf("%.1f&nbsp;%%", $hit * 100 / $found);
- }
write_html($handle, <<END_OF_HTML);
<td class="testPer">$rate</td>
<td class="testNum">$hit&nbsp;/&nbsp;$found</td>
@@ -4010,7 +4245,7 @@ sub write_frameset(*$$$)
<html lang="en">
<head>
- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
+ <meta http-equiv="Content-Type" content="text/html; charset=$charset">
<title>$_[3]</title>
<link rel="stylesheet" type="text/css" href="$_[1]gcov.css">
</head>
@@ -4073,7 +4308,7 @@ sub write_overview(*$$$$)
<head>
<title>$_[3]</title>
- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
+ <meta http-equiv="Content-Type" content="text/html; charset=$charset">
<link rel="stylesheet" type="text/css" href="$_[1]gcov.css">
</head>
@@ -4120,17 +4355,6 @@ END_OF_HTML
}
-# format_rate(found, hit)
-#
-# Return formatted percent string for coverage rate.
-#
-
-sub format_rate($$)
-{
- return $_[0] == 0 ? "-" : sprintf("%.1f", $_[1] * 100 / $_[0])." %";
-}
-
-
sub max($$)
{
my ($a, $b) = @_;
@@ -4172,6 +4396,7 @@ sub write_header(*$$$$$$$$$$)
my @row_right;
my $num_rows;
my $i;
+ my $esc_trunc_name = escape_html($trunc_name);
$base_name = basename($rel_filename);
@@ -4187,12 +4412,14 @@ sub write_header(*$$$$$$$$$$)
# Directory overview
$base_dir = get_relative_base_path($rel_filename);
$view = "<a href=\"$base_dir"."index.$html_ext\">".
- "$overview_title</a> - $trunc_name";
+ "$overview_title</a> - $esc_trunc_name";
}
elsif ($type == $HDR_SOURCE || $type == $HDR_FUNC)
{
# File view
my $dir_name = dirname($rel_filename);
+ my $esc_base_name = escape_html($base_name);
+ my $esc_dir_name = escape_html($dir_name);
$base_dir = get_relative_base_path($dir_name);
if ($frames)
@@ -4202,21 +4429,25 @@ sub write_header(*$$$$$$$$$$)
$view = "<a href=\"$base_dir"."index.$html_ext\" ".
"target=\"_parent\">$overview_title</a> - ".
"<a href=\"index.$html_ext\" target=\"_parent\">".
- "$dir_name</a> - $base_name";
+ "$esc_dir_name</a> - $esc_base_name";
}
else
{
$view = "<a href=\"$base_dir"."index.$html_ext\">".
"$overview_title</a> - ".
"<a href=\"index.$html_ext\">".
- "$dir_name</a> - $base_name";
+ "$esc_dir_name</a> - $esc_base_name";
}
# Add function suffix
if ($func_coverage) {
$view .= "<span style=\"font-size: 80%;\">";
if ($type == $HDR_SOURCE) {
- $view .= " (source / <a href=\"$base_name.func.$html_ext\">functions</a>)";
+ if ($sort) {
+ $view .= " (source / <a href=\"$base_name.func-sort-c.$html_ext\">functions</a>)";
+ } else {
+ $view .= " (source / <a href=\"$base_name.func.$html_ext\">functions</a>)";
+ }
} elsif ($type == $HDR_FUNC) {
$view .= " (<a href=\"$base_name.gcov.$html_ext\">source</a> / functions)";
}
@@ -4303,7 +4534,7 @@ END_OF_HTML
# Line coverage
$style = $rate_name[classify_rate($lines_found, $lines_hit,
$med_limit, $hi_limit)];
- $rate = format_rate($lines_found, $lines_hit);
+ $rate = rate($lines_hit, $lines_found, " %");
push(@row_right, [[undef, "headerItem", "Lines:"],
[undef, "headerCovTableEntry", $lines_hit],
[undef, "headerCovTableEntry", $lines_found],
@@ -4313,7 +4544,7 @@ END_OF_HTML
if ($func_coverage) {
$style = $rate_name[classify_rate($fn_found, $fn_hit,
$fn_med_limit, $fn_hi_limit)];
- $rate = format_rate($fn_found, $fn_hit);
+ $rate = rate($fn_hit, $fn_found, " %");
push(@row_right, [[undef, "headerItem", "Functions:"],
[undef, "headerCovTableEntry", $fn_hit],
[undef, "headerCovTableEntry", $fn_found],
@@ -4324,7 +4555,7 @@ END_OF_HTML
if ($br_coverage) {
$style = $rate_name[classify_rate($br_found, $br_hit,
$br_med_limit, $br_hi_limit)];
- $rate = format_rate($br_found, $br_hit);
+ $rate = rate($br_hit, $br_found, " %");
push(@row_right, [[undef, "headerItem", "Branches:"],
[undef, "headerCovTableEntry", $br_hit],
[undef, "headerCovTableEntry", $br_found],
@@ -4795,6 +5026,7 @@ sub br_ivec_get($$)
# Retrieve data from vector
$block = vec($vec, $offset + $BR_BLOCK, $BR_VEC_WIDTH);
+ $block = -1 if ($block == $BR_VEC_MAX);
$branch = vec($vec, $offset + $BR_BRANCH, $BR_VEC_WIDTH);
$taken = vec($vec, $offset + $BR_TAKEN, $BR_VEC_WIDTH);
@@ -4820,10 +5052,12 @@ sub br_ivec_push($$$$)
my $i;
$vec = "" if (!defined($vec));
+ $block = $BR_VEC_MAX if $block < 0;
# Check if branch already exists in vector
for ($i = 0; $i < $num; $i++) {
my ($v_block, $v_branch, $v_taken) = br_ivec_get($vec, $i);
+ $v_block = $BR_VEC_MAX if $v_block < 0;
next if ($v_block != $block || $v_branch != $branch);
@@ -4958,19 +5192,43 @@ sub write_source($$$$$$$)
my $sumbrcount = $_[6];
my $datafunc = get_hash_reverse($funcdata);
my $add_anchor;
+ my @file;
if ($_[2])
{
%count_data = %{$_[2]};
}
- open(SOURCE_HANDLE, "<".$source_filename)
- or die("ERROR: cannot open $source_filename for reading!\n");
+ if (!open(SOURCE_HANDLE, "<", $source_filename)) {
+ my @lines;
+ my $last_line = 0;
+
+ if (!$ignore[$ERROR_SOURCE]) {
+ die("ERROR: cannot read $source_filename\n");
+ }
+
+ # Continue without source file
+ warn("WARNING: cannot read $source_filename!\n");
+
+ @lines = sort( { $a <=> $b } keys(%count_data));
+ if (@lines) {
+ $last_line = $lines[scalar(@lines) - 1];
+ }
+ return ( ":" ) if ($last_line < 1);
+
+ # Simulate gcov behavior
+ for ($line_number = 1; $line_number <= $last_line;
+ $line_number++) {
+ push(@file, "/* EOF */");
+ }
+ } else {
+ @file = <SOURCE_HANDLE>;
+ }
write_source_prolog(*HTML_HANDLE);
-
- for ($line_number = 1; <SOURCE_HANDLE> ; $line_number++)
- {
+ $line_number = 0;
+ foreach (@file) {
+ $line_number++;
chomp($_);
# Also remove CR from line-end
@@ -5055,8 +5313,51 @@ sub funcview_get_sorted($$$)
if ($type == 0) {
return sort(keys(%{$funcdata}));
}
- return sort({$sumfncdata->{$b} <=> $sumfncdata->{$a}}
- keys(%{$sumfncdata}));
+ return sort({
+ $sumfncdata->{$b} == $sumfncdata->{$a} ?
+ $a cmp $b : $sumfncdata->{$a} <=> $sumfncdata->{$b}
+ } keys(%{$sumfncdata}));
+}
+
+sub demangle_list($)
+{
+ my ($list) = @_;
+ my $tmpfile;
+ my $handle;
+ my %demangle;
+ my %versions;
+
+ # Write function names to file
+ ($handle, $tmpfile) = tempfile();
+ die("ERROR: could not create temporary file") if (!defined($tmpfile));
+ print($handle join("\n", @$list));
+ close($handle);
+
+ # Build translation hash from c++filt output
+ open($handle, "-|", "c++filt < $tmpfile") or
+ die("ERROR: could not run c++filt: $!\n");
+ foreach my $func (@$list) {
+ my $translated = <$handle>;
+ my $version;
+
+ last if (!defined($translated));
+ chomp($translated);
+
+ $version = ++$versions{$translated};
+ $translated .= ".$version" if ($version > 1);
+ $demangle{$func} = $translated;
+ }
+ close($handle);
+
+ if (scalar(keys(%demangle)) != scalar(@$list)) {
+ die("ERROR: c++filt output not as expected (".
+ scalar(keys(%demangle))." vs ".scalar(@$list).") lines\n");
+ }
+
+ unlink($tmpfile) or
+ warn("WARNING: could not remove temporary file $tmpfile: $!\n");
+
+ return \%demangle;
}
#
@@ -5086,6 +5387,7 @@ sub write_function_table(*$$$$$$$$$$)
my $func;
my $func_code;
my $count_code;
+ my $demangle;
# Get HTML code for headings
$func_code = funcview_get_func_code($name, $base, $type);
@@ -5100,7 +5402,12 @@ sub write_function_table(*$$$$$$$$$$)
</tr>
END_OF_HTML
;
-
+
+ # Get demangle translation hash
+ if ($demangle_cpp) {
+ $demangle = demangle_list([ sort(keys(%{$funcdata})) ]);
+ }
+
# Get a sorted table
foreach $func (funcview_get_sorted($funcdata, $sumfncdata, $type)) {
if (!defined($funcdata->{$func}))
@@ -5113,12 +5420,10 @@ END_OF_HTML
my $count = $sumfncdata->{$name};
my $countstyle;
- # Demangle C++ function names if requested
- if ($demangle_cpp) {
- $name = `c++filt "$name"`;
- chomp($name);
- }
- # Escape any remaining special characters
+ # Replace function name with demangled version if available
+ $name = $demangle->{$name} if (exists($demangle->{$name}));
+
+ # Escape special characters
$name = escape_html($name);
if ($startline < 1) {
$startline = 1;
@@ -5412,22 +5717,25 @@ sub remove_unused_descriptions()
#
-# apply_prefix(filename, prefix)
+# apply_prefix(filename, PREFIXES)
#
-# If FILENAME begins with PREFIX, remove PREFIX from FILENAME and return
-# resulting string, otherwise return FILENAME.
+# If FILENAME begins with PREFIX from PREFIXES, remove PREFIX from FILENAME
+# and return resulting string, otherwise return FILENAME.
#
-sub apply_prefix($$)
+sub apply_prefix($@)
{
- my $filename = $_[0];
- my $prefix = $_[1];
+ my $filename = shift;
+ my @dir_prefix = @_;
- if (defined($prefix) && ($prefix ne ""))
+ if (@dir_prefix)
{
- if ($filename =~ /^\Q$prefix\E\/(.*)$/)
+ foreach my $prefix (@dir_prefix)
{
- return substr($filename, length($prefix) + 1);
+ if ($prefix ne "" && $filename =~ /^\Q$prefix\E\/(.*)$/)
+ {
+ return substr($filename, length($prefix) + 1);
+ }
}
}
@@ -5455,12 +5763,12 @@ sub system_no_output($@)
local *OLD_STDOUT;
# Save old stdout and stderr handles
- ($mode & 1) && open(OLD_STDOUT, ">>&STDOUT");
- ($mode & 2) && open(OLD_STDERR, ">>&STDERR");
+ ($mode & 1) && open(OLD_STDOUT, ">>&", "STDOUT");
+ ($mode & 2) && open(OLD_STDERR, ">>&", "STDERR");
# Redirect to /dev/null
- ($mode & 1) && open(STDOUT, ">/dev/null");
- ($mode & 2) && open(STDERR, ">/dev/null");
+ ($mode & 1) && open(STDOUT, ">", "/dev/null");
+ ($mode & 2) && open(STDERR, ">", "/dev/null");
system(@_);
$result = $?;
@@ -5470,8 +5778,8 @@ sub system_no_output($@)
($mode & 2) && close(STDERR);
# Restore old handles
- ($mode & 1) && open(STDOUT, ">>&OLD_STDOUT");
- ($mode & 2) && open(STDERR, ">>&OLD_STDERR");
+ ($mode & 1) && open(STDOUT, ">>&", "OLD_STDOUT");
+ ($mode & 2) && open(STDERR, ">>&", "OLD_STDERR");
return $result;
}
@@ -5492,7 +5800,7 @@ sub read_config($)
my $value;
local *HANDLE;
- if (!open(HANDLE, "<$filename"))
+ if (!open(HANDLE, "<", $filename))
{
warn("WARNING: cannot read configuration file $filename\n");
return undef;
@@ -5531,8 +5839,8 @@ sub read_config($)
# key_string => var_ref
#
# where KEY_STRING is a keyword and VAR_REF is a reference to an associated
-# variable. If the global configuration hash CONFIG contains a value for
-# keyword KEY_STRING, VAR_REF will be assigned the value for that keyword.
+# variable. If the global configuration hashes CONFIG or OPT_RC contain a value
+# for keyword KEY_STRING, VAR_REF will be assigned the value for that keyword.
#
sub apply_config($)
@@ -5541,8 +5849,9 @@ sub apply_config($)
foreach (keys(%{$ref}))
{
- if (defined($config->{$_}))
- {
+ if (defined($opt_rc{$_})) {
+ ${$ref->{$_}} = $opt_rc{$_};
+ } elsif (defined($config->{$_})) {
${$ref->{$_}} = $config->{$_};
}
}
@@ -5565,7 +5874,7 @@ sub get_html_prolog($)
{
local *HANDLE;
- open(HANDLE, "<".$filename)
+ open(HANDLE, "<", $filename)
or die("ERROR: cannot open html prolog $filename!\n");
while (<HANDLE>)
{
@@ -5581,7 +5890,7 @@ sub get_html_prolog($)
<html lang="en">
<head>
- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
+ <meta http-equiv="Content-Type" content="text/html; charset=$charset">
<title>\@pagetitle\@</title>
<link rel="stylesheet" type="text/css" href="\@basedir\@gcov.css">
</head>
@@ -5611,7 +5920,7 @@ sub get_html_epilog($)
{
local *HANDLE;
- open(HANDLE, "<".$filename)
+ open(HANDLE, "<", $filename)
or die("ERROR: cannot open html epilog $filename!\n");
while (<HANDLE>)
{
@@ -5646,3 +5955,96 @@ sub die_handler($)
die("$tool_name: $msg");
}
+
+#
+# parse_ignore_errors(@ignore_errors)
+#
+# Parse user input about which errors to ignore.
+#
+
+sub parse_ignore_errors(@)
+{
+ my (@ignore_errors) = @_;
+ my @items;
+ my $item;
+
+ return if (!@ignore_errors);
+
+ foreach $item (@ignore_errors) {
+ $item =~ s/\s//g;
+ if ($item =~ /,/) {
+ # Split and add comma-separated parameters
+ push(@items, split(/,/, $item));
+ } else {
+ # Add single parameter
+ push(@items, $item);
+ }
+ }
+ foreach $item (@items) {
+ my $item_id = $ERROR_ID{lc($item)};
+
+ if (!defined($item_id)) {
+ die("ERROR: unknown argument for --ignore-errors: ".
+ "$item\n");
+ }
+ $ignore[$item_id] = 1;
+ }
+}
+
+#
+# parse_dir_prefix(@dir_prefix)
+#
+# Parse user input about the prefix list
+#
+
+sub parse_dir_prefix(@)
+{
+ my (@opt_dir_prefix) = @_;
+ my $item;
+
+ return if (!@opt_dir_prefix);
+
+ foreach $item (@opt_dir_prefix) {
+ if ($item =~ /,/) {
+ # Split and add comma-separated parameters
+ push(@dir_prefix, split(/,/, $item));
+ } else {
+ # Add single parameter
+ push(@dir_prefix, $item);
+ }
+ }
+}
+
+#
+# rate(hit, found[, suffix, precision, width])
+#
+# Return the coverage rate [0..100] for HIT and FOUND values. 0 is only
+# returned when HIT is 0. 100 is only returned when HIT equals FOUND.
+# PRECISION specifies the precision of the result. SUFFIX defines a
+# string that is appended to the result if FOUND is non-zero. Spaces
+# are added to the start of the resulting string until it is at least WIDTH
+# characters wide.
+#
+
+sub rate($$;$$$)
+{
+ my ($hit, $found, $suffix, $precision, $width) = @_;
+ my $rate;
+
+ # Assign defaults if necessary
+ $precision = $default_precision if (!defined($precision));
+ $suffix = "" if (!defined($suffix));
+ $width = 0 if (!defined($width));
+
+ return sprintf("%*s", $width, "-") if (!defined($found) || $found == 0);
+ $rate = sprintf("%.*f", $precision, $hit * 100 / $found);
+
+ # Adjust rates if necessary
+ if ($rate == 0 && $hit > 0) {
+ $rate = sprintf("%.*f", $precision, 1 / 10 ** $precision);
+ } elsif ($rate == 100 && $hit != $found) {
+ $rate = sprintf("%.*f", $precision, 100 - 1 / 10 ** $precision);
+ }
+
+ return sprintf("%*s", $width, $rate.$suffix);
+}
diff --git a/3rdParty/LCov/geninfo b/3rdParty/LCov/geninfo
index dcb1a67..7c4e6cc 100755
--- a/3rdParty/LCov/geninfo
+++ b/3rdParty/LCov/geninfo
@@ -1,6 +1,6 @@
#!/usr/bin/perl -w
#
-# Copyright (c) International Business Machines Corp., 2002,2010
+# Copyright (c) International Business Machines Corp., 2002,2012
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -52,17 +52,23 @@
use strict;
use File::Basename;
use File::Spec::Functions qw /abs2rel catdir file_name_is_absolute splitdir
- splitpath/;
+ splitpath catpath/;
use Getopt::Long;
use Digest::MD5 qw(md5_base64);
-
+use Cwd qw/abs_path/;
+if( $^O eq "msys" )
+{
+ require File::Spec::Win32;
+}
# Constants
-our $lcov_version = 'LCOV version 1.9';
+our $tool_dir = abs_path(dirname($0));
+our $lcov_version = "LCOV version 1.12";
our $lcov_url = "http://ltp.sourceforge.net/coverage/lcov.php";
our $gcov_tool = "gcov";
our $tool_name = basename($0);
+our $GCOV_VERSION_4_7_0 = 0x40700;
our $GCOV_VERSION_3_4_0 = 0x30400;
our $GCOV_VERSION_3_3_0 = 0x30300;
our $GCNO_FUNCTION_TAG = 0x01000000;
@@ -70,15 +76,68 @@ our $GCNO_LINES_TAG = 0x01450000;
our $GCNO_FILE_MAGIC = 0x67636e6f;
our $BBG_FILE_MAGIC = 0x67626267;
-our $COMPAT_HAMMER = "hammer";
-
+# Error classes which users may specify to ignore during processing
our $ERROR_GCOV = 0;
our $ERROR_SOURCE = 1;
our $ERROR_GRAPH = 2;
+our %ERROR_ID = (
+ "gcov" => $ERROR_GCOV,
+ "source" => $ERROR_SOURCE,
+ "graph" => $ERROR_GRAPH,
+);
our $EXCL_START = "LCOV_EXCL_START";
our $EXCL_STOP = "LCOV_EXCL_STOP";
-our $EXCL_LINE = "LCOV_EXCL_LINE";
+
+# Marker to exclude branch coverage but keep function and line coveage
+our $EXCL_BR_START = "LCOV_EXCL_BR_START";
+our $EXCL_BR_STOP = "LCOV_EXCL_BR_STOP";
+
+# Compatibility mode values
+our $COMPAT_VALUE_OFF = 0;
+our $COMPAT_VALUE_ON = 1;
+our $COMPAT_VALUE_AUTO = 2;
+
+# Compatibility mode value names
+our %COMPAT_NAME_TO_VALUE = (
+ "off" => $COMPAT_VALUE_OFF,
+ "on" => $COMPAT_VALUE_ON,
+ "auto" => $COMPAT_VALUE_AUTO,
+);
+
+# Compatiblity modes
+our $COMPAT_MODE_LIBTOOL = 1 << 0;
+our $COMPAT_MODE_HAMMER = 1 << 1;
+our $COMPAT_MODE_SPLIT_CRC = 1 << 2;
+
+# Compatibility mode names
+our %COMPAT_NAME_TO_MODE = (
+ "libtool" => $COMPAT_MODE_LIBTOOL,
+ "hammer" => $COMPAT_MODE_HAMMER,
+ "split_crc" => $COMPAT_MODE_SPLIT_CRC,
+ "android_4_4_0" => $COMPAT_MODE_SPLIT_CRC,
+);
+
+# Map modes to names
+our %COMPAT_MODE_TO_NAME = (
+ $COMPAT_MODE_LIBTOOL => "libtool",
+ $COMPAT_MODE_HAMMER => "hammer",
+ $COMPAT_MODE_SPLIT_CRC => "split_crc",
+);
+
+# Compatibility mode default values
+our %COMPAT_MODE_DEFAULTS = (
+ $COMPAT_MODE_LIBTOOL => $COMPAT_VALUE_ON,
+ $COMPAT_MODE_HAMMER => $COMPAT_VALUE_AUTO,
+ $COMPAT_MODE_SPLIT_CRC => $COMPAT_VALUE_AUTO,
+);
+
+# Compatibility mode auto-detection routines
+sub compat_hammer_autodetect();
+our %COMPAT_MODE_AUTO = (
+ $COMPAT_MODE_HAMMER => \&compat_hammer_autodetect,
+ $COMPAT_MODE_SPLIT_CRC => 1, # will be done later
+);
our $BR_LINE = 0;
our $BR_BLOCK = 1;
@@ -86,8 +145,9 @@ our $BR_BRANCH = 2;
our $BR_TAKEN = 3;
our $BR_VEC_ENTRIES = 4;
our $BR_VEC_WIDTH = 32;
+our $BR_VEC_MAX = vec(pack('b*', 1 x $BR_VEC_WIDTH), 0, $BR_VEC_WIDTH);
-our $UNNAMED_BLOCK = 9999;
+our $UNNAMED_BLOCK = -1;
# Prototypes
sub print_usage(*);
@@ -112,8 +172,9 @@ sub warn_handler($);
sub die_handler($);
sub graph_error($$);
sub graph_expect($);
-sub graph_read(*$;$);
+sub graph_read(*$;$$);
sub graph_skip(*$;$);
+sub uniq(@);
sub sort_uniq(@);
sub sort_uniq_lex(@);
sub graph_cleanup($);
@@ -123,18 +184,19 @@ sub graph_add_order($$$);
sub read_bb_word(*;$);
sub read_bb_value(*;$);
sub read_bb_string(*$);
-sub read_bb($$);
+sub read_bb($);
sub read_bbg_word(*;$);
sub read_bbg_value(*;$);
sub read_bbg_string(*);
-sub read_bbg_lines_record(*$$$$$$);
-sub read_bbg($$);
-sub read_gcno_word(*;$);
-sub read_gcno_value(*$;$);
+sub read_bbg_lines_record(*$$$$$);
+sub read_bbg($);
+sub read_gcno_word(*;$$);
+sub read_gcno_value(*$;$$);
sub read_gcno_string(*$);
-sub read_gcno_lines_record(*$$$$$$$);
+sub read_gcno_lines_record(*$$$$$$);
+sub determine_gcno_split_crc($$$);
sub read_gcno_function_record(*$$$$);
-sub read_gcno($$);
+sub read_gcno($);
sub get_gcov_capabilities();
sub get_overall_line($$$$);
sub print_overall_rate($$$$$$$$$);
@@ -142,10 +204,17 @@ sub br_gvec_len($);
sub br_gvec_get($$);
sub debug($);
sub int_handler();
+sub parse_ignore_errors(@);
+sub is_external($);
+sub compat_name($);
+sub parse_compat_modes($);
+sub is_compat($);
+sub is_compat_auto($);
# Global variables
our $gcov_version;
+our $gcov_version_string;
our $graph_file_extension;
our $data_file_extension;
our @data_directory;
@@ -158,12 +227,13 @@ our $version;
our $follow;
our $checksum;
our $no_checksum;
-our $compat_libtool;
-our $no_compat_libtool;
+our $opt_compat_libtool;
+our $opt_no_compat_libtool;
+our $rc_adjust_src_path;# Regexp specifying parts to remove from source path
+our $adjust_src_pattern;
+our $adjust_src_replace;
our $adjust_testname;
our $config; # Configuration file contents
-our $compatibility; # Compatibility version flag - used to indicate
- # non-standard GCOV data format versions
our @ignore_errors; # List of errors to ignore (parameter)
our @ignore; # List of errors to ignore (array)
our $initial;
@@ -171,9 +241,23 @@ our $no_recursion = 0;
our $maxdepth;
our $no_markers = 0;
our $opt_derive_func_data = 0;
+our $opt_external = 1;
+our $opt_no_external;
our $debug = 0;
our $gcov_caps;
our @gcov_options;
+our @internal_dirs;
+our $opt_config_file;
+our $opt_gcov_all_blocks = 1;
+our $opt_compat;
+our %opt_rc;
+our %compat_value;
+our $gcno_split_crc;
+our $func_coverage = 1;
+our $br_coverage = 0;
+our $rc_auto_base = 1;
+our $excl_line = "LCOV_EXCL_LINE";
+our $excl_br_line = "LCOV_EXCL_BR_LINE";
our $cwd = `pwd`;
chomp($cwd);
@@ -188,14 +272,32 @@ $SIG{"INT"} = \&int_handler;
$SIG{__WARN__} = \&warn_handler;
$SIG{__DIE__} = \&die_handler;
-# Prettify version string
-$lcov_version =~ s/\$\s*Revision\s*:?\s*(\S+)\s*\$/$1/;
+# Set LC_ALL so that gcov output will be in a unified format
+$ENV{"LC_ALL"} = "C";
-# Set LANG so that gcov output will be in a unified format
-$ENV{"LANG"} = "C";
+# Check command line for a configuration file name
+Getopt::Long::Configure("pass_through", "no_auto_abbrev");
+GetOptions("config-file=s" => \$opt_config_file,
+ "rc=s%" => \%opt_rc);
+Getopt::Long::Configure("default");
+
+{
+ # Remove spaces around rc options
+ my %new_opt_rc;
+
+ while (my ($key, $value) = each(%opt_rc)) {
+ $key =~ s/^\s+|\s+$//g;
+ $value =~ s/^\s+|\s+$//g;
+
+ $new_opt_rc{$key} = $value;
+ }
+ %opt_rc = %new_opt_rc;
+}
# Read configuration file if available
-if (defined($ENV{"HOME"}) && (-r $ENV{"HOME"}."/.lcovrc"))
+if (defined($opt_config_file)) {
+ $config = read_config($opt_config_file);
+} elsif (defined($ENV{"HOME"}) && (-r $ENV{"HOME"}."/.lcovrc"))
{
$config = read_config($ENV{"HOME"}."/.lcovrc");
}
@@ -204,15 +306,25 @@ elsif (-r "/etc/lcovrc")
$config = read_config("/etc/lcovrc");
}
-if ($config)
+if ($config || %opt_rc)
{
- # Copy configuration file values to variables
+ # Copy configuration file and --rc values to variables
apply_config({
"geninfo_gcov_tool" => \$gcov_tool,
"geninfo_adjust_testname" => \$adjust_testname,
"geninfo_checksum" => \$checksum,
"geninfo_no_checksum" => \$no_checksum, # deprecated
- "geninfo_compat_libtool" => \$compat_libtool});
+ "geninfo_compat_libtool" => \$opt_compat_libtool,
+ "geninfo_external" => \$opt_external,
+ "geninfo_gcov_all_blocks" => \$opt_gcov_all_blocks,
+ "geninfo_compat" => \$opt_compat,
+ "geninfo_adjust_src_path" => \$rc_adjust_src_path,
+ "geninfo_auto_base" => \$rc_auto_base,
+ "lcov_function_coverage" => \$func_coverage,
+ "lcov_branch_coverage" => \$br_coverage,
+ "lcov_excl_line" => \$excl_line,
+ "lcov_excl_br_line" => \$excl_br_line,
+ });
# Merge options
if (defined($no_checksum))
@@ -220,6 +332,34 @@ if ($config)
$checksum = ($no_checksum ? 0 : 1);
$no_checksum = undef;
}
+
+ # Check regexp
+ if (defined($rc_adjust_src_path)) {
+ my ($pattern, $replace) = split(/\s*=>\s*/,
+ $rc_adjust_src_path);
+ local $SIG{__DIE__};
+ eval '$adjust_src_pattern = qr>'.$pattern.'>;';
+ if (!defined($adjust_src_pattern)) {
+ my $msg = $@;
+
+ chomp($msg);
+ $msg =~ s/at \(eval.*$//;
+ warn("WARNING: invalid pattern in ".
+ "geninfo_adjust_src_path: $msg\n");
+ } elsif (!defined($replace)) {
+ # If no replacement is specified, simply remove pattern
+ $adjust_src_replace = "";
+ } else {
+ $adjust_src_replace = $replace;
+ }
+ }
+ for my $regexp (($excl_line, $excl_br_line)) {
+ eval 'qr/'.$regexp.'/';
+ my $error = $@;
+ chomp($error);
+ $error =~ s/at \(eval.*$//;
+ die("ERROR: invalid exclude pattern: $error") if $error;
+ }
}
# Parse command line options
@@ -232,8 +372,8 @@ if (!GetOptions("test-name|t=s" => \$test_name,
"quiet|q" => \$quiet,
"help|h|?" => \$help,
"follow|f" => \$follow,
- "compat-libtool" => \$compat_libtool,
- "no-compat-libtool" => \$no_compat_libtool,
+ "compat-libtool" => \$opt_compat_libtool,
+ "no-compat-libtool" => \$opt_no_compat_libtool,
"gcov-tool=s" => \$gcov_tool,
"ignore-errors=s" => \@ignore_errors,
"initial|i" => \$initial,
@@ -241,6 +381,11 @@ if (!GetOptions("test-name|t=s" => \$test_name,
"no-markers" => \$no_markers,
"derive-func-data" => \$opt_derive_func_data,
"debug" => \$debug,
+ "external" => \$opt_external,
+ "no-external" => \$opt_no_external,
+ "compat=s" => \$opt_compat,
+ "config-file=s" => \$opt_config_file,
+ "rc=s%" => \%opt_rc,
))
{
print(STDERR "Use $tool_name --help to get usage information\n");
@@ -255,10 +400,15 @@ else
$no_checksum = undef;
}
- if (defined($no_compat_libtool))
+ if (defined($opt_no_compat_libtool))
{
- $compat_libtool = ($no_compat_libtool ? 0 : 1);
- $no_compat_libtool = undef;
+ $opt_compat_libtool = ($opt_no_compat_libtool ? 0 : 1);
+ $opt_no_compat_libtool = undef;
+ }
+
+ if (defined($opt_no_external)) {
+ $opt_external = 0;
+ $opt_no_external = undef;
}
}
@@ -278,6 +428,30 @@ if ($version)
exit(0);
}
+# Check gcov tool
+if (system_no_output(3, $gcov_tool, "--help") == -1)
+{
+ die("ERROR: need tool $gcov_tool!\n");
+}
+
+($gcov_version, $gcov_version_string) = get_gcov_version();
+
+# Determine gcov options
+$gcov_caps = get_gcov_capabilities();
+push(@gcov_options, "-b") if ($gcov_caps->{'branch-probabilities'} &&
+ ($br_coverage || $func_coverage));
+push(@gcov_options, "-c") if ($gcov_caps->{'branch-counts'} &&
+ $br_coverage);
+push(@gcov_options, "-a") if ($gcov_caps->{'all-blocks'} &&
+ $opt_gcov_all_blocks && $br_coverage);
+push(@gcov_options, "-p") if ($gcov_caps->{'preserve-paths'});
+
+# Determine compatibility modes
+parse_compat_modes($opt_compat);
+
+# Determine which errors the user wants us to ignore
+parse_ignore_errors(@ignore_errors);
+
# Make sure test names only contain valid characters
if ($test_name =~ s/\W/_/g)
{
@@ -319,17 +493,6 @@ else
$checksum = 0;
}
-# Determine libtool compatibility mode
-if (defined($compat_libtool))
-{
- $compat_libtool = ($compat_libtool? 1 : 0);
-}
-else
-{
- # Default is on
- $compat_libtool = 1;
-}
-
# Determine max depth for recursion
if ($no_recursion)
{
@@ -358,42 +521,9 @@ else
}
}
-if (@ignore_errors)
-{
- my @expanded;
- my $error;
-
- # Expand comma-separated entries
- foreach (@ignore_errors) {
- if (/,/)
- {
- push(@expanded, split(",", $_));
- }
- else
- {
- push(@expanded, $_);
- }
- }
-
- foreach (@expanded)
- {
- /^gcov$/ && do { $ignore[$ERROR_GCOV] = 1; next; } ;
- /^source$/ && do { $ignore[$ERROR_SOURCE] = 1; next; };
- /^graph$/ && do { $ignore[$ERROR_GRAPH] = 1; next; };
- die("ERROR: unknown argument for --ignore-errors: $_\n");
- }
-}
-
-if (system_no_output(3, $gcov_tool, "--help") == -1)
-{
- die("ERROR: need tool $gcov_tool!\n");
-}
-
-$gcov_version = get_gcov_version();
-
if ($gcov_version < $GCOV_VERSION_3_4_0)
{
- if (defined($compatibility) && $compatibility eq $COMPAT_HAMMER)
+ if (is_compat($COMPAT_MODE_HAMMER))
{
$data_file_extension = ".da";
$graph_file_extension = ".bbg";
@@ -410,20 +540,13 @@ else
$graph_file_extension = ".gcno";
}
-# Determine gcov options
-$gcov_caps = get_gcov_capabilities();
-push(@gcov_options, "-b") if ($gcov_caps->{'branch-probabilities'});
-push(@gcov_options, "-c") if ($gcov_caps->{'branch-counts'});
-push(@gcov_options, "-a") if ($gcov_caps->{'all-blocks'});
-push(@gcov_options, "-p") if ($gcov_caps->{'preserve-paths'});
-
# Check output filename
if (defined($output_filename) && ($output_filename ne "-"))
{
# Initially create output filename, data is appended
# for each data file processed
local *DUMMY_HANDLE;
- open(DUMMY_HANDLE, ">$output_filename")
+ open(DUMMY_HANDLE, ">", $output_filename)
or die("ERROR: cannot create $output_filename!\n");
close(DUMMY_HANDLE);
@@ -435,12 +558,18 @@ if (defined($output_filename) && ($output_filename ne "-"))
}
}
+# Build list of directories to identify external files
+foreach my $entry(@data_directory, $base_directory) {
+ next if (!defined($entry));
+ push(@internal_dirs, solve_relative_path($cwd, $entry));
+}
+
# Do something
foreach my $entry (@data_directory) {
gen_info($entry);
}
-if ($initial) {
+if ($initial && $br_coverage) {
warn("Note: --initial does not generate branch coverage ".
"data\n");
}
@@ -480,9 +609,12 @@ sequentially.
--gcov-tool TOOL Specify gcov tool location
--ignore-errors ERROR Continue after ERROR (gcov, source, graph)
--no-recursion Exclude subdirectories from processing
- --function-coverage Capture function call counts
--no-markers Ignore exclusion markers in source code
--derive-func-data Generate function data from line data
+ --(no-)external Include (ignore) data for external files
+ --config-file FILENAME Specify configuration file location
+ --rc SETTING=VALUE Override configuration file setting
+ --compat MODE=on|off|auto Set compat MODE (libtool, hammer, split_crc)
For more information see: $lcov_url
END_OF_USAGE
@@ -578,10 +710,13 @@ sub gen_info($)
{
info("Scanning $directory for $ext files ...\n");
- @file_list = `find "$directory" $maxdepth $follow -name \\*$ext -type f 2>/dev/null`;
+ @file_list = `find "$directory" $maxdepth $follow -name \\*$ext -type f -o -name \\*$ext -type l 2>/dev/null`;
chomp(@file_list);
- @file_list or
- die("ERROR: no $ext files found in $directory!\n");
+ if (!@file_list) {
+ warn("WARNING: no $ext files found in $directory - ".
+ "skipping!\n");
+ return;
+ }
$prefix = get_common_prefix(1, @file_list);
info("Found %d %s files in %s\n", $#file_list+1, $type,
$directory);
@@ -604,6 +739,25 @@ sub gen_info($)
}
+#
+# derive_data(contentdata, funcdata, bbdata)
+#
+# Calculate function coverage data by combining line coverage data and the
+# list of lines belonging to a function.
+#
+# contentdata: [ instr1, count1, source1, instr2, count2, source2, ... ]
+# instr<n>: Instrumentation flag for line n
+# count<n>: Execution count for line n
+# source<n>: Source code for line n
+#
+# funcdata: [ count1, func1, count2, func2, ... ]
+# count<n>: Execution count for function number n
+# func<n>: Function name for function number n
+#
+# bbdata: function_name -> [ line1, line2, ... ]
+# line<n>: Line number belonging to the corresponding function
+#
+
sub derive_data($$$)
{
my ($contentdata, $funcdata, $bbdata) = @_;
@@ -633,6 +787,7 @@ sub derive_data($$$)
foreach $fn (keys(%{$bbdata})) {
my $line_data = $bbdata->{$fn};
my $line;
+ my $fninstr = 0;
if ($fn eq "") {
next;
@@ -640,13 +795,17 @@ sub derive_data($$$)
# Find the lowest line count for this function
$count = 0;
foreach $line (@$line_data) {
+ my $linstr = $gcov_content[ ( $line - 1 ) * 3 + 0 ];
my $lcount = $gcov_content[ ( $line - 1 ) * 3 + 1 ];
+ next if (!$linstr);
+ $fninstr = 1;
if (($lcount > 0) &&
(($count == 0) || ($lcount < $count))) {
$count = $lcount;
}
}
+ next if (!$fninstr);
$fn_count{$fn} = $count;
}
@@ -733,7 +892,6 @@ sub process_dafile($$)
my $source; # gcov source header information
my $object; # gcov object header information
my @matches; # List of absolute paths matching filename
- my @unprocessed; # List of unprocessed source code files
my $base_dir; # Base directory for current file
my @tmp_links; # Temporary links to be cleaned up
my @result;
@@ -749,11 +907,10 @@ sub process_dafile($$)
# Get directory and basename of data file
($da_dir, $da_basename) = split_filename($da_filename);
- # avoid files from .libs dirs
- if ($compat_libtool && $da_dir =~ m/(.*)\/\.libs$/) {
- $source_dir = $1;
- } else {
- $source_dir = $da_dir;
+ $source_dir = $da_dir;
+ if (is_compat($COMPAT_MODE_LIBTOOL)) {
+ # Avoid files from .libs dirs
+ $source_dir =~ s/\.libs$//;
}
if (-z $da_filename)
@@ -808,20 +965,27 @@ sub process_dafile($$)
# information about functions and their source code positions.
if ($gcov_version < $GCOV_VERSION_3_4_0)
{
- if (defined($compatibility) && $compatibility eq $COMPAT_HAMMER)
+ if (is_compat($COMPAT_MODE_HAMMER))
{
- ($instr, $graph) = read_bbg($bb_filename, $base_dir);
+ ($instr, $graph) = read_bbg($bb_filename);
}
else
{
- ($instr, $graph) = read_bb($bb_filename, $base_dir);
+ ($instr, $graph) = read_bb($bb_filename);
}
}
else
{
- ($instr, $graph) = read_gcno($bb_filename, $base_dir);
+ ($instr, $graph) = read_gcno($bb_filename);
}
+ # Try to find base directory automatically if requested by user
+ if ($rc_auto_base) {
+ $base_dir = find_base_from_graph($base_dir, $instr, $graph);
+ }
+
+ ($instr, $graph) = adjust_graph_filenames($base_dir, $instr, $graph);
+
# Set $object_dir to real location of object files. This may differ
# from $da_dir if the graph file is just a link to the "real" object
# file location.
@@ -850,6 +1014,7 @@ sub process_dafile($$)
}
# Change to directory containing data files and apply GCOV
+ debug("chdir($base_dir)\n");
chdir($base_dir);
if ($da_renamed)
@@ -905,7 +1070,7 @@ sub process_dafile($$)
else
{
# Append to output file
- open(INFO_HANDLE, ">>$output_filename")
+ open(INFO_HANDLE, ">>", $output_filename)
or die("ERROR: cannot write to ".
"$output_filename!\n");
}
@@ -913,7 +1078,7 @@ sub process_dafile($$)
else
{
# Open .info file for output
- open(INFO_HANDLE, ">$da_filename.info")
+ open(INFO_HANDLE, ">", "$da_filename.info")
or die("ERROR: cannot create $da_filename.info!\n");
}
@@ -922,23 +1087,34 @@ sub process_dafile($$)
# Traverse the list of generated .gcov files and combine them into a
# single .info file
- @unprocessed = keys(%{$instr});
foreach $gcov_file (sort(@gcov_list))
{
my $i;
my $num;
+ # Skip gcov file for gcc built-in code
+ next if ($gcov_file eq "<built-in>.gcov");
+
($source, $object) = read_gcov_header($gcov_file);
- if (defined($source))
- {
- $source = solve_relative_path($base_dir, $source);
+ if (!defined($source)) {
+ # Derive source file name from gcov file name if
+ # header format could not be parsed
+ $source = $gcov_file;
+ $source =~ s/\.gcov$//;
+ }
+
+ $source = solve_relative_path($base_dir, $source);
+
+ if (defined($adjust_src_pattern)) {
+ # Apply transformation as specified by user
+ $source =~ s/$adjust_src_pattern/$adjust_src_replace/g;
}
# gcov will happily create output even if there's no source code
# available - this interferes with checksum creation so we need
# to pull the emergency brake here.
- if (defined($source) && ! -r $source && $checksum)
+ if (! -r $source && $checksum)
{
if ($ignore[$ERROR_SOURCE])
{
@@ -949,8 +1125,7 @@ sub process_dafile($$)
die("ERROR: could not read source file $source\n");
}
- @matches = match_filename(defined($source) ? $source :
- $gcov_file, keys(%{$instr}));
+ @matches = match_filename($source, keys(%{$instr}));
# Skip files that are not mentioned in the graph file
if (!@matches)
@@ -994,13 +1169,13 @@ sub process_dafile($$)
\@matches, \@gcov_content);
}
- # Remove processed file from list
- for ($index = scalar(@unprocessed) - 1; $index >= 0; $index--)
- {
- if ($unprocessed[$index] eq $source_filename)
- {
- splice(@unprocessed, $index, 1);
- last;
+ # Skip external files if requested
+ if (!$opt_external) {
+ if (is_external($source_filename)) {
+ info(" ignoring data for external file ".
+ "$source_filename\n");
+ unlink($gcov_file);
+ next;
}
}
@@ -1090,6 +1265,7 @@ sub process_dafile($$)
my ($line, $block, $branch, $taken) =
br_gvec_get($gcov_branches, $i);
+ $block = $BR_VEC_MAX if ($block < 0);
print(INFO_HANDLE "BRDA:$line,$block,$branch,$taken\n");
$br_found++;
$br_hit++ if ($taken ne '-' && $taken > 0);
@@ -1138,16 +1314,6 @@ sub process_dafile($$)
unlink($gcov_file);
}
- # Check for files which show up in the graph file but were never
- # processed
- if (@unprocessed && @gcov_list)
- {
- foreach (@unprocessed)
- {
- warn("WARNING: no data found for $_\n");
- }
- }
-
if (!($output_filename && ($output_filename eq "-")))
{
close(INFO_HANDLE);
@@ -1168,8 +1334,40 @@ sub solve_relative_path($$)
{
my $path = $_[0];
my $dir = $_[1];
+ my $volume;
+ my $directories;
+ my $filename;
+ my @dirs; # holds path elements
my $result;
+ # Convert from Windows path to msys path
+ if( $^O eq "msys" )
+ {
+ # search for a windows drive letter at the beginning
+ ($volume, $directories, $filename) = File::Spec::Win32->splitpath( $dir );
+ if( $volume ne '' )
+ {
+ my $uppercase_volume;
+ # transform c/d\../e/f\g to Windows style c\d\..\e\f\g
+ $dir = File::Spec::Win32->canonpath( $dir );
+ # use Win32 module to retrieve path components
+ # $uppercase_volume is not used any further
+ ( $uppercase_volume, $directories, $filename ) = File::Spec::Win32->splitpath( $dir );
+ @dirs = File::Spec::Win32->splitdir( $directories );
+
+ # prepend volume, since in msys C: is always mounted to /c
+ $volume =~ s|^([a-zA-Z]+):|/\L$1\E|;
+ unshift( @dirs, $volume );
+
+ # transform to Unix style '/' path
+ $directories = File::Spec->catdir( @dirs );
+ $dir = File::Spec->catpath( '', $directories, $filename );
+ } else {
+ # eliminate '\' path separators
+ $dir = File::Spec->canonpath( $dir );
+ }
+ }
+
$result = $dir;
# Prepend path if not absolute
if ($dir =~ /^[^\/]/)
@@ -1182,6 +1380,10 @@ sub solve_relative_path($$)
# Remove .
$result =~ s/\/\.\//\//g;
+ $result =~ s/\/\.$/\//g;
+
+ # Remove trailing /
+ $result =~ s/\/$//g;
# Solve ..
while ($result =~ s/\/[^\/]+\/\.\.\//\//)
@@ -1266,7 +1468,7 @@ sub solve_ambiguous_match($$$)
{
# Compare file contents
- open(SOURCE, $filename)
+ open(SOURCE, "<", $filename)
or die("ERROR: cannot read $filename!\n");
$no_match = 0;
@@ -1336,7 +1538,7 @@ sub read_gcov_header($)
my $object;
local *INPUT;
- if (!open(INPUT, $_[0]))
+ if (!open(INPUT, "<", $_[0]))
{
if ($ignore_errors[$ERROR_GCOV])
{
@@ -1408,6 +1610,7 @@ sub br_gvec_get($$)
# Retrieve data from vector
$line = vec($vec, $offset + $BR_LINE, $BR_VEC_WIDTH);
$block = vec($vec, $offset + $BR_BLOCK, $BR_VEC_WIDTH);
+ $block = -1 if ($block == $BR_VEC_MAX);
$branch = vec($vec, $offset + $BR_BRANCH, $BR_VEC_WIDTH);
$taken = vec($vec, $offset + $BR_TAKEN, $BR_VEC_WIDTH);
@@ -1435,6 +1638,7 @@ sub br_gvec_push($$$$$)
$vec = "" if (!defined($vec));
$offset = br_gvec_len($vec) * $BR_VEC_ENTRIES;
+ $block = $BR_VEC_MAX if $block < 0;
# Encode taken value into an integer
if ($taken eq "-") {
@@ -1484,11 +1688,13 @@ sub read_gcov_file($)
my $number;
my $exclude_flag = 0;
my $exclude_line = 0;
+ my $exclude_br_flag = 0;
+ my $exclude_branch = 0;
my $last_block = $UNNAMED_BLOCK;
my $last_line = 0;
local *INPUT;
- if (!open(INPUT, $filename)) {
+ if (!open(INPUT, "<", $filename)) {
if ($ignore_errors[$ERROR_GCOV])
{
warn("WARNING: cannot read $filename!\n");
@@ -1508,11 +1714,15 @@ sub read_gcov_file($)
s/\015$//;
if (/^branch\s+(\d+)\s+taken\s+=\s+(\d+)/) {
+ next if (!$br_coverage);
next if ($exclude_line);
+ next if ($exclude_branch);
$branches = br_gvec_push($branches, $last_line,
$last_block, $1, $2);
} elsif (/^branch\s+(\d+)\s+never\s+executed/) {
+ next if (!$br_coverage);
next if ($exclude_line);
+ next if ($exclude_branch);
$branches = br_gvec_push($branches, $last_line,
$last_block, $1, '-');
}
@@ -1530,12 +1740,25 @@ sub read_gcov_file($)
} elsif (/$EXCL_START/) {
$exclude_flag = 1;
}
- if (/$EXCL_LINE/ || $exclude_flag) {
+ if (/$excl_line/ || $exclude_flag) {
$exclude_line = 1;
} else {
$exclude_line = 0;
}
}
+ # Check for exclusion markers (branch exclude)
+ if (!$no_markers) {
+ if (/$EXCL_BR_STOP/) {
+ $exclude_br_flag = 0;
+ } elsif (/$EXCL_BR_START/) {
+ $exclude_br_flag = 1;
+ }
+ if (/$excl_br_line/ || $exclude_br_flag) {
+ $exclude_branch = 1;
+ } else {
+ $exclude_branch = 0;
+ }
+ }
# Source code execution data
if (/^\t\t(.*)$/)
{
@@ -1579,16 +1802,21 @@ sub read_gcov_file($)
$last_line = $2;
$last_block = $3;
} elsif (/^branch\s+(\d+)\s+taken\s+(\d+)/) {
+ next if (!$br_coverage);
next if ($exclude_line);
+ next if ($exclude_branch);
$branches = br_gvec_push($branches, $last_line,
$last_block, $1, $2);
} elsif (/^branch\s+(\d+)\s+never\s+executed/) {
+ next if (!$br_coverage);
next if ($exclude_line);
+ next if ($exclude_branch);
$branches = br_gvec_push($branches, $last_line,
$last_block, $1, '-');
}
- elsif (/^function\s+(\S+)\s+called\s+(\d+)/)
+ elsif (/^function\s+(.+)\s+called\s+(\d+)\s+/)
{
+ next if (!$func_coverage);
if ($exclude_line) {
next;
}
@@ -1611,12 +1839,26 @@ sub read_gcov_file($)
} elsif (/$EXCL_START/) {
$exclude_flag = 1;
}
- if (/$EXCL_LINE/ || $exclude_flag) {
+ if (/$excl_line/ || $exclude_flag) {
$exclude_line = 1;
} else {
$exclude_line = 0;
}
}
+ # Check for exclusion markers (branch exclude)
+ if (!$no_markers) {
+ if (/$EXCL_BR_STOP/) {
+ $exclude_br_flag = 0;
+ } elsif (/$EXCL_BR_START/) {
+ $exclude_br_flag = 1;
+ }
+ if (/$excl_br_line/ || $exclude_br_flag) {
+ $exclude_branch = 1;
+ } else {
+ $exclude_branch = 0;
+ }
+ }
+
# <exec count>:<line number>:<source code>
if ($line eq "0")
{
@@ -1636,7 +1878,7 @@ sub read_gcov_file($)
push(@result, 0);
} else {
# Check for zero count
- if ($count eq "#####") {
+ if ($count =~ /^[#=]/) {
$count = 0;
}
push(@result, 1);
@@ -1649,7 +1891,7 @@ sub read_gcov_file($)
}
close(INPUT);
- if ($exclude_flag) {
+ if ($exclude_flag || $exclude_br_flag) {
warn("WARNING: unterminated exclusion section in $filename\n");
}
return(\@result, $branches, \@functions);
@@ -1667,12 +1909,29 @@ sub get_gcov_version()
local *HANDLE;
my $version_string;
my $result;
+ my $pipe_next_line;
- open(GCOV_PIPE, "$gcov_tool -v |")
+ open(GCOV_PIPE, "-|", "$gcov_tool --version")
or die("ERROR: cannot retrieve gcov version!\n");
$version_string = <GCOV_PIPE>;
+ # LLVM gcov keeps version information on the second line.
+ # For example, gcov --version yields:
+ # LLVM (http://llvm.org/):
+ # LLVM version 3.4svn
+
+ $pipe_next_line = <GCOV_PIPE>;
+ # In case version information is on first line.
+ # For example, with Xcode 7.0 gcov --version yields:
+ # Apple LLVM 7.0.0 (clang-700.0.65)
+
+ $version_string = $pipe_next_line if ($pipe_next_line && $version_string =~ /LLVM/);
close(GCOV_PIPE);
+ # Remove version information in parenthesis to cope with the following:
+ # - gcov (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)
+ # - gcov (crosstool-NG 1.18.0) 4.7.2
+ $version_string =~ s/\([^\)]*\)//g;
+
$result = 0;
if ($version_string =~ /(\d+)\.(\d+)(\.(\d+))?/)
{
@@ -1687,13 +1946,22 @@ sub get_gcov_version()
$result = $1 << 16 | $2 << 8;
}
}
- if ($version_string =~ /suse/i && $result == 0x30303 ||
- $version_string =~ /mandrake/i && $result == 0x30302)
+ if ($version_string =~ /LLVM/)
{
- info("Using compatibility mode for GCC 3.3 (hammer)\n");
- $compatibility = $COMPAT_HAMMER;
+ # Map LLVM versions to the version of GCC gcov which
+ # they emulate
+ if ($result >= 0x030400)
+ {
+ info("Found LLVM gcov version 3.4, which emulates gcov version 4.2\n");
+ $result = 0x040200;
+ }
+ else
+ {
+ warn("This version of LLVM's gcov is unknown. Assuming it emulates GCC gcov version 4.2.\n");
+ $result = 0x040200;
+ }
}
- return $result;
+ return ($result, $version_string);
}
@@ -1756,13 +2024,14 @@ sub system_no_output($@)
local *OLD_STDOUT;
# Save old stdout and stderr handles
- ($mode & 1) && open(OLD_STDOUT, ">>&STDOUT");
- ($mode & 2) && open(OLD_STDERR, ">>&STDERR");
+ ($mode & 1) && open(OLD_STDOUT, ">>&", "STDOUT");
+ ($mode & 2) && open(OLD_STDERR, ">>&", "STDERR");
# Redirect to /dev/null
- ($mode & 1) && open(STDOUT, ">/dev/null");
- ($mode & 2) && open(STDERR, ">/dev/null");
+ ($mode & 1) && open(STDOUT, ">", "/dev/null");
+ ($mode & 2) && open(STDERR, ">", "/dev/null");
+ debug("system(".join(' ', @_).")\n");
system(@_);
$result = $?;
@@ -1771,8 +2040,8 @@ sub system_no_output($@)
($mode & 2) && close(STDERR);
# Restore old handles
- ($mode & 1) && open(STDOUT, ">>&OLD_STDOUT");
- ($mode & 2) && open(STDERR, ">>&OLD_STDERR");
+ ($mode & 1) && open(STDOUT, ">>&", "OLD_STDOUT");
+ ($mode & 2) && open(STDERR, ">>&", "OLD_STDERR");
return $result;
}
@@ -1793,7 +2062,7 @@ sub read_config($)
my $value;
local *HANDLE;
- if (!open(HANDLE, "<$filename"))
+ if (!open(HANDLE, "<", $filename))
{
warn("WARNING: cannot read configuration file $filename\n");
return undef;
@@ -1832,8 +2101,8 @@ sub read_config($)
# key_string => var_ref
#
# where KEY_STRING is a keyword and VAR_REF is a reference to an associated
-# variable. If the global configuration hash CONFIG contains a value for
-# keyword KEY_STRING, VAR_REF will be assigned the value for that keyword.
+# variable. If the global configuration hashes CONFIG or OPT_RC contain a value
+# for keyword KEY_STRING, VAR_REF will be assigned the value for that keyword.
#
sub apply_config($)
@@ -1842,8 +2111,9 @@ sub apply_config($)
foreach (keys(%{$ref}))
{
- if (defined($config->{$_}))
- {
+ if (defined($opt_rc{$_})) {
+ ${$ref->{$_}} = $opt_rc{$_};
+ } elsif (defined($config->{$_})) {
${$ref->{$_}} = $config->{$_};
}
}
@@ -1865,7 +2135,7 @@ sub get_exclusion_data($)
my $flag = 0;
local *HANDLE;
- if (!open(HANDLE, "<$filename")) {
+ if (!open(HANDLE, "<", $filename)) {
warn("WARNING: could not open $filename\n");
return undef;
}
@@ -1875,7 +2145,7 @@ sub get_exclusion_data($)
} elsif (/$EXCL_START/) {
$flag = 1;
}
- if (/$EXCL_LINE/ || $flag) {
+ if (/$excl_line/ || $flag) {
$list{$.} = 1;
}
}
@@ -1989,12 +2259,7 @@ sub apply_exclusion_data($$)
}
# Store modified list
- if (scalar(@new_data) > 0) {
- $instr->{$filename} = \@new_data;
- } else {
- # All of this file was excluded
- delete($instr->{$filename});
- }
+ $instr->{$filename} = \@new_data;
}
return ($instr, $graph);
@@ -2023,11 +2288,10 @@ sub process_graphfile($$)
# Get directory and basename of data file
($graph_dir, $graph_basename) = split_filename($graph_filename);
- # avoid files from .libs dirs
- if ($compat_libtool && $graph_dir =~ m/(.*)\/\.libs$/) {
- $source_dir = $1;
- } else {
- $source_dir = $graph_dir;
+ $source_dir = $graph_dir;
+ if (is_compat($COMPAT_MODE_LIBTOOL)) {
+ # Avoid files from .libs dirs
+ $source_dir =~ s/\.libs$//;
}
# Construct base_dir for current file
@@ -2040,22 +2304,36 @@ sub process_graphfile($$)
$base_dir = $source_dir;
}
+ # Ignore empty graph file (e.g. source file with no statement)
+ if (-z $graph_filename)
+ {
+ warn("WARNING: empty $graph_filename (skipped)\n");
+ return;
+ }
+
if ($gcov_version < $GCOV_VERSION_3_4_0)
{
- if (defined($compatibility) && $compatibility eq $COMPAT_HAMMER)
+ if (is_compat($COMPAT_MODE_HAMMER))
{
- ($instr, $graph) = read_bbg($graph_filename, $base_dir);
+ ($instr, $graph) = read_bbg($graph_filename);
}
else
{
- ($instr, $graph) = read_bb($graph_filename, $base_dir);
+ ($instr, $graph) = read_bb($graph_filename);
}
}
else
{
- ($instr, $graph) = read_gcno($graph_filename, $base_dir);
+ ($instr, $graph) = read_gcno($graph_filename);
}
+ # Try to find base directory automatically if requested by user
+ if ($rc_auto_base) {
+ $base_dir = find_base_from_graph($base_dir, $instr, $graph);
+ }
+
+ ($instr, $graph) = adjust_graph_filenames($base_dir, $instr, $graph);
+
if (!$no_markers) {
# Apply exclusion marker data to graph file data
($instr, $graph) = apply_exclusion_data($instr, $graph);
@@ -2071,7 +2349,7 @@ sub process_graphfile($$)
else
{
# Append to output file
- open(INFO_HANDLE, ">>$output_filename")
+ open(INFO_HANDLE, ">>", $output_filename)
or die("ERROR: cannot write to ".
"$output_filename!\n");
}
@@ -2079,7 +2357,7 @@ sub process_graphfile($$)
else
{
# Open .info file for output
- open(INFO_HANDLE, ">$graph_filename.info")
+ open(INFO_HANDLE, ">", "$graph_filename.info")
or die("ERROR: cannot create $graph_filename.info!\n");
}
@@ -2091,9 +2369,18 @@ sub process_graphfile($$)
my $line;
my $linedata;
+ # Skip external files if requested
+ if (!$opt_external) {
+ if (is_external($filename)) {
+ info(" ignoring data for external file ".
+ "$filename\n");
+ next;
+ }
+ }
+
print(INFO_HANDLE "SF:$filename\n");
- if (defined($funcdata)) {
+ if (defined($funcdata) && $func_coverage) {
my @functions = sort {$funcdata->{$a}->[0] <=>
$funcdata->{$b}->[0]}
keys(%{$funcdata});
@@ -2194,26 +2481,36 @@ sub graph_expect($)
}
#
-# graph_read(handle, bytes[, description])
+# graph_read(handle, bytes[, description, peek])
#
# Read and return the specified number of bytes from handle. Return undef
-# if the number of bytes could not be read.
+# if the number of bytes could not be read. If PEEK is non-zero, reset
+# file position after read.
#
-sub graph_read(*$;$)
+sub graph_read(*$;$$)
{
- my ($handle, $length, $desc) = @_;
+ my ($handle, $length, $desc, $peek) = @_;
my $data;
my $result;
+ my $pos;
graph_expect($desc);
+ if ($peek) {
+ $pos = tell($handle);
+ if ($pos == -1) {
+ warn("Could not get current file position: $!\n");
+ return undef;
+ }
+ }
$result = read($handle, $data, $length);
if ($debug) {
+ my $op = $peek ? "peek" : "read";
my $ascii = "";
my $hex = "";
my $i;
- print(STDERR "DEBUG: read($length)=$result: ");
+ print(STDERR "DEBUG: $op($length)=$result: ");
for ($i = 0; $i < length($data); $i++) {
my $c = substr($data, $i, 1);;
my $n = ord($c);
@@ -2228,6 +2525,12 @@ sub graph_read(*$;$)
print(STDERR "$hex |$ascii|");
print(STDERR "\n");
}
+ if ($peek) {
+ if (!seek($handle, $pos, 0)) {
+ warn("Could not set file position: $!\n");
+ return undef;
+ }
+ }
if ($result != $length) {
return undef;
}
@@ -2252,6 +2555,27 @@ sub graph_skip(*$;$)
}
#
+# uniq(list)
+#
+# Return list without duplicate entries.
+#
+
+sub uniq(@)
+{
+ my (@list) = @_;
+ my @new_list;
+ my %known;
+
+ foreach my $item (@list) {
+ next if ($known{$item});
+ $known{$item} = 1;
+ push(@new_list, $item);
+ }
+
+ return @new_list;
+}
+
+#
# sort_uniq(list)
#
# Return list in numerically ascending order and without duplicate entries.
@@ -2286,6 +2610,133 @@ sub sort_uniq_lex(@)
}
#
+# parent_dir(dir)
+#
+# Return parent directory for DIR. DIR must not contain relative path
+# components.
+#
+
+sub parent_dir($)
+{
+ my ($dir) = @_;
+ my ($v, $d, $f) = splitpath($dir, 1);
+ my @dirs = splitdir($d);
+
+ pop(@dirs);
+
+ return catpath($v, catdir(@dirs), $f);
+}
+
+#
+# find_base_from_graph(base_dir, instr, graph)
+#
+# Try to determine the base directory of the graph file specified by INSTR
+# and GRAPH. The base directory is the base for all relative filenames in
+# the graph file. It is defined by the current working directory at time
+# of compiling the source file.
+#
+# This function implements a heuristic which relies on the following
+# assumptions:
+# - all files used for compilation are still present at their location
+# - the base directory is either BASE_DIR or one of its parent directories
+# - files by the same name are not present in multiple parent directories
+#
+
+sub find_base_from_graph($$$)
+{
+ my ($base_dir, $instr, $graph) = @_;
+ my $old_base;
+ my $best_miss;
+ my $best_base;
+ my %rel_files;
+
+ # Determine list of relative paths
+ foreach my $filename (keys(%{$instr}), keys(%{$graph})) {
+ next if (file_name_is_absolute($filename));
+
+ $rel_files{$filename} = 1;
+ }
+
+ # Early exit if there are no relative paths
+ return $base_dir if (!%rel_files);
+
+ do {
+ my $miss = 0;
+
+ foreach my $filename (keys(%rel_files)) {
+ if (!-e solve_relative_path($base_dir, $filename)) {
+ $miss++;
+ }
+ }
+
+ debug("base_dir=$base_dir miss=$miss\n");
+
+ # Exit if we find an exact match with no misses
+ return $base_dir if ($miss == 0);
+
+ # No exact match, aim for the one with the least source file
+ # misses
+ if (!defined($best_base) || $miss < $best_miss) {
+ $best_base = $base_dir;
+ $best_miss = $miss;
+ }
+
+ # Repeat until there's no more parent directory
+ $old_base = $base_dir;
+ $base_dir = parent_dir($base_dir);
+ } while ($old_base ne $base_dir);
+
+ return $best_base;
+}
+
+#
+# adjust_graph_filenames(base_dir, instr, graph)
+#
+# Make relative paths in INSTR and GRAPH absolute and apply
+# geninfo_adjust_src_path setting to graph file data.
+#
+
+sub adjust_graph_filenames($$$)
+{
+ my ($base_dir, $instr, $graph) = @_;
+
+ foreach my $filename (keys(%{$instr})) {
+ my $old_filename = $filename;
+
+ # Convert to absolute canonical form
+ $filename = solve_relative_path($base_dir, $filename);
+
+ # Apply adjustment
+ if (defined($adjust_src_pattern)) {
+ $filename =~ s/$adjust_src_pattern/$adjust_src_replace/g;
+ }
+
+ if ($filename ne $old_filename) {
+ $instr->{$filename} = delete($instr->{$old_filename});
+ }
+ }
+
+ foreach my $filename (keys(%{$graph})) {
+ my $old_filename = $filename;
+
+ # Make absolute
+ # Convert to absolute canonical form
+ $filename = solve_relative_path($base_dir, $filename);
+
+ # Apply adjustment
+ if (defined($adjust_src_pattern)) {
+ $filename =~ s/$adjust_src_pattern/$adjust_src_replace/g;
+ }
+
+ if ($filename ne $old_filename) {
+ $graph->{$filename} = delete($graph->{$old_filename});
+ }
+ }
+
+ return ($instr, $graph);
+}
+
+#
# graph_cleanup(graph)
#
# Remove entries for functions with no lines. Remove duplicate line numbers.
@@ -2310,7 +2761,7 @@ sub graph_cleanup($)
next;
}
# Normalize list
- $per_file->{$function} = [ sort_uniq(@$lines) ];
+ $per_file->{$function} = [ uniq(@$lines) ];
}
if (scalar(keys(%{$per_file})) == 0) {
# Remove empty file
@@ -2454,6 +2905,7 @@ sub graph_add_order($$$)
push(@$list, $filename);
$fileorder->{$function} = $list;
}
+
#
# read_bb_word(handle[, description])
#
@@ -2513,7 +2965,7 @@ sub read_bb_string(*$)
}
#
-# read_bb(filename, base_dir)
+# read_bb(filename)
#
# Read the contents of the specified .bb file and return (instr, graph), where:
#
@@ -2524,14 +2976,12 @@ sub read_bb_string(*$)
# file_data : function name -> line_data
# line_data : [ line1, line2, ... ]
#
-# Relative filenames are converted to absolute form using base_dir as
-# base directory. See the gcov info pages of gcc 2.95 for a description of
-# the .bb file format.
+# See the gcov info pages of gcc 2.95 for a description of the .bb file format.
#
-sub read_bb($$)
+sub read_bb($)
{
- my ($bb_filename, $base) = @_;
+ my ($bb_filename) = @_;
my $minus_one = 0x80000001;
my $minus_two = 0x80000002;
my $value;
@@ -2543,7 +2993,7 @@ sub read_bb($$)
my $graph;
local *HANDLE;
- open(HANDLE, "<$bb_filename") or goto open_error;
+ open(HANDLE, "<", $bb_filename) or goto open_error;
binmode(HANDLE);
while (!eof(HANDLE)) {
$value = read_bb_value(*HANDLE, "data word");
@@ -2553,10 +3003,6 @@ sub read_bb($$)
graph_expect("filename");
$filename = read_bb_string(*HANDLE, $minus_one);
goto incomplete if (!defined($filename));
- if ($filename ne "") {
- $filename = solve_relative_path($base,
- $filename);
- }
} elsif ($value == $minus_two) {
# Function name
graph_expect("function name");
@@ -2647,16 +3093,15 @@ sub read_bbg_string(*)
#
# read_bbg_lines_record(handle, bbg_filename, bb, fileorder, filename,
-# function, base)
+# function)
#
# Read a bbg format lines record from handle and add the relevant data to
# bb and fileorder. Return filename on success, undef on error.
#
-sub read_bbg_lines_record(*$$$$$$)
+sub read_bbg_lines_record(*$$$$$)
{
- my ($handle, $bbg_filename, $bb, $fileorder, $filename, $function,
- $base) = @_;
+ my ($handle, $bbg_filename, $bb, $fileorder, $filename, $function) = @_;
my $string;
my $lineno;
@@ -2676,7 +3121,10 @@ sub read_bbg_lines_record(*$$$$$$)
if ($string eq "") {
return $filename;
}
- $filename = solve_relative_path($base, $string);
+ $filename = $string;
+ if (!exists($bb->{$function}->{$filename})) {
+ $bb->{$function}->{$filename} = [];
+ }
next;
}
# Got an actual line number
@@ -2691,21 +3139,20 @@ sub read_bbg_lines_record(*$$$$$$)
}
#
-# read_bbg(filename, base_dir)
+# read_bbg(filename)
#
# Read the contents of the specified .bbg file and return the following mapping:
# graph: filename -> file_data
# file_data: function name -> line_data
# line_data: [ line1, line2, ... ]
#
-# Relative filenames are converted to absolute form using base_dir as
-# base directory. See the gcov-io.h file in the SLES 9 gcc 3.3.3 source code
-# for a description of the .bbg format.
+# See the gcov-io.h file in the SLES 9 gcc 3.3.3 source code for a description
+# of the .bbg format.
#
-sub read_bbg($$)
+sub read_bbg($)
{
- my ($bbg_filename, $base) = @_;
+ my ($bbg_filename) = @_;
my $file_magic = 0x67626267;
my $tag_function = 0x01000000;
my $tag_lines = 0x01450000;
@@ -2720,7 +3167,7 @@ sub read_bbg($$)
my $graph;
local *HANDLE;
- open(HANDLE, "<$bbg_filename") or goto open_error;
+ open(HANDLE, "<", $bbg_filename) or goto open_error;
binmode(HANDLE);
# Read magic
$word = read_bbg_value(*HANDLE, "file magic");
@@ -2752,7 +3199,7 @@ sub read_bbg($$)
# Read lines record
$filename = read_bbg_lines_record(HANDLE, $bbg_filename,
$bb, $fileorder, $filename,
- $function, $base);
+ $function);
goto incomplete if (!defined($filename));
} else {
# Skip record contents
@@ -2778,31 +3225,33 @@ magic_error:
}
#
-# read_gcno_word(handle[, description])
+# read_gcno_word(handle[, description, peek])
#
# Read and return a word in .gcno format.
#
-sub read_gcno_word(*;$)
+sub read_gcno_word(*;$$)
{
- my ($handle, $desc) = @_;
+ my ($handle, $desc, $peek) = @_;
- return graph_read($handle, 4, $desc);
+ return graph_read($handle, 4, $desc, $peek);
}
#
-# read_gcno_value(handle, big_endian[, description])
+# read_gcno_value(handle, big_endian[, description, peek])
#
# Read a word in .gcno format from handle and return its integer value
-# according to the specified endianness.
+# according to the specified endianness. If PEEK is non-zero, reset file
+# position after read.
#
-sub read_gcno_value(*$;$)
+sub read_gcno_value(*$;$$)
{
- my ($handle, $big_endian, $desc) = @_;
+ my ($handle, $big_endian, $desc, $peek) = @_;
my $word;
+ my $pos;
- $word = read_gcno_word($handle, $desc);
+ $word = read_gcno_word($handle, $desc, $peek);
return undef if (!defined($word));
if ($big_endian) {
return unpack("N", $word);
@@ -2841,16 +3290,16 @@ sub read_gcno_string(*$)
#
# read_gcno_lines_record(handle, gcno_filename, bb, fileorder, filename,
-# function, base, big_endian)
+# function, big_endian)
#
# Read a gcno format lines record from handle and add the relevant data to
# bb and fileorder. Return filename on success, undef on error.
#
-sub read_gcno_lines_record(*$$$$$$$)
+sub read_gcno_lines_record(*$$$$$$)
{
my ($handle, $gcno_filename, $bb, $fileorder, $filename, $function,
- $base, $big_endian) = @_;
+ $big_endian) = @_;
my $string;
my $lineno;
@@ -2870,7 +3319,10 @@ sub read_gcno_lines_record(*$$$$$$$)
if ($string eq "") {
return $filename;
}
- $filename = solve_relative_path($base, $string);
+ $filename = $string;
+ if (!exists($bb->{$function}->{$filename})) {
+ $bb->{$function}->{$filename} = [];
+ }
next;
}
# Got an actual line number
@@ -2886,7 +3338,52 @@ sub read_gcno_lines_record(*$$$$$$$)
}
#
-# read_gcno_function_record(handle, graph, base, big_endian)
+# determine_gcno_split_crc(handle, big_endian, rec_length)
+#
+# Determine if HANDLE refers to a .gcno file with a split checksum function
+# record format. Return non-zero in case of split checksum format, zero
+# otherwise, undef in case of read error.
+#
+
+sub determine_gcno_split_crc($$$)
+{
+ my ($handle, $big_endian, $rec_length) = @_;
+ my $strlen;
+ my $overlong_string;
+
+ return 1 if ($gcov_version >= $GCOV_VERSION_4_7_0);
+ return 1 if (is_compat($COMPAT_MODE_SPLIT_CRC));
+
+ # Heuristic:
+ # Decide format based on contents of next word in record:
+ # - pre-gcc 4.7
+ # This is the function name length / 4 which should be
+ # less than the remaining record length
+ # - gcc 4.7
+ # This is a checksum, likely with high-order bits set,
+ # resulting in a large number
+ $strlen = read_gcno_value($handle, $big_endian, undef, 1);
+ return undef if (!defined($strlen));
+ $overlong_string = 1 if ($strlen * 4 >= $rec_length - 12);
+
+ if ($overlong_string) {
+ if (is_compat_auto($COMPAT_MODE_SPLIT_CRC)) {
+ info("Auto-detected compatibility mode for split ".
+ "checksum .gcno file format\n");
+
+ return 1;
+ } else {
+ # Sanity check
+ warn("Found overlong string in function record: ".
+ "try '--compat split_crc'\n");
+ }
+ }
+
+ return 0;
+}
+
+#
+# read_gcno_function_record(handle, graph, big_endian, rec_length)
#
# Read a gcno format function record from handle and add the relevant data
# to graph. Return (filename, function) on success, undef on error.
@@ -2894,7 +3391,7 @@ sub read_gcno_lines_record(*$$$$$$$)
sub read_gcno_function_record(*$$$$)
{
- my ($handle, $bb, $fileorder, $base, $big_endian) = @_;
+ my ($handle, $bb, $fileorder, $big_endian, $rec_length) = @_;
my $filename;
my $function;
my $lineno;
@@ -2903,6 +3400,14 @@ sub read_gcno_function_record(*$$$$)
graph_expect("function record");
# Skip ident and checksum
graph_skip($handle, 8, "function ident and checksum") or return undef;
+ # Determine if this is a function record with split checksums
+ if (!defined($gcno_split_crc)) {
+ $gcno_split_crc = determine_gcno_split_crc($handle, $big_endian,
+ $rec_length);
+ return undef if (!defined($gcno_split_crc));
+ }
+ # Skip cfg checksum word in case of split checksums
+ graph_skip($handle, 4, "function cfg checksum") if ($gcno_split_crc);
# Read function name
graph_expect("function name");
$function = read_gcno_string($handle, $big_endian);
@@ -2911,7 +3416,6 @@ sub read_gcno_function_record(*$$$$)
graph_expect("filename");
$filename = read_gcno_string($handle, $big_endian);
return undef if (!defined($filename));
- $filename = solve_relative_path($base, $filename);
# Read first line number
$lineno = read_gcno_value($handle, $big_endian, "initial line number");
return undef if (!defined($lineno));
@@ -2923,7 +3427,7 @@ sub read_gcno_function_record(*$$$$)
}
#
-# read_gcno(filename, base_dir)
+# read_gcno(filename)
#
# Read the contents of the specified .gcno file and return the following
# mapping:
@@ -2931,14 +3435,13 @@ sub read_gcno_function_record(*$$$$)
# file_data: function name -> line_data
# line_data: [ line1, line2, ... ]
#
-# Relative filenames are converted to absolute form using base_dir as
-# base directory. See the gcov-io.h file in the gcc 3.3 source code
-# for a description of the .gcno format.
+# See the gcov-io.h file in the gcc 3.3 source code for a description of
+# the .gcno format.
#
-sub read_gcno($$)
+sub read_gcno($)
{
- my ($gcno_filename, $base) = @_;
+ my ($gcno_filename) = @_;
my $file_magic = 0x67636e6f;
my $tag_function = 0x01000000;
my $tag_lines = 0x01450000;
@@ -2952,9 +3455,11 @@ sub read_gcno($$)
my $fileorder = {};
my $instr;
my $graph;
+ my $filelength;
local *HANDLE;
- open(HANDLE, "<$gcno_filename") or goto open_error;
+ open(HANDLE, "<", $gcno_filename) or goto open_error;
+ $filelength = (stat(HANDLE))[7];
binmode(HANDLE);
# Read magic
$word = read_gcno_word(*HANDLE, "file magic");
@@ -2986,16 +3491,25 @@ sub read_gcno($$)
$next_pos = tell(HANDLE);
goto tell_error if ($next_pos == -1);
$next_pos += $length;
+ # Catch garbage at the end of a gcno file
+ if ($next_pos > $filelength) {
+ debug("Overlong record: file_length=$filelength ".
+ "rec_length=$length\n");
+ warn("WARNING: $gcno_filename: Overlong record at end ".
+ "of file!\n");
+ last;
+ }
# Process record
if ($tag == $tag_function) {
($filename, $function) = read_gcno_function_record(
- *HANDLE, $bb, $fileorder, $base, $big_endian);
+ *HANDLE, $bb, $fileorder, $big_endian,
+ $length);
goto incomplete if (!defined($function));
} elsif ($tag == $tag_lines) {
# Read lines record
$filename = read_gcno_lines_record(*HANDLE,
$gcno_filename, $bb, $fileorder,
- $filename, $function, $base,
+ $filename, $function,
$big_endian);
goto incomplete if (!defined($filename));
} else {
@@ -3053,16 +3567,236 @@ sub get_gcov_capabilities()
{
my $help = `$gcov_tool --help`;
my %capabilities;
+ my %short_option_translations = (
+ 'a' => 'all-blocks',
+ 'b' => 'branch-probabilities',
+ 'c' => 'branch-counts',
+ 'f' => 'function-summaries',
+ 'h' => 'help',
+ 'l' => 'long-file-names',
+ 'n' => 'no-output',
+ 'o' => 'object-directory',
+ 'p' => 'preserve-paths',
+ 'u' => 'unconditional-branches',
+ 'v' => 'version',
+ );
foreach (split(/\n/, $help)) {
- next if (!/--(\S+)/);
- next if ($1 eq 'help');
- next if ($1 eq 'version');
- next if ($1 eq 'object-directory');
+ my $capability;
+ if (/--(\S+)/) {
+ $capability = $1;
+ } else {
+ # If the line provides a short option, translate it.
+ next if (!/^\s*-(\S)\s/);
+ $capability = $short_option_translations{$1};
+ next if not defined($capability);
+ }
+ next if ($capability eq 'help');
+ next if ($capability eq 'version');
+ next if ($capability eq 'object-directory');
- $capabilities{$1} = 1;
- debug("gcov has capability '$1'\n");
+ $capabilities{$capability} = 1;
+ debug("gcov has capability '$capability'\n");
}
return \%capabilities;
}
+
+#
+# parse_ignore_errors(@ignore_errors)
+#
+# Parse user input about which errors to ignore.
+#
+
+sub parse_ignore_errors(@)
+{
+ my (@ignore_errors) = @_;
+ my @items;
+ my $item;
+
+ return if (!@ignore_errors);
+
+ foreach $item (@ignore_errors) {
+ $item =~ s/\s//g;
+ if ($item =~ /,/) {
+ # Split and add comma-separated parameters
+ push(@items, split(/,/, $item));
+ } else {
+ # Add single parameter
+ push(@items, $item);
+ }
+ }
+ foreach $item (@items) {
+ my $item_id = $ERROR_ID{lc($item)};
+
+ if (!defined($item_id)) {
+ die("ERROR: unknown argument for --ignore-errors: ".
+ "$item\n");
+ }
+ $ignore[$item_id] = 1;
+ }
+}
+
+#
+# is_external(filename)
+#
+# Determine if a file is located outside of the specified data directories.
+#
+
+sub is_external($)
+{
+ my ($filename) = @_;
+ my $dir;
+
+ foreach $dir (@internal_dirs) {
+ return 0 if ($filename =~ /^\Q$dir\/\E/);
+ }
+ return 1;
+}
+
+#
+# compat_name(mode)
+#
+# Return the name of compatibility mode MODE.
+#
+
+sub compat_name($)
+{
+ my ($mode) = @_;
+ my $name = $COMPAT_MODE_TO_NAME{$mode};
+
+ return $name if (defined($name));
+
+ return "<unknown>";
+}
+
+#
+# parse_compat_modes(opt)
+#
+# Determine compatibility mode settings.
+#
+
+sub parse_compat_modes($)
+{
+ my ($opt) = @_;
+ my @opt_list;
+ my %specified;
+
+ # Initialize with defaults
+ %compat_value = %COMPAT_MODE_DEFAULTS;
+
+ # Add old style specifications
+ if (defined($opt_compat_libtool)) {
+ $compat_value{$COMPAT_MODE_LIBTOOL} =
+ $opt_compat_libtool ? $COMPAT_VALUE_ON
+ : $COMPAT_VALUE_OFF;
+ }
+
+ # Parse settings
+ if (defined($opt)) {
+ @opt_list = split(/\s*,\s*/, $opt);
+ }
+ foreach my $directive (@opt_list) {
+ my ($mode, $value);
+
+ # Either
+ # mode=off|on|auto or
+ # mode (implies on)
+ if ($directive !~ /^(\w+)=(\w+)$/ &&
+ $directive !~ /^(\w+)$/) {
+ die("ERROR: Unknown compatibility mode specification: ".
+ "$directive!\n");
+ }
+ # Determine mode
+ $mode = $COMPAT_NAME_TO_MODE{lc($1)};
+ if (!defined($mode)) {
+ die("ERROR: Unknown compatibility mode '$1'!\n");
+ }
+ $specified{$mode} = 1;
+ # Determine value
+ if (defined($2)) {
+ $value = $COMPAT_NAME_TO_VALUE{lc($2)};
+ if (!defined($value)) {
+ die("ERROR: Unknown compatibility mode ".
+ "value '$2'!\n");
+ }
+ } else {
+ $value = $COMPAT_VALUE_ON;
+ }
+ $compat_value{$mode} = $value;
+ }
+ # Perform auto-detection
+ foreach my $mode (sort(keys(%compat_value))) {
+ my $value = $compat_value{$mode};
+ my $is_autodetect = "";
+ my $name = compat_name($mode);
+
+ if ($value == $COMPAT_VALUE_AUTO) {
+ my $autodetect = $COMPAT_MODE_AUTO{$mode};
+
+ if (!defined($autodetect)) {
+ die("ERROR: No auto-detection for ".
+ "mode '$name' available!\n");
+ }
+
+ if (ref($autodetect) eq "CODE") {
+ $value = &$autodetect();
+ $compat_value{$mode} = $value;
+ $is_autodetect = " (auto-detected)";
+ }
+ }
+
+ if ($specified{$mode}) {
+ if ($value == $COMPAT_VALUE_ON) {
+ info("Enabling compatibility mode ".
+ "'$name'$is_autodetect\n");
+ } elsif ($value == $COMPAT_VALUE_OFF) {
+ info("Disabling compatibility mode ".
+ "'$name'$is_autodetect\n");
+ } else {
+ info("Using delayed auto-detection for ".
+ "compatibility mode ".
+ "'$name'\n");
+ }
+ }
+ }
+}
+
+sub compat_hammer_autodetect()
+{
+ if ($gcov_version_string =~ /suse/i && $gcov_version == 0x30303 ||
+ $gcov_version_string =~ /mandrake/i && $gcov_version == 0x30302)
+ {
+ info("Auto-detected compatibility mode for GCC 3.3 (hammer)\n");
+ return $COMPAT_VALUE_ON;
+ }
+ return $COMPAT_VALUE_OFF;
+}
+
+#
+# is_compat(mode)
+#
+# Return non-zero if compatibility mode MODE is enabled.
+#
+
+sub is_compat($)
+{
+ my ($mode) = @_;
+
+ return 1 if ($compat_value{$mode} == $COMPAT_VALUE_ON);
+ return 0;
+}
+
+#
+# is_compat_auto(mode)
+#
+# Return non-zero if compatibility mode MODE is set to auto-detect.
+#
+
+sub is_compat_auto($)
+{
+ my ($mode) = @_;
+
+ return 1 if ($compat_value{$mode} == $COMPAT_VALUE_AUTO);
+ return 0;
+}
diff --git a/3rdParty/LCov/genpng b/3rdParty/LCov/genpng
index 7fe9dfe..55e013e 100755
--- a/3rdParty/LCov/genpng
+++ b/3rdParty/LCov/genpng
@@ -22,7 +22,7 @@
# This script creates an overview PNG image of a source code file by
# representing each source code character by a single pixel.
#
-# Note that the PERL module GD.pm is required for this script to work.
+# Note that the Perl module GD.pm is required for this script to work.
# It may be obtained from http://www.cpan.org
#
# History:
@@ -32,10 +32,12 @@
use strict;
use File::Basename;
use Getopt::Long;
+use Cwd qw/abs_path/;
# Constants
-our $lcov_version = 'LCOV version 1.9';
+our $tool_dir = abs_path(dirname($0));
+our $lcov_version = "LCOV version 1.12";
our $lcov_url = "http://ltp.sourceforge.net/coverage/lcov.php";
our $tool_name = basename($0);
@@ -53,9 +55,6 @@ sub genpng_die_handler($);
# Code entry point
#
-# Prettify version string
-$lcov_version =~ s/\$\s*Revision\s*:?\s*(\S+)\s*\$/$1/;
-
# Check whether required module GD.pm is installed
if (check_and_load_module("GD"))
{
@@ -182,7 +181,7 @@ sub genpng_process_file($$$$)
local *HANDLE;
my @source;
- open(HANDLE, "<$filename")
+ open(HANDLE, "<", $filename)
or die("ERROR: cannot open $filename!\n");
# Check for .gcov filename extension
@@ -238,7 +237,7 @@ sub gen_png($$$@)
my $overview_width = shift(@_); # Imagewidth for image
my $tab_size = shift(@_); # Replacement string for tab signs
my @source = @_; # Source code as passed via argument 2
- my $height = scalar(@source); # Height as define by source size
+ my $height; # Height as define by source size
my $overview; # Source code overview image data
my $col_plain_back; # Color for overview background
my $col_plain_text; # Color for uninstrumented text
@@ -261,6 +260,11 @@ sub gen_png($$$@)
my $replacement; # Replacement string for tabulator chars
local *PNG_HANDLE; # Handle for output PNG file
+ # Handle empty source files
+ if (!@source) {
+ @source = ( "" );
+ }
+ $height = scalar(@source);
# Create image
$overview = new GD::Image($overview_width, $height)
or die("ERROR: cannot allocate overview image!\n");
@@ -362,7 +366,7 @@ sub gen_png($$$@)
}
# Write PNG file
- open (PNG_HANDLE, ">$filename")
+ open (PNG_HANDLE, ">", $filename)
or die("ERROR: cannot write png file $filename!\n");
binmode(*PNG_HANDLE);
print(PNG_HANDLE $overview->png());
diff --git a/3rdParty/LCov/lcov b/3rdParty/LCov/lcov
index 4e392ff..7760ba2 100755
--- a/3rdParty/LCov/lcov
+++ b/3rdParty/LCov/lcov
@@ -1,6 +1,6 @@
#!/usr/bin/perl -w
#
-# Copyright (c) International Business Machines Corp., 2002,2010
+# Copyright (c) International Business Machines Corp., 2002,2012
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -71,7 +71,8 @@ use Cwd qw /abs_path getcwd/;
# Global constants
-our $lcov_version = 'LCOV version 1.9';
+our $tool_dir = abs_path(dirname($0));
+our $lcov_version = "LCOV version 1.12";
our $lcov_url = "http://ltp.sourceforge.net/coverage/lcov.php";
our $tool_name = basename($0);
@@ -93,6 +94,7 @@ our $BR_BRANCH = 1;
our $BR_TAKEN = 2;
our $BR_VEC_ENTRIES = 3;
our $BR_VEC_WIDTH = 32;
+our $BR_VEC_MAX = vec(pack('b*', 1 x $BR_VEC_WIDTH), 0, $BR_VEC_WIDTH);
# Branch data combination types
our $BR_SUB = 0;
@@ -139,6 +141,8 @@ sub lcov_geninfo(@);
sub create_package($$$;$);
sub get_func_found_and_hit($);
sub br_ivec_get($$);
+sub summary();
+sub rate($$;$$$);
# Global variables & initialization
our @directory; # Specifies where to get coverage data from
@@ -168,7 +172,7 @@ our $no_checksum; # If set, don't calculate a checksum for each line
our $compat_libtool; # If set, indicates that libtool mode is to be enabled
our $no_compat_libtool; # If set, indicates that libtool mode is to be disabled
our $gcov_tool;
-our $ignore_errors;
+our @opt_ignore_errors;
our $initial;
our $no_recursion = 0;
our $to_package;
@@ -177,7 +181,6 @@ our $maxdepth;
our $no_markers;
our $config; # Configuration file contents
chomp($cwd);
-our $tool_dir = dirname($0); # Directory where genhtml tool is installed
our @temp_dirs;
our $gcov_gkv; # gcov kernel support version found on machine
our $opt_derive_func_data;
@@ -186,12 +189,20 @@ our $opt_list_full_path;
our $opt_no_list_full_path;
our $opt_list_width = 80;
our $opt_list_truncate_max = 20;
+our $opt_external;
+our $opt_no_external;
+our $opt_config_file;
+our %opt_rc;
+our @opt_summary;
+our $opt_compat;
our $ln_overall_found;
our $ln_overall_hit;
our $fn_overall_found;
our $fn_overall_hit;
our $br_overall_found;
our $br_overall_hit;
+our $func_coverage = 1;
+our $br_coverage = 0;
#
@@ -203,17 +214,29 @@ $SIG{__DIE__} = \&die_handler;
$SIG{'INT'} = \&abort_handler;
$SIG{'QUIT'} = \&abort_handler;
-# Prettify version string
-$lcov_version =~ s/\$\s*Revision\s*:?\s*(\S+)\s*\$/$1/;
+# Check command line for a configuration file name
+Getopt::Long::Configure("pass_through", "no_auto_abbrev");
+GetOptions("config-file=s" => \$opt_config_file,
+ "rc=s%" => \%opt_rc);
+Getopt::Long::Configure("default");
-# Add current working directory if $tool_dir is not already an absolute path
-if (! ($tool_dir =~ /^\/(.*)$/))
{
- $tool_dir = "$cwd/$tool_dir";
+ # Remove spaces around rc options
+ my %new_opt_rc;
+
+ while (my ($key, $value) = each(%opt_rc)) {
+ $key =~ s/^\s+|\s+$//g;
+ $value =~ s/^\s+|\s+$//g;
+
+ $new_opt_rc{$key} = $value;
+ }
+ %opt_rc = %new_opt_rc;
}
# Read configuration file if available
-if (defined($ENV{"HOME"}) && (-r $ENV{"HOME"}."/.lcovrc"))
+if (defined($opt_config_file)) {
+ $config = read_config($opt_config_file);
+} elsif (defined($ENV{"HOME"}) && (-r $ENV{"HOME"}."/.lcovrc"))
{
$config = read_config($ENV{"HOME"}."/.lcovrc");
}
@@ -222,15 +245,17 @@ elsif (-r "/etc/lcovrc")
$config = read_config("/etc/lcovrc");
}
-if ($config)
+if ($config || %opt_rc)
{
- # Copy configuration file values to variables
+ # Copy configuration file and --rc values to variables
apply_config({
"lcov_gcov_dir" => \$gcov_dir,
"lcov_tmp_dir" => \$tmp_dir,
"lcov_list_full_path" => \$opt_list_full_path,
"lcov_list_width" => \$opt_list_width,
"lcov_list_truncate_max"=> \$opt_list_truncate_max,
+ "lcov_branch_coverage" => \$br_coverage,
+ "lcov_function_coverage"=> \$func_coverage,
});
}
@@ -259,7 +284,7 @@ if (!GetOptions("directory|d|di=s" => \@directory,
"compat-libtool" => \$compat_libtool,
"no-compat-libtool" => \$no_compat_libtool,
"gcov-tool=s" => \$gcov_tool,
- "ignore-errors=s" => \$ignore_errors,
+ "ignore-errors=s" => \@opt_ignore_errors,
"initial|i" => \$initial,
"no-recursion" => \$no_recursion,
"to-package=s" => \$to_package,
@@ -269,6 +294,12 @@ if (!GetOptions("directory|d|di=s" => \@directory,
"debug" => \$opt_debug,
"list-full-path" => \$opt_list_full_path,
"no-list-full-path" => \$opt_no_list_full_path,
+ "external" => \$opt_external,
+ "no-external" => \$opt_no_external,
+ "summary=s" => \@opt_summary,
+ "compat=s" => \$opt_compat,
+ "config-file=s" => \$opt_config_file,
+ "rc=s%" => \%opt_rc,
))
{
print(STDERR "Use $tool_name --help to get usage information\n");
@@ -294,6 +325,11 @@ else
$opt_list_full_path = ($opt_no_list_full_path ? 0 : 1);
$opt_no_list_full_path = undef;
}
+
+ if (defined($opt_no_external)) {
+ $opt_external = 0;
+ $opt_no_external = undef;
+ }
}
# Check for help option
@@ -341,7 +377,7 @@ else
check_options();
# Only --extract, --remove and --diff allow unnamed parameters
-if (@ARGV && !($extract || $remove || $diff))
+if (@ARGV && !($extract || $remove || $diff || @opt_summary))
{
die("Extra parameter found: '".join(" ", @ARGV)."'\n".
"Use $tool_name --help to get usage information\n");
@@ -429,6 +465,12 @@ elsif ($diff)
$fn_overall_found, $fn_overall_hit,
$br_overall_found, $br_overall_hit) = diff();
}
+elsif (@opt_summary)
+{
+ ($ln_overall_found, $ln_overall_hit,
+ $fn_overall_found, $fn_overall_hit,
+ $br_overall_found, $br_overall_hit) = summary();
+}
temp_cleanup();
@@ -471,6 +513,7 @@ Operation:
-r, --remove FILE PATTERN Remove files matching PATTERN from FILE
-l, --list FILE List contents of tracefile FILE
--diff FILE DIFF Transform tracefile FILE according to DIFF
+ --summary FILE Show summary coverage data for tracefiles
Options:
-i, --initial Capture initial zero coverage data
@@ -493,6 +536,10 @@ Options:
--no-markers Ignore exclusion markers in source code
--derive-func-data Generate function data from line data
--list-full-path Print full path during a list operation
+ --(no-)external Include (ignore) data for external files
+ --config-file FILENAME Specify configuration file location
+ --rc SETTING=VALUE Override configuration file setting
+ --compat MODE=on|off|auto Set compat MODE (libtool, hammer, split_crc)
For more information see: $lcov_url
END_OF_USAGE
@@ -518,17 +565,18 @@ sub check_options()
$remove && $i++;
$list && $i++;
$diff && $i++;
+ @opt_summary && $i++;
if ($i == 0)
{
- die("Need one of the options -z, -c, -a, -e, -r, -l or ".
- "--diff\n".
+ die("Need one of options -z, -c, -a, -e, -r, -l, ".
+ "--diff or --summary\n".
"Use $tool_name --help to get usage information\n");
}
elsif ($i > 1)
{
- die("ERROR: only one of -z, -c, -a, -e, -r, -l or ".
- "--diff allowed!\n".
+ die("ERROR: only one of -z, -c, -a, -e, -r, -l, ".
+ "--diff or --summary allowed!\n".
"Use $tool_name --help to get usage information\n");
}
}
@@ -551,7 +599,7 @@ sub userspace_reset()
{
info("Deleting all .da files in $current_dir".
($no_recursion?"\n":" and subdirectories\n"));
- @file_list = `find "$current_dir" $maxdepth $follow -name \\*\\.da -o -name \\*\\.gcda -type f 2>/dev/null`;
+ @file_list = `find "$current_dir" $maxdepth $follow -name \\*\\.da -type f -o -name \\*\\.gcda -type f 2>/dev/null`;
chomp(@file_list);
foreach (@file_list)
{
@@ -613,7 +661,7 @@ sub kernel_reset()
} else {
die("ERROR: no reset control found in $gcov_dir\n");
}
- open(HANDLE, ">$reset_file") or
+ open(HANDLE, ">", $reset_file) or
die("ERROR: cannot write to $reset_file!\n");
print(HANDLE "0");
close(HANDLE);
@@ -635,10 +683,10 @@ sub lcov_copy_single($$)
local $/;
local *HANDLE;
- open(HANDLE, "<$from") or die("ERROR: cannot read $from: $!\n");
+ open(HANDLE, "<", $from) or die("ERROR: cannot read $from: $!\n");
$content = <HANDLE>;
close(HANDLE);
- open(HANDLE, ">$to") or die("ERROR: cannot write $from: $!\n");
+ open(HANDLE, ">", $to) or die("ERROR: cannot write $from: $!\n");
if (defined($content)) {
print(HANDLE $content);
}
@@ -798,9 +846,11 @@ sub lcov_geninfo(@)
{
@param = (@param, "--gcov-tool", $gcov_tool);
}
- if ($ignore_errors)
- {
- @param = (@param, "--ignore-errors", $ignore_errors);
+ foreach (@opt_ignore_errors) {
+ @param = (@param, "--ignore-errors", $_);
+ }
+ if ($no_recursion) {
+ @param = (@param, "--no-recursion");
}
if ($initial)
{
@@ -818,6 +868,26 @@ sub lcov_geninfo(@)
{
@param = (@param, "--debug");
}
+ if (defined($opt_external) && $opt_external)
+ {
+ @param = (@param, "--external");
+ }
+ if (defined($opt_external) && !$opt_external)
+ {
+ @param = (@param, "--no-external");
+ }
+ if (defined($opt_compat)) {
+ @param = (@param, "--compat", $opt_compat);
+ }
+ if (%opt_rc) {
+ foreach my $key (keys(%opt_rc)) {
+ @param = (@param, "--rc", "$key=".$opt_rc{$key});
+ }
+ }
+ if (defined($opt_config_file)) {
+ @param = (@param, "--config-file", $opt_config_file);
+ }
+
system(@param) and exit($? >> 8);
}
@@ -834,7 +904,7 @@ sub read_file($)
local $\;
local *HANDLE;
- open(HANDLE, "<$filename") || return undef;
+ open(HANDLE, "<", $filename) || return undef;
$content = <HANDLE>;
close(HANDLE);
@@ -860,17 +930,21 @@ sub get_package($)
local *HANDLE;
info("Reading package $file:\n");
- info(" data directory .......: $dir\n");
$file = abs_path($file);
chdir($dir);
- open(HANDLE, "tar xvfz $file 2>/dev/null|")
+ open(HANDLE, "-|", "tar xvfz '$file' 2>/dev/null")
or die("ERROR: could not process package $file\n");
+ $count = 0;
while (<HANDLE>) {
if (/\.da$/ || /\.gcda$/) {
$count++;
}
}
close(HANDLE);
+ if ($count == 0) {
+ die("ERROR: no data file found in package $file\n");
+ }
+ info(" data directory .......: $dir\n");
$build = read_file("$dir/$pkg_build_file");
if (defined($build)) {
info(" build directory ......: $build\n");
@@ -904,7 +978,7 @@ sub write_file($$)
my ($filename, $content) = @_;
local *HANDLE;
- open(HANDLE, ">$filename") || return 0;
+ open(HANDLE, ">", $filename) || return 0;
print(HANDLE $content);
close(HANDLE) || return 0;
@@ -922,7 +996,7 @@ sub count_package_data($)
local *HANDLE;
my $count = 0;
- open(HANDLE, "tar tfz $filename|") or return undef;
+ open(HANDLE, "-|", "tar tfz '$filename'") or return undef;
while (<HANDLE>) {
if (/\.da$/ || /\.gcda$/) {
$count++;
@@ -944,6 +1018,10 @@ sub create_package($$$;$)
my ($file, $dir, $build, $gkv) = @_;
my $cwd = getcwd();
+ # Check for availability of tar tool first
+ system("tar --help > /dev/null")
+ and die("ERROR: tar command not available\n");
+
# Print information about the package
info("Creating package $file:\n");
info(" data directory .......: $dir\n");
@@ -972,6 +1050,7 @@ sub create_package($$$;$)
chdir($dir);
system("tar cfz $file .")
and die("ERROR: could not create package $file\n");
+ chdir($cwd);
# Remove temporary files
unlink("$dir/$pkg_build_file");
@@ -985,7 +1064,6 @@ sub create_package($$$;$)
info(" data files ...........: $count\n");
}
}
- chdir($cwd);
}
sub find_link_fn($$$)
@@ -1208,6 +1286,113 @@ sub kernel_capture()
}
#
+# link_data_cb(datadir, rel, graphdir)
+#
+# Create symbolic link in GRAPDIR/REL pointing to DATADIR/REL.
+#
+
+sub link_data_cb($$$)
+{
+ my ($datadir, $rel, $graphdir) = @_;
+ my $absfrom = catfile($datadir, $rel);
+ my $absto = catfile($graphdir, $rel);
+ my $base;
+ my $dir;
+
+ if (-e $absto) {
+ die("ERROR: could not create symlink at $absto: ".
+ "File already exists!\n");
+ }
+ if (-l $absto) {
+ # Broken link - possibly from an interrupted earlier run
+ unlink($absto);
+ }
+
+ # Check for graph file
+ $base = $absto;
+ $base =~ s/\.(gcda|da)$//;
+ if (! -e $base.".gcno" && ! -e $base.".bbg" && ! -e $base.".bb") {
+ die("ERROR: No graph file found for $absfrom in ".
+ dirname($base)."!\n");
+ }
+
+ symlink($absfrom, $absto) or
+ die("ERROR: could not create symlink at $absto: $!\n");
+}
+
+#
+# unlink_data_cb(datadir, rel, graphdir)
+#
+# Remove symbolic link from GRAPHDIR/REL to DATADIR/REL.
+#
+
+sub unlink_data_cb($$$)
+{
+ my ($datadir, $rel, $graphdir) = @_;
+ my $absfrom = catfile($datadir, $rel);
+ my $absto = catfile($graphdir, $rel);
+ my $target;
+
+ return if (!-l $absto);
+ $target = readlink($absto);
+ return if (!defined($target) || $target ne $absfrom);
+
+ unlink($absto) or
+ warn("WARNING: could not remove symlink $absto: $!\n");
+}
+
+#
+# link_data(datadir, graphdir, create)
+#
+# If CREATE is non-zero, create symbolic links in GRAPHDIR for data files
+# found in DATADIR. Otherwise remove link in GRAPHDIR.
+#
+
+sub link_data($$$)
+{
+ my ($datadir, $graphdir, $create) = @_;
+
+ $datadir = abs_path($datadir);
+ $graphdir = abs_path($graphdir);
+ if ($create) {
+ lcov_find($datadir, \&link_data_cb, $graphdir, '\.gcda$',
+ '\.da$');
+ } else {
+ lcov_find($datadir, \&unlink_data_cb, $graphdir, '\.gcda$',
+ '\.da$');
+ }
+}
+
+#
+# find_graph_cb(datadir, rel, count_ref)
+#
+# Count number of files found.
+#
+
+sub find_graph_cb($$$)
+{
+ my ($dir, $rel, $count_ref) = @_;
+
+ ($$count_ref)++;
+}
+
+#
+# find_graph(dir)
+#
+# Search DIR for a graph file. Return non-zero if one was found, zero otherwise.
+#
+
+sub find_graph($)
+{
+ my ($dir) = @_;
+ my $count = 0;
+
+ lcov_find($dir, \&find_graph_cb, \$count, '\.gcno$', '\.bb$', '\.bbg$');
+
+ return $count > 0 ? 1 : 0;
+}
+
+#
# package_capture()
#
# Capture coverage data from a package of unprocessed coverage data files
@@ -1242,7 +1427,16 @@ sub package_capture()
} else {
# Build directory needs to be passed to geninfo
$base_directory = $build;
- lcov_geninfo($dir);
+ if (find_graph($dir)) {
+ # Package contains graph files - collect from there
+ lcov_geninfo($dir);
+ } else {
+ # No graph files found, link data files next to
+ # graph files
+ link_data($dir, $base_directory, 1);
+ lcov_geninfo($base_directory);
+ link_data($dir, $base_directory, 0);
+ }
}
}
@@ -1397,10 +1591,12 @@ sub br_ivec_push($$$$)
my $i;
$vec = "" if (!defined($vec));
+ $block = $BR_VEC_MAX if $block < 0;
# Check if branch already exists in vector
for ($i = 0; $i < $num; $i++) {
my ($v_block, $v_branch, $v_taken) = br_ivec_get($vec, $i);
+ $v_block = $BR_VEC_MAX if $v_block < 0;
next if ($v_block != $block || $v_branch != $branch);
@@ -1437,6 +1633,7 @@ sub br_ivec_get($$)
# Retrieve data from vector
$block = vec($vec, $offset + $BR_BLOCK, $BR_VEC_WIDTH);
+ $block = -1 if ($block == $BR_VEC_MAX);
$branch = vec($vec, $offset + $BR_BRANCH, $BR_VEC_WIDTH);
$taken = vec($vec, $offset + $BR_TAKEN, $BR_VEC_WIDTH);
@@ -1492,6 +1689,10 @@ sub get_br_found_and_hit($)
# "func" -> \%funcdata
# "found" -> $lines_found (number of instrumented lines found in file)
# "hit" -> $lines_hit (number of executed lines in file)
+# "f_found" -> $fn_found (number of instrumented functions found in file)
+# "f_hit" -> $fn_hit (number of executed functions in file)
+# "b_found" -> $br_found (number of instrumented branches found in file)
+# "b_hit" -> $br_hit (number of executed branches in file)
# "check" -> \%checkdata
# "testfnc" -> \%testfncdata
# "sumfnc" -> \%sumfnccount
@@ -1576,14 +1777,14 @@ sub read_info_file($)
"compressed file $_[0]!\n");
# Open compressed file
- open(INFO_HANDLE, "gunzip -c $_[0]|")
+ open(INFO_HANDLE, "-|", "gunzip -c '$_[0]'")
or die("ERROR: cannot start gunzip to decompress ".
"file $_[0]!\n");
}
else
{
# Open decompressed file
- open(INFO_HANDLE, $_[0])
+ open(INFO_HANDLE, "<", $_[0])
or die("ERROR: cannot read file $_[0]!\n");
}
@@ -1674,6 +1875,8 @@ sub read_info_file($)
/^FN:(\d+),([^,]+)/ && do
{
+ last if (!$func_coverage);
+
# Function data found, add to structure
$funcdata->{$2} = $1;
@@ -1692,6 +1895,8 @@ sub read_info_file($)
/^FNDA:(\d+),([^,]+)/ && do
{
+ last if (!$func_coverage);
+
# Function call count found, add to structure
# Add summary counts
$sumfnccount->{$2} += $1;
@@ -1709,6 +1914,7 @@ sub read_info_file($)
my ($line, $block, $branch, $taken) =
($1, $2, $3, $4);
+ last if (!$br_coverage);
$sumbrcount->{$line} =
br_ivec_push($sumbrcount->{$line},
$block, $branch, $taken);
@@ -1912,8 +2118,8 @@ sub set_info_entry($$$$$$$$$;$$$$$$)
sub add_counts($$)
{
- my %data1 = %{$_[0]}; # Hash 1
- my %data2 = %{$_[1]}; # Hash 2
+ my $data1_ref = $_[0]; # Hash 1
+ my $data2_ref = $_[1]; # Hash 2
my %result; # Resulting hash
my $line; # Current line iteration scalar
my $data1_count; # Count of line in hash1
@@ -1921,10 +2127,10 @@ sub add_counts($$)
my $found = 0; # Total number of lines found
my $hit = 0; # Number of lines with a count > 0
- foreach $line (keys(%data1))
+ foreach $line (keys(%$data1_ref))
{
- $data1_count = $data1{$line};
- $data2_count = $data2{$line};
+ $data1_count = $data1_ref->{$line};
+ $data2_count = $data2_ref->{$line};
# Add counts if present in both hashes
if (defined($data2_count)) { $data1_count += $data2_count; }
@@ -1936,14 +2142,14 @@ sub add_counts($$)
if ($data1_count > 0) { $hit++; }
}
- # Add lines unique to data2
- foreach $line (keys(%data2))
+ # Add lines unique to data2_ref
+ foreach $line (keys(%$data2_ref))
{
- # Skip lines already in data1
- if (defined($data1{$line})) { next; }
+ # Skip lines already in data1_ref
+ if (defined($data1_ref->{$line})) { next; }
- # Copy count from data2
- $result{$line} = $data2{$line};
+ # Copy count from data2_ref
+ $result{$line} = $data2_ref->{$line};
$found++;
if ($result{$line} > 0) { $hit++; }
@@ -2439,7 +2645,7 @@ sub add_traces()
if ($to_file)
{
info("Writing data to $output_filename\n");
- open(INFO_HANDLE, ">$output_filename")
+ open(INFO_HANDLE, ">", $output_filename)
or die("ERROR: cannot write to $output_filename!\n");
@result = write_info_file(*INFO_HANDLE, $total_trace);
close(*INFO_HANDLE);
@@ -2548,6 +2754,7 @@ sub write_info_file(*$)
my ($block, $branch, $taken) =
br_ivec_get($brdata, $i);
+ $block = $BR_VEC_MAX if ($block < 0);
print(INFO_HANDLE "BRDA:$line,$block,".
"$branch,$taken\n");
$br_found++;
@@ -2589,7 +2796,7 @@ sub write_info_file(*$)
#
# transform_pattern(pattern)
#
-# Transform shell wildcard expression to equivalent PERL regular expression.
+# Transform shell wildcard expression to equivalent Perl regular expression.
# Return transformed pattern.
#
@@ -2669,7 +2876,7 @@ sub extract()
{
info("Extracted $extracted files\n");
info("Writing data to $output_filename\n");
- open(INFO_HANDLE, ">$output_filename")
+ open(INFO_HANDLE, ">", $output_filename)
or die("ERROR: cannot write to $output_filename!\n");
@result = write_info_file(*INFO_HANDLE, $data);
close(*INFO_HANDLE);
@@ -2725,7 +2932,7 @@ sub remove()
{
info("Deleted $removed files\n");
info("Writing data to $output_filename\n");
- open(INFO_HANDLE, ">$output_filename")
+ open(INFO_HANDLE, ">", $output_filename)
or die("ERROR: cannot write to $output_filename!\n");
@result = write_info_file(*INFO_HANDLE, $data);
close(*INFO_HANDLE);
@@ -2836,13 +3043,13 @@ sub shorten_number($$)
return '#';
}
-sub shorten_rate($$)
+sub shorten_rate($$$)
{
- my ($rate, $width) = @_;
- my $result = sprintf("%*.1f%%", $width - 3, $rate);
+ my ($hit, $found, $width) = @_;
+ my $result = rate($hit, $found, "%", 1, $width);
return $result if (length($result) <= $width);
- $result = sprintf("%*d%%", $width - 1, $rate);
+ $result = rate($hit, $found, "%", 0, $width);
return $result if (length($result) <= $width);
return "#";
}
@@ -3060,26 +3267,11 @@ sub list()
$br_total_hit += $br_hit;
# Determine line coverage rate for this file
- if ($found == 0) {
- $rate = "-";
- } else {
- $rate = shorten_rate(100 * $hit / $found,
- $fwidth[$F_LN_RATE]);
- }
+ $rate = shorten_rate($hit, $found, $fwidth[$F_LN_RATE]);
# Determine function coverage rate for this file
- if (!defined($fn_found) || $fn_found == 0) {
- $fnrate = "-";
- } else {
- $fnrate = shorten_rate(100 * $fn_hit / $fn_found,
- $fwidth[$F_FN_RATE]);
- }
+ $fnrate = shorten_rate($fn_hit, $fn_found, $fwidth[$F_FN_RATE]);
# Determine branch coverage rate for this file
- if (!defined($br_found) || $br_found == 0) {
- $brrate = "-";
- } else {
- $brrate = shorten_rate(100 * $br_hit / $br_found,
- $fwidth[$F_BR_RATE]);
- }
+ $brrate = shorten_rate($br_hit, $br_found, $fwidth[$F_BR_RATE]);
# Assemble line parameters
push(@file_data, $print_filename);
@@ -3095,26 +3287,13 @@ sub list()
}
# Determine total line coverage rate
- if ($total_found == 0) {
- $rate = "-";
- } else {
- $rate = shorten_rate(100 * $total_hit / $total_found,
- $fwidth[$F_LN_RATE]);
- }
+ $rate = shorten_rate($total_hit, $total_found, $fwidth[$F_LN_RATE]);
# Determine total function coverage rate
- if ($fn_total_found == 0) {
- $fnrate = "-";
- } else {
- $fnrate = shorten_rate(100 * $fn_total_hit / $fn_total_found,
- $fwidth[$F_FN_RATE]);
- }
+ $fnrate = shorten_rate($fn_total_hit, $fn_total_found,
+ $fwidth[$F_FN_RATE]);
# Determine total branch coverage rate
- if ($br_total_found == 0) {
- $brrate = "-";
- } else {
- $brrate = shorten_rate(100 * $br_total_hit / $br_total_found,
- $fwidth[$F_BR_RATE]);
- }
+ $brrate = shorten_rate($br_total_hit, $br_total_found,
+ $fwidth[$F_BR_RATE]);
# Print separator
print(("="x$barlen)."\n");
@@ -3253,14 +3432,14 @@ sub read_diff($)
"compressed file $diff_file!\n");
# Open compressed file
- open(HANDLE, "gunzip -c $diff_file|")
+ open(HANDLE, "-|", "gunzip -c '$diff_file'")
or die("ERROR: cannot start gunzip to decompress ".
"file $_[0]!\n");
}
else
{
# Open decompressed file
- open(HANDLE, $diff_file)
+ open(HANDLE, "<", $diff_file)
or die("ERROR: cannot read file $_[0]!\n");
}
@@ -3668,10 +3847,10 @@ sub adjust_fncdata($$$)
# Remove count data in testfncdata for functions which are no longer
# in funcdata
- foreach $testname (%{$testfncdata}) {
+ foreach $testname (keys(%{$testfncdata})) {
my $fnccount = $testfncdata->{$testname};
- foreach $func (%{$fnccount}) {
+ foreach $func (keys(%{$fnccount})) {
if (!defined($funcdata->{$func})) {
delete($fnccount->{$func});
}
@@ -3679,7 +3858,7 @@ sub adjust_fncdata($$$)
}
# Remove count data in sumfnccount for functions which are no longer
# in funcdata
- foreach $func (%{$sumfnccount}) {
+ foreach $func (keys(%{$sumfnccount})) {
if (!defined($funcdata->{$func})) {
delete($sumfnccount->{$func});
}
@@ -3886,7 +4065,7 @@ sub diff()
if ($to_file)
{
info("Writing data to $output_filename\n");
- open(INFO_HANDLE, ">$output_filename")
+ open(INFO_HANDLE, ">", $output_filename)
or die("ERROR: cannot write to $output_filename!\n");
@result = write_info_file(*INFO_HANDLE, $trace_data);
close(*INFO_HANDLE);
@@ -3899,6 +4078,59 @@ sub diff()
return @result;
}
+#
+# summary()
+#
+
+sub summary()
+{
+ my $filename;
+ my $current;
+ my $total;
+ my $ln_total_found;
+ my $ln_total_hit;
+ my $fn_total_found;
+ my $fn_total_hit;
+ my $br_total_found;
+ my $br_total_hit;
+
+ # Read and combine trace files
+ foreach $filename (@opt_summary) {
+ $current = read_info_file($filename);
+ if (!defined($total)) {
+ $total = $current;
+ } else {
+ $total = combine_info_files($total, $current);
+ }
+ }
+ # Calculate coverage data
+ foreach $filename (keys(%{$total}))
+ {
+ my $entry = $total->{$filename};
+ my $ln_found;
+ my $ln_hit;
+ my $fn_found;
+ my $fn_hit;
+ my $br_found;
+ my $br_hit;
+
+ (undef, undef, undef, undef, undef, undef, undef, undef,
+ $ln_found, $ln_hit, $fn_found, $fn_hit, $br_found,
+ $br_hit) = get_info_entry($entry);
+
+ # Add to totals
+ $ln_total_found += $ln_found;
+ $ln_total_hit += $ln_hit;
+ $fn_total_found += $fn_found;
+ $fn_total_hit += $fn_hit;
+ $br_total_found += $br_found;
+ $br_total_hit += $br_hit;
+ }
+
+
+ return ($ln_total_found, $ln_total_hit, $fn_total_found, $fn_total_hit,
+ $br_total_found, $br_total_hit);
+}
#
# system_no_output(mode, parameters)
@@ -3920,12 +4152,12 @@ sub system_no_output($@)
local *OLD_STDOUT;
# Save old stdout and stderr handles
- ($mode & 1) && open(OLD_STDOUT, ">>&STDOUT");
- ($mode & 2) && open(OLD_STDERR, ">>&STDERR");
+ ($mode & 1) && open(OLD_STDOUT, ">>&", "STDOUT");
+ ($mode & 2) && open(OLD_STDERR, ">>&", "STDERR");
# Redirect to /dev/null
- ($mode & 1) && open(STDOUT, ">/dev/null");
- ($mode & 2) && open(STDERR, ">/dev/null");
+ ($mode & 1) && open(STDOUT, ">", "/dev/null");
+ ($mode & 2) && open(STDERR, ">", "/dev/null");
system(@_);
$result = $?;
@@ -3935,8 +4167,8 @@ sub system_no_output($@)
($mode & 2) && close(STDERR);
# Restore old handles
- ($mode & 1) && open(STDOUT, ">>&OLD_STDOUT");
- ($mode & 2) && open(STDERR, ">>&OLD_STDERR");
+ ($mode & 1) && open(STDOUT, ">>&", "OLD_STDOUT");
+ ($mode & 2) && open(STDERR, ">>&", "OLD_STDERR");
return $result;
}
@@ -3957,7 +4189,7 @@ sub read_config($)
my $value;
local *HANDLE;
- if (!open(HANDLE, "<$filename"))
+ if (!open(HANDLE, "<", $filename))
{
warn("WARNING: cannot read configuration file $filename\n");
return undef;
@@ -3996,8 +4228,8 @@ sub read_config($)
# key_string => var_ref
#
# where KEY_STRING is a keyword and VAR_REF is a reference to an associated
-# variable. If the global configuration hash CONFIG contains a value for
-# keyword KEY_STRING, VAR_REF will be assigned the value for that keyword.
+# variable. If the global configuration hashes CONFIG or OPT_RC contain a value
+# for keyword KEY_STRING, VAR_REF will be assigned the value for that keyword.
#
sub apply_config($)
@@ -4006,8 +4238,9 @@ sub apply_config($)
foreach (keys(%{$ref}))
{
- if (defined($config->{$_}))
- {
+ if (defined($opt_rc{$_})) {
+ ${$ref->{$_}} = $opt_rc{$_};
+ } elsif (defined($config->{$_})) {
${$ref->{$_}} = $config->{$_};
}
}
@@ -4037,6 +4270,9 @@ sub abort_handler($)
sub temp_cleanup()
{
+ # Ensure temp directory is not in use by current process
+ chdir("/");
+
if (@temp_dirs) {
info("Removing temporary directories.\n");
foreach (@temp_dirs) {
@@ -4145,8 +4381,8 @@ sub get_overall_line($$$$)
return "no data found" if (!defined($found) || $found == 0);
$name = ($found == 1) ? $name_sn : $name_pl;
- return sprintf("%.1f%% (%d of %d %s)", $hit * 100 / $found, $hit,
- $found, $name);
+
+ return rate($hit, $found, "% ($hit of $found $name)");
}
@@ -4162,7 +4398,7 @@ sub print_overall_rate($$$$$$$$$)
my ($ln_do, $ln_found, $ln_hit, $fn_do, $fn_found, $fn_hit,
$br_do, $br_found, $br_hit) = @_;
- info("Overall coverage rate:\n");
+ info("Summary coverage rate:\n");
info(" lines......: %s\n",
get_overall_line($ln_found, $ln_hit, "line", "lines"))
if ($ln_do);
@@ -4173,3 +4409,38 @@ sub print_overall_rate($$$$$$$$$)
get_overall_line($br_found, $br_hit, "branch", "branches"))
if ($br_do);
}
+
+
+#
+# rate(hit, found[, suffix, precision, width])
+#
+# Return the coverage rate [0..100] for HIT and FOUND values. 0 is only
+# returned when HIT is 0. 100 is only returned when HIT equals FOUND.
+# PRECISION specifies the precision of the result. SUFFIX defines a
+# string that is appended to the result if FOUND is non-zero. Spaces
+# are added to the start of the resulting string until it is at least WIDTH
+# characters wide.
+#
+
+sub rate($$;$$$)
+{
+ my ($hit, $found, $suffix, $precision, $width) = @_;
+ my $rate;
+
+ # Assign defaults if necessary
+ $precision = 1 if (!defined($precision));
+ $suffix = "" if (!defined($suffix));
+ $width = 0 if (!defined($width));
+
+ return sprintf("%*s", $width, "-") if (!defined($found) || $found == 0);
+ $rate = sprintf("%.*f", $precision, $hit * 100 / $found);
+
+ # Adjust rates if necessary
+ if ($rate == 0 && $hit > 0) {
+ $rate = sprintf("%.*f", $precision, 1 / 10 ** $precision);
+ } elsif ($rate == 100 && $hit != $found) {
+ $rate = sprintf("%.*f", $precision, 100 - 1 / 10 ** $precision);
+ }
+
+ return sprintf("%*s", $width, $rate.$suffix);
+}
diff --git a/3rdParty/Ldns/SConscript b/3rdParty/Ldns/SConscript
index a43bde7..eae2e5c 100644
--- a/3rdParty/Ldns/SConscript
+++ b/3rdParty/Ldns/SConscript
@@ -2,69 +2,68 @@ Import("env")
if env.get("LDNS_BUNDLED", False) :
- if env["PLATFORM"] == "win32" :
- cppflags = ["/I" + Dir("#/3rdParty/Ldns/src/ldns").abspath]
- else :
- cppflags = [("-isystem", Dir("#/3rdParty/Ldns/src/ldns").abspath)]
+ if env["PLATFORM"] == "win32" :
+ cppflags = ["/I" + Dir("#/3rdParty/Ldns/src/ldns").abspath]
+ else :
+ cppflags = [("-isystem", Dir("#/3rdParty/Ldns/src/ldns").abspath)]
################################################################################
# Flags
################################################################################
-
- if env["SCONS_STAGE"] == "flags" :
- env["LDNS_FLAGS"] = {
- "CPPPATH": [Dir("src/ldns")],
- "CPPFLAGS": cppflags,
- "LIBPATH": [env.Dir(".")],
- "LIBS": ["Swiften_Ldns"],
- }
- if env["target"] == "android" :
- env["LDNS_FLAGS"]["CPPPATH"].append(Dir("src/android"))
+ if env["SCONS_STAGE"] == "flags" :
+ env["LDNS_FLAGS"] = {
+ "CPPPATH": [Dir("src/ldns")],
+ "CPPFLAGS": cppflags,
+ "LIBPATH": [env.Dir(".")],
+ "LIBS": ["Swiften_Ldns"],
+ }
+ if env["target"] == "android" :
+ env["LDNS_FLAGS"]["CPPPATH"].append(Dir("src/android"))
################################################################################
# Build
################################################################################
- if env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
- myenv.Append(CPPDEFINES = [("LDNS_STATICLIB")])
- myenv.Append(CPPPATH = ["src/ldns", "."])
- if env["target"] == "android" :
- myenv.Append(CPPPATH = ["src/android"])
- myenv.UseFlags(env["OPENSSL_FLAGS"])
-
- env["LDNS_OBJECTS"] = myenv.SwiftenObject([
- "src/ldns/compat/b32_ntop.c",
- "src/ldns/compat/b32_pton.c",
- "src/ldns/compat/b64_ntop.c",
- "src/ldns/compat/b64_pton.c",
- "src/ldns/buffer.c",
- "src/ldns/dname.c",
- "src/ldns/dnssec_sign.c",
- "src/ldns/dnssec_verify.c",
- "src/ldns/dnssec_zone.c",
- "src/ldns/dnssec.c",
- "src/ldns/error.c",
- "src/ldns/higher.c",
- "src/ldns/host2str.c",
- "src/ldns/host2wire.c",
- "src/ldns/keys.c",
- "src/ldns/linktest.c",
- "src/ldns/net.c",
- "src/ldns/packet.c",
- "src/ldns/parse.c",
- "src/ldns/rbtree.c",
- "src/ldns/rdata.c",
- "src/ldns/resolver.c",
- "src/ldns/rr_functions.c",
- "src/ldns/rr.c",
- "src/ldns/sha1.c",
- "src/ldns/sha2.c",
- "src/ldns/str2host.c",
- "src/ldns/tsig.c",
- "src/ldns/update.c",
- "src/ldns/util.c",
- "src/ldns/wire2host.c",
- "src/ldns/zone.c",
- ])
+ if env["SCONS_STAGE"] == "build" :
+ myenv = env.Clone()
+ myenv.Append(CPPDEFINES = [("LDNS_STATICLIB")])
+ myenv.Append(CPPPATH = ["src/ldns", "."])
+ if env["target"] == "android" :
+ myenv.Append(CPPPATH = ["src/android"])
+ myenv.UseFlags(env["OPENSSL_FLAGS"])
+
+ env["LDNS_OBJECTS"] = myenv.SwiftenObject([
+ "src/ldns/compat/b32_ntop.c",
+ "src/ldns/compat/b32_pton.c",
+ "src/ldns/compat/b64_ntop.c",
+ "src/ldns/compat/b64_pton.c",
+ "src/ldns/buffer.c",
+ "src/ldns/dname.c",
+ "src/ldns/dnssec_sign.c",
+ "src/ldns/dnssec_verify.c",
+ "src/ldns/dnssec_zone.c",
+ "src/ldns/dnssec.c",
+ "src/ldns/error.c",
+ "src/ldns/higher.c",
+ "src/ldns/host2str.c",
+ "src/ldns/host2wire.c",
+ "src/ldns/keys.c",
+ "src/ldns/linktest.c",
+ "src/ldns/net.c",
+ "src/ldns/packet.c",
+ "src/ldns/parse.c",
+ "src/ldns/rbtree.c",
+ "src/ldns/rdata.c",
+ "src/ldns/resolver.c",
+ "src/ldns/rr_functions.c",
+ "src/ldns/rr.c",
+ "src/ldns/sha1.c",
+ "src/ldns/sha2.c",
+ "src/ldns/str2host.c",
+ "src/ldns/tsig.c",
+ "src/ldns/update.c",
+ "src/ldns/util.c",
+ "src/ldns/wire2host.c",
+ "src/ldns/zone.c",
+ ])
diff --git a/3rdParty/LibIDN/SConscript b/3rdParty/LibIDN/SConscript
index e3ed839..90892b0 100644
--- a/3rdParty/LibIDN/SConscript
+++ b/3rdParty/LibIDN/SConscript
@@ -8,67 +8,67 @@ if env.get("LIBIDN_BUNDLED", False) :
# Module flags
################################################################################
- if env["SCONS_STAGE"] == "flags" :
- env["LIBIDN_FLAGS"] = {
- "CPPDEFINES": ["LIBIDN_STATIC"],
- }
- if os.path.basename(env["CC"]) in ("clang", "gcc") :
- env["LIBIDN_FLAGS"].update({"CPPFLAGS": ["-isystem" "3rdParty/LibIDN/src"]})
- else :
- env["LIBIDN_FLAGS"].update({"CPPPATH": [Dir("src")]})
+ if env["SCONS_STAGE"] == "flags" :
+ env["LIBIDN_FLAGS"] = {
+ "CPPDEFINES": ["LIBIDN_STATIC"],
+ }
+ if os.path.basename(env["CC"]) in ("clang", "gcc") :
+ env["LIBIDN_FLAGS"].update({"CPPFLAGS": ["-isystem" "3rdParty/LibIDN/src"]})
+ else :
+ env["LIBIDN_FLAGS"].update({"CPPPATH": [Dir("src")]})
- if env["PLATFORM"] == "win32" :
- env["LIBIDN_FLAGS"]["CPPPATH"] += [Dir("stubs/win32")]
- if float(env["MSVC_VERSION"]) < 14:
- env["LIBIDN_FLAGS"]["CPPPATH"] += [Dir("stubs/win32/stdbool")]
- if env["MSVC_VERSION"][:3] == "9.0" :
- env["LIBIDN_FLAGS"]["CPPPATH"] += [Dir("stubs/win32/VC2008")]
+ if env["PLATFORM"] == "win32" :
+ env["LIBIDN_FLAGS"]["CPPPATH"] += [Dir("stubs/win32")]
+ if float(env["MSVC_VERSION"]) < 14:
+ env["LIBIDN_FLAGS"]["CPPPATH"] += [Dir("stubs/win32/stdbool")]
+ if env["MSVC_VERSION"][:3] == "9.0" :
+ env["LIBIDN_FLAGS"]["CPPPATH"] += [Dir("stubs/win32/VC2008")]
################################################################################
# Build
################################################################################
- if env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
+ if env["SCONS_STAGE"] == "build" :
+ myenv = env.Clone()
- # Remove warn flags
- myenv.Replace(CCFLAGS = [flag for flag in env["CCFLAGS"] if flag not in ["-W", "-Wall"]])
+ # Remove warn flags
+ myenv.Replace(CCFLAGS = [flag for flag in env["CCFLAGS"] if flag not in ["-W", "-Wall"]])
- # Check for strcasecmp() or replacement
- conf = Configure(conf_env)
- if not conf.CheckFunc('strcasecmp') :
- if conf.CheckFunc("stricmp") :
- myenv.Append(CPPDEFINES = [("strcasecmp", "stricmp")])
- else :
- print "Error: Cannot find strcasecmp() or stricmp()"
- Exit(1)
- if not conf.CheckFunc('strncasecmp') :
- if conf.CheckFunc("strnicmp") :
- myenv.Append(CPPDEFINES = [("strncasecmp", "strnicmp")])
- else :
- print "Error: Cannot find strncasecmp() or strnicmp()"
- Exit(1)
- conf.Finish()
+ # Check for strcasecmp() or replacement
+ conf = Configure(conf_env)
+ if not conf.CheckFunc('strcasecmp') :
+ if conf.CheckFunc("stricmp") :
+ myenv.Append(CPPDEFINES = [("strcasecmp", "stricmp")])
+ else :
+ print "Error: Cannot find strcasecmp() or stricmp()"
+ Exit(1)
+ if not conf.CheckFunc('strncasecmp') :
+ if conf.CheckFunc("strnicmp") :
+ myenv.Append(CPPDEFINES = [("strncasecmp", "strnicmp")])
+ else :
+ print "Error: Cannot find strncasecmp() or strnicmp()"
+ Exit(1)
+ conf.Finish()
- myenv.Append(CPPDEFINES = ["LIBIDN_STATIC", "HAVE_CONFIG_H"])
- myenv.Append(CPPPATH = ["src", "stubs", "src/gl"])
- if myenv["PLATFORM"] == "win32" :
- myenv.Append(CPPPATH = "stubs/win32")
- if float(env["MSVC_VERSION"]) < 14:
- myenv.Append(CPPPATH = "stubs/win32/stdbool")
- if myenv["MSVC_VERSION"][:3] == "9.0" :
- myenv.Append(CPPPATH = "stubs/win32/VC2008")
+ myenv.Append(CPPDEFINES = ["LIBIDN_STATIC", "HAVE_CONFIG_H"])
+ myenv.Append(CPPPATH = ["src", "stubs", "src/gl"])
+ if myenv["PLATFORM"] == "win32" :
+ myenv.Append(CPPPATH = "stubs/win32")
+ if float(env["MSVC_VERSION"]) < 14:
+ myenv.Append(CPPPATH = "stubs/win32/stdbool")
+ if myenv["MSVC_VERSION"][:3] == "9.0" :
+ myenv.Append(CPPPATH = "stubs/win32/VC2008")
- env["LIBIDN_OBJECTS"] = myenv.SwiftenObject([
- "src/stringprep.c",
- "src/profiles.c",
- "src/rfc3454.c",
- "src/punycode.c",
- "src/idna.c",
- "src/toutf8.c",
- "src/nfkc.c",
- "src/gl/c-ctype.c",
- "src/gl/c-strcasecmp.c",
- "src/gl/c-strncasecmp.c",
- "src/gl/unistr/u8-check.c"
- ])
+ env["LIBIDN_OBJECTS"] = myenv.SwiftenObject([
+ "src/stringprep.c",
+ "src/profiles.c",
+ "src/rfc3454.c",
+ "src/punycode.c",
+ "src/idna.c",
+ "src/toutf8.c",
+ "src/nfkc.c",
+ "src/gl/c-ctype.c",
+ "src/gl/c-strcasecmp.c",
+ "src/gl/c-strncasecmp.c",
+ "src/gl/unistr/u8-check.c"
+ ])
diff --git a/3rdParty/LibMiniUPnPc/SConscript b/3rdParty/LibMiniUPnPc/SConscript
index 05eed8f..3c2e29d 100644
--- a/3rdParty/LibMiniUPnPc/SConscript
+++ b/3rdParty/LibMiniUPnPc/SConscript
@@ -8,51 +8,51 @@ if env.get("LIBMINIUPNPC_BUNDLED", False) :
# Module flags
################################################################################
- if env["SCONS_STAGE"] == "flags" :
- env["HAVE_LIBMINIUPNPC"] = True
- env["LIBMINIUPNPC_FLAGS"] = {
- "LIBPATH": [Dir(".")],
- "INTERNAL_CPPDEFINES": ["STATICLIB"],
- }
- if os.path.basename(env["CC"]) in ("clang", "gcc") :
- env["LIBMINIUPNPC_FLAGS"].update({"CPPFLAGS": ["-isystem" "3rdParty/LibMiniUPnPc/src/miniupnpc"]})
- else :
- env["LIBMINIUPNPC_FLAGS"].update({"CPPPATH": [Dir("src/miniupnpc")]})
-
- #if env["PLATFORM"] == "win32" :
- # env["LIBIDN_FLAGS"]["CPPPATH"] += [Dir("stubs/win32")]
- # if env["MSVC_VERSION"][:3] == "9.0" :
- # env["LIBIDN_FLAGS"]["CPPPATH"] += [Dir("stubs/win32/VC2008")]
+ if env["SCONS_STAGE"] == "flags" :
+ env["HAVE_LIBMINIUPNPC"] = True
+ env["LIBMINIUPNPC_FLAGS"] = {
+ "LIBPATH": [Dir(".")],
+ "INTERNAL_CPPDEFINES": ["STATICLIB"],
+ }
+ if os.path.basename(env["CC"]) in ("clang", "gcc") :
+ env["LIBMINIUPNPC_FLAGS"].update({"CPPFLAGS": ["-isystem" "3rdParty/LibMiniUPnPc/src/miniupnpc"]})
+ else :
+ env["LIBMINIUPNPC_FLAGS"].update({"CPPPATH": [Dir("src/miniupnpc")]})
+
+ #if env["PLATFORM"] == "win32" :
+ # env["LIBIDN_FLAGS"]["CPPPATH"] += [Dir("stubs/win32")]
+ # if env["MSVC_VERSION"][:3] == "9.0" :
+ # env["LIBIDN_FLAGS"]["CPPPATH"] += [Dir("stubs/win32/VC2008")]
################################################################################
# Build
################################################################################
- if env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
- myenv.Append(CPPPATH = ["src"])
- # Remove warn flags
- myenv.Replace(CCFLAGS = [flag for flag in env["CCFLAGS"] if flag not in ["-W", "-Wall"]])
+ if env["SCONS_STAGE"] == "build" :
+ myenv = env.Clone()
+ myenv.Append(CPPPATH = ["src"])
+ # Remove warn flags
+ myenv.Replace(CCFLAGS = [flag for flag in env["CCFLAGS"] if flag not in ["-W", "-Wall"]])
- myenv.Append(CCFLAGS = ["-DNDEBUG", "-DSTATICLIB"])
+ myenv.Append(CCFLAGS = ["-DNDEBUG", "-DSTATICLIB"])
- if myenv["PLATFORM"] != "win32":
- myenv.Append(CCFLAGS = ["-DMINIUPNPC_SET_SOCKET_TIMEOUT"])
- myenv.Append(CCFLAGS = ["-D_BSD_SOURCE"])
+ if myenv["PLATFORM"] != "win32":
+ myenv.Append(CCFLAGS = ["-DMINIUPNPC_SET_SOCKET_TIMEOUT"])
+ myenv.Append(CCFLAGS = ["-D_BSD_SOURCE"])
- if myenv["PLATFORM"] == "darwin":
- myenv.Append(CCFLAGS = ["-DMACOSX", "-D_DARWIN_C_SOURCE"])
+ if myenv["PLATFORM"] == "darwin":
+ myenv.Append(CCFLAGS = ["-DMACOSX", "-D_DARWIN_C_SOURCE"])
- if myenv["PLATFORM"] == "win32":
- myenv.Append(CCFLAGS = ["-DWIN32", "-D_WIN32_WINNT=0x0501"])
+ if myenv["PLATFORM"] == "win32":
+ myenv.Append(CCFLAGS = ["-DWIN32", "-D_WIN32_WINNT=0x0501"])
- if myenv["PLATFORM"] != "win32" and myenv["PLATFORM"] != "darwin":
- conf = Configure(conf_env)
- if conf.CheckTypeSize("struct ip_mreqn", includes="#include <netinet/in.h>") == 0:
- myenv.Append(CCFLAGS = ["-DNEED_STRUCT_IP_MREQN"])
- conf.Finish()
+ if myenv["PLATFORM"] != "win32" and myenv["PLATFORM"] != "darwin":
+ conf = Configure(conf_env)
+ if conf.CheckTypeSize("struct ip_mreqn", includes="#include <netinet/in.h>") == 0:
+ myenv.Append(CCFLAGS = ["-DNEED_STRUCT_IP_MREQN"])
+ conf.Finish()
- myenv.WriteVal("src/miniupnpc/miniupnpcstrings.h", myenv.Value(
+ myenv.WriteVal("src/miniupnpc/miniupnpcstrings.h", myenv.Value(
"""
#ifndef __MINIUPNPCSTRINGS_H__
#define __MINIUPNPCSTRINGS_H__
@@ -63,22 +63,22 @@ if env.get("LIBMINIUPNPC_BUNDLED", False) :
#endif
""".replace("$OS_STRING", myenv["PLATFORM"])))
- miniupnpc_objects = [
- "src/miniupnpc/igd_desc_parse.c",
- "src/miniupnpc/miniupnpc.c",
- "src/miniupnpc/minixml.c",
- "src/miniupnpc/minisoap.c",
- "src/miniupnpc/miniwget.c",
- #"src/miniupnpc/upnpc.c",
- "src/miniupnpc/upnpcommands.c",
- "src/miniupnpc/upnpreplyparse.c",
- "src/miniupnpc/upnperrors.c",
- "src/miniupnpc/connecthostport.c",
- "src/miniupnpc/portlistingparse.c",
- "src/miniupnpc/receivedata.c"
- ]
-
- if myenv["PLATFORM"] != "win32":
- miniupnpc_objects.append("src/miniupnpc/minissdpc.c")
-
- env["LIBMINIUPNPC_OBJECTS"] = myenv.SwiftenObject(miniupnpc_objects)
+ miniupnpc_objects = [
+ "src/miniupnpc/igd_desc_parse.c",
+ "src/miniupnpc/miniupnpc.c",
+ "src/miniupnpc/minixml.c",
+ "src/miniupnpc/minisoap.c",
+ "src/miniupnpc/miniwget.c",
+ #"src/miniupnpc/upnpc.c",
+ "src/miniupnpc/upnpcommands.c",
+ "src/miniupnpc/upnpreplyparse.c",
+ "src/miniupnpc/upnperrors.c",
+ "src/miniupnpc/connecthostport.c",
+ "src/miniupnpc/portlistingparse.c",
+ "src/miniupnpc/receivedata.c"
+ ]
+
+ if myenv["PLATFORM"] != "win32":
+ miniupnpc_objects.append("src/miniupnpc/minissdpc.c")
+
+ env["LIBMINIUPNPC_OBJECTS"] = myenv.SwiftenObject(miniupnpc_objects)
diff --git a/3rdParty/LibNATPMP/SConscript b/3rdParty/LibNATPMP/SConscript
index 2a58242..e1aef1c 100644
--- a/3rdParty/LibNATPMP/SConscript
+++ b/3rdParty/LibNATPMP/SConscript
@@ -8,49 +8,49 @@ if env.get("LIBNATPMP_BUNDLED", False) :
# Module flags
################################################################################
- if env["SCONS_STAGE"] == "flags" :
- env["HAVE_LIBNATPMP"] = True
- env["LIBNATPMP_FLAGS"] = {
- "LIBPATH": [Dir(".")],
- "INTERNAL_CPPDEFINES": ["STATICLIB"],
- }
- if os.path.basename(env["CC"]) in ("clang", "gcc") :
- env["LIBNATPMP_FLAGS"].update({"CPPFLAGS": ["-isystem" "3rdParty/LibNATPMP/src/libnatpmp"]})
- else :
- env["LIBNATPMP_FLAGS"].update({"CPPPATH": [Dir("src/libnatpmp")]})
- #if env["PLATFORM"] == "win32" :
- # env["LIBIDN_FLAGS"]["CPPPATH"] += [Dir("stubs/win32")]
- # if env["MSVC_VERSION"][:3] == "9.0" :
- # env["LIBIDN_FLAGS"]["CPPPATH"] += [Dir("stubs/win32/VC2008")]
+ if env["SCONS_STAGE"] == "flags" :
+ env["HAVE_LIBNATPMP"] = True
+ env["LIBNATPMP_FLAGS"] = {
+ "LIBPATH": [Dir(".")],
+ "INTERNAL_CPPDEFINES": ["STATICLIB"],
+ }
+ if os.path.basename(env["CC"]) in ("clang", "gcc") :
+ env["LIBNATPMP_FLAGS"].update({"CPPFLAGS": ["-isystem" "3rdParty/LibNATPMP/src/libnatpmp"]})
+ else :
+ env["LIBNATPMP_FLAGS"].update({"CPPPATH": [Dir("src/libnatpmp")]})
+ #if env["PLATFORM"] == "win32" :
+ # env["LIBIDN_FLAGS"]["CPPPATH"] += [Dir("stubs/win32")]
+ # if env["MSVC_VERSION"][:3] == "9.0" :
+ # env["LIBIDN_FLAGS"]["CPPPATH"] += [Dir("stubs/win32/VC2008")]
################################################################################
# Build
################################################################################
- if env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
- myenv.Append(CPPPATH = ["src"])
- # Remove warn flags
- myenv.Replace(CCFLAGS = [flag for flag in env["CCFLAGS"] if flag not in ["-W", "-Wall"]])
-
- myenv.Append(CCFLAGS = ["-DNDEBUG", "-DSTATICLIB"])
-
- #if myenv["PLATFORM"] != "win32":
- # myenv.Append(CCFLAGS = ["-DMINIUPNPC_SET_SOCKET_TIMEOUT"])
-
- if myenv["PLATFORM"] == "darwin":
- myenv.Append(CCFLAGS = ["-DMACOSX", "-D_DARWIN_C_SOURCE"])
-
- if myenv["PLATFORM"] == "win32":
- myenv.Append(CCFLAGS = ["-DWIN32"])
-
- src_files = [
- "src/libnatpmp/getgateway.c",
- "src/libnatpmp/natpmp.c",
- "src/libnatpmp/natpmpc.c",
- ]
-
- if myenv["PLATFORM"] == "win32":
- src_files += ["src/libnatpmp/wingettimeofday.c"]
-
- env["LIBNATPMP_OBJECTS"] = myenv.SwiftenObject(src_files)
+ if env["SCONS_STAGE"] == "build" :
+ myenv = env.Clone()
+ myenv.Append(CPPPATH = ["src"])
+ # Remove warn flags
+ myenv.Replace(CCFLAGS = [flag for flag in env["CCFLAGS"] if flag not in ["-W", "-Wall"]])
+
+ myenv.Append(CCFLAGS = ["-DNDEBUG", "-DSTATICLIB"])
+
+ #if myenv["PLATFORM"] != "win32":
+ # myenv.Append(CCFLAGS = ["-DMINIUPNPC_SET_SOCKET_TIMEOUT"])
+
+ if myenv["PLATFORM"] == "darwin":
+ myenv.Append(CCFLAGS = ["-DMACOSX", "-D_DARWIN_C_SOURCE"])
+
+ if myenv["PLATFORM"] == "win32":
+ myenv.Append(CCFLAGS = ["-DWIN32"])
+
+ src_files = [
+ "src/libnatpmp/getgateway.c",
+ "src/libnatpmp/natpmp.c",
+ "src/libnatpmp/natpmpc.c",
+ ]
+
+ if myenv["PLATFORM"] == "win32":
+ src_files += ["src/libnatpmp/wingettimeofday.c"]
+
+ env["LIBNATPMP_OBJECTS"] = myenv.SwiftenObject(src_files)
diff --git a/3rdParty/Lua/SConscript b/3rdParty/Lua/SConscript
index f73286f..d2475f6 100644
--- a/3rdParty/Lua/SConscript
+++ b/3rdParty/Lua/SConscript
@@ -6,76 +6,76 @@ if env.get("LUA_BUNDLED", False) :
# Module flags
################################################################################
- if env["SCONS_STAGE"] == "flags" :
- env["HAVE_LUA"] = True
- cppdefines = []
- if not env["optimize"] :
- cppdefines.append("LUA_USE_APICHECK")
- if env["PLATFORM"] == "win32" :
- pass
- elif env["PLATFORM"] == "darwin" :
- cppdefines += ["LUA_USE_POSIX", "LUA_USE_DLOPEN"]
- else :
- cppdefines += ["LUA_USE_POSIX", "LUA_USE_DLOPEN"]
+ if env["SCONS_STAGE"] == "flags" :
+ env["HAVE_LUA"] = True
+ cppdefines = []
+ if not env["optimize"] :
+ cppdefines.append("LUA_USE_APICHECK")
+ if env["PLATFORM"] == "win32" :
+ pass
+ elif env["PLATFORM"] == "darwin" :
+ cppdefines += ["LUA_USE_POSIX", "LUA_USE_DLOPEN"]
+ else :
+ cppdefines += ["LUA_USE_POSIX", "LUA_USE_DLOPEN"]
- env["LUA_FLAGS"] = {
- "CPPDEFINES": cppdefines,
- "CPPPATH": [Dir("src")],
- "LIBPATH": [Dir(".")],
- "LIBS": ["Swiften_Lua"],
- }
+ env["LUA_FLAGS"] = {
+ "CPPDEFINES": cppdefines,
+ "CPPPATH": [Dir("src")],
+ "LIBPATH": [Dir(".")],
+ "LIBS": ["Swiften_Lua"],
+ }
################################################################################
# Build
################################################################################
- if env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
+ if env["SCONS_STAGE"] == "build" :
+ myenv = env.Clone()
- # Remove warn flags
- myenv.Replace(CCFLAGS = [flag for flag in env["CCFLAGS"] if not flag.startswith("-W")])
- if "clang" in env["CC"] :
- myenv.Append(CCFLAGS = ["-Wno-unknown-warning-option", "-Wno-empty-body"])
+ # Remove warn flags
+ myenv.Replace(CCFLAGS = [flag for flag in env["CCFLAGS"] if not flag.startswith("-W")])
+ if "clang" in env["CC"] :
+ myenv.Append(CCFLAGS = ["-Wno-unknown-warning-option", "-Wno-empty-body"])
- myenv.MergeFlags(myenv["LUA_FLAGS"])
- myenv.StaticLibrary("Swiften_Lua", [
- "src/lapi.c",
- "src/lcode.c",
- "src/ldebug.c",
- "src/ldo.c",
- "src/ldump.c",
- "src/lfunc.c",
- "src/lgc.c",
- "src/llex.c",
- "src/lmem.c",
- "src/lobject.c",
- "src/lopcodes.c",
- "src/lparser.c",
- "src/lstate.c",
- "src/lstring.c",
- "src/ltable.c",
- "src/ltm.c",
- "src/lundump.c",
- "src/lvm.c",
- "src/lzio.c",
- "src/lauxlib.c",
- "src/lbaselib.c",
- "src/ldblib.c",
- "src/liolib.c",
- "src/lmathlib.c",
- "src/loslib.c",
- "src/ltablib.c",
- "src/lstrlib.c",
- "src/loadlib.c",
- ])
+ myenv.MergeFlags(myenv["LUA_FLAGS"])
+ myenv.StaticLibrary("Swiften_Lua", [
+ "src/lapi.c",
+ "src/lcode.c",
+ "src/ldebug.c",
+ "src/ldo.c",
+ "src/ldump.c",
+ "src/lfunc.c",
+ "src/lgc.c",
+ "src/llex.c",
+ "src/lmem.c",
+ "src/lobject.c",
+ "src/lopcodes.c",
+ "src/lparser.c",
+ "src/lstate.c",
+ "src/lstring.c",
+ "src/ltable.c",
+ "src/ltm.c",
+ "src/lundump.c",
+ "src/lvm.c",
+ "src/lzio.c",
+ "src/lauxlib.c",
+ "src/lbaselib.c",
+ "src/ldblib.c",
+ "src/liolib.c",
+ "src/lmathlib.c",
+ "src/loslib.c",
+ "src/ltablib.c",
+ "src/lstrlib.c",
+ "src/loadlib.c",
+ ])
- lua_env = myenv.Clone()
- lua_env.MergeFlags(lua_env["LUA_FLAGS"])
- if lua_env.get("HAVE_READLINE", False) :
- lua_env.Append(CPPDEFINES = ["LUA_USE_READLINE"])
- lua_env.MergeFlags(lua_env["READLINE_FLAGS"])
- lua_env.MergeFlags(myenv["PLATFORM_FLAGS"])
- lua_env.Program("lua", [
- "src/linit.c",
- "src/lua.c",
- ])
+ lua_env = myenv.Clone()
+ lua_env.MergeFlags(lua_env["LUA_FLAGS"])
+ if lua_env.get("HAVE_READLINE", False) :
+ lua_env.Append(CPPDEFINES = ["LUA_USE_READLINE"])
+ lua_env.MergeFlags(lua_env["READLINE_FLAGS"])
+ lua_env.MergeFlags(myenv["PLATFORM_FLAGS"])
+ lua_env.Program("lua", [
+ "src/linit.c",
+ "src/lua.c",
+ ])
diff --git a/3rdParty/OpenSSL/SConscript b/3rdParty/OpenSSL/SConscript
index 6af3d49..c95ea05 100644
--- a/3rdParty/OpenSSL/SConscript
+++ b/3rdParty/OpenSSL/SConscript
@@ -3,658 +3,658 @@ Import("env", "conf_env")
openssl_bundle_dir = "openssl"
if env.get("OPENSSL_BUNDLED", False) :
- if env["SCONS_STAGE"] == "flags" :
- env["OPENSSL_FLAGS"] = {
- "CPPPATH": [Dir(openssl_bundle_dir + "/include")],
- "LIBPATH": [Dir(".")],
- "LIBS": ["ssl", "crypto"]
- }
+ if env["SCONS_STAGE"] == "flags" :
+ env["OPENSSL_FLAGS"] = {
+ "CPPPATH": [Dir(openssl_bundle_dir + "/include")],
+ "LIBPATH": [Dir(".")],
+ "LIBS": ["ssl", "crypto"]
+ }
- if env["SCONS_STAGE"] == "build" :
- openssl_env = env.Clone()
- openssl_env["OPENSSL_BUNDLE_DIR"] = openssl_bundle_dir
- openssl_env.Replace(CCFLAGS = [flag for flag in env["CCFLAGS"] if flag not in ["-W", "-Wall"]])
- openssl_env.Append(CPPPATH = [
- "$OPENSSL_BUNDLE_DIR",
- "$OPENSSL_BUNDLE_DIR/crypto",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1",
- "$OPENSSL_BUNDLE_DIR/crypto/evp",
- "$OPENSSL_BUNDLE_DIR/crypto/modes",
- "$OPENSSL_BUNDLE_DIR/include"
- ])
- if env["PLATFORM"] == "win32" :
- openssl_env.Append(CPPDEFINES = ["OPENSSL_THREADS", "_REENTRANT", "L_ENDIAN", "OPENSSL_SYSNAME_WIN32", "WIN32_LEAN_AND_MEAN"])
- else :
- openssl_env.Append(CPPDEFINES = ["OPENSSL_THREADS", "_REENTRANT", "DSO_DLFCN", "HAVE_DLFCN_H", "L_ENDIAN"])
+ if env["SCONS_STAGE"] == "build" :
+ openssl_env = env.Clone()
+ openssl_env["OPENSSL_BUNDLE_DIR"] = openssl_bundle_dir
+ openssl_env.Replace(CCFLAGS = [flag for flag in env["CCFLAGS"] if flag not in ["-W", "-Wall"]])
+ openssl_env.Append(CPPPATH = [
+ "$OPENSSL_BUNDLE_DIR",
+ "$OPENSSL_BUNDLE_DIR/crypto",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp",
+ "$OPENSSL_BUNDLE_DIR/crypto/modes",
+ "$OPENSSL_BUNDLE_DIR/include"
+ ])
+ if env["PLATFORM"] == "win32" :
+ openssl_env.Append(CPPDEFINES = ["OPENSSL_THREADS", "_REENTRANT", "L_ENDIAN", "OPENSSL_SYSNAME_WIN32", "WIN32_LEAN_AND_MEAN"])
+ else :
+ openssl_env.Append(CPPDEFINES = ["OPENSSL_THREADS", "_REENTRANT", "DSO_DLFCN", "HAVE_DLFCN_H", "L_ENDIAN"])
- # Detect 32/64 bit
- conf = Configure(conf_env)
- if conf.CheckDeclaration("__LP64__") :
- openssl_env.Append(CPPDEFINES = [("DES_LONG", "unsigned int"), ("MD32_REG_T", "int")])
- else :
- openssl_env.Append(CPPDEFINES = [("DES_LONG", "unsigned long")])
- conf.Finish()
+ # Detect 32/64 bit
+ conf = Configure(conf_env)
+ if conf.CheckDeclaration("__LP64__") :
+ openssl_env.Append(CPPDEFINES = [("DES_LONG", "unsigned int"), ("MD32_REG_T", "int")])
+ else :
+ openssl_env.Append(CPPDEFINES = [("DES_LONG", "unsigned long")])
+ conf.Finish()
- # case-sensitive sorted list of OpenSSL objects for openssl-1.0.1j
- env["OPENSSL_OBJECTS"] = openssl_env.SwiftenObject([
- "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_cbc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_cfb.c",
- "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_core.c",
- "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_ctr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_ecb.c",
- "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_ige.c",
- "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_misc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_ofb.c",
- "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_wrap.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_bitstr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_bool.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_bytes.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_d2i_fp.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_digest.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_dup.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_enum.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_gentm.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_i2d_fp.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_int.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_mbstr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_object.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_octet.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_print.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_set.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_sign.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_strex.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_strnid.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_time.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_type.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_utctm.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_utf8.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_verify.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/ameth_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/asn1_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/asn1_gen.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/asn1_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/asn1_par.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/asn_mime.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/asn_moid.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/asn_pack.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/bio_asn1.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/bio_ndef.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/d2i_pr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/d2i_pu.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/evp_asn1.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/f_enum.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/f_int.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/f_string.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/i2d_pr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/i2d_pu.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/n_pkey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/nsseq.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/p5_pbe.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/p5_pbev2.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/p8_pkey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/t_bitst.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/t_crl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/t_pkey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/t_req.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/t_spki.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/t_x509.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/t_x509a.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/tasn_dec.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/tasn_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/tasn_fre.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/tasn_new.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/tasn_prn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/tasn_typ.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/tasn_utl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_algor.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_attrib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_bignum.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_crl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_exten.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_info.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_long.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_name.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_nx509.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_pkey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_pubkey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_req.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_sig.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_spki.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_val.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_x509.c",
- "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_x509a.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bf/bf_cfb64.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bf/bf_ecb.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bf/bf_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bf/bf_ofb64.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bf/bf_skey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/b_dump.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/b_print.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/b_sock.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bf_buff.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bf_nbio.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bf_null.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bio_cb.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bio_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bio_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_acpt.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_bio.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_conn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_dgram.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_fd.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_file.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_log.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_mem.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_null.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_sock.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_add.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_asm.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_blind.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_const.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_ctx.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_depr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_div.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_exp.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_exp2.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_gcd.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_gf2m.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_kron.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_mod.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_mont.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_mpi.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_mul.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_nist.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_prime.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_print.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_rand.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_recp.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_shift.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_sqr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_sqrt.c",
- "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_word.c",
- "$OPENSSL_BUNDLE_DIR/crypto/buffer/buf_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/buffer/buf_str.c",
- "$OPENSSL_BUNDLE_DIR/crypto/buffer/buffer.c",
- "$OPENSSL_BUNDLE_DIR/crypto/camellia/camellia.c",
- "$OPENSSL_BUNDLE_DIR/crypto/camellia/cmll_cbc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/camellia/cmll_cfb.c",
- "$OPENSSL_BUNDLE_DIR/crypto/camellia/cmll_ctr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/camellia/cmll_ecb.c",
- "$OPENSSL_BUNDLE_DIR/crypto/camellia/cmll_misc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/camellia/cmll_ofb.c",
- "$OPENSSL_BUNDLE_DIR/crypto/camellia/cmll_utl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cast/c_cfb64.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cast/c_ecb.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cast/c_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cast/c_ofb64.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cast/c_skey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cmac/cm_ameth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cmac/cm_pmeth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cmac/cmac.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_asn1.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_att.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_cd.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_dd.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_env.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_ess.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_io.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_pwri.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_sd.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_smime.c",
- "$OPENSSL_BUNDLE_DIR/crypto/comp/c_rle.c",
- "$OPENSSL_BUNDLE_DIR/crypto/comp/c_zlib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/comp/comp_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/comp/comp_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/conf/conf_api.c",
- "$OPENSSL_BUNDLE_DIR/crypto/conf/conf_def.c",
- "$OPENSSL_BUNDLE_DIR/crypto/conf/conf_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/conf/conf_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/conf/conf_mall.c",
- "$OPENSSL_BUNDLE_DIR/crypto/conf/conf_mod.c",
- "$OPENSSL_BUNDLE_DIR/crypto/conf/conf_sap.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cpt_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cryptlib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/cversion.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/cbc_cksm.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/cbc_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/cfb64ede.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/cfb64enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/cfb_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/des_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/des_old.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/des_old2.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/ecb3_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/ecb_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/ede_cbcm_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/enc_read.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/enc_writ.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/fcrypt.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/fcrypt_b.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/ofb64ede.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/ofb64enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/ofb_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/pcbc_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/qud_cksm.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/rand_key.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/read2pwd.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/rpc_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/set_key.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/str2key.c",
- "$OPENSSL_BUNDLE_DIR/crypto/des/xcbc_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_ameth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_asn1.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_check.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_depr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_gen.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_key.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_pmeth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_prn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_ameth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_asn1.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_depr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_gen.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_key.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_ossl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_pmeth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_prn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_sign.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_vrf.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_beos.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_dl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_dlfcn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_null.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_openssl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_vms.c",
- "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_win32.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ebcdic.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec2_mult.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec2_oct.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec2_smpl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_ameth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_asn1.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_check.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_curve.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_cvt.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_key.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_mult.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_oct.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_pmeth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_print.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/eck_prn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ecp_mont.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ecp_nist.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ecp_oct.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ec/ecp_smpl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ecdh/ech_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ecdh/ech_key.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ecdh/ech_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ecdh/ech_ossl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ecdsa/ecs_asn1.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ecdsa/ecs_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ecdsa/ecs_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ecdsa/ecs_ossl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ecdsa/ecs_sign.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ecdsa/ecs_vrf.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_all.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_cnf.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_cryptodev.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_ctrl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_dyn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_fat.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_init.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_list.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_openssl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_pkey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_table.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_asnmth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_cipher.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_dh.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_digest.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_dsa.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_ecdh.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_ecdsa.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_pkmeth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_rand.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_rsa.c",
- "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_store.c",
- "$OPENSSL_BUNDLE_DIR/crypto/err/err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/err/err_all.c",
- "$OPENSSL_BUNDLE_DIR/crypto/err/err_prn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/bio_b64.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/bio_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/bio_md.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/bio_ok.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/c_all.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/c_allc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/c_alld.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/digest.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_aes.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_aes_cbc_hmac_sha1.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_bf.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_camellia.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_cast.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_des.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_des3.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_idea.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_null.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_old.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_rc2.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_rc4.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_rc4_hmac_md5.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_rc5.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_seed.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/e_xcbc_d.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/encode.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/evp_acnf.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/evp_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/evp_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/evp_key.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/evp_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/evp_pbe.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/evp_pkey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/m_dss.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/m_dss1.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/m_ecdsa.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/m_md2.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/m_md4.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/m_md5.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/m_mdc2.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/m_null.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/m_ripemd.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/m_sha.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/m_sha1.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/m_sigver.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/m_wp.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/names.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/p5_crpt.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/p5_crpt2.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/p_dec.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/p_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/p_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/p_open.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/p_seal.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/p_sign.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/p_verify.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/pmeth_fn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/pmeth_gn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/evp/pmeth_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ex_data.c",
- "$OPENSSL_BUNDLE_DIR/crypto/hmac/hm_ameth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/hmac/hm_pmeth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/hmac/hmac.c",
- "$OPENSSL_BUNDLE_DIR/crypto/idea/i_cbc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/idea/i_cfb64.c",
- "$OPENSSL_BUNDLE_DIR/crypto/idea/i_ecb.c",
- "$OPENSSL_BUNDLE_DIR/crypto/idea/i_ofb64.c",
- "$OPENSSL_BUNDLE_DIR/crypto/idea/i_skey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/krb5/krb5_asn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/lhash/lh_stats.c",
- "$OPENSSL_BUNDLE_DIR/crypto/lhash/lhash.c",
- "$OPENSSL_BUNDLE_DIR/crypto/md4/md4_dgst.c",
- "$OPENSSL_BUNDLE_DIR/crypto/md4/md4_one.c",
- "$OPENSSL_BUNDLE_DIR/crypto/md5/md5_dgst.c",
- "$OPENSSL_BUNDLE_DIR/crypto/md5/md5_one.c",
- "$OPENSSL_BUNDLE_DIR/crypto/mdc2/mdc2_one.c",
- "$OPENSSL_BUNDLE_DIR/crypto/mdc2/mdc2dgst.c",
- "$OPENSSL_BUNDLE_DIR/crypto/mem.c",
- "$OPENSSL_BUNDLE_DIR/crypto/mem_clr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/mem_dbg.c",
- "$OPENSSL_BUNDLE_DIR/crypto/modes/cbc128.c",
- "$OPENSSL_BUNDLE_DIR/crypto/modes/ccm128.c",
- "$OPENSSL_BUNDLE_DIR/crypto/modes/cfb128.c",
- "$OPENSSL_BUNDLE_DIR/crypto/modes/ctr128.c",
- "$OPENSSL_BUNDLE_DIR/crypto/modes/cts128.c",
- "$OPENSSL_BUNDLE_DIR/crypto/modes/gcm128.c",
- "$OPENSSL_BUNDLE_DIR/crypto/modes/ofb128.c",
- "$OPENSSL_BUNDLE_DIR/crypto/modes/xts128.c",
- "$OPENSSL_BUNDLE_DIR/crypto/o_dir.c",
- "$OPENSSL_BUNDLE_DIR/crypto/o_init.c",
- "$OPENSSL_BUNDLE_DIR/crypto/o_str.c",
- "$OPENSSL_BUNDLE_DIR/crypto/o_time.c",
- "$OPENSSL_BUNDLE_DIR/crypto/objects/o_names.c",
- "$OPENSSL_BUNDLE_DIR/crypto/objects/obj_dat.c",
- "$OPENSSL_BUNDLE_DIR/crypto/objects/obj_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/objects/obj_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/objects/obj_xref.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_asn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_cl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_ext.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_ht.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_prn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_srv.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_vfy.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_all.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_info.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_oth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_pk8.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_pkey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_seal.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_sign.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_x509.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_xaux.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pem/pvkfmt.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_add.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_asn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_attr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_crpt.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_crt.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_decr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_init.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_key.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_kiss.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_mutl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_npas.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_p8d.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_p8e.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_utl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/pk12err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/bio_pk7.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/pk7_asn1.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/pk7_attr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/pk7_doit.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/pk7_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/pk7_mime.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/pk7_smime.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/pkcs7err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/pqueue/pqueue.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rand/md_rand.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rand/rand_egd.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rand/rand_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rand/rand_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rand/rand_nw.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rand/rand_os2.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rand/rand_unix.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rand/rand_win.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rand/randfile.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rc2/rc2_cbc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rc2/rc2_ecb.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rc2/rc2_skey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rc2/rc2cfb64.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rc2/rc2ofb64.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rc4/rc4_enc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rc4/rc4_skey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rc4/rc4_utl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ripemd/rmd_dgst.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ripemd/rmd_one.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_ameth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_asn1.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_chk.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_crpt.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_depr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_eay.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_gen.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_none.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_null.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_oaep.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_pk1.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_pmeth.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_prn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_pss.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_saos.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_sign.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_ssl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_x931.c",
- "$OPENSSL_BUNDLE_DIR/crypto/seed/seed.c",
- "$OPENSSL_BUNDLE_DIR/crypto/seed/seed_cbc.c",
- "$OPENSSL_BUNDLE_DIR/crypto/seed/seed_cfb.c",
- "$OPENSSL_BUNDLE_DIR/crypto/seed/seed_ecb.c",
- "$OPENSSL_BUNDLE_DIR/crypto/seed/seed_ofb.c",
- "$OPENSSL_BUNDLE_DIR/crypto/sha/sha1_one.c",
- "$OPENSSL_BUNDLE_DIR/crypto/sha/sha1dgst.c",
- "$OPENSSL_BUNDLE_DIR/crypto/sha/sha256.c",
- "$OPENSSL_BUNDLE_DIR/crypto/sha/sha512.c",
- "$OPENSSL_BUNDLE_DIR/crypto/sha/sha_dgst.c",
- "$OPENSSL_BUNDLE_DIR/crypto/sha/sha_one.c",
- "$OPENSSL_BUNDLE_DIR/crypto/srp/srp_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/srp/srp_vfy.c",
- "$OPENSSL_BUNDLE_DIR/crypto/stack/stack.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_asn1.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_conf.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_req_print.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_req_utils.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_rsp_print.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_rsp_sign.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_rsp_utils.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_rsp_verify.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_verify_ctx.c",
- "$OPENSSL_BUNDLE_DIR/crypto/txt_db/txt_db.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ui/ui_compat.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ui/ui_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ui/ui_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ui/ui_openssl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/ui/ui_util.c",
- "$OPENSSL_BUNDLE_DIR/crypto/uid.c",
- "$OPENSSL_BUNDLE_DIR/crypto/whrlpool/wp_block.c",
- "$OPENSSL_BUNDLE_DIR/crypto/whrlpool/wp_dgst.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/by_dir.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/by_file.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_att.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_cmp.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_d2.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_def.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_err.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_ext.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_lu.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_obj.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_r2x.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_req.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_set.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_trs.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_txt.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_v3.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_vfy.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_vpm.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509cset.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509name.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509rset.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509spki.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x509type.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509/x_all.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/pcy_cache.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/pcy_data.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/pcy_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/pcy_map.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/pcy_node.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/pcy_tree.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_addr.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_akey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_akeya.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_alt.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_asid.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_bcons.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_bitst.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_conf.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_cpols.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_crld.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_enum.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_extku.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_genn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_ia5.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_info.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_int.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_lib.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_ncons.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_ocsp.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_pci.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_pcia.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_pcons.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_pku.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_pmaps.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_prn.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_purp.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_skey.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_sxnet.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_utl.c",
- "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3err.c",
- "$OPENSSL_BUNDLE_DIR/ssl/bio_ssl.c",
- "$OPENSSL_BUNDLE_DIR/ssl/d1_both.c",
- "$OPENSSL_BUNDLE_DIR/ssl/d1_clnt.c",
- "$OPENSSL_BUNDLE_DIR/ssl/d1_enc.c",
- "$OPENSSL_BUNDLE_DIR/ssl/d1_lib.c",
- "$OPENSSL_BUNDLE_DIR/ssl/d1_meth.c",
- "$OPENSSL_BUNDLE_DIR/ssl/d1_pkt.c",
- "$OPENSSL_BUNDLE_DIR/ssl/d1_srtp.c",
- "$OPENSSL_BUNDLE_DIR/ssl/d1_srvr.c",
- "$OPENSSL_BUNDLE_DIR/ssl/kssl.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s23_clnt.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s23_lib.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s23_meth.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s23_pkt.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s23_srvr.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s2_clnt.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s2_enc.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s2_lib.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s2_meth.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s2_pkt.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s2_srvr.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s3_both.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s3_cbc.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s3_clnt.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s3_enc.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s3_lib.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s3_meth.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s3_pkt.c",
- "$OPENSSL_BUNDLE_DIR/ssl/s3_srvr.c",
- "$OPENSSL_BUNDLE_DIR/ssl/ssl_algs.c",
- "$OPENSSL_BUNDLE_DIR/ssl/ssl_asn1.c",
- "$OPENSSL_BUNDLE_DIR/ssl/ssl_cert.c",
- "$OPENSSL_BUNDLE_DIR/ssl/ssl_ciph.c",
- "$OPENSSL_BUNDLE_DIR/ssl/ssl_err.c",
- "$OPENSSL_BUNDLE_DIR/ssl/ssl_err2.c",
- "$OPENSSL_BUNDLE_DIR/ssl/ssl_lib.c",
- "$OPENSSL_BUNDLE_DIR/ssl/ssl_rsa.c",
- "$OPENSSL_BUNDLE_DIR/ssl/ssl_sess.c",
- "$OPENSSL_BUNDLE_DIR/ssl/ssl_stat.c",
- "$OPENSSL_BUNDLE_DIR/ssl/ssl_txt.c",
- "$OPENSSL_BUNDLE_DIR/ssl/t1_clnt.c",
- "$OPENSSL_BUNDLE_DIR/ssl/t1_enc.c",
- "$OPENSSL_BUNDLE_DIR/ssl/t1_lib.c",
- "$OPENSSL_BUNDLE_DIR/ssl/t1_meth.c",
- "$OPENSSL_BUNDLE_DIR/ssl/t1_reneg.c",
- "$OPENSSL_BUNDLE_DIR/ssl/t1_srvr.c",
- "$OPENSSL_BUNDLE_DIR/ssl/tls_srp.c",
- ])
- openssl_env.WriteVal("$OPENSSL_BUNDLE_DIR/crypto/buildinf.h", openssl_env.Value("#define CFLAGS \"\"\n#define PLATFORM \"-\"\n#define DATE \"-\""))
+ # case-sensitive sorted list of OpenSSL objects for openssl-1.0.1j
+ env["OPENSSL_OBJECTS"] = openssl_env.SwiftenObject([
+ "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_cbc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_cfb.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_core.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_ctr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_ecb.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_ige.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_misc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_ofb.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/aes/aes_wrap.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_bitstr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_bool.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_bytes.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_d2i_fp.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_digest.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_dup.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_enum.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_gentm.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_i2d_fp.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_int.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_mbstr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_object.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_octet.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_print.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_set.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_sign.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_strex.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_strnid.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_time.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_type.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_utctm.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_utf8.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/a_verify.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/ameth_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/asn1_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/asn1_gen.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/asn1_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/asn1_par.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/asn_mime.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/asn_moid.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/asn_pack.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/bio_asn1.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/bio_ndef.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/d2i_pr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/d2i_pu.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/evp_asn1.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/f_enum.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/f_int.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/f_string.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/i2d_pr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/i2d_pu.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/n_pkey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/nsseq.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/p5_pbe.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/p5_pbev2.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/p8_pkey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/t_bitst.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/t_crl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/t_pkey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/t_req.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/t_spki.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/t_x509.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/t_x509a.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/tasn_dec.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/tasn_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/tasn_fre.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/tasn_new.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/tasn_prn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/tasn_typ.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/tasn_utl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_algor.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_attrib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_bignum.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_crl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_exten.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_info.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_long.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_name.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_nx509.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_pkey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_pubkey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_req.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_sig.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_spki.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_val.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_x509.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/asn1/x_x509a.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bf/bf_cfb64.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bf/bf_ecb.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bf/bf_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bf/bf_ofb64.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bf/bf_skey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/b_dump.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/b_print.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/b_sock.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bf_buff.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bf_nbio.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bf_null.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bio_cb.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bio_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bio_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_acpt.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_bio.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_conn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_dgram.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_fd.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_file.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_log.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_mem.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_null.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bio/bss_sock.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_add.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_asm.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_blind.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_const.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_ctx.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_depr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_div.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_exp.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_exp2.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_gcd.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_gf2m.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_kron.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_mod.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_mont.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_mpi.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_mul.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_nist.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_prime.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_print.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_rand.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_recp.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_shift.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_sqr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_sqrt.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/bn/bn_word.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/buffer/buf_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/buffer/buf_str.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/buffer/buffer.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/camellia/camellia.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/camellia/cmll_cbc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/camellia/cmll_cfb.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/camellia/cmll_ctr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/camellia/cmll_ecb.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/camellia/cmll_misc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/camellia/cmll_ofb.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/camellia/cmll_utl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cast/c_cfb64.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cast/c_ecb.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cast/c_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cast/c_ofb64.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cast/c_skey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cmac/cm_ameth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cmac/cm_pmeth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cmac/cmac.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_asn1.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_att.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_cd.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_dd.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_env.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_ess.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_io.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_pwri.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_sd.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cms/cms_smime.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/comp/c_rle.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/comp/c_zlib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/comp/comp_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/comp/comp_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/conf/conf_api.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/conf/conf_def.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/conf/conf_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/conf/conf_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/conf/conf_mall.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/conf/conf_mod.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/conf/conf_sap.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cpt_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cryptlib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/cversion.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/cbc_cksm.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/cbc_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/cfb64ede.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/cfb64enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/cfb_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/des_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/des_old.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/des_old2.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/ecb3_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/ecb_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/ede_cbcm_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/enc_read.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/enc_writ.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/fcrypt.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/fcrypt_b.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/ofb64ede.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/ofb64enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/ofb_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/pcbc_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/qud_cksm.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/rand_key.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/read2pwd.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/rpc_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/set_key.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/str2key.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/des/xcbc_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_ameth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_asn1.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_check.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_depr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_gen.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_key.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_pmeth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dh/dh_prn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_ameth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_asn1.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_depr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_gen.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_key.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_ossl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_pmeth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_prn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_sign.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dsa/dsa_vrf.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_beos.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_dl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_dlfcn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_null.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_openssl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_vms.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/dso/dso_win32.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ebcdic.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec2_mult.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec2_oct.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec2_smpl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_ameth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_asn1.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_check.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_curve.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_cvt.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_key.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_mult.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_oct.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_pmeth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ec_print.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/eck_prn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ecp_mont.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ecp_nist.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ecp_oct.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ec/ecp_smpl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ecdh/ech_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ecdh/ech_key.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ecdh/ech_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ecdh/ech_ossl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ecdsa/ecs_asn1.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ecdsa/ecs_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ecdsa/ecs_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ecdsa/ecs_ossl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ecdsa/ecs_sign.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ecdsa/ecs_vrf.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_all.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_cnf.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_cryptodev.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_ctrl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_dyn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_fat.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_init.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_list.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_openssl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_pkey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/eng_table.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_asnmth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_cipher.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_dh.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_digest.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_dsa.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_ecdh.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_ecdsa.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_pkmeth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_rand.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_rsa.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/engine/tb_store.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/err/err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/err/err_all.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/err/err_prn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/bio_b64.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/bio_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/bio_md.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/bio_ok.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/c_all.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/c_allc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/c_alld.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/digest.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_aes.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_aes_cbc_hmac_sha1.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_bf.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_camellia.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_cast.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_des.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_des3.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_idea.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_null.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_old.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_rc2.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_rc4.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_rc4_hmac_md5.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_rc5.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_seed.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/e_xcbc_d.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/encode.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/evp_acnf.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/evp_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/evp_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/evp_key.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/evp_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/evp_pbe.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/evp_pkey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/m_dss.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/m_dss1.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/m_ecdsa.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/m_md2.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/m_md4.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/m_md5.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/m_mdc2.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/m_null.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/m_ripemd.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/m_sha.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/m_sha1.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/m_sigver.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/m_wp.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/names.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/p5_crpt.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/p5_crpt2.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/p_dec.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/p_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/p_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/p_open.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/p_seal.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/p_sign.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/p_verify.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/pmeth_fn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/pmeth_gn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/evp/pmeth_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ex_data.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/hmac/hm_ameth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/hmac/hm_pmeth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/hmac/hmac.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/idea/i_cbc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/idea/i_cfb64.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/idea/i_ecb.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/idea/i_ofb64.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/idea/i_skey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/krb5/krb5_asn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/lhash/lh_stats.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/lhash/lhash.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/md4/md4_dgst.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/md4/md4_one.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/md5/md5_dgst.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/md5/md5_one.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/mdc2/mdc2_one.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/mdc2/mdc2dgst.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/mem.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/mem_clr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/mem_dbg.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/modes/cbc128.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/modes/ccm128.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/modes/cfb128.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/modes/ctr128.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/modes/cts128.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/modes/gcm128.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/modes/ofb128.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/modes/xts128.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/o_dir.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/o_init.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/o_str.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/o_time.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/objects/o_names.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/objects/obj_dat.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/objects/obj_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/objects/obj_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/objects/obj_xref.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_asn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_cl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_ext.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_ht.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_prn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_srv.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ocsp/ocsp_vfy.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_all.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_info.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_oth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_pk8.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_pkey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_seal.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_sign.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_x509.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pem/pem_xaux.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pem/pvkfmt.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_add.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_asn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_attr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_crpt.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_crt.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_decr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_init.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_key.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_kiss.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_mutl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_npas.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_p8d.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_p8e.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/p12_utl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs12/pk12err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/bio_pk7.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/pk7_asn1.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/pk7_attr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/pk7_doit.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/pk7_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/pk7_mime.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/pk7_smime.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pkcs7/pkcs7err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/pqueue/pqueue.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rand/md_rand.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rand/rand_egd.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rand/rand_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rand/rand_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rand/rand_nw.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rand/rand_os2.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rand/rand_unix.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rand/rand_win.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rand/randfile.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rc2/rc2_cbc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rc2/rc2_ecb.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rc2/rc2_skey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rc2/rc2cfb64.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rc2/rc2ofb64.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rc4/rc4_enc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rc4/rc4_skey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rc4/rc4_utl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ripemd/rmd_dgst.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ripemd/rmd_one.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_ameth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_asn1.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_chk.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_crpt.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_depr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_eay.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_gen.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_none.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_null.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_oaep.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_pk1.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_pmeth.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_prn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_pss.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_saos.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_sign.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_ssl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/rsa/rsa_x931.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/seed/seed.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/seed/seed_cbc.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/seed/seed_cfb.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/seed/seed_ecb.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/seed/seed_ofb.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/sha/sha1_one.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/sha/sha1dgst.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/sha/sha256.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/sha/sha512.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/sha/sha_dgst.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/sha/sha_one.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/srp/srp_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/srp/srp_vfy.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/stack/stack.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_asn1.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_conf.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_req_print.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_req_utils.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_rsp_print.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_rsp_sign.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_rsp_utils.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_rsp_verify.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ts/ts_verify_ctx.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/txt_db/txt_db.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ui/ui_compat.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ui/ui_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ui/ui_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ui/ui_openssl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/ui/ui_util.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/uid.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/whrlpool/wp_block.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/whrlpool/wp_dgst.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/by_dir.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/by_file.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_att.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_cmp.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_d2.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_def.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_err.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_ext.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_lu.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_obj.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_r2x.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_req.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_set.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_trs.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_txt.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_v3.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_vfy.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509_vpm.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509cset.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509name.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509rset.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509spki.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x509type.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509/x_all.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/pcy_cache.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/pcy_data.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/pcy_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/pcy_map.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/pcy_node.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/pcy_tree.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_addr.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_akey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_akeya.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_alt.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_asid.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_bcons.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_bitst.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_conf.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_cpols.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_crld.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_enum.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_extku.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_genn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_ia5.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_info.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_int.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_lib.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_ncons.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_ocsp.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_pci.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_pcia.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_pcons.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_pku.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_pmaps.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_prn.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_purp.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_skey.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_sxnet.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3_utl.c",
+ "$OPENSSL_BUNDLE_DIR/crypto/x509v3/v3err.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/bio_ssl.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/d1_both.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/d1_clnt.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/d1_enc.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/d1_lib.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/d1_meth.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/d1_pkt.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/d1_srtp.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/d1_srvr.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/kssl.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s23_clnt.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s23_lib.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s23_meth.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s23_pkt.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s23_srvr.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s2_clnt.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s2_enc.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s2_lib.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s2_meth.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s2_pkt.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s2_srvr.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s3_both.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s3_cbc.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s3_clnt.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s3_enc.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s3_lib.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s3_meth.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s3_pkt.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/s3_srvr.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/ssl_algs.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/ssl_asn1.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/ssl_cert.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/ssl_ciph.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/ssl_err.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/ssl_err2.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/ssl_lib.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/ssl_rsa.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/ssl_sess.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/ssl_stat.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/ssl_txt.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/t1_clnt.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/t1_enc.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/t1_lib.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/t1_meth.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/t1_reneg.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/t1_srvr.c",
+ "$OPENSSL_BUNDLE_DIR/ssl/tls_srp.c",
+ ])
+ openssl_env.WriteVal("$OPENSSL_BUNDLE_DIR/crypto/buildinf.h", openssl_env.Value("#define CFLAGS \"\"\n#define PLATFORM \"-\"\n#define DATE \"-\""))
diff --git a/3rdParty/SQLite/SConscript b/3rdParty/SQLite/SConscript
index ffa8946..1f4bcd7 100644
--- a/3rdParty/SQLite/SConscript
+++ b/3rdParty/SQLite/SConscript
@@ -6,14 +6,14 @@ if env.get("SQLITE_BUNDLED", False) :
# Flags
################################################################################
- if env["SCONS_STAGE"] == "flags" :
- env["SQLITE_FLAGS"] = {
- "CPPPATH": [Dir(".")],
- "LIBPATH": [Dir(".")],
- }
+ if env["SCONS_STAGE"] == "flags" :
+ env["SQLITE_FLAGS"] = {
+ "CPPPATH": [Dir(".")],
+ "LIBPATH": [Dir(".")],
+ }
- if env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
- myenv.Replace(CCFLAGS = [flag for flag in env["CCFLAGS"] if flag not in ["-W", "-Wall"]])
- myenv.Append(CPPPATH = ["."])
- env["SQLITE_OBJECTS"] = myenv.SwiftenObject(["sqlite3.c"])
+ if env["SCONS_STAGE"] == "build" :
+ myenv = env.Clone()
+ myenv.Replace(CCFLAGS = [flag for flag in env["CCFLAGS"] if flag not in ["-W", "-Wall"]])
+ myenv.Append(CPPPATH = ["."])
+ env["SQLITE_OBJECTS"] = myenv.SwiftenObject(["sqlite3.c"])
diff --git a/3rdParty/Snarl/SConscript b/3rdParty/Snarl/SConscript
deleted file mode 100644
index 8733390..0000000
--- a/3rdParty/Snarl/SConscript
+++ /dev/null
@@ -1,18 +0,0 @@
-Import("env")
-
-################################################################################
-# Flags
-################################################################################
-
-if env.get("HAVE_SNARL", False) :
- if env["SCONS_STAGE"] == "flags" :
- env["SNARL_FLAGS"] = {
- "CPPPATH": [Dir(".")],
- "LIBPATH": [Dir(".")],
- "LIBS": ["Snarl"],
- }
-
- elif env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
- myenv.Replace(CCFLAGS = [flag for flag in env["CCFLAGS"] if flag not in ["-W", "-Wall"]])
- myenv.StaticLibrary("Snarl", ["SnarlInterface.cpp"], CPPPATH = ["."])
diff --git a/3rdParty/Snarl/SnarlInterface.cpp b/3rdParty/Snarl/SnarlInterface.cpp
deleted file mode 100644
index 0ae0b37..0000000
--- a/3rdParty/Snarl/SnarlInterface.cpp
+++ /dev/null
@@ -1,517 +0,0 @@
-/// <summary>
-/// Snarl C++ interface implementation
-///
-/// Written and maintained by Toke Noer Nøttrup (toke@noer.it)
-///
-/// Please note the following changes compared to the VB6 (official API) dokumentation:
-/// - Function names doesn't have the prefix "sn". Naming of constants and variables are
-/// generally changed to follow Microsoft C# standard. This naming convention is kept for
-/// the C++ version, to keep them alike.
-/// - Grouped variables like SNARL_LAUNCHED, SNARL_QUIT is enums in SnarlEnums namespace.
-/// - Message events like SNARL_NOTIFICATION_CLICKED, is found in SnarlEnums::MessageEvent.
-/// - Please note that string functions return NULL when they fail and not an empty string.
-/// - Some functions in the VB API takes an appToken as first parameter. This token is a
-/// member variable in C++ version, so it is omitted from the functions.
-/// (Always call RegisterApp as first function!)
-/// - Functions manipulating messages (Update, Hide etc.) still takes a message token as
-/// parameter, but you can get the last message token calling GetLastMsgToken();
-/// Example: snarl.Hide(snarl.GetLastMsgToken());
-///
-/// The functions in SnarlInterface both have ANSI(UTF8) and UNICODE versions.
-/// If the LPCWSTR (unicode) version of the functions are called, the strings
-/// are converted to UTF8 by SnarlInterface before sent to Snarl. So using the
-/// ANSI/UTF8/LPCSTR versions of the functions are faster!
-///
-/// Funtions special to C++ V41 API compared to VB version:
-/// GetLastMsgToken()
-/// GetAppPath()
-/// GetIconsPath()
-/// </summary>
-///----------------------------------------------------------------------------
-/// <example>
-/// SnarlInterface snarl;
-/// snarl.RegisterApp(_T("CppTest"), _T("C++ test app"), NULL);
-/// snarl.AddClass(_T("Class1"), _T("Class 1"));
-/// snarl.EZNotify(_T("Class1"), _T("C++ example 1"), _T("Some text"), 10);
-/// snarl.UnregisterApp();
-///
-/// Please see the SimpleTest.cpp and SnarlV41Test.cpp for more example code.
-/// </example>
-///----------------------------------------------------------------------------
-/// <VersionHistory>
-/// 2010-08-13 : First release of V41 Snarl API implementation
-/// </VersionHistory>
-
-#define _CRT_SECURE_NO_WARNINGS
-
-#include "SnarlInterface.h"
-
-
-namespace Snarl {
-namespace V41 {
-
-//-----------------------------------------------------------------------------
-// Constructor/Destructor
-//-----------------------------------------------------------------------------
-SnarlInterface::SnarlInterface()
- : appToken(0), lastMsgToken(0), localError(SnarlEnums::Success)
-{
-}
-
-SnarlInterface::~SnarlInterface()
-{
-}
-
-// ----------------------------------------------------------------------------
-
-LONG32 SnarlInterface::RegisterApp(LPCSTR signature, LPCSTR title, LPCSTR icon, HWND hWndReply /* = NULL */, LONG32 msgReply /* = 0 */, SnarlEnums::AppFlags flags /* = SnarlEnums::AppDefault */)
-{
- SnarlMessage msg;
- msg.Command = SnarlEnums::RegisterApp;
- msg.Token = 0;
- PackData(msg.PacketData,
- "id::%s#?title::%s#?icon::%s#?hwnd::%d#?umsg::%d#?flags::%d",
- signature, title, icon, hWndReply, msgReply, flags);
-
- appToken = Send(msg);
- lastMsgToken = 0;
-
- return appToken;
-}
-
-LONG32 SnarlInterface::RegisterApp(LPCWSTR signature, LPCWSTR title, LPCWSTR icon, HWND hWndReply /* = NULL */, LONG32 msgReply /* = 0 */, SnarlEnums::AppFlags flags /* = SnarlEnums::AppDefault */)
-{
- LPCSTR szParam1 = WideToUTF8(signature);
- LPCSTR szParam2 = WideToUTF8(title);
- LPCSTR szParam3 = WideToUTF8(icon);
-
- LONG32 result = RegisterApp(szParam1, szParam2, szParam3, hWndReply, msgReply, flags);
-
- delete [] szParam1;
- delete [] szParam2;
- delete [] szParam3;
-
- return result;
-}
-
-LONG32 SnarlInterface::UnregisterApp()
-{
- SnarlMessage msg;
- msg.Command = SnarlEnums::UnregisterApp;
- msg.Token = appToken;
- PackData(msg.PacketData, NULL);
-
- appToken = 0;
- lastMsgToken = 0;
-
- return Send(msg);
-}
-
-LONG32 SnarlInterface::UpdateApp(LPCSTR title /* = NULL */, LPCSTR icon /* = NULL */)
-{
- if (title == NULL && icon == NULL)
- return 0;
-
- SnarlMessage msg;
- msg.Command = SnarlEnums::UpdateApp;
- msg.Token = appToken;
-
- // TODO: Uckly code ahead
- if (title != NULL && title[0] != 0 && icon != NULL && icon[0] != 0)
- PackData(msg.PacketData, "title::%s#?icon::%s", title, icon);
- else if (title != NULL && title[0] != 0)
- PackData(msg.PacketData, "title::%s", title);
- else if (icon != NULL && icon[0] != 0)
- PackData(msg.PacketData, "icon::%s", icon);
-
- return Send(msg);
-}
-
-LONG32 SnarlInterface::UpdateApp(LPCWSTR title /* = NULL */, LPCWSTR icon /* = NULL */)
-{
- LPCSTR szParam1 = WideToUTF8(title);
- LPCSTR szParam2 = WideToUTF8(icon);
-
- LONG32 result = UpdateApp(szParam1, szParam2);
-
- delete [] szParam1;
- delete [] szParam2;
-
- return result;
-}
-
-LONG32 SnarlInterface::AddClass(LPCSTR className, LPCSTR description, bool enabled /* = true */)
-{
- SnarlMessage msg;
- msg.Command = SnarlEnums::AddClass;
- msg.Token = appToken;
- PackData(msg.PacketData, "id::%s#?name::%s#?enabled::%d", className, description, (enabled ? 1 : 0));
-
- return Send(msg);
-}
-
-LONG32 SnarlInterface::AddClass(LPCWSTR className, LPCWSTR description, bool enabled /* = true */)
-{
- LPCSTR szParam1 = WideToUTF8(className);
- LPCSTR szParam2 = WideToUTF8(description);
-
- LONG32 result = AddClass(szParam1, szParam2, enabled);
-
- delete [] szParam1;
- delete [] szParam2;
-
- return result;
-}
-
-LONG32 SnarlInterface::RemoveClass(LPCSTR className, bool forgetSettings /* = false */)
-{
- SnarlMessage msg;
- msg.Command = SnarlEnums::RemoveClass;
- msg.Token = appToken;
- PackData(msg.PacketData, "id::%s#?forget::%d", className, (forgetSettings ? 1 : 0));
-
- return Send(msg);
-}
-
-LONG32 SnarlInterface::RemoveClass(LPCWSTR className, bool forgetSettings /* = false */)
-{
- LPCSTR szParam1 = WideToUTF8(className);
-
- LONG32 result = RemoveClass(szParam1, forgetSettings);
-
- delete [] szParam1;
-
- return result;
-}
-
-LONG32 SnarlInterface::RemoveAllClasses(bool forgetSettings /* = false */)
-{
- SnarlMessage msg;
- msg.Command = SnarlEnums::RemoveClass;
- msg.Token = appToken;
- PackData(msg.PacketData, "all::1#?forget::%d", (forgetSettings ? 1 : 0));
-
- return Send(msg);
-}
-
-LONG32 SnarlInterface::EZNotify(LPCSTR className, LPCSTR title, LPCSTR text, LONG32 timeout /* = -1 */, LPCSTR icon /* = NULL */, LONG32 priority /* = 0 */, LPCSTR acknowledge /* = NULL */, LPCSTR value /* = NULL */)
-{
- SnarlMessage msg;
- msg.Command = SnarlEnums::Notify;
- msg.Token = appToken;
- PackData(msg.PacketData,
- "id::%s#?title::%s#?text::%s#?timeout::%d#?icon::%s#?priority::%d#?ack::%s#?value::%s",
- className, title, text, timeout, (icon ? icon : ""), priority, (acknowledge ? acknowledge : ""), (value ? value : ""));
-
- lastMsgToken = Send(msg);
- return lastMsgToken;
-}
-
-LONG32 SnarlInterface::EZNotify(LPCWSTR className, LPCWSTR title, LPCWSTR text, LONG32 timeout /* = -1 */, LPCWSTR icon /* = NULL */, LONG32 priority /* = 0 */, LPCWSTR acknowledge /* = NULL */, LPCWSTR value /* = NULL */)
-{
- LPCSTR szParam1 = WideToUTF8(className);
- LPCSTR szParam2 = WideToUTF8(title);
- LPCSTR szParam3 = WideToUTF8(text);
- LPCSTR szParam4 = WideToUTF8(icon);
- LPCSTR szParam5 = WideToUTF8(acknowledge);
- LPCSTR szParam6 = WideToUTF8(value);
-
- LONG32 result = EZNotify(szParam1, szParam2, szParam3, timeout, szParam4, priority, szParam5, szParam6);
-
- delete [] szParam1; delete [] szParam2; delete [] szParam3;
- delete [] szParam4; delete [] szParam5; delete [] szParam6;
-
- return result;
-}
-
-LONG32 SnarlInterface::Notify(LPCSTR className, LPCSTR packetData)
-{
- SnarlMessage msg;
- msg.Command = SnarlEnums::Notify;
- msg.Token = appToken;
- PackData(msg.PacketData, "id::%s#?%s", className, packetData);
-
- lastMsgToken = Send(msg);
- return lastMsgToken;
-}
-
-LONG32 SnarlInterface::Notify(LPCWSTR className, LPCWSTR packetData)
-{
- LPCSTR szParam1 = WideToUTF8(className);
- LPCSTR szParam2 = WideToUTF8(packetData);
-
- LONG32 result = Notify(szParam1, szParam2);
-
- delete [] szParam1; delete [] szParam2;
-
- return result;
-}
-
-LONG32 SnarlInterface::EZUpdate(LONG32 msgToken, LPCSTR title /* = NULL */, LPCSTR text /* = NULL */, LONG32 timeout /* = -1 */, LPCSTR icon /* = NULL */)
-{
- SnarlMessage msg;
- msg.Command = SnarlEnums::UpdateNotification;
- msg.Token = msgToken;
-
- // Create packed data
- errno_t err = 0;
- ZeroMemory(msg.PacketData, sizeof(msg.PacketData));
- char* pData = reinterpret_cast<char*>(msg.PacketData);
-
- if (title != NULL) {
- err |= strncat_s(pData, SnarlPacketDataSize, (pData[0] != NULL) ? "#?title::" : "title::", _TRUNCATE); //StringCbCat(tmp, SnarlPacketDataSize, "title::%s");
- err |= strncat_s(pData, SnarlPacketDataSize, title, _TRUNCATE);
- }
- if (text != NULL) {
- err |= strncat_s(pData, SnarlPacketDataSize, (pData[0] != NULL) ? "#?text::" : "text::", _TRUNCATE);
- err |= strncat_s(pData, SnarlPacketDataSize, text, _TRUNCATE);
- }
- if (icon != NULL) {
- err |= strncat_s(pData, SnarlPacketDataSize, (pData[0] != NULL) ? "#?icon::" : "icon::", _TRUNCATE);
- err |= strncat_s(pData, SnarlPacketDataSize, icon, _TRUNCATE);
- }
- if (timeout != -1) {
- char tmp[32];
- _itoa_s(timeout, tmp, 10);
-
- err |= strncat_s(pData, SnarlPacketDataSize, (pData[0] != NULL) ? "#?timeout::" : "timeout::", _TRUNCATE);
- err |= strncat_s(pData, SnarlPacketDataSize, tmp, _TRUNCATE);
- }
-
- // Check for strcat errors and exit on error
- if (err != 0) {
- localError = SnarlEnums::ErrorFailed;
- return 0;
- }
-
- return Send(msg);
-}
-
-LONG32 SnarlInterface::EZUpdate(LONG32 msgToken, LPCWSTR title /* = NULL */, LPCWSTR text /* = NULL */, LONG32 timeout /* = -1 */, LPCWSTR icon /* = NULL */)
-{
- LPCSTR szParam1 = WideToUTF8(title);
- LPCSTR szParam2 = WideToUTF8(text);
- LPCSTR szParam3 = WideToUTF8(icon);
-
- LONG32 result = EZUpdate(msgToken, szParam1, szParam2, timeout, szParam3);
-
- delete [] szParam1; delete [] szParam2; delete [] szParam3;
-
- return result;
-}
-
-LONG32 SnarlInterface::Update(LONG32 msgToken, LPCSTR packetData)
-{
- SnarlMessage msg;
- msg.Command = SnarlEnums::UpdateNotification;
- msg.Token = msgToken;
- PackData(msg.PacketData, packetData);
-
- return Send(msg);
-}
-
-LONG32 SnarlInterface::Update(LONG32 msgToken, LPCWSTR packetData)
-{
- LPCSTR szParam1 = WideToUTF8(packetData);
-
- LONG32 result = Update(msgToken, szParam1);
-
- delete [] szParam1;
-
- return result;
-}
-
-LONG32 SnarlInterface::Hide(LONG32 msgToken)
-{
- SnarlMessage msg;
- msg.Command = SnarlEnums::HideNotification;
- msg.Token = msgToken;
- PackData(msg.PacketData, NULL);
-
- return Send(msg);
-}
-
-LONG32 SnarlInterface::IsVisible(LONG32 msgToken)
-{
- SnarlMessage msg;
- msg.Command = SnarlEnums::IsNotificationVisible;
- msg.Token = msgToken;
- PackData(msg.PacketData, NULL);
-
- return Send(msg);
-}
-
-SnarlEnums::SnarlStatus SnarlInterface::GetLastError()
-{
- return localError;
-}
-
-// static
-BOOL SnarlInterface::IsSnarlRunning()
-{
- return IsWindow(GetSnarlWindow());
-}
-
-LONG32 SnarlInterface::GetVersion()
-{
- localError = SnarlEnums::Success;
-
- HWND hWnd = GetSnarlWindow();
- if (!IsWindow(hWnd))
- {
- localError = SnarlEnums::ErrorNotRunning;
- return 0;
- }
-
- HANDLE hProp = GetProp(hWnd, _T("_version"));
- return reinterpret_cast<int>(hProp);
-}
-
-// static
-UINT SnarlInterface::Broadcast()
-{
- return RegisterWindowMessage(SnarlGlobalMsg);
-}
-
-// static
-UINT SnarlInterface::AppMsg()
-{
- return RegisterWindowMessage(SnarlAppMsg);
-}
-
-// static
-HWND SnarlInterface::GetSnarlWindow()
-{
- return FindWindow(SnarlWindowClass, SnarlWindowTitle);;
-}
-
-LPCTSTR SnarlInterface::GetAppPath()
-{
- HWND hWnd = GetSnarlWindow();
- if (hWnd)
- {
- HWND hWndPath = FindWindowEx(hWnd, NULL, _T("static"), NULL);
- if (hWndPath)
- {
- TCHAR strTmp[MAX_PATH] = {0};
- int nReturn = GetWindowText(hWndPath, strTmp, MAX_PATH-1);
- if (nReturn > 0) {
- TCHAR* strReturn = AllocateString(nReturn + 1);
- _tcsncpy(strReturn, strTmp, nReturn + 1);
- strReturn[nReturn] = 0;
- return strReturn;
- }
- }
- }
-
- return NULL;
-}
-
-LPCTSTR SnarlInterface::GetIconsPath()
-{
- TCHAR* szIconPath = NULL;
- LPCTSTR szPath = GetAppPath();
- if (!szPath)
- return NULL;
-
- size_t nLen = 0;
- // TODO: _tcsnlen MAX_PATH
- if (nLen = _tcsnlen(szPath, MAX_PATH))
- {
- nLen += 10 + 1; // etc\\icons\\ + NULL
- szIconPath = AllocateString(nLen);
-
- _tcsncpy(szIconPath, szPath, nLen);
- _tcsncat(szIconPath, _T("etc\\icons\\"), nLen);
- }
-
- FreeString(szPath);
-
- return szIconPath;
-}
-
-LONG32 SnarlInterface::GetLastMsgToken() const
-{
- return lastMsgToken;
-}
-
-
-//-----------------------------------------------------------------------------
-// Private functions
-//-----------------------------------------------------------------------------
-
-LONG32 SnarlInterface::Send(SnarlMessage msg)
-{
- DWORD_PTR nReturn = 0; // Failure
-
- HWND hWnd = GetSnarlWindow();
- if (!IsWindow(hWnd))
- {
- localError = SnarlEnums::ErrorNotRunning;
- return 0;
- }
-
- COPYDATASTRUCT cds;
- cds.dwData = 0x534E4C02; // "SNL",2;
- cds.cbData = sizeof(SnarlMessage);
- cds.lpData = &msg;
-
- if (SendMessageTimeout(hWnd, WM_COPYDATA, (WPARAM)GetCurrentProcessId(), (LPARAM)&cds, SMTO_ABORTIFHUNG | SMTO_NOTIMEOUTIFNOTHUNG, 500, &nReturn) == 0)
- {
- // return zero on failure
- if (GetLastError() == ERROR_TIMEOUT)
- localError = SnarlEnums::ErrorTimedOut;
- else
- localError = SnarlEnums::ErrorFailed;
-
- return 0;
- }
-
- // return result and cache LastError
- HANDLE hProp = GetProp(hWnd, _T("last_error"));
- localError = static_cast<SnarlEnums::SnarlStatus>(reinterpret_cast<int>(hProp));
-
- return nReturn;
-}
-
-//-----------------------------------------------------------------------------
-
-// Remember to delete [] returned string
-inline
-LPSTR SnarlInterface::WideToUTF8(LPCWSTR szWideStr)
-{
- if (szWideStr == NULL)
- return NULL;
-
- int nSize = WideCharToMultiByte(CP_UTF8, 0, szWideStr, -1, NULL, 0, NULL, NULL);
- LPSTR szUTF8 = new char[nSize];
- WideCharToMultiByte(CP_UTF8, 0, szWideStr, -1, szUTF8, nSize, NULL, NULL);
-
- return szUTF8;
-}
-
-void SnarlInterface::PackData(BYTE* data, LPCSTR format, ...)
-{
- // Always zero array - Used to clear the array in member functions
- ZeroMemory(data, SnarlPacketDataSize);
-
- // Return if format string is empty
- if (format == NULL || format[0] == 0)
- return;
-
- int cchStrTextLen = 0;
- va_list args;
- va_start(args, format);
-
- // Get size of buffer
- cchStrTextLen = _vscprintf(format, args) + 1; // + NULL
- if (cchStrTextLen <= 1)
- return;
-
- // Create formated string - _TRUNCATE will ensure zero terminated
- _vsnprintf_s((char*)data, SnarlPacketDataSize, _TRUNCATE, format, args);
-
- va_end(args);
-}
-
-}} // namespace Snarl::V41
diff --git a/3rdParty/Snarl/SnarlInterface.h b/3rdParty/Snarl/SnarlInterface.h
deleted file mode 100644
index 9440451..0000000
--- a/3rdParty/Snarl/SnarlInterface.h
+++ /dev/null
@@ -1,276 +0,0 @@
-#ifndef SNARL_INTERFACE_V41
-#define SNARL_INTERFACE_V41
-
-#include <tchar.h>
-#include <windows.h>
-#include <cstdio>
-
-#ifndef SMTO_NOTIMEOUTIFNOTHUNG
- #define SMTO_NOTIMEOUTIFNOTHUNG 8
-#endif
-
-
-namespace Snarl {
- namespace V41 {
-
- static const LPCTSTR SnarlWindowClass = _T("w>Snarl");
- static const LPCTSTR SnarlWindowTitle = _T("Snarl");
-
- static const LPCTSTR SnarlGlobalMsg = _T("SnarlGlobalEvent");
- static const LPCTSTR SnarlAppMsg = _T("SnarlAppMessage");
-
- static const int SnarlPacketDataSize = 4096;
-
- // Enums put in own namespace, because ANSI C++ doesn't decorate enums with tagname :(
- namespace SnarlEnums {
-
- /// <summary>
- /// Global event identifiers.
- /// Identifiers marked with a '*' are sent by Snarl in two ways:
- /// 1. As a broadcast message (uMsg = 'SNARL_GLOBAL_MSG')
- /// 2. To the window registered in snRegisterConfig() or snRegisterConfig2()
- /// (uMsg = reply message specified at the time of registering)
- /// In both cases these values appear in wParam.
- ///
- /// Identifiers not marked are not broadcast; they are simply sent to the application's registered window.
- /// </summary>
- enum GlobalEvent
- {
- SnarlLaunched = 1, // Snarl has just started running*
- SnarlQuit = 2, // Snarl is about to stop running*
- SnarlAskAppletVer = 3, // (R1.5) Reserved for future use
- SnarlShowAppUi = 4 // (R1.6) Application should show its UI
- };
-
- /// <summary>
- /// Message event identifiers.
- /// These are sent by Snarl to the window specified in RegisterApp() when the
- /// Snarl Notification raised times out or the user clicks on it.
- /// </summary>
- enum MessageEvent
- {
- NotificationClicked = 32, // Notification was right-clicked by user
- NotificationCancelled = 32, // Added in V37 (R1.6) -- same value, just improved the meaning of it
- NotificationTimedOut = 33, //
- NotificationAck = 34, // Notification was left-clicked by user
- NotificationMenu = 35, // Menu item selected (V39)
- NotificationMiddleButton = 36, // Notification middle-clicked by user (V39)
- NotificationClosed = 37 // User clicked the close gadget (V39)
- };
-
- /// <summary>
- /// Error values returned by calls to GetLastError().
- /// </summary>
- enum SnarlStatus
- {
- Success = 0,
-
- ErrorFailed = 101, // miscellaneous failure
- ErrorUnknownCommand, // specified command not recognised
- ErrorTimedOut, // Snarl took too long to respond
-
- ErrorArgMissing = 109, // required argument missing
- ErrorSystem, // internal system error
-
- ErrorNotRunning = 201, // Snarl handling window not found
- ErrorNotRegistered, //
- ErrorAlreadyRegistered, // not used yet; RegisterApp() returns existing token
- ErrorClassAlreadyExists, // not used yet; AddClass() returns existing token
- ErrorClassBlocked,
- ErrorClassNotFound,
- ErrorNotificationNotFound
- };
-
- /// <summary>
- /// Application flags - features this app supports.
- /// </summary>
- enum AppFlags
- {
- AppDefault = 0,
- AppHasPrefs = 1,
- AppHasAbout = 2,
- AppIsWindowless = 0x8000
- };
-
- enum SnarlCommand
- {
- RegisterApp = 1,
- UnregisterApp,
- UpdateApp,
- SetCallback,
- AddClass,
- RemoveClass,
- Notify,
- UpdateNotification,
- HideNotification,
- IsNotificationVisible,
- LastError // deprecated but retained for backwards compatability
- };
- }
-
- struct SnarlMessage
- {
- SnarlEnums::SnarlCommand Command;
- LONG32 Token;
- BYTE PacketData[SnarlPacketDataSize];
- };
-
- static const DWORD WM_SNARLTEST = WM_USER + 237;
-
-
- // ------------------------------------------------------------------------
- /// SnarlInterface class definition
- // ------------------------------------------------------------------------
- class SnarlInterface {
- public:
- SnarlInterface();
- ~SnarlInterface();
-
- LPTSTR AllocateString(size_t n) { return new TCHAR[n]; }
- void FreeString(LPTSTR str) { delete [] str; str = NULL; }
- void FreeString(LPCTSTR str) { delete [] str; }
-
- /// <summary>Register application with Snarl.</summary>
- /// <returns>The application token or 0 on failure.</returns>
- /// <remarks>The application token is saved in SnarlInterface member variable, so just use return value to check for error.</remarks>
- LONG32 RegisterApp(LPCSTR signature, LPCSTR title, LPCSTR icon, HWND hWndReply = NULL, LONG32 msgReply = 0, SnarlEnums::AppFlags flags = SnarlEnums::AppDefault);
- LONG32 RegisterApp(LPCWSTR signature, LPCWSTR title, LPCWSTR icon, HWND hWndReply = NULL, LONG32 msgReply = 0, SnarlEnums::AppFlags flags = SnarlEnums::AppDefault);
-
- /// <summary>Unregister application with Snarl when application is closing.</summary>
- /// <returns>0 on failure.</returns>
- LONG32 UnregisterApp();
-
- /// <summary>Update information provided when calling RegisterApp.</summary>
- /// <returns>0 on failure.</returns>
- LONG32 UpdateApp(LPCSTR title = NULL, LPCSTR icon = NULL);
- LONG32 UpdateApp(LPCWSTR title = NULL, LPCWSTR icon = NULL);
-
- /// <summary>Add a notification class to Snarl.</summary>
- /// <returns>0 on failure.</returns>
- LONG32 AddClass(LPCSTR className, LPCSTR description, bool enabled = true);
- LONG32 AddClass(LPCWSTR className, LPCWSTR description, bool enabled = true);
-
- /// <summary>Remove a notification class added with AddClass().</summary>
- /// <returns>0 on failure.</returns>
- LONG32 RemoveClass(LPCSTR className, bool forgetSettings = false);
- LONG32 RemoveClass(LPCWSTR className, bool forgetSettings = false);
-
- /// <summary>Remove all notification classes in one call.</summary>
- /// <returns>0 on failure.</returns>
- LONG32 RemoveAllClasses(bool forgetSettings = false);
-
- /// <summary>Show a Snarl notification.</summary>
- /// <returns>Returns the notification token or 0 on failure.</returns>
- /// <remarks>You can use <see cref="GetLastMsgToken()" /> to get the last token.</remarks>
- LONG32 EZNotify(LPCSTR className, LPCSTR title, LPCSTR text, LONG32 timeout = -1, LPCSTR icon = NULL, LONG32 priority = 0, LPCSTR acknowledge = NULL, LPCSTR value = NULL);
- LONG32 EZNotify(LPCWSTR className, LPCWSTR title, LPCWSTR text, LONG32 timeout = -1, LPCWSTR icon = NULL, LONG32 priority = 0, LPCWSTR acknowledge = NULL, LPCWSTR value = NULL);
-
- /// <summary>
- /// Show a Snarl notification.
- /// This function requires that you write your own packet data.
- /// </summary>
- /// <returns>Returns the notification token or 0 on failure.</returns>
- /// <remarks>You can use <see cref="GetLastMsgToken()" /> to get the last token.</remarks>
- LONG32 Notify(LPCSTR className, LPCSTR packetData);
- LONG32 Notify(LPCWSTR className, LPCWSTR packetData);
-
- /// <summary>Update the text or other parameters of a visible Snarl notification.</summary>
- /// <returns>0 on failure.</returns>
- LONG32 EZUpdate(LONG32 msgToken, LPCSTR title = NULL, LPCSTR text = NULL, LONG32 timeout = -1, LPCSTR icon = NULL);
- LONG32 EZUpdate(LONG32 msgToken, LPCWSTR title = NULL, LPCWSTR text = NULL, LONG32 timeout = -1, LPCWSTR icon = NULL);
-
- /// <summary>
- /// Update the text or other parameters of a visible Snarl notification.
- /// This function requires that you write your own packet data.
- /// </summary>
- /// <returns>0 on failure.</returns>
- LONG32 Update(LONG32 msgToken, LPCSTR packetData);
- LONG32 Update(LONG32 msgToken, LPCWSTR packetData);
-
- /// <summary>Hide a Snarl notification.</summary>
- /// <returns>0 on failure.</returns>
- LONG32 Hide(LONG32 msgToken);
-
- /// <summary>Test if a Snarl notification is visible.</summary>
- /// <returns>Returns -1 if message is visible. 0 if not visible or if an error occured.</returns>
- LONG32 IsVisible(LONG32 msgToken);
-
- /// <summary>Get the last error from Snarl. Call after other functions return 0 to know why it failed.</summary>
- /// <returns>Returns one of the SnarlEnums::SnarlStatus values.</returns>
- SnarlEnums::SnarlStatus GetLastError();
-
- /// <summary>Get Snarl version, if it is running.</summary>
- /// <returns>Returns a number indicating Snarl version.</returns>
- LONG32 GetVersion();
-
- /// <summary>
- /// Get the path to where Snarl is installed.
- /// ** Remember to call <see cref="FreeString(LPCTSTR)" /> on the returned string !!!
- /// </summary>
- /// <returns>Returns the path to where Snarl is installed.</returns>
- /// <remarks>This is a V39 API method.</remarks>
- LPCTSTR GetAppPath();
-
- /// <summary>
- /// Get the path to where the default Snarl icons are located.
- /// <para>** Remember to call <see cref="FreeString(LPCTSTR)" /> on the returned string !!!</para>
- /// </summary>
- /// <returns>Returns the path to where the default Snarl icons are located.</returns>
- /// <remarks>This is a V39 API method.</remarks>
- LPCTSTR GetIconsPath();
-
- /// <summary>GetLastMsgToken() returns token of the last message sent to Snarl.</summary>
- /// <returns>Returns message token of last message.</returns>
- /// <remarks>This function is not in the official API!</remarks>
- LONG32 GetLastMsgToken() const;
-
- /// <summary>Check whether Snarl is running</summary>
- /// <returns>Returns true if Snarl system was found running.</returns>
- static BOOL IsSnarlRunning();
-
- /// <summary>
- /// Returns the value of Snarl's global registered message.
- /// Notes:
- /// Snarl registers SNARL_GLOBAL_MSG during startup which it then uses to communicate
- /// with all running applications through a Windows broadcast message. This function can
- /// only fail if for some reason the Windows RegisterWindowMessage() function fails
- /// - given this, this function *cannnot* be used to test for the presence of Snarl.
- /// </summary>
- /// <returns>A 16-bit value (translated to 32-bit) which is the registered Windows message for Snarl.</returns>
- static UINT Broadcast();
-
- /// <summary>Returns the global Snarl Application message (V39)</summary>
- /// <returns>Returns Snarl application registered message.</returns>
- static UINT AppMsg();
-
- /// <summary>Returns a handle to the Snarl Dispatcher window (V37)</summary>
- /// <returns>Returns handle to Snarl Dispatcher window, or zero if it's not found.</returns>
- /// <remarks>This is now the preferred way to test if Snarl is actually running.</remarks>
- static HWND GetSnarlWindow();
-
- private:
- /// <summary>Send message to Snarl.</summary>
- /// <returns>Return zero on failure.</returns>
- LONG32 Send(SnarlMessage msg);
-
- /// <summary>Convert a unicode string to UTF8</summary>
- /// <returns>Returns pointer to the new string - Remember to delete [] returned string !</returns>
- /// <remarks>Remember to delete [] returned string !!!</remarks>
- LPSTR WideToUTF8(LPCWSTR szWideStr);
-
- /// <summary>Pack data into the PackedData member field.</summary>
- /// <param name="data">Should always be a pointer to the PackedData field</param>
- /// <param name="format">The format string. Can be NULL or "" to just zero PackedData!</param>
- /// <param name="...">Variable number of objects to convert</param>
- void PackData(BYTE* data, LPCSTR format, ...);
-
- LONG32 appToken;
- LONG32 lastMsgToken;
- SnarlEnums::SnarlStatus localError;
-
- }; // class
-
- } // namespace V41
-} // namespace Snarl
-
-#endif // SNARL_INTERFACE_V41
diff --git a/3rdParty/Unbound/SConscript b/3rdParty/Unbound/SConscript
index b0e6f42..fee2fa3 100644
--- a/3rdParty/Unbound/SConscript
+++ b/3rdParty/Unbound/SConscript
@@ -2,109 +2,109 @@ Import("env")
if env.get("UNBOUND_BUNDLED", False) :
- if env["PLATFORM"] == "win32" :
- cppflags = ["/I" + Dir("#/3rdParty/Unbound/src/unbound").abspath]
- else :
- cppflags = [("-isystem", Dir("#/3rdParty/Unbound/src/unbound").abspath)]
+ if env["PLATFORM"] == "win32" :
+ cppflags = ["/I" + Dir("#/3rdParty/Unbound/src/unbound").abspath]
+ else :
+ cppflags = [("-isystem", Dir("#/3rdParty/Unbound/src/unbound").abspath)]
################################################################################
# Flags
################################################################################
-
- if env["SCONS_STAGE"] == "flags" :
- env["UNBOUND_FLAGS"] = {
- "CPPPATH": [Dir("src/unbound/libunbound")],
- "CPPFLAGS": cppflags,
- "LIBPATH": [env.Dir(".")],
- "LIBS": ["Swiften_Unbound"],
- }
- if env["target"] == "android" :
- env["UNBOUND_FLAGS"]["CPPPATH"].append(Dir("src/android/compat"))
+
+ if env["SCONS_STAGE"] == "flags" :
+ env["UNBOUND_FLAGS"] = {
+ "CPPPATH": [Dir("src/unbound/libunbound")],
+ "CPPFLAGS": cppflags,
+ "LIBPATH": [env.Dir(".")],
+ "LIBS": ["Swiften_Unbound"],
+ }
+ if env["target"] == "android" :
+ env["UNBOUND_FLAGS"]["CPPPATH"].append(Dir("src/android/compat"))
################################################################################
# Build
################################################################################
- if env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
- myenv.Append(CPPDEFINES = [("UNBOUND_STATICLIB")])
- myenv.Append(CPPPATH = ["../Ldns/src/ldns", "src/unbound", "."])
- if env["target"] == "android" :
- myenv.Append(CPPPATH = ["src/android/compat", "src/android/config"])
- myenv.Append(CPPPATH = ["src/android/dns"])
- myenv.Append(CPPPATH = ["../Ldns/src/android"])
- myenv.UseFlags(env["OPENSSL_FLAGS"])
+ if env["SCONS_STAGE"] == "build" :
+ myenv = env.Clone()
+ myenv.Append(CPPDEFINES = [("UNBOUND_STATICLIB")])
+ myenv.Append(CPPPATH = ["../Ldns/src/ldns", "src/unbound", "."])
+ if env["target"] == "android" :
+ myenv.Append(CPPPATH = ["src/android/compat", "src/android/config"])
+ myenv.Append(CPPPATH = ["src/android/dns"])
+ myenv.Append(CPPPATH = ["../Ldns/src/android"])
+ myenv.UseFlags(env["OPENSSL_FLAGS"])
- unbound_objects = [
- "src/unbound/daemon/acl_list.c",
- "src/unbound/daemon/cachedump.c",
- "src/unbound/daemon/daemon.c",
- "src/unbound/daemon/remote.c",
- "src/unbound/daemon/stats.c",
- "src/unbound/daemon/unbound.c",
- # duplicate symbols: "src/src/daemon/worker.c",
- "src/unbound/iterator/iter_delegpt.c",
- "src/unbound/iterator/iter_donotq.c",
- "src/unbound/iterator/iter_fwd.c",
- "src/unbound/iterator/iter_hints.c",
- "src/unbound/iterator/iter_priv.c",
- "src/unbound/iterator/iter_resptype.c",
- "src/unbound/iterator/iter_scrub.c",
- "src/unbound/iterator/iter_utils.c",
- "src/unbound/iterator/iterator.c",
- "src/unbound/libunbound/context.c",
- "src/unbound/libunbound/libunbound.c",
- "src/unbound/libunbound/libworker.c",
- "src/unbound/services/cache/dns.c",
- "src/unbound/services/cache/infra.c",
- "src/unbound/services/cache/rrset.c",
- "src/unbound/services/listen_dnsport.c",
- "src/unbound/services/localzone.c",
- "src/unbound/services/mesh.c",
- "src/unbound/services/modstack.c",
- "src/unbound/services/outbound_list.c",
- "src/unbound/services/outside_network.c",
- "src/unbound/util/alloc.c",
- "src/unbound/util/config_file.c",
- "src/unbound/util/configlexer.c",
- "src/unbound/util/configparser.c",
- "src/unbound/util/data/dname.c",
- "src/unbound/util/data/msgencode.c",
- "src/unbound/util/data/msgparse.c",
- "src/unbound/util/data/msgreply.c",
- "src/unbound/util/data/packed_rrset.c",
- "src/unbound/util/fptr_wlist.c",
- "src/unbound/util/locks.c",
- "src/unbound/util/log.c",
- "src/unbound/util/mini_event.c",
- "src/unbound/util/module.c",
- "src/unbound/util/net_help.c",
- "src/unbound/util/netevent.c",
- "src/unbound/util/random.c",
- "src/unbound/util/rbtree.c",
- "src/unbound/util/regional.c",
- "src/unbound/util/rtt.c",
- "src/unbound/util/storage/dnstree.c",
- "src/unbound/util/storage/lookup3.c",
- "src/unbound/util/storage/lruhash.c",
- "src/unbound/util/storage/slabhash.c",
- "src/unbound/util/timehist.c",
- "src/unbound/util/tube.c",
- #src/unbound/util/winsock_event.c
- "src/unbound/validator/autotrust.c",
- "src/unbound/validator/val_anchor.c",
- "src/unbound/validator/val_kcache.c",
- "src/unbound/validator/val_kentry.c",
- "src/unbound/validator/val_neg.c",
- "src/unbound/validator/val_nsec.c",
- "src/unbound/validator/val_nsec3.c",
- "src/unbound/validator/val_secalgo.c",
- "src/unbound/validator/val_sigcrypt.c",
- "src/unbound/validator/val_utils.c",
- "src/unbound/validator/validator.c",
- ]
- if env["target"] == "android" :
- unbound_objects.append("src/android/compat/glob.c")
- unbound_objects.append("src/android/dns/dns_android.cpp")
- env["UNBOUND_OBJECTS"] = myenv.SwiftenObject(unbound_objects)
+ unbound_objects = [
+ "src/unbound/daemon/acl_list.c",
+ "src/unbound/daemon/cachedump.c",
+ "src/unbound/daemon/daemon.c",
+ "src/unbound/daemon/remote.c",
+ "src/unbound/daemon/stats.c",
+ "src/unbound/daemon/unbound.c",
+ # duplicate symbols: "src/src/daemon/worker.c",
+ "src/unbound/iterator/iter_delegpt.c",
+ "src/unbound/iterator/iter_donotq.c",
+ "src/unbound/iterator/iter_fwd.c",
+ "src/unbound/iterator/iter_hints.c",
+ "src/unbound/iterator/iter_priv.c",
+ "src/unbound/iterator/iter_resptype.c",
+ "src/unbound/iterator/iter_scrub.c",
+ "src/unbound/iterator/iter_utils.c",
+ "src/unbound/iterator/iterator.c",
+ "src/unbound/libunbound/context.c",
+ "src/unbound/libunbound/libunbound.c",
+ "src/unbound/libunbound/libworker.c",
+ "src/unbound/services/cache/dns.c",
+ "src/unbound/services/cache/infra.c",
+ "src/unbound/services/cache/rrset.c",
+ "src/unbound/services/listen_dnsport.c",
+ "src/unbound/services/localzone.c",
+ "src/unbound/services/mesh.c",
+ "src/unbound/services/modstack.c",
+ "src/unbound/services/outbound_list.c",
+ "src/unbound/services/outside_network.c",
+ "src/unbound/util/alloc.c",
+ "src/unbound/util/config_file.c",
+ "src/unbound/util/configlexer.c",
+ "src/unbound/util/configparser.c",
+ "src/unbound/util/data/dname.c",
+ "src/unbound/util/data/msgencode.c",
+ "src/unbound/util/data/msgparse.c",
+ "src/unbound/util/data/msgreply.c",
+ "src/unbound/util/data/packed_rrset.c",
+ "src/unbound/util/fptr_wlist.c",
+ "src/unbound/util/locks.c",
+ "src/unbound/util/log.c",
+ "src/unbound/util/mini_event.c",
+ "src/unbound/util/module.c",
+ "src/unbound/util/net_help.c",
+ "src/unbound/util/netevent.c",
+ "src/unbound/util/random.c",
+ "src/unbound/util/rbtree.c",
+ "src/unbound/util/regional.c",
+ "src/unbound/util/rtt.c",
+ "src/unbound/util/storage/dnstree.c",
+ "src/unbound/util/storage/lookup3.c",
+ "src/unbound/util/storage/lruhash.c",
+ "src/unbound/util/storage/slabhash.c",
+ "src/unbound/util/timehist.c",
+ "src/unbound/util/tube.c",
+ #src/unbound/util/winsock_event.c
+ "src/unbound/validator/autotrust.c",
+ "src/unbound/validator/val_anchor.c",
+ "src/unbound/validator/val_kcache.c",
+ "src/unbound/validator/val_kentry.c",
+ "src/unbound/validator/val_neg.c",
+ "src/unbound/validator/val_nsec.c",
+ "src/unbound/validator/val_nsec3.c",
+ "src/unbound/validator/val_secalgo.c",
+ "src/unbound/validator/val_sigcrypt.c",
+ "src/unbound/validator/val_utils.c",
+ "src/unbound/validator/validator.c",
+ ]
+ if env["target"] == "android" :
+ unbound_objects.append("src/android/compat/glob.c")
+ unbound_objects.append("src/android/dns/dns_android.cpp")
+ env["UNBOUND_OBJECTS"] = myenv.SwiftenObject(unbound_objects)
diff --git a/3rdParty/ZLib/SConscript b/3rdParty/ZLib/SConscript
index 3625ee6..f6f96ec 100644
--- a/3rdParty/ZLib/SConscript
+++ b/3rdParty/ZLib/SConscript
@@ -1,24 +1,24 @@
Import("env")
if env.get("ZLIB_BUNDLED", False) :
- if env["SCONS_STAGE"] == "flags" :
- env["ZLIB_FLAGS"] = {
- "CPPPATH": [Dir("src")],
- "LIBPATH": [Dir(".")],
- }
+ if env["SCONS_STAGE"] == "flags" :
+ env["ZLIB_FLAGS"] = {
+ "CPPPATH": [Dir("src")],
+ "LIBPATH": [Dir(".")],
+ }
- if env["SCONS_STAGE"] == "build" :
- env["ZLIB_OBJECTS"] = env.SwiftenObject([
- "src/adler32.c",
- "src/compress.c",
- "src/crc32.c",
- "src/deflate.c",
- "src/gzio.c",
- "src/infback.c",
- "src/inffast.c",
- "src/inflate.c",
- "src/inftrees.c",
- "src/trees.c",
- "src/uncompr.c",
- "src/zutil.c"
- ])
+ if env["SCONS_STAGE"] == "build" :
+ env["ZLIB_OBJECTS"] = env.SwiftenObject([
+ "src/adler32.c",
+ "src/compress.c",
+ "src/crc32.c",
+ "src/deflate.c",
+ "src/gzio.c",
+ "src/infback.c",
+ "src/inffast.c",
+ "src/inflate.c",
+ "src/inftrees.c",
+ "src/trees.c",
+ "src/uncompr.c",
+ "src/zutil.c"
+ ])
diff --git a/BuildTools/CheckHeaders.py b/BuildTools/CheckHeaders.py
index 8d20f4e..79ff85c 100755
--- a/BuildTools/CheckHeaders.py
+++ b/BuildTools/CheckHeaders.py
@@ -3,18 +3,18 @@
import os, sys
FORBIDDEN_INCLUDES = [
- ("iostream", ["Swiften/Base/format.h"]),
- ("Base/Log.h", []),
- ("Base/format.h", []),
- ("algorithm", ["Swiften/Base/Algorithm.h", "Swiften/Base/SafeAllocator.h", "Swiften/Base/Listenable.h", "Swiften/Base/Concat.h"]),
- ("boost/bind.hpp", ["Swiften/Base/Listenable.h", "Swiften/FileTransfer/S5BTransportSession.h"]),
- ("boost/filesystem.hpp", []),
- ("Base/foreach.h", []),
- ("boost/date_time/date_time.hpp", []),
- ("boost/filesystem/filesystem.hpp", []),
-
- # To avoid
- ("Base/Algorithm.h", ["Swiften/StringCodecs/HMAC.h"]),
+ ("iostream", ["Swiften/Base/format.h"]),
+ ("Base/Log.h", []),
+ ("Base/format.h", []),
+ ("algorithm", ["Swiften/Base/Algorithm.h", "Swiften/Base/SafeAllocator.h", "Swiften/Base/Listenable.h", "Swiften/Base/Concat.h"]),
+ ("boost/bind.hpp", ["Swiften/Base/Listenable.h", "Swiften/FileTransfer/S5BTransportSession.h"]),
+ ("boost/filesystem.hpp", []),
+ ("Base/foreach.h", []),
+ ("boost/date_time/date_time.hpp", []),
+ ("boost/filesystem/filesystem.hpp", []),
+
+ # To avoid
+ ("Base/Algorithm.h", ["Swiften/StringCodecs/HMAC.h"]),
]
foundBadHeaders = False
@@ -22,21 +22,21 @@ foundBadHeaders = False
filename = sys.argv[1]
if "3rdParty" in filename or ".sconf" in filename or ".framework" in filename or not filename.endswith(".h") :
- sys.exit(0)
+ sys.exit(0)
if not "Swiften" in filename :
- sys.exit(0)
+ sys.exit(0)
if filename.endswith("Swiften.h") :
- sys.exit(0)
+ sys.exit(0)
file = open(filename, "r")
for line in file.readlines() :
- if not "#include" in line :
- continue
- if "Base/Log.h" in filename :
- continue
- for forbiddenInclude, ignores in FORBIDDEN_INCLUDES :
- if forbiddenInclude in line and len([x for x in ignores if x in filename]) == 0 :
- print "Found " + forbiddenInclude + " include in " + filename
- foundBadHeaders = True
+ if not "#include" in line :
+ continue
+ if "Base/Log.h" in filename :
+ continue
+ for forbiddenInclude, ignores in FORBIDDEN_INCLUDES :
+ if forbiddenInclude in line and len([x for x in ignores if x in filename]) == 0 :
+ print "Found " + forbiddenInclude + " include in " + filename
+ foundBadHeaders = True
sys.exit(foundBadHeaders)
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/BuildTools/CheckTests.py b/BuildTools/CheckTests.py
index 0ea56bd..7f160e7 100755
--- a/BuildTools/CheckTests.py
+++ b/BuildTools/CheckTests.py
@@ -5,29 +5,29 @@ import os, sys, re
foundUnregisteredTests = False
for (path, dirs, files) in os.walk(".") :
- if not "3rdParty" in path :
- for filename in [os.path.join(path, file) for file in files if file.endswith("Test.cpp") and file != "IdleQuerierTest.cpp" and file != "NotifierTest.cpp" and file != "ClientTest.cpp" and file != "ConnectivityTest.cpp" and file != "ReconnectTest.cpp"] :
- file = open(filename, "r")
- isRegistered = False
- registeredTests = set()
- declaredTests = set()
- for line in file.readlines() :
- m = re.match("\s*CPPUNIT_TEST_SUITE_REGISTRATION\((.*)\)", line)
- if m :
- isRegistered = True
- m = re.match("\s*CPPUNIT_TEST\((.*)\)", line)
- if m :
- registeredTests.add(m.group(1))
- continue
- m = re.match("\s*void (test.*)\(\)", line)
- if m :
- declaredTests.add(m.group(1))
- if not isRegistered :
- print filename + ": Registration missing"
- foundUnregisteredTests = True
- if registeredTests - declaredTests != set([]) :
- print filename + ": " + str(registeredTests - declaredTests)
- foundUnregisteredTests = True
- file.close()
+ if not "3rdParty" in path :
+ for filename in [os.path.join(path, file) for file in files if file.endswith("Test.cpp") and file != "IdleQuerierTest.cpp" and file != "NotifierTest.cpp" and file != "ClientTest.cpp" and file != "ConnectivityTest.cpp" and file != "ReconnectTest.cpp"] :
+ file = open(filename, "r")
+ isRegistered = False
+ registeredTests = set()
+ declaredTests = set()
+ for line in file.readlines() :
+ m = re.match("\s*CPPUNIT_TEST_SUITE_REGISTRATION\((.*)\)", line)
+ if m :
+ isRegistered = True
+ m = re.match("\s*CPPUNIT_TEST\((.*)\)", line)
+ if m :
+ registeredTests.add(m.group(1))
+ continue
+ m = re.match("\s*void (test.*)\(\)", line)
+ if m :
+ declaredTests.add(m.group(1))
+ if not isRegistered :
+ print filename + ": Registration missing"
+ foundUnregisteredTests = True
+ if registeredTests - declaredTests != set([]) :
+ print filename + ": " + str(registeredTests - declaredTests)
+ foundUnregisteredTests = True
+ file.close()
sys.exit(foundUnregisteredTests)
diff --git a/BuildTools/CheckTranslations.py b/BuildTools/CheckTranslations.py
index a9b6afd..615f81f 100755
--- a/BuildTools/CheckTranslations.py
+++ b/BuildTools/CheckTranslations.py
@@ -3,48 +3,48 @@
import os, sys, re, xml.dom.minidom
def getText(nodelist):
- text = ""
- for node in nodelist:
- if node.nodeType == node.TEXT_NODE:
- text += node.data
- return text
+ text = ""
+ for node in nodelist:
+ if node.nodeType == node.TEXT_NODE:
+ text += node.data
+ return text
desktop_generic_names = set()
desktop_comments = set()
f = open("Swift/resources/swift.desktop", "r")
for l in f.readlines() :
- m = re.match("GenericName\[(\w+)\].*", l)
- if m :
- desktop_generic_names.add(m.group(1))
- m = re.match("Comment\[(\w+)\].*", l)
- if m :
- desktop_comments.add(m.group(1))
+ m = re.match("GenericName\[(\w+)\].*", l)
+ if m :
+ desktop_generic_names.add(m.group(1))
+ m = re.match("Comment\[(\w+)\].*", l)
+ if m :
+ desktop_comments.add(m.group(1))
f.close()
for filename in os.listdir("Swift/Translations") :
- m = re.match("swift_(.*)\.ts", filename)
- if m :
- language = m.group(1)
- finished = True
- f = open("Swift/Translations/" + filename, "r")
- document = xml.dom.minidom.parse(f)
- f.close()
+ m = re.match("swift_(.*)\.ts", filename)
+ if m :
+ language = m.group(1)
+ finished = True
+ f = open("Swift/Translations/" + filename, "r")
+ document = xml.dom.minidom.parse(f)
+ f.close()
- for message in document.getElementsByTagName("message") :
- source = message.getElementsByTagName("source")[0]
- sourceText = getText(source.childNodes)
- sourcePlaceholders = set(re.findall("%\d+%?", sourceText))
- translation = message.getElementsByTagName("translation")[0]
- if "type" in translation.attributes.keys() and translation.attributes["type"]. value == "unfinished" :
- finished = False
- translationText = getText(translation.childNodes)
- translationPlaceholders = set(re.findall("%\d+%?", translationText))
- if translationPlaceholders != sourcePlaceholders :
- print "[Error] " + filename + ": Placeholder mismatch in translation '" + sourceText + "'"
- if not finished :
- print "[Warning] " + filename + ": Unfinished"
- if language not in desktop_generic_names and language != "en" :
- print "[Warning] GenericName field missing in desktop entry for " + language
- if language not in desktop_comments and language != "en" :
- print "[Warning] Comment field missing in desktop entry for " + language
+ for message in document.getElementsByTagName("message") :
+ source = message.getElementsByTagName("source")[0]
+ sourceText = getText(source.childNodes)
+ sourcePlaceholders = set(re.findall("%\d+%?", sourceText))
+ translation = message.getElementsByTagName("translation")[0]
+ if "type" in translation.attributes.keys() and translation.attributes["type"]. value == "unfinished" :
+ finished = False
+ translationText = getText(translation.childNodes)
+ translationPlaceholders = set(re.findall("%\d+%?", translationText))
+ if translationPlaceholders != sourcePlaceholders :
+ print "[Error] " + filename + ": Placeholder mismatch in translation '" + sourceText + "'"
+ if not finished :
+ print "[Warning] " + filename + ": Unfinished"
+ if language not in desktop_generic_names and language != "en" :
+ print "[Warning] GenericName field missing in desktop entry for " + language
+ if language not in desktop_comments and language != "en" :
+ print "[Warning] Comment field missing in desktop entry for " + language
diff --git a/BuildTools/Copyright/find-contribs.py b/BuildTools/Copyright/find-contribs.py
index 63c454e..ac30afb 100755
--- a/BuildTools/Copyright/find-contribs.py
+++ b/BuildTools/Copyright/find-contribs.py
@@ -3,46 +3,46 @@
import subprocess
def print_log(full_log):
- full_log_lines = full_log.split("\n")
-
- commits = []
-
- commit_bit = "commit "
- author_bit = "Author: "
- date_bit = "Date: "
-
- commit = None
- for line in full_log_lines:
-
- if line[0:len(commit_bit)] == commit_bit:
- if commit:
- commits.append(commit)
- commit = {'text':''}
- handled = False
- for bit in [commit_bit, author_bit, date_bit]:
- if line[0:len(bit)] == bit:
- commit[bit] = line
- handled = True
- if not handled:
- commit['text'] += line
-
- commits.append(commit)
-
- contributions = []
-
- for commit in commits:
- if not "git@kismith.co.uk" in commit[author_bit] and not "git@el-tramo.be" in commit[author_bit]:
- contributions.append(commit)
-
- #print contributions
- contributors = {}
- for commit in contributions:
- if not commit[author_bit] in contributors:
- contributors[commit[author_bit]] = []
- contributors[commit[author_bit]].append(commit[commit_bit])
-
- for contributor in contributors:
- print contributor + " has contributed patches " + ", ".join([commit[len(commit_bit):] for commit in contributors[contributor]])
+ full_log_lines = full_log.split("\n")
+
+ commits = []
+
+ commit_bit = "commit "
+ author_bit = "Author: "
+ date_bit = "Date: "
+
+ commit = None
+ for line in full_log_lines:
+
+ if line[0:len(commit_bit)] == commit_bit:
+ if commit:
+ commits.append(commit)
+ commit = {'text':''}
+ handled = False
+ for bit in [commit_bit, author_bit, date_bit]:
+ if line[0:len(bit)] == bit:
+ commit[bit] = line
+ handled = True
+ if not handled:
+ commit['text'] += line
+
+ commits.append(commit)
+
+ contributions = []
+
+ for commit in commits:
+ if not "git@kismith.co.uk" in commit[author_bit] and not "git@el-tramo.be" in commit[author_bit]:
+ contributions.append(commit)
+
+ #print contributions
+ contributors = {}
+ for commit in contributions:
+ if not commit[author_bit] in contributors:
+ contributors[commit[author_bit]] = []
+ contributors[commit[author_bit]].append(commit[commit_bit])
+
+ for contributor in contributors:
+ print contributor + " has contributed patches " + ", ".join([commit[len(commit_bit):] for commit in contributors[contributor]])
full_swiften_log = subprocess.check_output(["git", "log", "--", "Swiften"])
diff --git a/BuildTools/Copyrighter.py b/BuildTools/Copyrighter.py
index a3b6379..a16050c 100755
--- a/BuildTools/Copyrighter.py
+++ b/BuildTools/Copyrighter.py
@@ -11,32 +11,32 @@ LICENSE_DIR = "Documentation/Licenses"
reParseLicenseCommentBlocks = re.compile(ur'(\/\*\n\s\*\sCopyright \(c\) (?P<startYear>\d\d\d\d)(-(?P<endYear>\d\d\d\d))? (?P<author>[^\n\.]*)\.?\n.\* (?P<license>[^\n]*)\n \* (?P<seeMore>[^\n]+)\n *\*\/)')
class License :
- def __init__(self, name, file) :
- self.name = name
- self.file = file
+ def __init__(self, name, file) :
+ self.name = name
+ self.file = file
licenses = {
- "default": License("All rights reserved.", "See the COPYING file for more information."),
- "gpl3" : License("Licensed under the GNU General Public License v3.", "See " + LICENSE_DIR + "/" + "GPLv3.txt" + " for more information."),
- "mit" : License("Licensed under the MIT License.", "See " + LICENSE_DIR + "/" + "MIT.txt" + " for more information."),
- }
+ "default": License("All rights reserved.", "See the COPYING file for more information."),
+ "gpl3" : License("Licensed under the GNU General Public License v3.", "See " + LICENSE_DIR + "/" + "GPLv3.txt" + " for more information."),
+ "mit" : License("Licensed under the MIT License.", "See " + LICENSE_DIR + "/" + "MIT.txt" + " for more information."),
+ }
class Copyright :
- def __init__(self, author, year, license) :
- self.author = author
- self.year = year
- self.license = license
-
- def to_string(self, comment_chars) :
- return "\n".join([
- comment_chars[0],
- comment_chars[1] + " Copyright (c) %(year)s %(name)s" % {"year" : self.year, "name" : self.author },
- comment_chars[1] + licenses[self.license].name,
- comment_chars[1] + licenses[self.license].file,
- comment_chars[2],
- "\n"])
- def __str__(self):
- return """/*
+ def __init__(self, author, year, license) :
+ self.author = author
+ self.year = year
+ self.license = license
+
+ def to_string(self, comment_chars) :
+ return "\n".join([
+ comment_chars[0],
+ comment_chars[1] + " Copyright (c) %(year)s %(name)s" % {"year" : self.year, "name" : self.author },
+ comment_chars[1] + licenses[self.license].name,
+ comment_chars[1] + licenses[self.license].file,
+ comment_chars[2],
+ "\n"])
+ def __str__(self):
+ return """/*
* Copyright (c) %s %s.
* %s
* %s
@@ -44,145 +44,145 @@ class Copyright :
""" % (self.year, self.author, licenses[self.license].name, licenses[self.license].file)
class ContentRef :
- def __init__(self, begin, end, content):
- self.begin = begin
- self.end = end
- self.content = content
+ def __init__(self, begin, end, content):
+ self.begin = begin
+ self.end = end
+ self.content = content
class CopyrightBlock :
- def __init__(self, yearBegin, yearEnd, author, license, seeMore, total):
- self.yearBegin = yearBegin
- self.yearEnd = yearEnd
- self.author = author
- self.license = license
- self.seeMore = seeMore
- self.total = total
+ def __init__(self, yearBegin, yearEnd, author, license, seeMore, total):
+ self.yearBegin = yearBegin
+ self.yearEnd = yearEnd
+ self.author = author
+ self.license = license
+ self.seeMore = seeMore
+ self.total = total
def cref_from_group(match, group):
- if match.group(group):
- return ContentRef(match.start(group), match.end(group), match.group(group))
- else :
- return None
+ if match.group(group):
+ return ContentRef(match.start(group), match.end(group), match.group(group))
+ else :
+ return None
def parse_file_new(filename):
- copyrightBlocks = []
- with open(filename, 'r') as file:
- content = file.read()
- for match in re.finditer(reParseLicenseCommentBlocks, content):
- copyrightBlocks.append(CopyrightBlock(
- cref_from_group(match, "startYear"),
- cref_from_group(match, "endYear"),
- cref_from_group(match, "author"),
- cref_from_group(match, "license"),
- cref_from_group(match, "seeMore"),
- cref_from_group(match, 0)))
- return copyrightBlocks
+ copyrightBlocks = []
+ with open(filename, 'r') as file:
+ content = file.read()
+ for match in re.finditer(reParseLicenseCommentBlocks, content):
+ copyrightBlocks.append(CopyrightBlock(
+ cref_from_group(match, "startYear"),
+ cref_from_group(match, "endYear"),
+ cref_from_group(match, "author"),
+ cref_from_group(match, "license"),
+ cref_from_group(match, "seeMore"),
+ cref_from_group(match, 0)))
+ return copyrightBlocks
def get_userinfo() :
- p = subprocess.Popen("git config user.name", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(os.name != "nt"))
- username = p.stdout.read().rstrip()
- p.stdin.close()
- if p.wait() != 0 :
- return None
- p = subprocess.Popen("git config user.email", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(os.name != "nt"))
- email = p.stdout.read().rstrip()
- p.stdin.close()
- if p.wait() != 0 :
- return None
- return (username, email)
+ p = subprocess.Popen("git config user.name", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(os.name != "nt"))
+ username = p.stdout.read().rstrip()
+ p.stdin.close()
+ if p.wait() != 0 :
+ return None
+ p = subprocess.Popen("git config user.email", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(os.name != "nt"))
+ email = p.stdout.read().rstrip()
+ p.stdin.close()
+ if p.wait() != 0 :
+ return None
+ return (username, email)
def get_copyright(username, email) :
- if email in ["git@el-tramo.be", "git@kismith.co.uk"] :
- license = DEFAULT_LICENSE
- else :
- license = CONTRIBUTOR_LICENSE
- return Copyright(username, datetime.date.today().strftime("%Y"), license)
+ if email in ["git@el-tramo.be", "git@kismith.co.uk"] :
+ license = DEFAULT_LICENSE
+ else :
+ license = CONTRIBUTOR_LICENSE
+ return Copyright(username, datetime.date.today().strftime("%Y"), license)
def get_copyright_setting(username, email) :
- config = os.getenv("SWIFT_LICENSE_CONFIG")
- if config :
- copyrightHolder, license = config.split("|")
- else :
- if email.endswith("isode.com") or email in ["git@el-tramo.be", "git@kismith.co.uk", "tm@ayena.de"] :
- copyrightHolder, license = "Isode Limited", "default"
- else :
- copyrightHolder, license = username, "mit"
- return Copyright(copyrightHolder, datetime.date.today().year, license)
+ config = os.getenv("SWIFT_LICENSE_CONFIG")
+ if config :
+ copyrightHolder, license = config.split("|")
+ else :
+ if email.endswith("isode.com") or email in ["git@el-tramo.be", "git@kismith.co.uk", "tm@ayena.de"] :
+ copyrightHolder, license = "Isode Limited", "default"
+ else :
+ copyrightHolder, license = username, "mit"
+ return Copyright(copyrightHolder, datetime.date.today().year, license)
def check_copyright(filename, hints) :
- copyrightBlocks = parse_file_new(filename)
- if copyrightBlocks :
- # looking for copyright block for current author
- username, email = get_userinfo()
- copyrightSetting = get_copyright_setting(username, email)
- for block in copyrightBlocks :
- if block.author.content == copyrightSetting.author:
- year = block.yearBegin.content if not block.yearEnd else block.yearEnd.content
- if int(year) == copyrightSetting.year:
- return True
- else :
- if hints :
- print "Copyright block for " + copyrightSetting.author + " does not cover current year in: " + filename
- return False
- if hints :
- print "Missing copyright block for " + copyrightSetting.author + " in: " + filename
- return False
- else :
- if hints :
- print "No copyright found in: " + filename
- return False
+ copyrightBlocks = parse_file_new(filename)
+ if copyrightBlocks :
+ # looking for copyright block for current author
+ username, email = get_userinfo()
+ copyrightSetting = get_copyright_setting(username, email)
+ for block in copyrightBlocks :
+ if block.author.content == copyrightSetting.author:
+ year = block.yearBegin.content if not block.yearEnd else block.yearEnd.content
+ if int(year) == copyrightSetting.year:
+ return True
+ else :
+ if hints :
+ print "Copyright block for " + copyrightSetting.author + " does not cover current year in: " + filename
+ return False
+ if hints :
+ print "Missing copyright block for " + copyrightSetting.author + " in: " + filename
+ return False
+ else :
+ if hints :
+ print "No copyright found in: " + filename
+ return False
def replace_data_in_file(filename, begin, end, replaceWith) :
- with open(filename, 'r') as file:
- content = file.read()
- with open(filename, 'w') as file:
- file.write(content[:begin] + replaceWith + content[end:])
+ with open(filename, 'r') as file:
+ content = file.read()
+ with open(filename, 'w') as file:
+ file.write(content[:begin] + replaceWith + content[end:])
def set_or_update_copyright(filename) :
- if check_copyright(filename, False) :
- print "No update required for file: " + filename
- else :
- copyrightBlocks = parse_file_new(filename)
- username, email = get_userinfo()
- copyrightSetting = get_copyright_setting(username, email)
- lastBlock = 0
- for block in copyrightBlocks :
- if block.author.content == copyrightSetting.author :
- if not block.yearEnd :
- # replace year with range
- replace_data_in_file(filename, block.yearBegin.begin, block.yearBegin.end, "%s-%s" % (block.yearBegin.content, str(copyrightSetting.year)))
- else :
- # replace end of range with current year
- replace_data_in_file(filename, block.yearEnd.begin, block.yearEnd.end, "%s" % str(copyrightSetting.year))
- return
- lastBlock = block.total.end
-
- # No copyright block found. Append a new one.
- replace_data_in_file(filename, lastBlock+1, lastBlock+1, "\n" + str(copyrightSetting))
+ if check_copyright(filename, False) :
+ print "No update required for file: " + filename
+ else :
+ copyrightBlocks = parse_file_new(filename)
+ username, email = get_userinfo()
+ copyrightSetting = get_copyright_setting(username, email)
+ lastBlock = 0
+ for block in copyrightBlocks :
+ if block.author.content == copyrightSetting.author :
+ if not block.yearEnd :
+ # replace year with range
+ replace_data_in_file(filename, block.yearBegin.begin, block.yearBegin.end, "%s-%s" % (block.yearBegin.content, str(copyrightSetting.year)))
+ else :
+ # replace end of range with current year
+ replace_data_in_file(filename, block.yearEnd.begin, block.yearEnd.end, "%s" % str(copyrightSetting.year))
+ return
+ lastBlock = block.total.end
+
+ # No copyright block found. Append a new one.
+ replace_data_in_file(filename, lastBlock+1, lastBlock+1, "\n" + str(copyrightSetting))
def print_help() :
- print """Usage:
- Copyrighter.py check-copyright $filename
- Cheks for the existence of a copyright comment block.
+ print """Usage:
+ Copyrighter.py check-copyright $filename
+ Cheks for the existence of a copyright comment block.
- Copyrighter.py set-copyright $filename
- Adds or updates the existing copyright comment block.
+ Copyrighter.py set-copyright $filename
+ Adds or updates the existing copyright comment block.
- License setting:
- A users license configuration can be set via the SWIFT_LICENSE_CONFIG environment variable
- in the format "$copyright holder|$license", e.g. "Jane Doe|mit". Possible values for
- $license are default, mit and gpl.
- """
+ License setting:
+ A users license configuration can be set via the SWIFT_LICENSE_CONFIG environment variable
+ in the format "$copyright holder|$license", e.g. "Jane Doe|mit". Possible values for
+ $license are default, mit and gpl.
+ """
if sys.argv[1] == "check-copyright" :
- file = sys.argv[2]
- if (file.endswith(".cpp") or file.endswith(".h")) and not "3rdParty" in file :
- if not check_copyright(file, True) :
- sys.exit(-1)
+ file = sys.argv[2]
+ if (file.endswith(".cpp") or file.endswith(".h")) and not "3rdParty" in file :
+ if not check_copyright(file, True) :
+ sys.exit(-1)
elif sys.argv[1] == "set-copyright" :
- file = sys.argv[2]
- set_or_update_copyright(file)
+ file = sys.argv[2]
+ set_or_update_copyright(file)
else :
- print "Unknown command: " + sys.argv[1]
- print_help()
- sys.exit(-1)
+ print "Unknown command: " + sys.argv[1]
+ print_help()
+ sys.exit(-1)
diff --git a/BuildTools/Coverage/FilterLCovData.py b/BuildTools/Coverage/FilterLCovData.py
index 33fd682..e0f5c92 100755
--- a/BuildTools/Coverage/FilterLCovData.py
+++ b/BuildTools/Coverage/FilterLCovData.py
@@ -7,23 +7,23 @@ import sys, re, os.path
assert(len(sys.argv) == 2)
def isIgnored(file) :
- return (file.find("/Swiften/") == -1 and file.find("/Slimber/") == -1 and file.find("/Swift/") == -1) or (file.find("/UnitTest/") != -1 or file.find("/QA/") != -1)
+ return (file.find("/Swiften/") == -1 and file.find("/Slimber/") == -1 and file.find("/Swift/") == -1) or (file.find("/UnitTest/") != -1 or file.find("/QA/") != -1)
output = []
inputFile = open(sys.argv[1])
inIgnoredFile = False
for line in inputFile.readlines() :
- if inIgnoredFile :
- if line == "end_of_record\n" :
- inIgnoredFile = False
- else :
- if line.startswith("SF:") and isIgnored(line) :
- inIgnoredFile = True
- else :
- m = re.match("SF:(.*)", line)
- if m :
- line = "SF:" + os.path.realpath(m.group(1)) + "\n"
- output.append(line)
+ if inIgnoredFile :
+ if line == "end_of_record\n" :
+ inIgnoredFile = False
+ else :
+ if line.startswith("SF:") and isIgnored(line) :
+ inIgnoredFile = True
+ else :
+ m = re.match("SF:(.*)", line)
+ if m :
+ line = "SF:" + os.path.realpath(m.group(1)) + "\n"
+ output.append(line)
inputFile.close()
outputFile = open(sys.argv[1], 'w')
diff --git a/BuildTools/Coverage/GenerateSummary.py b/BuildTools/Coverage/GenerateSummary.py
index e572082..9de0f4d 100755
--- a/BuildTools/Coverage/GenerateSummary.py
+++ b/BuildTools/Coverage/GenerateSummary.py
@@ -8,27 +8,27 @@ inputFile = open(sys.argv[1])
currentFile = ""
coverage = {}
for line in inputFile.readlines() :
- line = line.strip()
- m = re.match("^SF:(.*)", line)
- if m :
- currentFile = m.group(1)
- else :
- m = re.match("^DA:(\d+),(\d+)", line)
- if m :
- currentFileCoverage = coverage.get(currentFile, {})
- line = int(m.group(1))
- count = int(m.group(2))
- currentFileCoverage[line] = currentFileCoverage.get(line, 0) + count
- coverage[currentFile] = currentFileCoverage
+ line = line.strip()
+ m = re.match("^SF:(.*)", line)
+ if m :
+ currentFile = m.group(1)
+ else :
+ m = re.match("^DA:(\d+),(\d+)", line)
+ if m :
+ currentFileCoverage = coverage.get(currentFile, {})
+ line = int(m.group(1))
+ count = int(m.group(2))
+ currentFileCoverage[line] = currentFileCoverage.get(line, 0) + count
+ coverage[currentFile] = currentFileCoverage
inputFile.close()
totalLines = 0
coveredLines = 0
for c in coverage.values() :
- totalLines += len(c)
- for l in c.values() :
- if l > 0 :
- coveredLines += 1
+ totalLines += len(c)
+ for l in c.values() :
+ if l > 0 :
+ coveredLines += 1
outputFile = open(sys.argv[2], 'w')
outputFile.write(str(coveredLines) + "/" + str(totalLines))
diff --git a/BuildTools/Cppcheck.sh b/BuildTools/Cppcheck.sh
index 9f14cb2..ee52b9b 100755
--- a/BuildTools/Cppcheck.sh
+++ b/BuildTools/Cppcheck.sh
@@ -1,21 +1,21 @@
#!/bin/sh
cppcheck $@ \
- --enable=all \
- --inline-suppr \
- --suppress=postfixOperator:3rdParty/hippomocks.h \
- --suppress=stlSize:3rdParty/hippomocks.h \
- --suppress=noConstructor \
- --suppress=publicAllocationError:Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp \
- -i 3rdParty -i .git -i .sconf_temp \
- -i Swift/QtUI/EventViewer/main.cpp \
- -i Swift/QtUI/ApplicationTest \
- -i Swift/QtUI/ChatView/main.cpp \
- -i Swift/QtUI/Roster/main.cpp \
- -i Swift/QtUI/NotifierTest/NotifierTest.cpp \
- -DSWIFTEN_BUILDING -DSWIFTEN_STATIC \
- -U__BEOS__ -U__CYGWIN__ -U__QNNXTO__ -U__amigaos__ -Uhpux -U__sgi \
- \
- -I . \
- -I Swift/QtUI \
- .
+ --enable=all \
+ --inline-suppr \
+ --suppress=postfixOperator:3rdParty/hippomocks.h \
+ --suppress=stlSize:3rdParty/hippomocks.h \
+ --suppress=noConstructor \
+ --suppress=publicAllocationError:Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp \
+ -i 3rdParty -i .git -i .sconf_temp \
+ -i Swift/QtUI/EventViewer/main.cpp \
+ -i Swift/QtUI/ApplicationTest \
+ -i Swift/QtUI/ChatView/main.cpp \
+ -i Swift/QtUI/Roster/main.cpp \
+ -i Swift/QtUI/NotifierTest/NotifierTest.cpp \
+ -DSWIFTEN_BUILDING -DSWIFTEN_STATIC \
+ -U__BEOS__ -U__CYGWIN__ -U__QNNXTO__ -U__amigaos__ -Uhpux -U__sgi \
+ \
+ -I . \
+ -I Swift/QtUI \
+ .
diff --git a/BuildTools/CrashReportAnalysis/WindowsMinidumpAnalyse.py b/BuildTools/CrashReportAnalysis/WindowsMinidumpAnalyse.py
new file mode 100644
index 0000000..dada920
--- /dev/null
+++ b/BuildTools/CrashReportAnalysis/WindowsMinidumpAnalyse.py
@@ -0,0 +1,134 @@
+#!/usr/bin/env python
+# Note
+# ----
+# This script requires:
+# - cdb, the Windows command line debugger installed and available in PATH.
+# - the SWIFT_DIST environment variable set to a locatioon that contains msi and pdb.gz files.
+
+import sys
+from subprocess import call
+from subprocess import Popen, PIPE
+import ntpath
+import shutil
+import re
+import urllib2
+import os
+import gzip
+import time
+
+
+swiftWindowBuildsPathPrefix = os.getenv("SWIFT_DIST")
+if swiftWindowBuildsPathPrefix == None :
+ print "Please set the SWIFT_DIST environment variable to a location containing msi and pdb.gz files."
+ sys.exit(1)
+
+if len(sys.argv) != 3:
+ print "Usage: python WindowsMinidumpAnalyse.py VERSION MINIDUMP_FILE"
+ sys.exit(1)
+
+version = sys.argv[1]
+minidump_file = sys.argv[2]
+minidump_filename = ntpath.basename(minidump_file)
+minidump_fullpath = os.path.abspath(minidump_file)
+humantext_fullpath = os.path.splitext(minidump_fullpath)[0]+".txt"
+symbol_cache_path = os.path.join(os.getenv("TEMP"), "\symbols")
+working_folder = "tmp-crash-{0}".format(minidump_filename)
+commit = ""
+
+def downloadInstaller(version) :
+ onlineFilename = "{0}.msi".format(version.capitalize())
+ url = "{0}{1}".format(swiftWindowBuildsPathPrefix, onlineFilename)
+ print("Download {0}.".format(url))
+ file = urllib2.urlopen(url)
+ with open(onlineFilename,'wb') as output:
+ output.write(file.read())
+
+def unpackInstaller(version) :
+ msiFilename = "{0}.msi".format(version.capitalize())
+ msiExtractDirectory = os.getcwd() + "\\msi"
+ if not os.path.exists(msiExtractDirectory):
+ os.makedirs(msiExtractDirectory)
+ print("Unpack {0} to {1}.".format(msiFilename, os.getcwd()))
+ call(["msiexec", "/a", msiFilename, "/qb", "TARGETDIR={0}".format(msiExtractDirectory)], shell=True)
+
+def unpackDebugSymbols(version) :
+ symbolsFilename = "{0}.pdb.gz".format(version.capitalize())
+ print("Unpack {0}.".format(symbolsFilename))
+ if not os.path.isdir(symbolsFilename):
+ with gzip.open(symbolsFilename, 'rb') as in_file:
+ s = in_file.read()
+
+ path_to_store = symbolsFilename[:-3]
+
+ with open("msi\PFiles\Swift\{0}".format("Swift.pdb"), 'wb') as f:
+ f.write(s)
+
+def downloadDebugSymbols(version) :
+ onlineFilename = "{0}.pdb.gz".format(version.capitalize())
+ url = "{0}{1}".format(swiftWindowBuildsPathPrefix, onlineFilename)
+ print("Download {0}.".format(url))
+ file = urllib2.urlopen(url)
+ with open(onlineFilename,'wb') as output:
+ output.write(file.read())
+
+def copyMinidump(filename) :
+ shutil.copyfile(filename, "msi\PFiles\Swift\{0}".format(minidump_filename))
+
+def printHumanReadableReport():
+ oldDir = os.getcwd()
+
+ # change dir to Swift.exe dir
+ os.chdir("msi\PFiles\Swift")
+
+ # print all stacks and analyze crash for exceptions
+ cdbCommand = ".symopt+0x40;.lines -e;.kframes 200;!analyze -v -p;!uniqstack -vp;.ecxr;k;q"
+
+ symbolPath = "cache*{0};srv*https://msdl.microsoft.com/download/symbols;C:\\Qt\\Qt5.4.2\\5.4\\msvc2013_opengl\\bin;C:\\Qt\\Qt5.4.2\\5.4\\msvc2013_opengl\\lib;{1}".format(symbol_cache_path, os.getcwd())
+
+ cdbFullCommand = ["cdb", "-i", os.getcwd(), "-y", symbolPath, "-z", minidump_filename, "-srcpath", oldDir, "-logo", humantext_fullpath, "-c", cdbCommand ]
+ print("Run command: " + str(cdbFullCommand))
+ call(cdbFullCommand)
+
+# for testing, delete the old folder
+try:
+ shutil.rmtree(working_folder)
+except:
+ print ""
+
+# clone local git repository into dedicated directory
+call(["git", "clone", ".", working_folder], shell=True)
+
+# git version from swift version
+match = re.match( r"(.*)-dev(\d+)", version)
+if match:
+ basetag = match.group(1)
+ commits = int(match.group(2))
+ process = Popen(["git", "-C", working_folder, "log", "--ancestry-path", "--format=%H", "{0}..HEAD".format(basetag)], stdout=PIPE)
+ (output, err) = process.communicate()
+ exit_code = process.wait()
+ commit = output.splitlines()[-commits].strip()
+else:
+ basetag = version
+ process = Popen(["git", "-C", working_folder, "log", "--format=%H", "-n", "1" "{0}".format(basetag)], stdout=PIPE)
+ (output, err) = process.communicate()
+ exit_code = process.wait()
+ commit = output.strip()
+
+assert(len(commit) > 0)
+
+# Create symbol cache directory
+if not os.path.exists(symbol_cache_path):
+ os.makedirs(symbol_cache_path)
+
+#print "Checking out commit {0}.".format(commit)
+call(["git", "-C", working_folder, "checkout", commit])
+
+os.chdir(working_folder)
+
+downloadInstaller(version)
+downloadDebugSymbols(version)
+unpackInstaller(version)
+unpackDebugSymbols(version)
+copyMinidump(minidump_fullpath)
+time.sleep(10)
+printHumanReadableReport()
diff --git a/BuildTools/DocBook/SCons/DocBook.py b/BuildTools/DocBook/SCons/DocBook.py
index 7641b65..ffb0bfc 100644
--- a/BuildTools/DocBook/SCons/DocBook.py
+++ b/BuildTools/DocBook/SCons/DocBook.py
@@ -6,100 +6,100 @@ import SCons.Util, SCons.Action
import xml.dom.minidom, re, os.path, sys
def generate(env) :
- # Location of stylesheets and catalogs
- docbook_dir = "#/BuildTools/DocBook"
- docbook_xsl_style_dir = env.Dir(docbook_dir + "/Stylesheets").abspath
- docbook_xml_catalog = env.File("catalog.xml").abspath
- if "DOCBOOK_XML_DIR" in env :
- docbook_xml_dir = env.Dir("$DOCBOOK_XML_DIR").abspath
- else :
- docbook_xml_dir = env.Dir("#/3rdParty/DocBook/XML").abspath
- if "DOCBOOK_XSL_DIR" in env :
- docbook_xsl_dir = env.Dir("$DOCBOOK_XSL_DIR").abspath
- else :
- docbook_xsl_dir = env.Dir("#/3rdParty/DocBook/XSL").abspath
- fop_fonts_dir = env.Dir(docbook_dir + "/Fonts").abspath
-
- # Generates a catalog from paths to external tools
- def buildCatalog(target, source, env) :
- catalog = """<?xml version='1.0'?>
+ # Location of stylesheets and catalogs
+ docbook_dir = "#/BuildTools/DocBook"
+ docbook_xsl_style_dir = env.Dir(docbook_dir + "/Stylesheets").abspath
+ docbook_xml_catalog = env.File("catalog.xml").abspath
+ if "DOCBOOK_XML_DIR" in env :
+ docbook_xml_dir = env.Dir("$DOCBOOK_XML_DIR").abspath
+ else :
+ docbook_xml_dir = env.Dir("#/3rdParty/DocBook/XML").abspath
+ if "DOCBOOK_XSL_DIR" in env :
+ docbook_xsl_dir = env.Dir("$DOCBOOK_XSL_DIR").abspath
+ else :
+ docbook_xsl_dir = env.Dir("#/3rdParty/DocBook/XSL").abspath
+ fop_fonts_dir = env.Dir(docbook_dir + "/Fonts").abspath
+
+ # Generates a catalog from paths to external tools
+ def buildCatalog(target, source, env) :
+ catalog = """<?xml version='1.0'?>
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="public">
- <rewriteSystem
- systemIdStartString="http://www.oasis-open.org/docbook/xml/4.5/"
- rewritePrefix="%(docbook_xml_dir)s/" />
- <rewriteSystem
- systemIdStartString="docbook-xsl:/"
- rewritePrefix="%(docbook_xsl_dir)s/" />
+ <rewriteSystem
+ systemIdStartString="http://www.oasis-open.org/docbook/xml/4.5/"
+ rewritePrefix="%(docbook_xml_dir)s/" />
+ <rewriteSystem
+ systemIdStartString="docbook-xsl:/"
+ rewritePrefix="%(docbook_xsl_dir)s/" />
</catalog>"""
- docbook_xml_dir = source[0].get_contents()
- docbook_xsl_dir = source[1].get_contents()
- if env["PLATFORM"] == "win32" :
- docbook_xml_dir = docbook_xml_dir.replace("\\","/")
- docbook_xsl_dir = docbook_xsl_dir.replace("\\","/")
- file = open(target[0].abspath, "w")
- file.write(catalog % {
- "docbook_xml_dir" : docbook_xml_dir,
- "docbook_xsl_dir" : docbook_xsl_dir,
- })
- file.close()
-
- # Generates a FOP config file
- def buildFopConfig(target, source, env) :
- fopcfg = """<fop version=\"1.0\">
- <renderers>
- <renderer mime=\"application/pdf\">
- <fonts>
- <directory recursive=\"true\">%(fonts_dir)s</directory>
- </fonts>
- </renderer>
- </renderers>
+ docbook_xml_dir = source[0].get_contents()
+ docbook_xsl_dir = source[1].get_contents()
+ if env["PLATFORM"] == "win32" :
+ docbook_xml_dir = docbook_xml_dir.replace("\\","/")
+ docbook_xsl_dir = docbook_xsl_dir.replace("\\","/")
+ file = open(target[0].abspath, "w")
+ file.write(catalog % {
+ "docbook_xml_dir" : docbook_xml_dir,
+ "docbook_xsl_dir" : docbook_xsl_dir,
+ })
+ file.close()
+
+ # Generates a FOP config file
+ def buildFopConfig(target, source, env) :
+ fopcfg = """<fop version=\"1.0\">
+ <renderers>
+ <renderer mime=\"application/pdf\">
+ <fonts>
+ <directory recursive=\"true\">%(fonts_dir)s</directory>
+ </fonts>
+ </renderer>
+ </renderers>
</fop>"""
- file = open(target[0].abspath, "w")
- file.write(fopcfg % {
- "fonts_dir" : source[0].get_contents()
- })
- file.close()
+ file = open(target[0].abspath, "w")
+ file.write(fopcfg % {
+ "fonts_dir" : source[0].get_contents()
+ })
+ file.close()
- # Builds a DocBook file
- def buildDocBook(env, source) :
- db_env = env.Clone()
- db_env["XMLCATALOGS"] = [docbook_xml_catalog]
- db_env["ENV"].update({"OS" : os.environ.get("OS", "")})
+ # Builds a DocBook file
+ def buildDocBook(env, source) :
+ db_env = env.Clone()
+ db_env["XMLCATALOGS"] = [docbook_xml_catalog]
+ db_env["ENV"].update({"OS" : os.environ.get("OS", "")})
- db_env["XMLLINT"] = env.WhereIs("xmllint")
- db_env["XSLT"] = env.WhereIs("xsltproc")
- db_env["FO"] = env.WhereIs("fop")
+ db_env["XMLLINT"] = env.WhereIs("xmllint")
+ db_env["XSLT"] = env.WhereIs("xsltproc")
+ db_env["FO"] = env.WhereIs("fop")
- if not db_env["XMLLINT"] or not db_env["XSLT"] :
- return
+ if not db_env["XMLLINT"] or not db_env["XSLT"] :
+ return
- # PDF generation
- if db_env["FO"] :
- fo = db_env.XSLT(os.path.splitext(source)[0] + ".fo", source,
- XSLTSTYLESHEET = db_env["DOCBOOK_XSL_FO"])
- pdf = db_env.FO(fo)
+ # PDF generation
+ if db_env["FO"] :
+ fo = db_env.XSLT(os.path.splitext(source)[0] + ".fo", source,
+ XSLTSTYLESHEET = db_env["DOCBOOK_XSL_FO"])
+ pdf = db_env.FO(fo)
- # HTML generation
- db_env.XSLT(os.path.splitext(source)[0] + ".html", source,
- XSLTSTYLESHEET = db_env["DOCBOOK_XSL_HTML"])
+ # HTML generation
+ db_env.XSLT(os.path.splitext(source)[0] + ".html", source,
+ XSLTSTYLESHEET = db_env["DOCBOOK_XSL_HTML"])
- # Import tools
- env.Tool("FO", toolpath = [docbook_dir + "/SCons"])
- env.Tool("XSLT", toolpath = [docbook_dir + "/SCons"])
+ # Import tools
+ env.Tool("FO", toolpath = [docbook_dir + "/SCons"])
+ env.Tool("XSLT", toolpath = [docbook_dir + "/SCons"])
- # Catalog file generation
- env.Command("catalog.xml", [env.Value(docbook_xml_dir), env.Value(docbook_xsl_dir)], SCons.Action.Action(buildCatalog, cmdstr = "$GENCOMSTR"))
+ # Catalog file generation
+ env.Command("catalog.xml", [env.Value(docbook_xml_dir), env.Value(docbook_xsl_dir)], SCons.Action.Action(buildCatalog, cmdstr = "$GENCOMSTR"))
- # FO config file generation
- env["FOCFG"] = env.File("fop.cfg").abspath
- env.Command("fop.cfg", [env.Value(fop_fonts_dir)], SCons.Action.Action(buildFopConfig, cmdstr = "$GENCOMSTR"))
+ # FO config file generation
+ env["FOCFG"] = env.File("fop.cfg").abspath
+ env.Command("fop.cfg", [env.Value(fop_fonts_dir)], SCons.Action.Action(buildFopConfig, cmdstr = "$GENCOMSTR"))
- # DocBook stylesheets
- env["DOCBOOK_XSL_FO"] = docbook_xsl_style_dir + "/fo/docbook.xsl"
- env["DOCBOOK_XSL_HTML"] = docbook_xsl_style_dir + "/html/docbook.xsl"
- env.AddMethod(buildDocBook, "DocBook")
+ # DocBook stylesheets
+ env["DOCBOOK_XSL_FO"] = docbook_xsl_style_dir + "/fo/docbook.xsl"
+ env["DOCBOOK_XSL_HTML"] = docbook_xsl_style_dir + "/html/docbook.xsl"
+ env.AddMethod(buildDocBook, "DocBook")
def exists(env) :
- return True
+ return True
diff --git a/BuildTools/DocBook/SCons/FO.py b/BuildTools/DocBook/SCons/FO.py
index a4079d7..c1c5614 100644
--- a/BuildTools/DocBook/SCons/FO.py
+++ b/BuildTools/DocBook/SCons/FO.py
@@ -6,40 +6,40 @@ import xml.dom.minidom, re
################################################################################
def generate(env) :
- def generate_actions(source, target, env, for_signature) :
- if len(env["FOCFG"]) > 0 :
- cmd = "$FO -c $FOCFG $FOFLAGS $SOURCE $TARGET"
- else :
- cmd = "$FO $FOFLAGS $SOURCE $TARGET"
- return SCons.Action.Action(cmd, cmdstr = "$FOCOMSTR")
+ def generate_actions(source, target, env, for_signature) :
+ if len(env["FOCFG"]) > 0 :
+ cmd = "$FO -c $FOCFG $FOFLAGS $SOURCE $TARGET"
+ else :
+ cmd = "$FO $FOFLAGS $SOURCE $TARGET"
+ return SCons.Action.Action(cmd, cmdstr = "$FOCOMSTR")
- def modify_sources(target, source, env) :
- if len(env["FOCFG"]) > 0 :
- source.append(env["FOCFG"])
- return target, source
+ def modify_sources(target, source, env) :
+ if len(env["FOCFG"]) > 0 :
+ source.append(env["FOCFG"])
+ return target, source
- def scan_fo(node, env, path) :
- dependencies = set()
- try :
- document = xml.dom.minidom.parseString(node.get_contents())
- except xml.parsers.expat.ExpatError:
- return []
- for include in document.getElementsByTagNameNS("http://www.w3.org/1999/XSL/Format", "external-graphic") :
- m = re.match("url\((.*)\)", include.getAttribute("src"))
- if m :
- dependencies.add(m.group(1))
- return list(dependencies)
+ def scan_fo(node, env, path) :
+ dependencies = set()
+ try :
+ document = xml.dom.minidom.parseString(node.get_contents())
+ except xml.parsers.expat.ExpatError:
+ return []
+ for include in document.getElementsByTagNameNS("http://www.w3.org/1999/XSL/Format", "external-graphic") :
+ m = re.match("url\((.*)\)", include.getAttribute("src"))
+ if m :
+ dependencies.add(m.group(1))
+ return list(dependencies)
- env["FO"] = "fop"
- env["FOFLAGS"] = ""
- env["FOCFG"] = ""
- env["BUILDERS"]["FO"] = SCons.Builder.Builder(
- generator = generate_actions,
- emitter = modify_sources,
- source_scanner = SCons.Scanner.Scanner(function = scan_fo, skeys = [".fo"]),
- suffix = ".pdf",
- src_suffix = ".fo"
- )
+ env["FO"] = "fop"
+ env["FOFLAGS"] = ""
+ env["FOCFG"] = ""
+ env["BUILDERS"]["FO"] = SCons.Builder.Builder(
+ generator = generate_actions,
+ emitter = modify_sources,
+ source_scanner = SCons.Scanner.Scanner(function = scan_fo, skeys = [".fo"]),
+ suffix = ".pdf",
+ src_suffix = ".fo"
+ )
def exists(env) :
- return True
+ return True
diff --git a/BuildTools/DocBook/SCons/XSLT.py b/BuildTools/DocBook/SCons/XSLT.py
index 825f129..38e36c5 100644
--- a/BuildTools/DocBook/SCons/XSLT.py
+++ b/BuildTools/DocBook/SCons/XSLT.py
@@ -6,58 +6,58 @@ import xml.dom.minidom, os, os.path
################################################################################
def generate(env) :
- def generate_actions(source, target, env, for_signature) :
- if not env.has_key("XSLTSTYLESHEET") :
- raise SCons.Errors.UserError, "The XSLTSTYLESHEET construction variable must be defined"
-
- # Process the XML catalog files
- # FIXME: It's probably not clean to do an ENV assignment globally
- env["ENV"]["XML_CATALOG_FILES"] = " ".join(env.get("XMLCATALOGS", ""))
-
- # Build the XMLLint command
- xmllintcmd = ["$XMLLINT", "--nonet", "--xinclude", "--postvalid", "--noout", "$SOURCE"]
-
- # Build the XSLT command
- xsltcmd = ["$XSLT", "--nonet", "--xinclude"]
- for (param, value) in env["XSLTPARAMS"] :
- xsltcmd += ["--stringparam", param, value]
- xsltcmd += ["-o", "$TARGET", "$XSLTSTYLESHEET", "$SOURCE"]
-
- return [
- SCons.Action.Action([xmllintcmd], cmdstr = "$XMLLINTCOMSTR"),
- SCons.Action.Action([xsltcmd], cmdstr = "$XSLTCOMSTR")]
-
- def modify_sources(target, source, env) :
- if len(env["FOCFG"]) > 0 :
- source.append(env["FOCFG"])
- source.append(env.get("XMLCATALOGS", []))
- return target, source
-
- def scan_xml(node, env, path) :
- dependencies = set()
- nodes = [node]
- while len(nodes) > 0 :
- node = nodes.pop()
- try :
- document = xml.dom.minidom.parseString(node.get_contents())
- except xml.parsers.expat.ExpatError:
- continue
- for include in document.getElementsByTagNameNS("http://www.w3.org/2001/XInclude", "include") :
- include_file = include.getAttribute("href")
- dependencies.add(include_file)
- if include.getAttribute("parse") != "text" :
- nodes.append(env.File(include_file))
- return list(dependencies)
-
- env["XMLLINT"] = "xmllint"
- env["XSLT"] = "xsltproc"
- env["XSLTPARAMS"] = []
- env["BUILDERS"]["XSLT"] = SCons.Builder.Builder(
- generator = generate_actions,
- emitter = modify_sources,
- source_scanner = SCons.Scanner.Scanner(function = scan_xml),
- src_suffix = ".xml"
- )
+ def generate_actions(source, target, env, for_signature) :
+ if not env.has_key("XSLTSTYLESHEET") :
+ raise SCons.Errors.UserError, "The XSLTSTYLESHEET construction variable must be defined"
+
+ # Process the XML catalog files
+ # FIXME: It's probably not clean to do an ENV assignment globally
+ env["ENV"]["XML_CATALOG_FILES"] = " ".join(env.get("XMLCATALOGS", ""))
+
+ # Build the XMLLint command
+ xmllintcmd = ["$XMLLINT", "--nonet", "--xinclude", "--postvalid", "--noout", "$SOURCE"]
+
+ # Build the XSLT command
+ xsltcmd = ["$XSLT", "--nonet", "--xinclude"]
+ for (param, value) in env["XSLTPARAMS"] :
+ xsltcmd += ["--stringparam", param, value]
+ xsltcmd += ["-o", "$TARGET", "$XSLTSTYLESHEET", "$SOURCE"]
+
+ return [
+ SCons.Action.Action([xmllintcmd], cmdstr = "$XMLLINTCOMSTR"),
+ SCons.Action.Action([xsltcmd], cmdstr = "$XSLTCOMSTR")]
+
+ def modify_sources(target, source, env) :
+ if len(env["FOCFG"]) > 0 :
+ source.append(env["FOCFG"])
+ source.append(env.get("XMLCATALOGS", []))
+ return target, source
+
+ def scan_xml(node, env, path) :
+ dependencies = set()
+ nodes = [node]
+ while len(nodes) > 0 :
+ node = nodes.pop()
+ try :
+ document = xml.dom.minidom.parseString(node.get_contents())
+ except xml.parsers.expat.ExpatError:
+ continue
+ for include in document.getElementsByTagNameNS("http://www.w3.org/2001/XInclude", "include") :
+ include_file = include.getAttribute("href")
+ dependencies.add(include_file)
+ if include.getAttribute("parse") != "text" :
+ nodes.append(env.File(include_file))
+ return list(dependencies)
+
+ env["XMLLINT"] = "xmllint"
+ env["XSLT"] = "xsltproc"
+ env["XSLTPARAMS"] = []
+ env["BUILDERS"]["XSLT"] = SCons.Builder.Builder(
+ generator = generate_actions,
+ emitter = modify_sources,
+ source_scanner = SCons.Scanner.Scanner(function = scan_xml),
+ src_suffix = ".xml"
+ )
def exists(env) :
- return True
+ return True
diff --git a/BuildTools/FilterScanBuildResults.py b/BuildTools/FilterScanBuildResults.py
index ed4a55f..a4861ac 100755
--- a/BuildTools/FilterScanBuildResults.py
+++ b/BuildTools/FilterScanBuildResults.py
@@ -6,23 +6,23 @@ resultsDir = sys.argv[1]
resultDirs = [ d for d in os.listdir(resultsDir) if os.path.isdir(os.path.join(resultsDir, d)) ]
resultDirs.sort()
if len(resultDirs) > 0 :
- resultDir = os.path.join(resultsDir, resultDirs[-1])
- resultFileName = os.path.join(resultDir, "index.html")
- resultData = []
- f = open(resultFileName, "r")
- skipLines = 0
- for line in f.readlines() :
- if skipLines > 0 :
- skipLines -= 1
- else :
- if ("3rdParty" in line or "SHA1.cpp" in line or "lua.c" in line) :
- m = re.match(".*(report-.*\.html)", line)
- os.remove(os.path.join(resultDir, m.group(1)))
- skipLines = 2
- else :
- resultData.append(line)
- f.close()
+ resultDir = os.path.join(resultsDir, resultDirs[-1])
+ resultFileName = os.path.join(resultDir, "index.html")
+ resultData = []
+ f = open(resultFileName, "r")
+ skipLines = 0
+ for line in f.readlines() :
+ if skipLines > 0 :
+ skipLines -= 1
+ else :
+ if ("3rdParty" in line or "SHA1.cpp" in line or "lua.c" in line) :
+ m = re.match(".*(report-.*\.html)", line)
+ os.remove(os.path.join(resultDir, m.group(1)))
+ skipLines = 2
+ else :
+ resultData.append(line)
+ f.close()
- f = open(resultFileName, "w")
- f.writelines(resultData)
- f.close()
+ f = open(resultFileName, "w")
+ f.writelines(resultData)
+ f.close()
diff --git a/BuildTools/FixIncludes.py b/BuildTools/FixIncludes.py
index 8ecbd4a..8984944 100755
--- a/BuildTools/FixIncludes.py
+++ b/BuildTools/FixIncludes.py
@@ -9,7 +9,7 @@ filename = sys.argv[1]
inPlace = False
if "-i" in sys.argv:
- inPlace = True
+ inPlace = True
filename_base = os.path.basename(filename)
(filename_name, filename_ext) = os.path.splitext(filename_base)
@@ -19,135 +19,147 @@ c_stdlib_headers = Set(["assert.h", "limits.h", "signal.h", "stdlib.h", "ctyp
cpp_stdlib_headers = Set(["algorithm", "fstream", "list", "regex", "typeindex", "array", "functional", "locale", "set", "typeinfo", "atomic", "future", "map", "sstream", "type_traits", "bitset", "initializer_list", "memory", "stack", "unordered_map", "chrono", "iomanip", "mutex", "stdexcept", "unordered_set", "codecvt", "ios", "new", "streambuf", "utility", "complex", "iosfwd", "numeric", "string", "valarray", "condition_variable", "iostream", "ostream", "strstream", "vector", "deque", "istream", "queue", "system_error", "exception", "iterator", "random", "thread", "forward_list", "limits", "ratio", "tuple", "cassert", "ciso646", "csetjmp", "cstdio", "ctime", "cctype", "climits", "csignal", "cstdlib", "cwchar", "cerrno", "clocale", "cstdarg", "cstring", "cwctype", "cfloat", "cmath", "cstddef"])
class HeaderType:
- PRAGMA_ONCE, CORRESPONDING_HEADER, C_STDLIB, CPP_STDLIB, BOOST, QT, OTHER, SWIFTEN, SWIFT_CONTROLLERS, SWIFTOOLS, SWIFT = range(11)
+ PRAGMA_ONCE, CORRESPONDING_HEADER, C_STDLIB, CPP_STDLIB, BOOST, QT, SWIFTEN_BASE_DEBUG, OTHER, SWIFTEN, LIMBER, SLIMBER, SWIFT_CONTROLLERS, SLUIFT, SWIFTOOLS, SWIFT = range(15)
def findHeaderBlock(lines):
- start = False
- end = False
- lastLine = None
-
- for idx, line in enumerate(lines):
- if not start and line.startswith("#"):
- start = idx
- elif start and (not end) and (not line.startswith("#")) and line.strip():
- end = idx-1
- break
- if not end:
- end = len(lines)
- return (start, end)
+ start = False
+ end = False
+ lastLine = None
+
+ for idx, line in enumerate(lines):
+ if not start and line.startswith("#"):
+ start = idx
+ elif start and (not end) and (not line.startswith("#")) and line.strip():
+ end = idx-1
+ break
+ if not end:
+ end = len(lines)
+ return (start, end)
def lineToFileName(line):
- match = re.match( r'#include "(.*)"', line)
- if match:
- return match.group(1)
- match = re.match( r'#include <(.*)>', line)
- if match:
- return match.group(1)
- return False
+ match = re.match( r'#include "(.*)"', line)
+ if match:
+ return match.group(1)
+ match = re.match( r'#include <(.*)>', line)
+ if match:
+ return match.group(1)
+ return False
def fileNameToHeaderType(name):
- if name.endswith(filename_name + ".h"):
- return HeaderType.CORRESPONDING_HEADER
+ if name.endswith("/" + filename_name + ".h"):
+ return HeaderType.CORRESPONDING_HEADER
- if name in c_stdlib_headers:
- return HeaderType.C_STDLIB
+ if name in c_stdlib_headers:
+ return HeaderType.C_STDLIB
- if name in cpp_stdlib_headers:
- return HeaderType.CPP_STDLIB
+ if name in cpp_stdlib_headers:
+ return HeaderType.CPP_STDLIB
- if name.startswith("boost"):
- return HeaderType.BOOST
+ if name.startswith("boost"):
+ return HeaderType.BOOST
- if name.startswith("Q"):
- return HeaderType.QT
+ if name.startswith("Q"):
+ return HeaderType.QT
- if name.startswith("Swiften"):
- return HeaderType.SWIFTEN
+ if name.startswith("Swiften/Base/Debug.h"):
+ return HeaderType.SWIFTEN_BASE_DEBUG
- if name.startswith("Swift/Controllers"):
- return HeaderType.SWIFT_CONTROLLERS
+ if name.startswith("Swiften"):
+ return HeaderType.SWIFTEN
- if name.startswith("SwifTools"):
- return HeaderType.SWIFTOOLS
+ if name.startswith("Limber"):
+ return HeaderType.LIMBER
- if name.startswith("Swift"):
- return HeaderType.SWIFT
+ if name.startswith("Slimber"):
+ return HeaderType.SLIMBER
- return HeaderType.OTHER
+ if name.startswith("Swift/Controllers"):
+ return HeaderType.SWIFT_CONTROLLERS
+
+ if name.startswith("Sluift"):
+ return HeaderType.SLUIFT
+
+ if name.startswith("SwifTools"):
+ return HeaderType.SWIFTOOLS
+
+ if name.startswith("Swift"):
+ return HeaderType.SWIFT
+
+ return HeaderType.OTHER
def serializeHeaderGroups(groups):
- headerList = []
- for group in range(0, HeaderType.SWIFT + 1):
- if group in groups:
- # sorted and without duplicates
- headers = sorted(list(set(groups[group])))
- headerList.extend(headers)
- headerList.extend(["\n"])
- headerList.pop()
- return headerList
+ headerList = []
+ for group in range(0, HeaderType.SWIFT + 1):
+ if group in groups:
+ # sorted and without duplicates
+ headers = sorted(list(set(groups[group])))
+ headerList.extend(headers)
+ headerList.extend(["\n"])
+ headerList.pop()
+ return headerList
def overwriteFile(filename, content):
- with open(filename, 'w') as f:
- for line in content:
- f.write(line)
+ with open(filename, 'w') as f:
+ for line in content:
+ f.write(line)
def cleanHeaderFile(content, headerStart, headerEnd, headerGroups):
- del content[headerStart:headerEnd]
- newHeaders = serializeHeaderGroups(headerGroups)
- content[headerStart:1] = newHeaders
+ del content[headerStart:headerEnd]
+ newHeaders = serializeHeaderGroups(headerGroups)
+ content[headerStart:1] = newHeaders
- if inPlace :
- overwriteFile(filename, content)
- else :
- for line in content:
- print line,
+ if inPlace :
+ overwriteFile(filename, content)
+ else :
+ for line in content:
+ print line,
def cleanImplementationFile(content, headerStart, headerEnd, headerGroups):
- del content[headerStart:headerEnd]
- newHeaders = serializeHeaderGroups(headerGroups)
- content[headerStart:1] = newHeaders
+ del content[headerStart:headerEnd]
+ newHeaders = serializeHeaderGroups(headerGroups)
+ content[headerStart:1] = newHeaders
- if inPlace :
- overwriteFile(filename, content)
- else :
- for line in content:
- print line,
+ if inPlace :
+ overwriteFile(filename, content)
+ else :
+ for line in content:
+ print line,
containsComplexPreprocessorDirectives = False
with open(filename) as f:
- content = f.readlines()
+ content = f.readlines()
(headerStart, headerEnd) = findHeaderBlock(content)
headerGroups = {}
for line in content[headerStart:headerEnd]:
- if line.strip():
- if line.strip().startswith("#pragma once"):
- headerType = HeaderType.PRAGMA_ONCE
- elif line.strip().startswith("#if") or line.strip().startswith("#def") or line.strip().startswith("#undef") or line.strip().startswith("#pragma "):
- containsComplexPreprocessorDirectives = True
- break
- else:
- #print line
- headerType = fileNameToHeaderType(lineToFileName(line))
-
- #filename = lineToFileName(line)
- if headerType in headerGroups:
- headerGroups[headerType].append(line)
- else:
- headerGroups[headerType] = [line]
+ if line.strip():
+ if line.strip().startswith("#pragma once"):
+ headerType = HeaderType.PRAGMA_ONCE
+ elif line.strip().startswith("#if") or line.strip().startswith("#def") or line.strip().startswith("#undef") or line.strip().startswith("#pragma "):
+ containsComplexPreprocessorDirectives = True
+ break
+ else:
+ #print line
+ headerType = fileNameToHeaderType(lineToFileName(line))
+
+ #filename = lineToFileName(line)
+ if headerType in headerGroups:
+ headerGroups[headerType].append(line)
+ else:
+ headerGroups[headerType] = [line]
if containsComplexPreprocessorDirectives:
- print "Cannot format headers containing preprocessor #if, #pragma, #define or #undef statements!"
- exit(1)
+ print "Cannot format headers containing preprocessor #if, #pragma, #define or #undef statements!"
+ exit(1)
if filename_base.endswith(".h"):
- if not HeaderType.PRAGMA_ONCE in headerGroups:
- print "Missing #pragma once!"
- exit(2)
- cleanHeaderFile(content, headerStart, headerEnd, headerGroups)
-elif filename_base.endswith(".cpp"):
- cleanImplementationFile(content, headerStart, headerEnd, headerGroups)
+ if not HeaderType.PRAGMA_ONCE in headerGroups:
+ print "Missing #pragma once!"
+ exit(2)
+ cleanHeaderFile(content, headerStart, headerEnd, headerGroups)
+elif filename_base.endswith(".cpp") or filename_base.endswith(".mm"):
+ cleanImplementationFile(content, headerStart, headerEnd, headerGroups)
diff --git a/BuildTools/GenerateAppCastFeeds.py b/BuildTools/GenerateAppCastFeeds.py
new file mode 100755
index 0000000..8135134
--- /dev/null
+++ b/BuildTools/GenerateAppCastFeeds.py
@@ -0,0 +1,153 @@
+#!/usr/bin/env python2
+
+# This script generates three app cast feeds for macOS Sparkle updates from Swift releases in the download folder on the Swift website.
+
+from xml.etree import ElementTree as ET
+import argparse
+import datetime
+import email.utils as eut
+import fnmatch
+import jinja2
+import os.path
+import re
+import time
+import urllib2
+import urlparse
+
+class Release:
+ def __init__(self, version, absoluteURL, sizeInBytes, date):
+ # This is the version string used for update detection.
+ self.fullVersion = version.split('-', 1)[1]
+ # This is a human readable version string, only used for presentation.
+ self.presentationVersion = version
+ self.url = absoluteURL
+ self.sizeInBytes = sizeInBytes
+ self.date = date
+ dateTumple = date.timetuple()
+ dateTimestamp = time.mktime(dateTumple)
+ self.dateString = eut.formatdate(dateTimestamp)
+
+ def __str__(self):
+ return "Release(%s, %s, %s, %s)" % (self.fullVersion, self.url, self.sizeInBytes, self.date)
+
+ def __repr__(self):
+ return "Release(%s, %s, %s, %s)" % (self.fullVersion, self.url, self.sizeInBytes, self.date)
+
+def getReleaseFromAbsoluteFilePath(absolutePath, downloadsFolder, releasesURL):
+ version = os.path.splitext(absolutePath.split('/')[-1])[0]
+ sizeInBytes = os.path.getsize(absolutePath)
+ date = datetime.datetime.fromtimestamp(os.path.getmtime(absolutePath))
+ absoluteURL = urlparse.urljoin(releasesURL, os.path.relpath(absolutePath, downloadsFolder))
+ return Release(version, absoluteURL, sizeInBytes, date)
+
+def getReleaseFromReleaseFolder(releaseFolder, downloadsFolder, releasesURL, extension):
+ release = None
+ regex = re.compile(fnmatch.translate(extension))
+
+ files = [f for f in os.listdir(releaseFolder) if os.path.isfile(os.path.join(releaseFolder, f))]
+ for file in files:
+ fileFullPath = os.path.join(releaseFolder, file)
+ if regex.match(fileFullPath):
+ release = getReleaseFromAbsoluteFilePath(fileFullPath, downloadsFolder, releasesURL)
+ return release
+
+def getReleaseFilesInReleasesFolder(releasesFolder, releasesURL, extension):
+ releases = []
+
+ dirs = [d for d in os.listdir(releasesFolder) if os.path.isdir(os.path.join(releasesFolder, d))]
+ for d in dirs:
+ release = getReleaseFromReleaseFolder(os.path.join(releasesFolder, d), releasesFolder, releasesURL, extension)
+ if release:
+ releases.append(release)
+
+ return releases
+
+def getReleaseFilesInDevelopmentFolder(developmentMacFolder, developmentMacURL, extension):
+ extensionRegex = re.compile(fnmatch.translate(extension))
+ devPatternRegex = re.compile(".+-dev\d+")
+
+ releases = []
+
+ files = [f for f in os.listdir(developmentMacFolder) if os.path.isfile(os.path.join(developmentMacFolder, f))]
+ for f in files:
+ # Only use dev builds from the development folder.
+ if devPatternRegex.match(f):
+ fileFullPath = os.path.join(developmentMacFolder, f)
+ if extensionRegex.match(fileFullPath):
+ releases.append(getReleaseFromAbsoluteFilePath(fileFullPath, developmentMacFolder, developmentMacURL))
+
+ return releases
+
+def writeAppcastFile(filename, title, description, regexPattern, appcastURL, releases):
+ template = jinja2.Template('''<rss xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
+ <channel>
+ <title>{{ title }}</title>
+ <link>{{ appcast_url }}</link>
+ <description>{{ description }}</description>
+ <language>en</language>
+ {% for item in releases %}<item>
+ <title>Swift version {{ item.fullVersion }}</title>
+ <pubDate>{{ item.dateString }}</pubDate>
+ <enclosure url="{{ item.url }}"
+ sparkle:version="{{ item.fullVersion }}"
+ sparkle:shortVersionString="{{ item.presentationVersion }}"
+ length="{{ item.sizeInBytes }}"
+ type="application/octet-stream" />
+ </item>
+ {% endfor %}</channel>
+</rss>''')
+
+ matchingReleases = [i for i in releases if re.match(regexPattern, i.fullVersion)]
+ matchingReleases = matchingReleases[:2] # only include the first two matches in the appcast
+
+ appcastContent = template.render(title=title, appcast_url=appcastURL, description=description, releases=matchingReleases)
+
+ contentParsesOK = False
+ try:
+ x = ET.fromstring(appcastContent)
+ contentParsesOK = True
+ except :
+ contentParsesOK = False
+
+ if contentParsesOK:
+ with open(filename, 'w') as file:
+ file.write(appcastContent)
+ else:
+ print("Failed to generate valid appcast feed %s." % filename)
+
+parser = argparse.ArgumentParser(description='Generate stable/testing/development appcast feeds for Sparkle updater.')
+parser.add_argument('downloadsFolder', type=str, help="e.g. /Users/foo/website/downloads/")
+parser.add_argument('downloadsURL', type=str, help="e.g. https://swift.im/downloads/")
+parser.add_argument('outputFolder', type=str, help="e.g. /Users/foo/website/downloads/")
+
+args = parser.parse_args()
+
+releasesPath = os.path.join(args.downloadsFolder, "releases")
+developmentMacPath = os.path.join(args.downloadsFolder, "development", "mac")
+
+manualReleases = getReleaseFilesInReleasesFolder(releasesPath, urlparse.urljoin(args.downloadsURL, "releases/"), "*.dmg")
+manualReleases.sort(key=lambda release: release.date, reverse=True)
+
+automaticReleases = manualReleases
+automaticReleases.extend(getReleaseFilesInDevelopmentFolder(developmentMacPath, urlparse.urljoin(args.downloadsURL, "development/mac/"), "*.dmg"))
+automaticReleases.sort(key=lambda release: release.date, reverse=True)
+
+
+writeAppcastFile(filename=os.path.join(args.outputFolder, "swift-stable-appcast-mac.xml"),
+ title="Swift Stable Releases",
+ description="",
+ regexPattern="^\d+(\.\d+)?(\.\d+)?$",
+ appcastURL=urlparse.urljoin(args.downloadsURL, "swift-stable-appcast-mac.xml"),
+ releases=manualReleases)
+writeAppcastFile(filename=os.path.join(args.outputFolder, "swift-testing-appcast-mac.xml"),
+ title="Swift Testing Releases",
+ description="",
+ regexPattern="^\d+(\.\d+)?(\.\d+)?(beta\d+)?(rc\d+)?$",
+ appcastURL=urlparse.urljoin(args.downloadsURL, "swift-testing-appcast-mac.xml"),
+ releases=manualReleases)
+writeAppcastFile(filename=os.path.join(args.outputFolder, "swift-development-appcast-mac.xml"),
+ title="Swift Development Releases",
+ description="",
+ regexPattern="^\d+(\.\d+)?(\.\d+)?(alpha)?(beta\d+)?(rc\d+)?(-dev\d+)?$",
+ appcastURL=urlparse.urljoin(args.downloadsURL, "swift-development-appcast-mac.xml"),
+ releases=automaticReleases)
diff --git a/BuildTools/GetBuildVersion.py b/BuildTools/GetBuildVersion.py
index fc92d15..70fdc5c 100755
--- a/BuildTools/GetBuildVersion.py
+++ b/BuildTools/GetBuildVersion.py
@@ -8,14 +8,14 @@ assert(len(sys.argv) >= 2)
only_major = False
if "--major" in sys.argv :
- only_major = True
+ only_major = True
if only_major :
- v = Version.getBuildVersion(os.path.dirname(sys.argv[0]) + "/..", sys.argv[1])
- version_match = re.match("(\d+)\.(\d+).*", v)
- if version_match :
- print version_match.group(1)
- else :
- print "0"
+ v = Version.getBuildVersion(os.path.dirname(sys.argv[0]) + "/..", sys.argv[1])
+ version_match = re.match("(\d+)\.(\d+).*", v)
+ if version_match :
+ print version_match.group(1)
+ else :
+ print "0"
else :
- print Version.getBuildVersion(os.path.dirname(sys.argv[0]) + "/..", sys.argv[1])
+ print Version.getBuildVersion(os.path.dirname(sys.argv[0]) + "/..", sys.argv[1])
diff --git a/BuildTools/Gource/GetGravatars.py b/BuildTools/Gource/GetGravatars.py
index 47f8a68..d1f40a4 100755
--- a/BuildTools/Gource/GetGravatars.py
+++ b/BuildTools/Gource/GetGravatars.py
@@ -5,8 +5,8 @@ import subprocess, os, sys, hashlib, urllib
GRAVATAR_URL = "http://www.gravatar.com/avatar/%(id)s?d=404"
if len(sys.argv) != 2 :
- print "Usage: " + sys.argv[0] + " <output-dir>"
- sys.exit(-1)
+ print "Usage: " + sys.argv[0] + " <output-dir>"
+ sys.exit(-1)
output_dir = sys.argv[1]
@@ -14,36 +14,36 @@ output_dir = sys.argv[1]
authors = {}
p = subprocess.Popen("git log --pretty=format:'%ae|%an'", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(os.name != "nt"))
for line in p.stdout.readlines() :
- author_components = line.rstrip().split("|")
- authors[author_components[0]] = author_components[1]
+ author_components = line.rstrip().split("|")
+ authors[author_components[0]] = author_components[1]
p.stdin.close()
if p.wait() != 0 :
- print "Error"
- sys.exit(-1)
+ print "Error"
+ sys.exit(-1)
# Get & save the avatars
if not os.path.isdir(output_dir) :
- os.makedirs(output_dir)
+ os.makedirs(output_dir)
for email, name in authors.items() :
- print "Processing avatar for " + name + " <" + email + ">"
- filename = os.path.join(output_dir, name + ".png")
- if os.path.isfile(filename) :
- print "-> Already there. Skipping."
- continue
+ print "Processing avatar for " + name + " <" + email + ">"
+ filename = os.path.join(output_dir, name + ".png")
+ if os.path.isfile(filename) :
+ print "-> Already there. Skipping."
+ continue
- m = hashlib.md5()
- m.update(email)
- url = GRAVATAR_URL % {"id" : m.hexdigest()}
- print "- Downloading " + url
- f = urllib.urlopen(url)
- input = None
- if f.getcode() == 200 :
- input = f.read()
- f.close()
- if input :
- print "- Saving file " + filename
- f = open(filename, "w")
- f.write(input)
- f.close()
- else :
- print "- No Gravatar found"
+ m = hashlib.md5()
+ m.update(email)
+ url = GRAVATAR_URL % {"id" : m.hexdigest()}
+ print "- Downloading " + url
+ f = urllib.urlopen(url)
+ input = None
+ if f.getcode() == 200 :
+ input = f.read()
+ f.close()
+ if input :
+ print "- Saving file " + filename
+ f = open(filename, "w")
+ f.write(input)
+ f.close()
+ else :
+ print "- No Gravatar found"
diff --git a/BuildTools/InstallSwiftDependencies.sh b/BuildTools/InstallSwiftDependencies.sh
index 64cdc5e..f957e3d 100755
--- a/BuildTools/InstallSwiftDependencies.sh
+++ b/BuildTools/InstallSwiftDependencies.sh
@@ -6,27 +6,31 @@ SYSTEM_NAME=$(uname)
if [ "$SYSTEM_NAME" == "Linux" ]
then
- # handle linux distributions
- SYSTEM_DISTRO=$(lsb_release -i -s)
- if [ "$SYSTEM_DISTRO" == "Debian" ]
- then
- sudo apt-get install pkg-config libssl-dev qt5-default libqt5x11extras5-dev libqt5webkit5-dev qtmultimedia5-dev qttools5-dev-tools
- elif [ "$SYSTEM_DISTRO" == "Ubuntu" ]
- then
- sudo apt-get install pkg-config libssl-dev qt5-default libqt5x11extras5-dev libqt5webkit5-dev qtmultimedia5-dev qttools5-dev-tools
- elif [ "$SYSTEM_DISTRO" == "Arch" ]
- then
- sudo pacman -S qt5-base qt5-x11extras qt5-webkit qt5-multimedia qt5-tools
- elif [ "$SYSTEM_DISTRO" == "openSUSE project" ]
- then
- sudo zypper in pkg-config libopenssl-devel libQt5Core-devel libQt5WebKit5-devel libQt5WebKitWidgets-devel libqt5-qtmultimedia-devel libqt5-qtx11extras-devel libqt5-qttools-devel libQt5Gui-devel libQt5Network-devel libQt5DBus-devel
- elif [ "$SYSTEM_DISTRO" == "Fedora" ]
- then
- sudo dnf groups install "C Development Tools and Libraries"
- sudo dnf install openssl-devel qt5-qtbase-devel qt5-linguist qt5-qtwebkit-devel qt5-qtmultimedia-devel qt5-qtx11extras-devel
- else
- echo "Unsupported Linux distribution."
- fi
+ # handle linux distributions
+ SYSTEM_DISTRO=$(lsb_release -i -s)
+ if [ "$SYSTEM_DISTRO" == "Debian" ]
+ then
+ sudo apt-get install build-essential pkg-config libssl-dev qt5-default libqt5x11extras5-dev libqt5webkit5-dev qtmultimedia5-dev qttools5-dev-tools qt5-image-formats-plugins libqt5svg5-dev libminiupnpc-dev libnatpmp-dev libhunspell-dev
+ elif [ "$SYSTEM_DISTRO" == "Ubuntu" ]
+ then
+ sudo apt-get install build-essential pkg-config libssl-dev qt5-default libqt5x11extras5-dev libqt5webkit5-dev qtmultimedia5-dev qttools5-dev-tools qt5-image-formats-plugins libqt5svg5-dev libminiupnpc-dev libnatpmp-dev libhunspell-dev
+ elif [ "$SYSTEM_DISTRO" == "Arch" ]
+ then
+ sudo pacman -S qt5-base qt5-x11extras qt5-webkit qt5-multimedia qt5-tools qt5-svg hunspell
+ elif [ "$SYSTEM_DISTRO" == "openSUSE project" ] || [ "$SYSTEM_DISTRO" == "SUSE LINUX" ]
+ then
+ sudo zypper "$@" in --type pattern devel_basis
+ sudo zypper "$@" in pkg-config libopenssl-devel libQt5Core-devel libQt5WebKit5-devel libQt5WebKitWidgets-devel libqt5-qtmultimedia-devel libqt5-qtx11extras-devel libqt5-qttools-devel libQt5Gui-devel libQt5Network-devel libQt5DBus-devel libQt5Svg-devel libQt5Svg5 python-xml hunspell-devel
+ elif [ "$SYSTEM_DISTRO" == "Fedora" ]
+ then
+ sudo dnf groups install "C Development Tools and Libraries"
+ sudo dnf install openssl-devel qt5-qtbase-devel qt5-linguist qt5-qtwebkit-devel qt5-qtmultimedia-devel qt5-qtx11extras-devel qt5-qtsvg-devel hunspell-devel
+ elif [ "$SYSTEM_DISTRO" == "Sabayon" ]
+ then
+ sudo -E equo install sys-devel/autoconf sys-devel/automake sys-devel/gcc sys-devel/g++ virtual/os-headers virtual/pkgconfig sys-libs/glibc dev-qt/linguist-tools dev-qt/qtcore dev-qt/qtmultimedia dev-qt/qtdbus dev-qt/qtgui dev-qt/qtimageformats dev-qt/qtsvg dev-qt/qtwebkit dev-qt/qtwidgets dev-qt/qtx11extras dev-libs/openssl net-libs/miniupnpc net-libs/libnatpmp app-text/hunspell
+ else
+ echo "Unsupported Linux distribution."
+ fi
else
- echo "Unsupported system."
+ echo "Unsupported system."
fi
diff --git a/BuildTools/SCons/SConscript.boot b/BuildTools/SCons/SConscript.boot
index 14f72c7..031c556 100644
--- a/BuildTools/SCons/SConscript.boot
+++ b/BuildTools/SCons/SConscript.boot
@@ -14,8 +14,9 @@ vars.Add('link', "Linker")
vars.Add('linkflags', "Extra linker flags")
vars.Add('ar', "Archiver (ar or lib)")
if os.name == "nt":
- vars.Add('mt', "manifest tool")
+ vars.Add('mt', "manifest tool")
vars.Add(BoolVariable("ccache", "Use CCache", "no"))
+vars.Add(BoolVariable("distcc", "Use distcc", "no"))
vars.Add(EnumVariable("test", "Compile and run tests", "none", ["none", "all", "unit", "system"]))
vars.Add(BoolVariable("optimize", "Compile with optimizations turned on", "no"))
vars.Add(BoolVariable("debug", "Compile with debug information", "yes"))
@@ -28,29 +29,30 @@ vars.Add('android_sdk_bin', "Path to Android SDK's tools directory")
vars.Add(BoolVariable("swift_mobile", "Build mobile Swift", "no"))
vars.Add(BoolVariable("swiften_dll", "Build Swiften as dynamically linked library", "no"))
if os.name != "nt" :
- vars.Add(BoolVariable("coverage", "Compile with coverage information", "no"))
+ vars.Add(BoolVariable("coverage", "Compile with coverage information", "no"))
if os.name == "posix" :
- vars.Add(BoolVariable("valgrind", "Run tests with valgrind", "no"))
+ vars.Add(BoolVariable("valgrind", "Run tests with valgrind", "no"))
if os.name == "mac" or (os.name == "posix" and os.uname()[0] == "Darwin"):
- vars.Add(BoolVariable("universal", "Create universal binaries", "no"))
- vars.Add(BoolVariable("mac105", "Link against the 10.5 frameworks", "no"))
- vars.Add(BoolVariable("mac106", "Link against the 10.6 frameworks", "no"))
+ vars.Add(BoolVariable("universal", "Create universal binaries", "no"))
+ vars.Add(BoolVariable("mac105", "Link against the 10.5 frameworks", "no"))
+ vars.Add(BoolVariable("mac106", "Link against the 10.6 frameworks", "no"))
if os.name == "nt" :
- vars.Add(PathVariable("vcredist", "MSVC redistributable dir", None, PathVariable.PathAccept))
+ vars.Add(PathVariable("vcredist", "MSVC redistributable dir", None, PathVariable.PathAccept))
if os.name == "nt" :
- vars.Add(PathVariable("wix_bindir", "Path to WiX binaries", "", PathVariable.PathAccept))
+ vars.Add(PathVariable("wix_bindir", "Path to WiX binaries", "", PathVariable.PathAccept))
if os.name == "nt" :
- vars.Add(PackageVariable("bonjour", "Bonjour SDK location", "yes"))
+ vars.Add(PackageVariable("bonjour", "Bonjour SDK location", "yes"))
+vars.Add(EnumVariable("tls_backend", "Choose the TLS backend", "native", ["native", "openssl", "openssl_bundled"]))
vars.Add(PackageVariable("openssl", "OpenSSL location", "yes"))
vars.Add("openssl_libnames", "Comma-separated openssl library names to override defaults", None)
-vars.Add(BoolVariable("openssl_force_bundled", "Force use of the bundled OpenSSL", "no"))
vars.Add("openssl_include", "Location of OpenSSL include files (if not under (openssl)/include)", None)
vars.Add("openssl_libdir", "Location of OpenSSL library files (if not under (openssl)/lib)", None)
vars.Add(PackageVariable("hunspell_prefix", "Hunspell location", False))
-vars.Add(BoolVariable("hunspell_enable", "Build with Hunspell support", False))
+vars.Add(BoolVariable("hunspell_enable", "Build with Hunspell support", True))
vars.Add(PathVariable("boost_includedir", "Boost headers location", None, PathVariable.PathAccept))
vars.Add(PathVariable("boost_libdir", "Boost library location", None, PathVariable.PathAccept))
vars.Add(BoolVariable("boost_bundled_enable", "Allow use of bundled Boost as last resort", "true"))
+vars.Add(BoolVariable("boost_force_bundled", "Force use of bundled Boost.", False))
vars.Add(PathVariable("zlib_includedir", "Zlib headers location", None, PathVariable.PathAccept))
vars.Add(PathVariable("zlib_libdir", "Zlib library location", None, PathVariable.PathAccept))
vars.Add(PathVariable("zlib_libfile", "Zlib library file (full path to file)", None, PathVariable.PathAccept))
@@ -68,12 +70,17 @@ vars.Add(PathVariable("libidn_includedir", "LibIDN headers location", None, Path
vars.Add(PathVariable("libidn_libdir", "LibIDN library location", None, PathVariable.PathAccept))
vars.Add("libidn_libname", "LibIDN library name", os.name == "nt" and "libidn" or "idn")
vars.Add(BoolVariable("need_idn", "Whether an IDN library is required. Without this, most internal binaries will fail", "true"))
+
vars.Add(PathVariable("libminiupnpc_includedir", "LibMiniUPNPC headers location", None, PathVariable.PathAccept))
vars.Add(PathVariable("libminiupnpc_libdir", "LibMiniUPNPC library location", None, PathVariable.PathAccept))
vars.Add("libminiupnpc_libname", "LibMiniUPNPC library name", os.name == "nt" and "libminiupnpc" or "miniupnpc")
+vars.Add(BoolVariable("libminiupnpc_force_bundled", "Force use of bundled LibMiniUPNPC", False))
+
vars.Add(PathVariable("libnatpmp_includedir", "LibNATPMP headers location", None, PathVariable.PathAccept))
vars.Add(PathVariable("libnatpmp_libdir", "LibNATPMP library location", None, PathVariable.PathAccept))
vars.Add("libnatpmp_libname", "LibNATPMP library name", os.name == "nt" and "libnatpmp" or "natpmp")
+vars.Add(BoolVariable("libnatpmp_force_bundled", "Force use of bundled LibNATPMP", False))
+
vars.Add(PathVariable("sqlite_includedir", "SQLite headers location", None, PathVariable.PathAccept))
vars.Add(PathVariable("sqlite_libdir", "SQLite library location", None, PathVariable.PathAccept))
vars.Add("sqlite_libname", "SQLite library name", os.name == "nt" and "libsqlite3" or "sqlite3")
@@ -104,36 +111,45 @@ vars.Add(BoolVariable("check_headers", "Independently build compilation units fo
vars.Add("win_target_arch", "Target architecture for Windows builds. x86 for 32-bit (default) or x86_64 for 64-bit.", "x86")
vars.Add(BoolVariable("install_git_hooks", "Install git hooks", "true"))
+# Code Signing Options
+vars.Add("codesign_identity", "macOS code signing identity to be passed to codesign when building the distribution package. Must match the Commen Name of the Subject of the code signing certificate.", "")
+vars.Add("signtool_key_pfx", "The keyfile (.pfx) that will be used to sign the Windows installer.", None)
+vars.Add("signtool_timestamp_url", "The timestamp server that will be queried for a signed time stamp in the signing process.", None)
+
+# Automatic Software Update Options
+vars.Add(PathVariable("sparkle_public_dsa_key", "Optional path to a public DSA key used to verify Sparkle software updates. Without specifiying this option, the app needs to be code signed for Sparkle to work.", None, PathVariable.PathIsFile))
+
+
################################################################################
# Set up default build & configure environment
################################################################################
env_ENV = {
- 'PATH' : os.environ['PATH'],
- 'LD_LIBRARY_PATH' : os.environ.get("LD_LIBRARY_PATH", ""),
- 'TERM' : os.environ.get("TERM", ""),
+ 'PATH' : os.environ['PATH'],
+ 'LD_LIBRARY_PATH' : os.environ.get("LD_LIBRARY_PATH", ""),
+ 'TERM' : os.environ.get("TERM", ""),
}
if "MSVC_VERSION" in ARGUMENTS :
- env = Environment(ENV = env_ENV, variables = vars, MSVC_VERSION = ARGUMENTS["MSVC_VERSION"], platform = ARGUMENTS.get("PLATFORM", None))
- env = Environment(ENV = env_ENV, variables = vars, MSVC_VERSION = ARGUMENTS["MSVC_VERSION"], platform = ARGUMENTS.get("PLATFORM", None), TARGET_ARCH=env["win_target_arch"])
+ env = Environment(ENV = env_ENV, variables = vars, MSVC_VERSION = ARGUMENTS["MSVC_VERSION"], platform = ARGUMENTS.get("PLATFORM", None))
+ env = Environment(ENV = env_ENV, variables = vars, MSVC_VERSION = ARGUMENTS["MSVC_VERSION"], platform = ARGUMENTS.get("PLATFORM", None), TARGET_ARCH=env["win_target_arch"])
else :
- env = Environment(ENV = env_ENV, variables = vars, platform = ARGUMENTS.get("PLATFORM", None))
- env = Environment(ENV = env_ENV, variables = vars, platform = ARGUMENTS.get("PLATFORM", None), TARGET_ARCH=env["win_target_arch"])
+ env = Environment(ENV = env_ENV, variables = vars, platform = ARGUMENTS.get("PLATFORM", None))
+ env = Environment(ENV = env_ENV, variables = vars, platform = ARGUMENTS.get("PLATFORM", None), TARGET_ARCH=env["win_target_arch"])
Help(vars.GenerateHelpText(env))
# Workaround for missing Visual Studio 2012 support in SCons
# Requires scons to be run from a VS2012 console
if env.get("MSVC_VERSION", "").startswith("11.0") :
- env["ENV"]["LIB"] = os.environ["LIB"]
- env["ENV"]["INCLUDE"] = os.environ["INCLUDE"]
+ env["ENV"]["LIB"] = os.environ["LIB"]
+ env["ENV"]["INCLUDE"] = os.environ["INCLUDE"]
# Default environment variables
env["PLATFORM_FLAGS"] = {
- "LIBPATH": [],
- "LIBS": [],
- "FRAMEWORKS": [],
+ "LIBPATH": [],
+ "LIBS": [],
+ "FRAMEWORKS": [],
}
# Default custom tools
@@ -142,24 +158,24 @@ env.Tool("WriteVal", toolpath = ["#/BuildTools/SCons/Tools"])
env.Tool("BuildVersion", toolpath = ["#/BuildTools/SCons/Tools"])
env.Tool("Flags", toolpath = ["#/BuildTools/SCons/Tools"])
if env["PLATFORM"] == "darwin" :
- env.Tool("Nib", toolpath = ["#/BuildTools/SCons/Tools"])
- env.Tool("AppBundle", toolpath = ["#/BuildTools/SCons/Tools"])
+ env.Tool("Nib", toolpath = ["#/BuildTools/SCons/Tools"])
+ env.Tool("AppBundle", toolpath = ["#/BuildTools/SCons/Tools"])
if env["PLATFORM"] == "win32" :
- env.Tool("WindowsBundle", toolpath = ["#/BuildTools/SCons/Tools"])
- #So we don't need to escalate with UAC
- if "TMP" in os.environ.keys() :
- env['ENV']['TMP'] = os.environ['TMP']
+ env.Tool("WindowsBundle", toolpath = ["#/BuildTools/SCons/Tools"])
+ #So we don't need to escalate with UAC
+ if "TMP" in os.environ.keys() :
+ env['ENV']['TMP'] = os.environ['TMP']
env.Tool("SLOCCount", toolpath = ["#/BuildTools/SCons/Tools"])
# Max out the number of jobs
if env["max_jobs"] :
- try :
- import multiprocessing
- SetOption("num_jobs", multiprocessing.cpu_count())
- except NotImplementedError :
- pass
- except ImportError :
- pass
+ try :
+ import multiprocessing
+ SetOption("num_jobs", multiprocessing.cpu_count())
+ except NotImplementedError :
+ pass
+ except ImportError :
+ pass
# Set speed options
env.Decider("MD5-timestamp")
@@ -168,19 +184,24 @@ env.SetOption("implicit_cache", True)
# Set the default compiler to CLang on OS X, and set the necessary flags
if env["PLATFORM"] == "darwin" and env["target"] == "native" :
- if "cc" not in env :
- env["CC"] = "clang"
- if platform.machine() == "x86_64" :
- env["CCFLAGS"] = ["-arch", "x86_64"]
- if "cxx" not in env :
- env["CXX"] = "clang++"
- # Compiling Qt5 in C++0x mode includes headers that we don't have
- if not env["qt5"] :
- env["CXXFLAGS"] = ["-std=c++11"]
- if "link" not in env :
- env["LINK"] = "clang"
- if platform.machine() == "x86_64" :
- env.Append(LINKFLAGS = ["-arch", "x86_64"])
+ if "cc" not in env :
+ env["CC"] = "clang"
+ if platform.machine() == "x86_64" :
+ env["CCFLAGS"] = ["-arch", "x86_64"]
+ if "cxx" not in env :
+ env["CXX"] = "clang++"
+ if "link" not in env :
+ # Use clang++ instead of clang, otherwise XCode's clang will cause linking errors due to missing C++ standard lib.
+ env["LINK"] = "clang++"
+ if platform.machine() == "x86_64" :
+ env.Append(LINKFLAGS = ["-arch", "x86_64"])
+
+# Set QT_SELECT variable to enable building on systems that have Qt4 and Qt5 installed and use qtselect
+if env["PLATFORM"] != "darwin" and env["PLATFORM"] != "win32" :
+ if env["qt5"] :
+ env["ENV"]["QT_SELECT"] = "qt5"
+ else:
+ env["ENV"]["QT_SELECT"] = "qt4"
# Set QT_SELECT variable to enable building on systems that have Qt4 and Qt5 installed and use qtselect
if env["PLATFORM"] != "darwin" and env["PLATFORM"] != "win32" :
@@ -191,198 +212,209 @@ if env["PLATFORM"] != "darwin" and env["PLATFORM"] != "win32" :
# Check whether we are running inside scan-build, and override compiler if so
if "CCC_ANALYZER_HTML" in os.environ :
- for key, value in os.environ.items() :
- if key.startswith("CCC_") or key.startswith("CLANG") :
- env["ENV"][key] = value
- env["CC"] = os.environ["CC"]
- env["CXX"] = os.environ["CXX"]
+ for key, value in os.environ.items() :
+ if key.startswith("CCC_") or key.startswith("CLANG") :
+ env["ENV"][key] = value
+ env["CC"] = os.environ["CC"]
+ env["CXX"] = os.environ["CXX"]
# Override the compiler with custom variables set at config time
if "cc" in env :
- env["CC"] = env["cc"]
+ env["CC"] = env["cc"]
if "cxx" in env :
- env["CXX"] = env["cxx"]
+ env["CXX"] = env["cxx"]
if "ar" in env :
- env["AR"] = env["ar"]
+ env["AR"] = env["ar"]
if "link" in env :
- env["SHLINK"] = env["link"]
- env["LINK"] = env["link"]
+ env["SHLINK"] = env["link"]
+ env["LINK"] = env["link"]
+
+# Process user-defined external flags
for flags_type in ["ccflags", "cxxflags", "linkflags"] :
- if flags_type in env :
- if isinstance(env[flags_type], str) :
- # FIXME: Make the splitting more robust
- env[flags_type.upper()] = env[flags_type].split(" ")
- else :
- env[flags_type.upper()] = env[flags_type]
+ if flags_type in env :
+ if isinstance(env[flags_type], str) :
+ # FIXME: Make the splitting more robust
+ env[flags_type.upper()] = env[flags_type].split(" ")
+ else :
+ env[flags_type.upper()] = env[flags_type]
# This isn't a real flag (yet) AFAIK. Be sure to append it to the CXXFLAGS
# where you need it
env["OBJCCFLAGS"] = []
+# Compile code as C++11
+if env["PLATFORM"] != "win32" :
+ env.Append(CXXFLAGS = ["-std=c++11"])
+
if env["optimize"] :
- if env["PLATFORM"] == "win32" :
- env.Append(CCFLAGS = ["/O2"])
- else :
- env.Append(CCFLAGS = ["-O2"])
+ if env["PLATFORM"] == "win32" :
+ env.Append(CCFLAGS = ["/O2"])
+ else :
+ env.Append(CCFLAGS = ["-O2"])
if env["target"] == "xcode" and os.environ["CONFIGURATION"] == "Release" :
- env.Append(CCFLAGS = ["-Os"])
+ env.Append(CCFLAGS = ["-Os"])
if env["debug"] :
- if env["PLATFORM"] == "win32" :
- env.Append(CCFLAGS = ["/Zi"])
- env.Append(LINKFLAGS = ["/DEBUG"])
- if GetOption("num_jobs") > 1 :
- env["CCPDBFLAGS"] = '/Fd${TARGET}.pdb'
- env["PDB"] = '${TARGET.base}.pdb'
- if env["set_iterator_debug_level"] :
- env.Append(CPPDEFINES = ["_ITERATOR_DEBUG_LEVEL=0"])
- if env["optimize"] :
- env.Append(LINKFLAGS = ["/OPT:NOREF"])
- env.Append(CCFLAGS = ["/MD"])
- else :
- env.Append(CCFLAGS = ["/MDd"])
- else :
- env.Append(CCFLAGS = ["-g"])
+ if env["PLATFORM"] == "win32" :
+ env.Append(CCFLAGS = ["/Zi"])
+ env.Append(LINKFLAGS = ["/DEBUG"])
+ if GetOption("num_jobs") > 1 :
+ env["CCPDBFLAGS"] = '/Fd${TARGET}.pdb'
+ env["PDB"] = '${TARGET.base}.pdb'
+ if env["set_iterator_debug_level"] :
+ env.Append(CPPDEFINES = ["_ITERATOR_DEBUG_LEVEL=0"])
+ env.Append(LINKFLAGS = ["/OPT:NOREF"])
+ env.Append(CCFLAGS = ["/MD"])
+ else :
+ env.Append(CCFLAGS = ["-g"])
elif env["PLATFORM"] == "win32" :
- env.Append(CCFLAGS = ["/MD"])
+ env.Append(CCFLAGS = ["/MD"])
if env.get("universal", 0) :
- assert(env["PLATFORM"] == "darwin")
- env.Append(CCFLAGS = [
- "-isysroot", "/Developer/SDKs/MacOSX10.4u.sdk",
- "-arch", "i386",
- "-arch", "ppc"])
- env.Append(LINKFLAGS = [
- "-mmacosx-version-min=10.4",
- "-isysroot", "/Developer/SDKs/MacOSX10.4u.sdk",
- "-arch", "i386",
- "-arch", "ppc"])
+ assert(env["PLATFORM"] == "darwin")
+ env.Append(CCFLAGS = [
+ "-isysroot", "/Developer/SDKs/MacOSX10.4u.sdk",
+ "-arch", "i386",
+ "-arch", "ppc"])
+ env.Append(LINKFLAGS = [
+ "-mmacosx-version-min=10.4",
+ "-isysroot", "/Developer/SDKs/MacOSX10.4u.sdk",
+ "-arch", "i386",
+ "-arch", "ppc"])
# Link against other versions of the OS X SDKs.
# FIXME: This method does not work anymore, we need to set deployment targets.
if env.get("mac105", 0) :
- assert(env["PLATFORM"] == "darwin")
- env.Append(CCFLAGS = [
- "-isysroot", "/Developer/SDKs/MacOSX10.5.sdk",
- "-arch", "i386"])
- env.Append(LINKFLAGS = [
- "-mmacosx-version-min=10.5",
- "-isysroot", "/Developer/SDKs/MacOSX10.5.sdk",
- "-arch", "i386"])
+ assert(env["PLATFORM"] == "darwin")
+ env.Append(CCFLAGS = [
+ "-isysroot", "/Developer/SDKs/MacOSX10.5.sdk",
+ "-arch", "i386"])
+ env.Append(LINKFLAGS = [
+ "-mmacosx-version-min=10.5",
+ "-isysroot", "/Developer/SDKs/MacOSX10.5.sdk",
+ "-arch", "i386"])
if env.get("mac106", 0) :
- assert(env["PLATFORM"] == "darwin")
- env.Append(CCFLAGS = [
- "-isysroot", "/Developer/SDKs/MacOSX10.6.sdk",
- "-arch", "i386"])
- env.Append(LINKFLAGS = [
- "-mmacosx-version-min=10.6",
- "-isysroot", "/Developer/SDKs/MacOSX10.6.sdk",
- "-arch", "i386"])
+ assert(env["PLATFORM"] == "darwin")
+ env.Append(CCFLAGS = [
+ "-isysroot", "/Developer/SDKs/MacOSX10.6.sdk",
+ "-arch", "i386"])
+ env.Append(LINKFLAGS = [
+ "-mmacosx-version-min=10.6",
+ "-isysroot", "/Developer/SDKs/MacOSX10.6.sdk",
+ "-arch", "i386"])
if not env["assertions"] :
- env.Append(CPPDEFINES = ["NDEBUG"])
+ env.Append(CPPDEFINES = ["NDEBUG"])
# disable file-transfer support on iOS
if env["target"] in ["iphone-device", "iphone-simulator", "xcode"] :
- env["experimental_ft"] = False
+ env["experimental_ft"] = False
if env["experimental_ft"] :
- env.Append(CPPDEFINES = ["SWIFT_EXPERIMENTAL_FT"])
+ env.Append(CPPDEFINES = ["SWIFT_EXPERIMENTAL_FT"])
if env["experimental"] :
- env.Append(CPPDEFINES = ["SWIFT_EXPERIMENTAL_HISTORY", "SWIFT_EXPERIMENTAL_WB"])
+ env.Append(CPPDEFINES = ["SWIFT_EXPERIMENTAL_HISTORY", "SWIFT_EXPERIMENTAL_WB"])
# If we build shared libs on AMD64, we need -fPIC.
# This should have no performance impact om AMD64
if env["PLATFORM"] == "posix" and platform.machine() in ["x86_64", "amd64"] :
- env.Append(CCFLAGS = ["-fPIC"])
+ env.Append(CCFLAGS = ["-fPIC"])
# Warnings
if env["PLATFORM"] == "win32" :
- env.Append(CXXFLAGS = ["/wd4068"])
+ env.Append(CXXFLAGS = ["/wd4068"])
+ env.Append(CXXFLAGS = ["/wd4503"]) # Disable 'decorated name length exceeded, name was truncated' warning
+ if not env.get("allow_warnings", "False") :
+ env.Append(CXXFLAGS = ["/WX"])
elif env["PLATFORM"] == "hpux" :
- # HP-UX gives a flood of minor warnings if this is enabled
- #env.Append(CXXFLAGS = ["+w"])
- pass
+ # HP-UX gives a flood of minor warnings if this is enabled
+ #env.Append(CXXFLAGS = ["+w"])
+ pass
elif env["PLATFORM"] == "sunos" :
- #env.Append(CXXFLAGS = ["-z verbose"])
- pass
+ #env.Append(CXXFLAGS = ["-z verbose"])
+ pass
else :
- if "clang" in env["CXX"] :
- env.Append(CXXFLAGS = [
- "-Weverything",
- "-Wno-unknown-warning-option", # To stay compatible between CLang versions
- "-Wno-unknown-pragmas", # To stay compatible between CLang versions
- "-Wno-weak-vtables", # Virtually none of our elements have outlined methods. This also seems to affect classes in .cpp files, which in turn affects all our tests, which may need fixing in CLang
- "-Wno-shadow", # Also warns for shadowing on constructor arguments, which we do a lot
- "-Wno-documentation", # We don't care about documentation warnings
- "-Wno-documentation-unknown-command", # We don't care about documentation warnings
- "-Wno-exit-time-destructors", # Used a lot in e.g. CPPUnit
- "-Wno-c++98-compat-pedantic", # We do different things that violate this, but they could be fixed
- "-Wno-global-constructors", # We depend on this for e.g. string constants
- "-Wno-disabled-macro-expansion", # Caused due to system headers
- "-Wno-c++11-extensions", # We use C++11; turn this off when we use -std=c++11
- "-Wno-long-long", # We use long long
- "-Wno-padded",
- "-Wno-missing-variable-declarations", # Getting rid of CPPUnit warnings
- "-Wno-direct-ivar-access", # Obj-C code warning
- "-Wno-potentially-evaluated-expression", # Caused due to calling shared_ptr::get() inside typeid()
- ])
- else :
- env.Append(CXXFLAGS = ["-Wextra", "-Wall", "-Wnon-virtual-dtor", "-Wundef", "-Wold-style-cast", "-Wno-long-long", "-Woverloaded-virtual", "-Wfloat-equal", "-Wredundant-decls", "-Wno-unknown-pragmas"])
- gccVersion = env.get("CCVERSION", "0.0.0").split(".")
- if gccVersion >= ["4", "5", "0"] and not "clang" in env["CC"] :
- env.Append(CXXFLAGS = ["-Wlogical-op"])
- if not env.get("allow_warnings", False) :
- env.Append(CXXFLAGS = ["-Werror"])
+ if os.path.basename(env["CXX"]) in ["clang", "clang++"] :
+ env.Append(CXXFLAGS = [
+ "-Weverything",
+ "-Wno-unknown-warning-option", # To stay compatible between CLang versions
+ "-Wno-unknown-pragmas", # To stay compatible between CLang versions
+ "-Wno-weak-vtables", # Virtually none of our elements have outlined methods. This also seems to affect classes in .cpp files, which in turn affects all our tests, which may need fixing in CLang
+ "-Wno-shadow", # Also warns for shadowing on constructor arguments, which we do a lot
+ "-Wno-documentation", # We don't care about documentation warnings
+ "-Wno-documentation-unknown-command", # We don't care about documentation warnings
+ "-Wno-exit-time-destructors", # Used a lot in e.g. CPPUnit
+ "-Wno-c++98-compat-pedantic", # We do different things that violate this, but they could be fixed
+ "-Wno-global-constructors", # We depend on this for e.g. string constants
+ "-Wno-disabled-macro-expansion", # Caused due to system headers
+ "-Wno-long-long", # We use long long
+ "-Wno-padded",
+ "-Wno-missing-variable-declarations", # Getting rid of CPPUnit warnings
+ "-Wno-direct-ivar-access", # Obj-C code warning
+ "-Wno-potentially-evaluated-expression", # Caused due to calling shared_ptr::get() inside typeid()
+ ])
+ else :
+ env.Append(CXXFLAGS = ["-Wextra", "-Wall", "-Wnon-virtual-dtor", "-Wundef", "-Wold-style-cast", "-Wno-long-long", "-Woverloaded-virtual", "-Wfloat-equal", "-Wredundant-decls", "-Wno-unknown-pragmas"])
+ gccVersion = env.get("CCVERSION", "0.0.0").split(".")
+ if gccVersion >= ["4", "5", "0"] and not "clang" in env["CC"] :
+ env.Append(CXXFLAGS = ["-Wlogical-op"])
+ if not env.get("allow_warnings", False) :
+ env.Append(CXXFLAGS = ["-Werror"])
if env.get("coverage", 0) :
- assert(env["PLATFORM"] != "win32")
- env.Append(CCFLAGS = ["-fprofile-arcs", "-ftest-coverage"])
- env.Append(LINKFLAGS = ["-fprofile-arcs", "-ftest-coverage"])
+ assert(env["PLATFORM"] != "win32")
+ env.Append(CCFLAGS = ["-fprofile-arcs", "-ftest-coverage"])
+ env.Append(LINKFLAGS = ["-fprofile-arcs", "-ftest-coverage"])
if env["PLATFORM"] == "win32" :
- env.Append(LIBS = ["user32", "crypt32", "dnsapi", "iphlpapi", "ws2_32", "wsock32", "Advapi32", "ntdsapi"])
- env.Append(CCFLAGS = ["/EHsc", "/nologo", "/Zm256"])
- env.Append(LINKFLAGS = ["/INCREMENTAL:no", "/NOLOGO"])
- if int(env["MSVS_VERSION"].split(".")[0]) < 10 :
- mt = env.get('mt')
- if not mt:
- mt = 'mt.exe'
- env["LINKCOM"] = [env["LINKCOM"], '%s -nologo -manifest ${TARGET}.manifest -outputresource:$TARGET;1' % mt]
- env["SHLINKCOM"] = [env["SHLINKCOM"], '%s -nologo -manifest ${TARGET}.manifest -outputresource:$TARGET;2' % mt]
+ env.Append(LIBS = ["user32", "crypt32", "dnsapi", "iphlpapi", "ws2_32", "wsock32", "Advapi32", "ntdsapi"])
+ env.Append(CCFLAGS = ["/EHsc", "/nologo", "/Zm256"])
+ env.Append(LINKFLAGS = ["/INCREMENTAL:no", "/NOLOGO"])
+ if int(env["MSVS_VERSION"].split(".")[0]) < 10 :
+ mt = env.get('mt')
+ if not mt:
+ mt = 'mt.exe'
+ env["LINKCOM"] = [env["LINKCOM"], '%s -nologo -manifest ${TARGET}.manifest -outputresource:$TARGET;1' % mt]
+ env["SHLINKCOM"] = [env["SHLINKCOM"], '%s -nologo -manifest ${TARGET}.manifest -outputresource:$TARGET;2' % mt]
if env["PLATFORM"] == "darwin" and not env["target"] in ["iphone-device", "iphone-simulator", "xcode", "android"] :
- env["PLATFORM_FLAGS"]["FRAMEWORKS"] += ["IOKit", "AppKit", "SystemConfiguration", "Security", "SecurityInterface"]
+ env["PLATFORM_FLAGS"]["FRAMEWORKS"] += ["IOKit", "AppKit", "SystemConfiguration", "Security", "SecurityInterface"]
# Required by boost headers on HP-UX
if env["PLATFORM"] == "hpux" :
- env.Append(CXXFLAGS = ["+hpxstd98", "-mt", "-AA"])
- # FIXME: Need -AA for linking C++ but not C
- #env.Append(LINKFLAGS = ["-AA"])
+ env.Append(CXXFLAGS = ["+hpxstd98", "-mt", "-AA"])
+ # FIXME: Need -AA for linking C++ but not C
+ #env.Append(LINKFLAGS = ["-AA"])
+# Code signing
+if env["PLATFORM"] == "darwin" :
+ env["CODE_SIGN_IDENTITY"] = env["codesign_identity"]
+if env["PLATFORM"] == "win32" :
+ env["SIGNTOOL_KEY_PFX"] = env.get("signtool_key_pfx", None)
+ env["SIGNTOOL_TIMESTAMP_URL"] = env.get("signtool_timestamp_url", None)
# Testing
env["TEST_TYPE"] = env["test"]
if "check" in ARGUMENTS :
- env["TEST_TYPE"] = "unit"
+ env["TEST_TYPE"] = "unit"
env["checker_report"] = ARGUMENTS.get("checker_report", False)
env["TEST"] = (env["TEST_TYPE"] != "none") or env.GetOption("clean")
if env.get("valgrind", 0) :
- env["TEST_RUNNER"] = "valgrind --suppressions=QA/valgrind.supp -q --leak-check=full --track-origins=yes "
+ env["TEST_RUNNER"] = "valgrind --suppressions=QA/valgrind.supp -q --leak-check=full --track-origins=yes "
env["TEST_IGNORE_RESULT"] = "ignore_test_result" in ARGUMENTS
env["TEST_CREATE_LIBRARIES"] = "create_test_libraries" in ARGUMENTS
# Packaging
env["DIST"] = "dist" in ARGUMENTS or env.GetOption("clean")
for path in ["SWIFT_INSTALLDIR", "SWIFTEN_INSTALLDIR", "SLUIFT_INSTALLDIR"] :
- if ARGUMENTS.get(path, "") :
- if os.path.isabs(ARGUMENTS[path]) :
- env[path] = Dir(ARGUMENTS[path]).abspath
- else :
- env[path] = Dir("#/" + ARGUMENTS[path]).abspath
+ if ARGUMENTS.get(path, "") :
+ if os.path.isabs(ARGUMENTS[path]) :
+ env[path] = Dir(ARGUMENTS[path]).abspath
+ else :
+ env[path] = Dir("#/" + ARGUMENTS[path]).abspath
################################################################################
@@ -391,70 +423,77 @@ for path in ["SWIFT_INSTALLDIR", "SWIFTEN_INSTALLDIR", "SLUIFT_INSTALLDIR"] :
target = env["target"]
if target in ["iphone-device", "iphone-simulator", "xcode"] :
- # Extract/initialize all the information we need
- if target == "xcode" :
- # Get the information from the XCode environment
- env["XCODE_PLATFORM_DEVELOPER_BIN_DIR"] = os.environ["PLATFORM_DEVELOPER_BIN_DIR"]
- env["XCODE_SDKROOT"] = os.environ["SDKROOT"]
- env["XCODE_ARCH_FLAGS"] = sum([["-arch", arch] for arch in os.environ["ARCHS"].split(" ")], [])
- env["IPHONEOS_DEPLOYMENT_TARGET"] = os.environ["IPHONEOS_DEPLOYMENT_TARGET"]
- # Use absolute path sources so Xcode can highlight compilation errors in swiften
- env['CXXCOM'] = '$CXX -o $TARGET -c $CXXFLAGS $CCFLAGS $_CCCOMCOM ${SOURCES.abspath}'
- else :
- # Hard code values
- env["XCODE_PLATFORM_DEVELOPER_BIN_DIR"] = "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin"
- if target == "iphone-device":
- env["XCODE_ARCH_FLAGS"] = ["-arch", "armv6", "-arch", "armv7"]
- sdkPart = "iPhoneOS"
- else :
- env["XCODE_ARCH_FLAGS"] = ["-arch", "i386"]
- sdkPart = "iPhoneSimulator"
- sdkVer = "6.0"
- env["XCODE_SDKROOT"] = "/Applications/Xcode.app/Contents/Developer/Platforms/" + sdkPart + ".platform/Developer/SDKs/" + sdkPart + sdkVer + ".sdk"
- env["IPHONEOS_DEPLOYMENT_TARGET"] = "4.1"
-
- # Set the build flags
- env["CC"] = os.environ["DEVELOPER_BIN_DIR"] + "/gcc"
- env["CXX"] = os.environ["DEVELOPER_BIN_DIR"] + "/g++"
- env["OBJCCFLAGS"] = ["-fobjc-abi-version=2", "-fobjc-legacy-dispatch"]
- env["LD"] = env["CC"]
- env.Append(CCFLAGS = env["XCODE_ARCH_FLAGS"] + ["-fvisibility=hidden", "-miphoneos-version-min=" + env["IPHONEOS_DEPLOYMENT_TARGET"]])
- env.Append(LINKFLAGS = "-miphoneos-version-min=" + env["IPHONEOS_DEPLOYMENT_TARGET"])
- if os.environ.get("GCC_THUMB_SUPPORT", False) :
- env.Append(CCFLAGS = ["-mthumb"])
- env.Append(LINKFLAGS = env["XCODE_ARCH_FLAGS"])
- env.Append(CPPFLAGS = ["-isysroot", "$XCODE_SDKROOT"])
- env.Append(FRAMEWORKS = ["CoreFoundation", "Foundation", "UIKit", "CoreGraphics"])
- env.Append(LINKFLAGS = env["XCODE_ARCH_FLAGS"] + ["-isysroot", "$XCODE_SDKROOT", "-L\"$XCODE_SDKROOT/usr/lib\"", "-F\"$XCODE_SDKROOT/System/Library/Frameworks\"", "-F\"$XCODE_SDKROOT/System/Library/PrivateFrameworks\""])
- # Bit of a hack, because BOOST doesn't know the endianness for ARM
- env.Append(CPPDEFINES = ["_LITTLE_ENDIAN"])
+ # Extract/initialize all the information we need
+ if target == "xcode" :
+ # Get the information from the XCode environment
+ env["XCODE_PLATFORM_DEVELOPER_BIN_DIR"] = os.environ["PLATFORM_DEVELOPER_BIN_DIR"]
+ env["XCODE_SDKROOT"] = os.environ["SDKROOT"]
+ env["XCODE_ARCH_FLAGS"] = sum([["-arch", arch] for arch in os.environ["ARCHS"].split(" ")], [])
+ env["IPHONEOS_DEPLOYMENT_TARGET"] = os.environ["IPHONEOS_DEPLOYMENT_TARGET"]
+ # Use absolute path sources so Xcode can highlight compilation errors in swiften
+ env['CXXCOM'] = '$CXX -o $TARGET -c $CXXFLAGS $CCFLAGS $_CCCOMCOM ${SOURCES.abspath}'
+ else :
+ # Hard code values
+ env["XCODE_PLATFORM_DEVELOPER_BIN_DIR"] = "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin"
+ if target == "iphone-device":
+ env["XCODE_ARCH_FLAGS"] = ["-arch", "armv6", "-arch", "armv7"]
+ sdkPart = "iPhoneOS"
+ else :
+ env["XCODE_ARCH_FLAGS"] = ["-arch", "i386"]
+ sdkPart = "iPhoneSimulator"
+ sdkVer = "6.0"
+ env["XCODE_SDKROOT"] = "/Applications/Xcode.app/Contents/Developer/Platforms/" + sdkPart + ".platform/Developer/SDKs/" + sdkPart + sdkVer + ".sdk"
+ env["IPHONEOS_DEPLOYMENT_TARGET"] = "4.1"
+
+ # Set the build flags
+ env["CC"] = os.environ["DEVELOPER_BIN_DIR"] + "/gcc"
+ env["CXX"] = os.environ["DEVELOPER_BIN_DIR"] + "/g++"
+ env["OBJCCFLAGS"] = ["-fobjc-abi-version=2", "-fobjc-legacy-dispatch"]
+ env["LD"] = env["CC"]
+ env.Append(CCFLAGS = env["XCODE_ARCH_FLAGS"] + ["-fvisibility=hidden", "-miphoneos-version-min=" + env["IPHONEOS_DEPLOYMENT_TARGET"]])
+ env.Append(LINKFLAGS = "-miphoneos-version-min=" + env["IPHONEOS_DEPLOYMENT_TARGET"])
+ if os.environ.get("GCC_THUMB_SUPPORT", False) :
+ env.Append(CCFLAGS = ["-mthumb"])
+ env.Append(LINKFLAGS = env["XCODE_ARCH_FLAGS"])
+ env.Append(CPPFLAGS = ["-isysroot", "$XCODE_SDKROOT"])
+ env.Append(FRAMEWORKS = ["CoreFoundation", "Foundation", "UIKit", "CoreGraphics"])
+ env.Append(LINKFLAGS = env["XCODE_ARCH_FLAGS"] + ["-isysroot", "$XCODE_SDKROOT", "-L\"$XCODE_SDKROOT/usr/lib\"", "-F\"$XCODE_SDKROOT/System/Library/Frameworks\"", "-F\"$XCODE_SDKROOT/System/Library/PrivateFrameworks\""])
+ # Bit of a hack, because BOOST doesn't know the endianness for ARM
+ env.Append(CPPDEFINES = ["_LITTLE_ENDIAN"])
################################################################################
# Android
################################################################################
if target in ["android"] :
- env["ENV"]["PATH"] = env["android_toolchain"] + "/bin:" + env["ENV"]["PATH"]
- env["CC"] = "arm-linux-androideabi-gcc"
- env["CXX"] = "arm-linux-androideabi-g++"
- env["AR"] = "arm-linux-androideabi-ar"
- env["RANLIB"] = "arm-linux-androideabi-ranlib"
- env.Append(CPPDEFINES = ["ANDROID"])
- env.Append(CPPDEFINES = ["_REENTRANT", "_GLIBCXX__PTHREADS"])
+ env["ENV"]["PATH"] = env["android_toolchain"] + "/bin:" + env["ENV"]["PATH"]
+ env["CC"] = "arm-linux-androideabi-gcc"
+ env["CXX"] = "arm-linux-androideabi-g++"
+ env["AR"] = "arm-linux-androideabi-ar"
+ env["RANLIB"] = "arm-linux-androideabi-ranlib"
+ env.Append(CPPDEFINES = ["ANDROID"])
+ env.Append(CPPDEFINES = ["_REENTRANT", "_GLIBCXX__PTHREADS"])
# CCache
if env.get("ccache", False) :
- env["ENV"]["HOME"] = os.environ["HOME"]
- for var in os.environ :
- if var.startswith("CCACHE_") :
- env["ENV"][var] = os.environ[var]
- if env.get("CC", "") != "" :
- env["CC"] = "ccache " + env["CC"]
- else :
- env["CC"] = "ccache gcc"
- if env.get("CXX", "") != "" :
- env["CXX"] = "ccache " + env["CXX"]
- else :
- env["CC"] = "ccache g++"
+ env["ENV"]["HOME"] = os.environ["HOME"]
+ for var in os.environ :
+ if var.startswith("CCACHE_") :
+ env["ENV"][var] = os.environ[var]
+ if env.get("CC", "") != "" :
+ env["CC"] = "ccache " + env["CC"]
+ else :
+ env["CC"] = "ccache gcc"
+ if env.get("CXX", "") != "" :
+ env["CXX"] = "ccache " + env["CXX"]
+ else :
+ env["CC"] = "ccache g++"
+
+# distcc
+if env.get("distcc", False) :
+ env["ENV"]["HOME"] = os.environ["HOME"]
+ for var in os.environ :
+ if var.startswith("DISTCC_") :
+ env["ENV"][var] = os.environ[var]
conf_env = env.Clone()
@@ -463,12 +502,12 @@ Export("conf_env")
variant = ""
if env["enable_variants"] :
- fingerprint = ",".join([flag for flag in env["CXXFLAGS"] + env["CCFLAGS"] if not flag.startswith("-W") and not flag.startswith("-fvisibility")])
- variant = "build/" + fingerprint
- if not os.path.exists(Dir("#/build").abspath) :
- os.mkdir(Dir("#/build").abspath)
- if os.path.exists(Dir("#/build/current").abspath) :
- os.unlink(Dir("#/build/current").abspath)
- os.symlink(os.path.basename(variant), Dir("#/build/current").abspath)
+ fingerprint = ",".join([flag for flag in env["CXXFLAGS"] + env["CCFLAGS"] if not flag.startswith("-W") and not flag.startswith("-fvisibility")])
+ variant = "build/" + fingerprint
+ if not os.path.exists(Dir("#/build").abspath) :
+ os.mkdir(Dir("#/build").abspath)
+ if os.path.exists(Dir("#/build/current").abspath) :
+ os.unlink(Dir("#/build/current").abspath)
+ os.symlink(os.path.basename(variant), Dir("#/build/current").abspath)
Return("variant")
diff --git a/BuildTools/SCons/SConstruct b/BuildTools/SCons/SConstruct
index de24728..c084cff 100644
--- a/BuildTools/SCons/SConstruct
+++ b/BuildTools/SCons/SConstruct
@@ -8,8 +8,8 @@ root = Dir("../..").abspath
# Override SConscript to handle tests
oldSConscript = SConscript
def SConscript(*arguments, **keywords) :
- if not keywords.get("test_only", False) or env["TEST"] :
- return apply(oldSConscript, arguments, keywords)
+ if not keywords.get("test_only", False) or env["TEST"] :
+ return apply(oldSConscript, arguments, keywords)
env.SConscript = SConscript
################################################################################
@@ -21,313 +21,352 @@ env.SConscript = SConscript
################################################################################
#if env["PLATFORM"] == "win32" :
-# env["MSVC_BATCH"] = 1
+# env["MSVC_BATCH"] = 1
# Pretty output
def colorize(command, target, color) :
- colors = { "red": "31", "green": "32", "yellow": "33", "blue": "34" }
- prefix = ""
- suffix = ""
- if sys.stdout.isatty() and env["PLATFORM"] != "win32":
- prefix = "\033[0;" + colors[color] + ";140m"
- suffix = "\033[0m"
- return " " + prefix + command + suffix + " " + target
+ colors = { "red": "31", "green": "32", "yellow": "33", "blue": "34" }
+ prefix = ""
+ suffix = ""
+ if sys.stdout.isatty() and env["PLATFORM"] != "win32":
+ prefix = "\033[0;" + colors[color] + ";140m"
+ suffix = "\033[0m"
+ return " " + prefix + command + suffix + " " + target
if int(ARGUMENTS.get("V", 0)) == 0 and not ARGUMENTS.get("dump_trace", False) :
- env["CCCOMSTR"] = colorize("CC", "$TARGET", "green")
- env["SHCCCOMSTR"] = colorize("CC", "$TARGET", "green")
- env["CXXCOMSTR"] = colorize("CXX", "$TARGET", "green")
- env["SHCXXCOMSTR"] = colorize("CXX", "$TARGET", "green")
- env["LINKCOMSTR"] = colorize("LINK", "$TARGET", "red")
- env["SHLINKCOMSTR"] = colorize("LINK", "$TARGET", "red")
- env["ARCOMSTR"] = colorize("AR", "$TARGET", "red")
- env["RANLIBCOMSTR"] = colorize("RANLIB", "$TARGET", "red")
- env["PCHCOMSTR"] = colorize("PCH", "$TARGET", "blue")
- env["QT4_RCCCOMSTR"] = colorize("RCC", "$TARGET", "blue")
- env["QT4_UICCOMSTR"] = colorize("UIC", "$TARGET", "blue")
- env["QT4_MOCFROMHCOMSTR"] = colorize("MOC", "$TARGET", "blue")
- env["QT4_MOCFROMCXXCOMSTR"] = colorize("MOC", "$TARGET", "blue")
- env["QT4_LRELEASECOMSTR"] = colorize("LRELEASE", "$TARGET", "blue")
- env["QT4_LUPDATECOMSTR"] = colorize("LUPDATE", "$TARGET", "blue")
- env["GENCOMSTR"] = colorize("GEN", "$TARGET", "blue")
- env["RCCOMSTR"] = colorize("RC", "$TARGET", "blue")
- env["BUNDLECOMSTR"] = colorize("BUNDLE", "$TARGET", "blue")
- env["NIBCOMSTR"] = colorize("NIB", "$TARGET", "blue")
- env["NSISCOMSTR"] = colorize("NSIS", "$TARGET", "blue")
- env["INSTALLSTR"] = colorize("INSTALL", "$TARGET", "blue")
- env["TESTCOMSTR"] = colorize("TEST", "$SOURCE", "yellow")
- env["FOCOMSTR"] = colorize("FO", "$TARGET", "blue")
- env["XSLTCOMSTR"] = colorize("XSLT", "$TARGET", "blue")
- env["XMLLINTCOMSTR"] = colorize("XMLLINT", "$SOURCE", "blue")
- env["DOXYCOMSTR"] = colorize("DOXY", "$SOURCE", "blue")
- #Progress(colorize("DEP", "$TARGET", "red")
+ env["CCCOMSTR"] = colorize("CC", "$TARGET", "green")
+ env["SHCCCOMSTR"] = colorize("CC", "$TARGET", "green")
+ env["CXXCOMSTR"] = colorize("CXX", "$TARGET", "green")
+ env["SHCXXCOMSTR"] = colorize("CXX", "$TARGET", "green")
+ env["LINKCOMSTR"] = colorize("LINK", "$TARGET", "red")
+ env["SHLINKCOMSTR"] = colorize("LINK", "$TARGET", "red")
+ env["ARCOMSTR"] = colorize("AR", "$TARGET", "red")
+ env["RANLIBCOMSTR"] = colorize("RANLIB", "$TARGET", "red")
+ env["PCHCOMSTR"] = colorize("PCH", "$TARGET", "blue")
+ env["QT4_RCCCOMSTR"] = colorize("RCC", "$TARGET", "blue")
+ env["QT4_UICCOMSTR"] = colorize("UIC", "$TARGET", "blue")
+ env["QT4_MOCFROMHCOMSTR"] = colorize("MOC", "$TARGET", "blue")
+ env["QT4_MOCFROMCXXCOMSTR"] = colorize("MOC", "$TARGET", "blue")
+ env["QT4_LRELEASECOMSTR"] = colorize("LRELEASE", "$TARGET", "blue")
+ env["QT4_LUPDATECOMSTR"] = colorize("LUPDATE", "$TARGET", "blue")
+ env["GENCOMSTR"] = colorize("GEN", "$TARGET", "blue")
+ env["RCCOMSTR"] = colorize("RC", "$TARGET", "blue")
+ env["BUNDLECOMSTR"] = colorize("BUNDLE", "$TARGET", "blue")
+ env["NIBCOMSTR"] = colorize("NIB", "$TARGET", "blue")
+ env["NSISCOMSTR"] = colorize("NSIS", "$TARGET", "blue")
+ env["INSTALLSTR"] = colorize("INSTALL", "$TARGET", "blue")
+ env["TESTCOMSTR"] = colorize("TEST", "$SOURCE", "yellow")
+ env["FOCOMSTR"] = colorize("FO", "$TARGET", "blue")
+ env["XSLTCOMSTR"] = colorize("XSLT", "$TARGET", "blue")
+ env["XMLLINTCOMSTR"] = colorize("XMLLINT", "$SOURCE", "blue")
+ env["DOXYCOMSTR"] = colorize("DOXY", "$SOURCE", "blue")
+ #Progress(colorize("DEP", "$TARGET", "red")
def checkObjCHeader(context, header) :
- context.Message("Checking for Objective-C header " + header + " ... ")
- ret = context.TryCompile("#include <Cocoa/Cocoa.h>\n#include <" + header + ">", ".m")
- context.Result(ret)
- return ret
+ context.Message("Checking for Objective-C header " + header + " ... ")
+ ret = context.TryCompile("#include <Cocoa/Cocoa.h>\n#include <" + header + ">", ".m")
+ context.Result(ret)
+ return ret
+
+def checkForCpp11Support(context) :
+ context.Message('Checking whether the C++ compiler supports C++11... ')
+ result = context.TryLink(
+ """
+#include <memory>
+
+int main(int, char **) {
+ // shared_ptr test
+ std::shared_ptr<int> intPtr = std::make_shared<int>();
+
+ // unique_ptr test
+ std::unique_ptr<int> intPtrUnique = std::unique_ptr<int>(new int(1));
+
+ // auto test
+ auto otherIntPtr = intPtr;
+ std::shared_ptr<int> fooIntPtr = otherIntPtr;
+
+ // lambda test
+ auto someFunction = [](int i){ i = i * i; };
+ someFunction(2);
+
+ // nullptr test
+ double* fooDouble = nullptr;
+ double bazDouble = 8.0;
+ fooDouble = &bazDouble;
+ bazDouble = *fooDouble;
+
+ return 0;
+}
+""", '.cpp')
+ context.Result(result)
+ return result
+
################################################################################
# Platform configuration
################################################################################
if ARGUMENTS.get("force-configure", 0) :
- SCons.SConf.SetCacheMode("force")
+ SCons.SConf.SetCacheMode("force")
def CheckPKG(context, name):
- context.Message( 'Checking for package %s... ' % name )
- ret = context.TryAction('pkg-config --exists \'%s\'' % name)[0]
- context.Result( ret )
- return ret
+ context.Message( 'Checking for package %s... ' % name )
+ ret = context.TryAction('pkg-config --exists \'%s\'' % name)[0]
+ context.Result( ret )
+ return ret
def CheckVersion(context, library, version, define, header, value) :
- context.Message("Checking " + library + " version (>= " + version + ") ...")
- version = GetVersion(context, define, header)
- ok = version >= value
- context.Result(ok)
- return ok
+ context.Message("Checking " + library + " version (>= " + version + ") ...")
+ version = GetVersion(context, define, header)
+ ok = version >= value
+ context.Result(ok)
+ return ok
def GetVersion(context, define, header, extension = ".c") :
- ret = context.TryRun("""
+ ret = context.TryRun("""
#include <%(header)s>
#include <stdio.h>
int main(int argc, char* argv[]) {
- printf("%%d\\n", %(define)s);
- return 0;
+ printf("%%d\\n", %(define)s);
+ return 0;
}
""" % { "header" : header, "define": define }, extension)
- if ret[0] :
- return int(ret[1])
- else :
- return -1
-
+ if ret[0] :
+ return int(ret[1])
+ else :
+ return -1
-conf = Configure(conf_env)
+conf = Configure(conf_env, custom_tests = {
+ 'CheckCpp11Support' : checkForCpp11Support,
+ })
if not conf.CheckCXX() or not conf.CheckCC() :
- print "Error: You need a working compiler"
- Exit(1)
+ print "Error: You need a working compiler"
+ Exit(1)
+
+if not conf.CheckCpp11Support() :
+ print "Error: You need a compiler with support for the C++11 standard"
+ Exit(1)
+
env["HAVE_ZLIB"] = True
zlib_flags = {}
zlib_okay = False
if env.get("zlib_libdir", None) :
- zlib_flags["LIBPATH"] = [env["zlib_libdir"]]
- zlib_okay = True
+ zlib_flags["LIBPATH"] = [env["zlib_libdir"]]
+ zlib_okay = True
if env.get("zlib_includedir", None) :
- zlib_flags["CPPPATH"] = [env["zlib_includedir"]]
- zlib_okay = True
+ zlib_flags["CPPPATH"] = [env["zlib_includedir"]]
+ zlib_okay = True
if env.get("zlib_libfile", None) :
- zlib_flags["LIBS"] = [File(env["zlib_libfile"])]
- zlib_okay = True
+ zlib_flags["LIBS"] = [File(env["zlib_libfile"])]
+ zlib_okay = True
elif zlib_okay :
- zlib_flags["LIBS"] = ["z"]
+ zlib_flags["LIBS"] = ["z"]
if (not zlib_okay) and conf.CheckLib("z") :
- zlib_flags["LIBS"] = ["z"]
- zlib_okay = True
+ zlib_flags["LIBS"] = ["z"]
+ zlib_okay = True
if zlib_okay :
- env["ZLIB_FLAGS"] = zlib_flags
+ env["ZLIB_FLAGS"] = zlib_flags
elif not env.get("zlib_bundled_enable", True) :
- print "Error: Zlib not found and zlib_bundled_enable is false"
- Exit(1)
+ print "Error: Zlib not found and zlib_bundled_enable is false"
+ Exit(1)
else :
- env["ZLIB_BUNDLED"] = True
+ env["ZLIB_BUNDLED"] = True
if conf.CheckLib("resolv") :
- env["PLATFORM_FLAGS"]["LIBS"] = env["PLATFORM_FLAGS"].get("LIBS", []) + ["resolv"]
+ env["PLATFORM_FLAGS"]["LIBS"] = env["PLATFORM_FLAGS"].get("LIBS", []) + ["resolv"]
if env["PLATFORM"] != "win32" :
- if conf.CheckLib("pthread") :
- env["PLATFORM_FLAGS"]["LIBS"] = env["PLATFORM_FLAGS"].get("LIBS", []) + ["pthread"]
+ if conf.CheckLib("pthread") :
+ env["PLATFORM_FLAGS"]["LIBS"] = env["PLATFORM_FLAGS"].get("LIBS", []) + ["pthread"]
if conf.CheckLib("dl") :
- env["PLATFORM_FLAGS"]["LIBS"] = env["PLATFORM_FLAGS"].get("LIBS", []) + ["dl"]
+ env["PLATFORM_FLAGS"]["LIBS"] = env["PLATFORM_FLAGS"].get("LIBS", []) + ["dl"]
if conf.CheckLib("m") :
- env["PLATFORM_FLAGS"]["LIBS"] = env["PLATFORM_FLAGS"].get("LIBS", []) + ["m"]
+ env["PLATFORM_FLAGS"]["LIBS"] = env["PLATFORM_FLAGS"].get("LIBS", []) + ["m"]
if conf.CheckLib("c") :
- env["PLATFORM_FLAGS"]["LIBS"] = env["PLATFORM_FLAGS"].get("LIBS", []) + ["c"]
+ env["PLATFORM_FLAGS"]["LIBS"] = env["PLATFORM_FLAGS"].get("LIBS", []) + ["c"]
# Even if you find stdc++ on HP-UX, it is the wrong one for aCC
if env["PLATFORM"] != "hpux" :
- if conf.CheckLib("stdc++", language='CXX') :
- env["PLATFORM_FLAGS"]["LIBS"] = env["PLATFORM_FLAGS"].get("LIBS", []) + ["stdc++"]
+ if conf.CheckLib("stdc++", language='CXX') :
+ env["PLATFORM_FLAGS"]["LIBS"] = env["PLATFORM_FLAGS"].get("LIBS", []) + ["stdc++"]
conf.Finish()
# Boost
boost_conf_env = conf_env.Clone()
boost_flags = {}
if env.get("boost_libdir", None) :
- boost_flags["LIBPATH"] = [env["boost_libdir"]]
+ boost_flags["LIBPATH"] = [env["boost_libdir"]]
if env.get("boost_includedir", None) :
- if env["PLATFORM"] == "win32" or env["PLATFORM"] == "hpux" or env["PLATFORM"] == "sunos" :
- boost_flags["CPPPATH"] = [env["boost_includedir"]]
- else :
- # Using isystem to avoid getting warnings from a system boost
- # Unfortunately, this also disables dependency tracking
- boost_flags["CPPFLAGS"] = [("-isystem", env["boost_includedir"])]
+ if env["PLATFORM"] == "win32" or env["PLATFORM"] == "hpux" or env["PLATFORM"] == "sunos" :
+ boost_flags["CPPPATH"] = [env["boost_includedir"]]
+ else :
+ # Using isystem to avoid getting warnings from a system boost
+ # Unfortunately, this also disables dependency tracking
+ boost_flags["CPPFLAGS"] = [("-isystem", env["boost_includedir"])]
boost_conf_env.MergeFlags(boost_flags)
conf = Configure(boost_conf_env)
-boostLibs = [("signals", None), ("system", "system/system_error.hpp"), ("thread", None), ("regex", None), ("program_options", None), ("filesystem", None), ("serialization", "archive/text_oarchive.hpp"), ("date_time", "date_time/date.hpp")]
+boostLibs = [(None, "signals2.hpp"), ("system", "system/system_error.hpp"), ("thread", None), ("regex", None), ("program_options", None), ("filesystem", None), ("serialization", "archive/text_oarchive.hpp"), ("date_time", "date_time/date.hpp")]
allLibsPresent = True
libNames = []
for (lib, header) in boostLibs :
- if header :
- header = "boost/" + header
- else :
- header = "boost/" + lib + ".hpp"
- if not conf.CheckCXXHeader(header) :
- allLibsPresent = False
- break
- if env["PLATFORM"] != "win32" :
- libName = "boost_" + lib
- if not conf.CheckLib(libName, language='CXX') :
- libName += "-mt"
- if not conf.CheckLib(libName, language='CXX') :
- allLibsPresent = False
- break
- libNames.append(libName)
-if allLibsPresent :
- boost_flags["CPPDEFINES"] = ["BOOST_SIGNALS_NO_DEPRECATION_WARNING"]
- env["BOOST_FLAGS"] = boost_flags
- if env["PLATFORM"] != "win32" :
- env["BOOST_FLAGS"].update({"LIBS": libNames})
- if not conf.CheckCXXHeader("boost/uuid/uuid.hpp") :
- # FIXME: Remove this workaround when UUID is available in most distros
- env["BOOST_BUNDLED_UUID_ONLY"] = True
- env["BOOST_FLAGS"]["CPPDEFINES"] = ["BOOST_SIGNALS_NO_DEPRECATION_WARNING"]
+ if header :
+ header = "boost/" + header
+ else :
+ header = "boost/" + lib + ".hpp"
+ if not conf.CheckCXXHeader(header) :
+ allLibsPresent = False
+ break
+ if lib and env["PLATFORM"] != "win32" :
+ libName = "boost_" + lib
+ if not conf.CheckLib(libName, language='CXX') :
+ libName += "-mt"
+ if not conf.CheckLib(libName, language='CXX') :
+ allLibsPresent = False
+ break
+ libNames.append(libName)
+if not env.get("boost_force_bundled") and allLibsPresent :
+ env["BOOST_FLAGS"] = boost_flags
+ if env["PLATFORM"] != "win32" :
+ env["BOOST_FLAGS"].update({"LIBS": libNames})
+ if not conf.CheckCXXHeader("boost/uuid/uuid.hpp") :
+ # FIXME: Remove this workaround when UUID is available in most distros
+ env["BOOST_BUNDLED_UUID_ONLY"] = True
elif not env.get("boost_bundled_enable", True) :
- print "Error: Boost not found and boost_bundled_enable is false"
- Exit(1)
+ print "Error: Boost not found and boost_bundled_enable is false"
+ Exit(1)
else :
- env["BOOST_BUNDLED"] = True
+ env["BOOST_BUNDLED"] = True
conf.Finish()
# Xss
env["HAVE_XSS"] = 0
if env["PLATFORM"] != "win32" and env["PLATFORM"] != "darwin" :
- xss_flags = {
- "LIBPATH": ["/usr/X11R6/lib"],
- "LIBS": ["Xss"]
- }
- xss_env = conf_env.Clone()
- xss_env.MergeFlags(xss_flags)
- conf = Configure(xss_env)
- if conf.CheckFunc("XScreenSaverQueryExtension") :
- env["HAVE_XSS"] = 1
- env["XSS_FLAGS"] = xss_flags
- conf.Finish()
+ xss_flags = {
+ "LIBPATH": ["/usr/X11R6/lib"],
+ "LIBS": ["Xss"]
+ }
+ xss_env = conf_env.Clone()
+ xss_env.MergeFlags(xss_flags)
+ conf = Configure(xss_env)
+ if conf.CheckFunc("XScreenSaverQueryExtension") :
+ env["HAVE_XSS"] = 1
+ env["XSS_FLAGS"] = xss_flags
+ conf.Finish()
# GConf
env["HAVE_GCONF"] = 0
if env.get("try_gconf", True) and env["PLATFORM"] != "win32" and env["PLATFORM"] != "darwin" :
- gconf_env = conf_env.Clone()
- conf = Configure(gconf_env, custom_tests = {"CheckPKG": CheckPKG})
- if conf.CheckPKG("gconf-2.0") :
- gconf_bare_env = Environment()
- gconf_bare_env.ParseConfig('pkg-config --cflags gconf-2.0 gobject-2.0 --libs gconf-2.0 gobject-2.0')
- gconf_flags = {
- "LIBS": gconf_bare_env["LIBS"],
- "CCFLAGS": gconf_bare_env["CCFLAGS"],
- "CPPPATH": gconf_bare_env["CPPPATH"],
- "CPPDEFINES": gconf_bare_env.get("CPPDEFINES", []),
- }
- gconf_env.MergeFlags(gconf_flags)
- if conf.CheckCHeader("gconf/gconf-client.h") and conf.CheckLib("gconf-2") :
- env["HAVE_GCONF"] = 1
- env["GCONF_FLAGS"] = {
- "LIBS": gconf_env["LIBS"],
- "CCFLAGS": gconf_env["CCFLAGS"],
- "CPPPATH": gconf_env["CPPPATH"],
- "CPPDEFINES": gconf_env.get("CPPDEFINES", []),
- }
- conf.Finish()
+ gconf_env = conf_env.Clone()
+ conf = Configure(gconf_env, custom_tests = {"CheckPKG": CheckPKG})
+ if conf.CheckPKG("gconf-2.0") :
+ gconf_bare_env = Environment()
+ gconf_bare_env.ParseConfig('pkg-config --cflags gconf-2.0 gobject-2.0 --libs gconf-2.0 gobject-2.0')
+ gconf_flags = {
+ "LIBS": gconf_bare_env["LIBS"],
+ "CCFLAGS": gconf_bare_env["CCFLAGS"],
+ "CPPPATH": gconf_bare_env["CPPPATH"],
+ "CPPDEFINES": gconf_bare_env.get("CPPDEFINES", []),
+ }
+ gconf_env.MergeFlags(gconf_flags)
+ if conf.CheckCHeader("gconf/gconf-client.h") and conf.CheckLib("gconf-2") :
+ env["HAVE_GCONF"] = 1
+ env["GCONF_FLAGS"] = {
+ "LIBS": gconf_env["LIBS"],
+ "CCFLAGS": gconf_env["CCFLAGS"],
+ "CPPPATH": gconf_env["CPPPATH"],
+ "CPPDEFINES": gconf_env.get("CPPDEFINES", []),
+ }
+ conf.Finish()
# Sparkle
env["HAVE_SPARKLE"] = 0
if env["PLATFORM"] == "darwin" :
- sparkle_flags = {
- "FRAMEWORKPATH": ["/Library/Frameworks"],
- "FRAMEWORKS": ["Sparkle"]
- }
- sparkle_env = conf_env.Clone()
- sparkle_env.MergeFlags(sparkle_flags)
- conf = Configure(sparkle_env, custom_tests = { "CheckObjCHeader" : checkObjCHeader })
- if conf.CheckObjCHeader("Sparkle/Sparkle.h") :
- env["HAVE_SPARKLE"] = 1
- env["SPARKLE_FLAGS"] = sparkle_flags
- env["SPARKLE_FRAMEWORK"] = "/Library/Frameworks/Sparkle.framework"
- conf.Finish()
+ sparkle_flags = {
+ "FRAMEWORKPATH": ["3rdParty/Sparkle/Sparkle-1.14.0"],
+ "FRAMEWORKS": ["Sparkle"]
+ }
+ sparkle_env = conf_env.Clone()
+ sparkle_env.MergeFlags(sparkle_flags)
+ conf = Configure(sparkle_env, custom_tests = { "CheckObjCHeader" : checkObjCHeader })
+ if conf.CheckObjCHeader("Sparkle/Sparkle.h") :
+ env["HAVE_SPARKLE"] = 1
+ env["SPARKLE_FLAGS"] = sparkle_flags
+ env["SPARKLE_FRAMEWORK"] = Dir("../../3rdParty/Sparkle/Sparkle-1.14.0/Sparkle.framework")
+ conf.Finish()
+
+ if env.get("sparkle_public_dsa_key", None) != None :
+ env["SWIFT_SPARKLE_PUBLIC_DSA_KEY"] = File(env.get("sparkle_public_dsa_key"))
+ else :
+ env["SWIFT_SPARKLE_PUBLIC_DSA_KEY"] = None
# Growl
env["HAVE_GROWL"] = 0
if env["PLATFORM"] == "darwin" :
- growl_flags = {
- "FRAMEWORKPATH": ["/Library/Frameworks"],
- "FRAMEWORKS": ["Growl"]
- }
- growl_env = conf_env.Clone()
- growl_env.MergeFlags(growl_flags)
- conf = Configure(growl_env, custom_tests = { "CheckObjCHeader" : checkObjCHeader })
- if conf.CheckObjCHeader("Growl/Growl.h") :
- env["HAVE_GROWL"] = 1
- env["GROWL_FLAGS"] = growl_flags
- env["GROWL_FRAMEWORK"] = "/Library/Frameworks/Growl.framework"
- conf.Finish()
-
-# Snarl
-if env["PLATFORM"] == "win32" :
- env["HAVE_SNARL"] = True
+ growl_flags = {
+ "FRAMEWORKPATH": ["/Library/Frameworks"],
+ "FRAMEWORKS": ["Growl"]
+ }
+ growl_env = conf_env.Clone()
+ growl_env.MergeFlags(growl_flags)
+ conf = Configure(growl_env, custom_tests = { "CheckObjCHeader" : checkObjCHeader })
+ if conf.CheckObjCHeader("Growl/Growl.h") :
+ env["HAVE_GROWL"] = 1
+ env["GROWL_FLAGS"] = growl_flags
+ env["GROWL_FRAMEWORK"] = "/Library/Frameworks/Growl.framework"
+ conf.Finish()
# LibXML
conf = Configure(conf_env, custom_tests = {"CheckVersion": CheckVersion})
if env.get("try_libxml", True) and conf.CheckCHeader("libxml/parser.h") and conf.CheckLib("xml2") :
#and conf.CheckVersion("LibXML", "2.6.23", "LIBXML_VERSION", "libxml/xmlversion.h", 20623) :
- env["HAVE_LIBXML"] = 1
- env["LIBXML_FLAGS"] = { "LIBS": ["xml2"] }
+ env["HAVE_LIBXML"] = 1
+ env["LIBXML_FLAGS"] = { "LIBS": ["xml2"] }
conf.Finish()
if env.get("try_libxml", True) and not env.get("HAVE_LIBXML", 0) :
- libxml_env = conf_env.Clone()
- libxml_env.Append(CPPPATH = ["/usr/include/libxml2"])
- conf = Configure(libxml_env, custom_tests = {"CheckVersion": CheckVersion})
- if conf.CheckCHeader("libxml/parser.h") and conf.CheckLib("xml2") :
-# and conf.CheckVersion("LibXML", "2.6.23", "LIBXML_VERSION", "libxml/xmlversion.h", 20623):
- env["HAVE_LIBXML"] = 1
- libxml_env.Append()
- if os.path.basename(env["CC"]) in ("clang", "gcc"):
- env["LIBXML_FLAGS"] = { "CXXFLAGS": ["-isystem/usr/include/libxml2"], "LIBS": ["xml2"] }
- else:
- env["LIBXML_FLAGS"] = { "CPPPATH": ["/usr/include/libxml2"], "LIBS": ["xml2"] }
- conf.Finish()
+ libxml_env = conf_env.Clone()
+ libxml_env.Append(CPPPATH = ["/usr/include/libxml2"])
+ conf = Configure(libxml_env, custom_tests = {"CheckVersion": CheckVersion})
+ if conf.CheckCHeader("libxml/parser.h") and conf.CheckLib("xml2") :
+# and conf.CheckVersion("LibXML", "2.6.23", "LIBXML_VERSION", "libxml/xmlversion.h", 20623):
+ env["HAVE_LIBXML"] = 1
+ libxml_env.Append()
+ if os.path.basename(env["CC"]) in ("clang", "gcc"):
+ env["LIBXML_FLAGS"] = { "CXXFLAGS": ["-isystem/usr/include/libxml2"], "LIBS": ["xml2"] }
+ else:
+ env["LIBXML_FLAGS"] = { "CPPPATH": ["/usr/include/libxml2"], "LIBS": ["xml2"] }
+ conf.Finish()
# Expat
if env.get("try_expat", True) and not env.get("HAVE_LIBXML",0) :
- expat_conf_env = conf_env.Clone()
- expat_flags = {}
- if env.get("expat_libdir", None) :
- expat_flags["LIBPATH"] = [env["expat_libdir"]]
- if env.get("expat_includedir", None) :
- expat_flags["CPPPATH"] = [env["expat_includedir"]]
- expat_conf_env.MergeFlags(expat_flags)
- conf = Configure(expat_conf_env)
- if conf.CheckCHeader("expat.h") and conf.CheckLib(env["expat_libname"]) :
- env["HAVE_EXPAT"] = 1
- env["EXPAT_FLAGS"] = { "LIBS": [env["expat_libname"]] }
- env["EXPAT_FLAGS"].update(expat_flags)
- conf.Finish()
+ expat_conf_env = conf_env.Clone()
+ expat_flags = {}
+ if env.get("expat_libdir", None) :
+ expat_flags["LIBPATH"] = [env["expat_libdir"]]
+ if env.get("expat_includedir", None) :
+ expat_flags["CPPPATH"] = [env["expat_includedir"]]
+ expat_conf_env.MergeFlags(expat_flags)
+ conf = Configure(expat_conf_env)
+ if conf.CheckCHeader("expat.h") and conf.CheckLib(env["expat_libname"]) :
+ env["HAVE_EXPAT"] = 1
+ env["EXPAT_FLAGS"] = { "LIBS": [env["expat_libname"]] }
+ env["EXPAT_FLAGS"].update(expat_flags)
+ conf.Finish()
# Bundled expat
bundledExpat = False
if not env.get("HAVE_EXPAT", 0) and not env.get("HAVE_LIBXML", 0) :
- print "Expat or LibXML not found. Using bundled Expat"
- SConscript("#/3rdParty/Expat/SConscript")
- env["HAVE_EXPAT"] = 1
- env["EXPAT_BUNDLED"] = True
+ print "Expat or LibXML not found. Using bundled Expat"
+ SConscript("#/3rdParty/Expat/SConscript")
+ env["HAVE_EXPAT"] = 1
+ env["EXPAT_BUNDLED"] = True
################################################################################
# IDN library
@@ -340,292 +379,294 @@ icu_env = conf_env.Clone()
use_icu = bool(env["icu"])
icu_prefix = ""
if isinstance(env["icu"], str) :
- icu_prefix = env["icu"]
+ icu_prefix = env["icu"]
icu_flags = {}
if icu_prefix :
- icu_flags = { "CPPPATH": [os.path.join(icu_prefix, "include")] }
- icu_flags["LIBPATH"] = [os.path.join(icu_prefix, "lib")]
- icu_env.MergeFlags(icu_flags)
+ icu_flags = { "CPPPATH": [os.path.join(icu_prefix, "include")] }
+ icu_flags["LIBPATH"] = [os.path.join(icu_prefix, "lib")]
+ icu_env.MergeFlags(icu_flags)
icu_conf = Configure(icu_env)
if use_icu and icu_conf.CheckCHeader("unicode/usprep.h") :
- env["HAVE_ICU"] = 1
- env["ICU_FLAGS"] = icu_flags
- env["ICU_FLAGS"]["LIBS"] = ["icuuc"]
+ env["HAVE_ICU"] = 1
+ env["ICU_FLAGS"] = icu_flags
+ env["ICU_FLAGS"]["LIBS"] = ["icuuc"]
icu_conf.Finish()
# LibIDN
libidn_conf_env = conf_env.Clone()
libidn_flags = {}
if env.get("libidn_libdir", None) :
- libidn_flags["LIBPATH"] = [env["libidn_libdir"]]
+ libidn_flags["LIBPATH"] = [env["libidn_libdir"]]
if env.get("libidn_includedir", None) :
- libidn_flags["CPPPATH"] = [env["libidn_includedir"]]
+ libidn_flags["CPPPATH"] = [env["libidn_includedir"]]
libidn_conf_env.MergeFlags(libidn_flags)
conf = Configure(libidn_conf_env)
if env.get("try_libidn", True) and not env.get("HAVE_ICU") and conf.CheckCHeader("idna.h") and conf.CheckLib(env["libidn_libname"]) :
- env["HAVE_LIBIDN"] = 1
- env["LIBIDN_FLAGS"] = { "LIBS": [env["libidn_libname"]] }
- env["LIBIDN_FLAGS"].update(libidn_flags)
+ env["HAVE_LIBIDN"] = 1
+ env["LIBIDN_FLAGS"] = { "LIBS": [env["libidn_libname"]] }
+ env["LIBIDN_FLAGS"].update(libidn_flags)
conf.Finish()
# Fallback to bundled LibIDN
if not env.get("HAVE_ICU", False) and not env.get("HAVE_LIBIDN", False) :
- if env.get("libidn_bundled_enable", True) :
- env["HAVE_LIBIDN"] = 1
- env["LIBIDN_BUNDLED"] = 1
- elif env.get("need_idn", True):
- print "Error: ICU and LIBIDN not found, and libidn_bundled_enable is false"
- Exit(1)
- else:
- print "Proceeding without an IDN library because need_idn was false. This will break all internal binaries"
+ if env.get("libidn_bundled_enable", True) :
+ env["HAVE_LIBIDN"] = 1
+ env["LIBIDN_BUNDLED"] = 1
+ elif env.get("need_idn", True):
+ print "Error: ICU and LIBIDN not found, and libidn_bundled_enable is false"
+ Exit(1)
+ else:
+ print "Proceeding without an IDN library because need_idn was false. This will break all internal binaries"
# Unbound
if env["unbound"] :
- env["LDNS_BUNDLED"] = 1
- env["UNBOUND_BUNDLED"] = 1
+ env["LDNS_BUNDLED"] = 1
+ env["UNBOUND_BUNDLED"] = 1
else :
- env["LDNS_FLAGS"] = {}
- env["UNBOUND_FLAGS"] = {}
+ env["LDNS_FLAGS"] = {}
+ env["UNBOUND_FLAGS"] = {}
# LibMiniUPnPc
if env["experimental_ft"] :
- libminiupnpc_flags = {"CPPPATH": ["/usr/include/miniupnpc/"]}
- libminiupnpc_conf_env = conf_env.Clone()
- if env.get("libminiupnpc_libdir", None) :
- libminiupnpc_flags["LIBPATH"] = [env["libminiupnpc_libdir"]]
- if env.get("libminiupnpc_includedir", None) :
- libminiupnpc_flags["CPPPATH"] = [env["libminiupnpc_includedir"]]
- libminiupnpc_conf_env.MergeFlags(libminiupnpc_flags)
- conf = Configure(libminiupnpc_conf_env)
- if conf.CheckCHeader("miniupnpc.h") and conf.CheckLib(env["libminiupnpc_libname"]) :
- env["HAVE_LIBMINIUPNPC"] = 1
- env["LIBMINIUPNPC_FLAGS"] = { "LIBS": ["miniupnpc"] }
- env["LIBMINIUPNPC_FLAGS"].update(libminiupnpc_flags)
- else :
- env["LIBMINIUPNPC_BUNDLED"] = 1
- conf.Finish()
+ libminiupnpc_flags = {"CPPPATH": ["/usr/include/miniupnpc/"]}
+ libminiupnpc_conf_env = conf_env.Clone()
+ if env.get("libminiupnpc_libdir", None) :
+ libminiupnpc_flags["LIBPATH"] = [env["libminiupnpc_libdir"]]
+ if env.get("libminiupnpc_includedir", None) :
+ libminiupnpc_flags["CPPPATH"] = [env["libminiupnpc_includedir"]]
+ libminiupnpc_conf_env.MergeFlags(libminiupnpc_flags)
+ conf = Configure(libminiupnpc_conf_env)
+ if not env.get("libminiupnpc_force_bundled") and conf.CheckCHeader("miniupnpc.h") and conf.CheckLib(env["libminiupnpc_libname"]) :
+ env["HAVE_LIBMINIUPNPC"] = 1
+ env["LIBMINIUPNPC_FLAGS"] = { "LIBS": ["miniupnpc"] }
+ env["LIBMINIUPNPC_FLAGS"].update(libminiupnpc_flags)
+ else :
+ env["LIBMINIUPNPC_BUNDLED"] = 1
+ conf.Finish()
else :
- env["LIBMINIUPNPC_FLAGS"] = {}
+ env["LIBMINIUPNPC_FLAGS"] = {}
# LibNATPMP
if env["experimental_ft"] :
- libnatpmp_flags = {}
- libnatpmp_conf_env = conf_env.Clone()
- if env.get("libnatpmp_libdir", None) :
- libnatpmp_flags["LIBPATH"] = [env["libnatpmp_libdir"]]
- if env.get("libnatpmp_includedir", None) :
- libnatpmp_flags["CPPPATH"] = [env["libnatpmp_includedir"]]
- libnatpmp_conf_env.MergeFlags(libnatpmp_flags)
- conf = Configure(libnatpmp_conf_env)
- if conf.CheckCHeader("natpmp.h") and conf.CheckLib(env["libnatpmp_libname"]) :
- env["HAVE_LIBNATPMP"] = 1
- env["LIBNATPMP_FLAGS"] = { "LIBS": ["natpmp"] }
- env["LIBNATPMP_FLAGS"].update(libnatpmp_flags)
- else :
- env["LIBNATPMP_BUNDLED"] = 1
- conf.Finish()
+ libnatpmp_flags = {}
+ libnatpmp_conf_env = conf_env.Clone()
+ if env.get("libnatpmp_libdir", None) :
+ libnatpmp_flags["LIBPATH"] = [env["libnatpmp_libdir"]]
+ if env.get("libnatpmp_includedir", None) :
+ libnatpmp_flags["CPPPATH"] = [env["libnatpmp_includedir"]]
+ libnatpmp_conf_env.MergeFlags(libnatpmp_flags)
+ conf = Configure(libnatpmp_conf_env)
+ if not env.get("libnatpmp_force_bundled") and conf.CheckCHeader("natpmp.h") and conf.CheckLib(env["libnatpmp_libname"]) :
+ env["HAVE_LIBNATPMP"] = 1
+ env["LIBNATPMP_FLAGS"] = { "LIBS": ["natpmp"] }
+ env["LIBNATPMP_FLAGS"].update(libnatpmp_flags)
+ else :
+ env["LIBNATPMP_BUNDLED"] = 1
+ conf.Finish()
else :
- env["LIBNATPMP_FLAGS"] = {}
+ env["LIBNATPMP_FLAGS"] = {}
# SQLite
if env["experimental"] :
- sqlite_conf_env = conf_env.Clone()
- sqlite_flags = {}
- if env.get("sqlite_libdir", None) :
- sqlite_flags["LIBPATH"] = [env["sqlite_libdir"]]
- if env.get("sqlite_includedir", None) :
- sqlite_flags["CPPPATH"] = [env["sqlite_includedir"]]
- sqlite_conf_env.MergeFlags(sqlite_flags)
- conf = Configure(sqlite_conf_env)
- if conf.CheckCHeader("sqlite3.h") and conf.CheckLib(env["sqlite_libname"]) and not env.get("sqlite_force_bundled", False):
- env["HAVE_SQLITE"] = 1
- env["SQLITE_FLAGS"] = { "LIBS": [env["sqlite_libname"]] }
- env["SQLITE_FLAGS"].update(sqlite_flags)
- else :
- env["SQLITE_BUNDLED"] = 1
- conf.Finish()
+ sqlite_conf_env = conf_env.Clone()
+ sqlite_flags = {}
+ if env.get("sqlite_libdir", None) :
+ sqlite_flags["LIBPATH"] = [env["sqlite_libdir"]]
+ if env.get("sqlite_includedir", None) :
+ sqlite_flags["CPPPATH"] = [env["sqlite_includedir"]]
+ sqlite_conf_env.MergeFlags(sqlite_flags)
+ conf = Configure(sqlite_conf_env)
+ if conf.CheckCHeader("sqlite3.h") and conf.CheckLib(env["sqlite_libname"]) and not env.get("sqlite_force_bundled", False):
+ env["HAVE_SQLITE"] = 1
+ env["SQLITE_FLAGS"] = { "LIBS": [env["sqlite_libname"]] }
+ env["SQLITE_FLAGS"].update(sqlite_flags)
+ else :
+ env["SQLITE_BUNDLED"] = 1
+ conf.Finish()
else :
- env["SQLITE_FLAGS"] = {}
+ env["SQLITE_FLAGS"] = {}
# Lua
lua_conf_env = conf_env.Clone()
lua_flags = {}
if env.get("lua_libdir", None) :
- lua_flags["LIBPATH"] = [env["lua_libdir"]]
+ lua_flags["LIBPATH"] = [env["lua_libdir"]]
if env.get("lua_includedir", None) :
- lua_flags["CPPPATH"] = [env["lua_includedir"]]
+ lua_flags["CPPPATH"] = [env["lua_includedir"]]
lua_conf_env.MergeFlags(lua_flags)
conf = Configure(lua_conf_env)
if not env.get("lua_force_bundled", False) and conf.CheckLibWithHeader(env["lua_libname"], "lua.hpp", "cxx", autoadd = 0) :
- env["HAVE_LUA"] = 1
- env["LUA_FLAGS"] = { "LIBS": [env["lua_libname"]] }
- lua_version = GetVersion(conf, "LUA_VERSION_NUM", "lua.h")
- if lua_version > 0 :
- env["LUA_FLAGS"]["LUA_VERSION"] = str(lua_version // 100) + "." + str(lua_version % 100)
- else :
- print "Warning: Unable to determine Lua version. Not installing Lua libraries."
- env["LUA_FLAGS"].update(lua_flags)
+ env["HAVE_LUA"] = 1
+ env["LUA_FLAGS"] = { "LIBS": [env["lua_libname"]] }
+ lua_version = GetVersion(conf, "LUA_VERSION_NUM", "lua.h")
+ if lua_version > 0 :
+ env["LUA_FLAGS"]["LUA_VERSION"] = str(lua_version // 100) + "." + str(lua_version % 100)
+ else :
+ print "Warning: Unable to determine Lua version. Not installing Lua libraries."
+ env["LUA_FLAGS"].update(lua_flags)
else :
- env["LUA_BUNDLED"] = 1
+ env["LUA_BUNDLED"] = 1
conf.Finish()
# Readline
editline_conf_env = conf_env.Clone()
editline_flags = {}
if env.get("editline_libdir", None) :
- editline_flags["LIBPATH"] = [env["editline_libdir"]]
+ editline_flags["LIBPATH"] = [env["editline_libdir"]]
if env.get("editline_includedir", None) :
- editline_flags["CPPPATH"] = [env["editline_includedir"]]
+ editline_flags["CPPPATH"] = [env["editline_includedir"]]
editline_conf_env.MergeFlags(editline_flags)
conf = Configure(editline_conf_env)
if conf.CheckLibWithHeader(env["editline_libname"], ["stdio.h", "editline/readline.h"], "c") :
- env["HAVE_EDITLINE"] = 1
- env["EDITLINE_FLAGS"] = { "LIBS": [env["editline_libname"]] }
- env["EDITLINE_FLAGS"].update(editline_flags)
+ env["HAVE_EDITLINE"] = 1
+ env["EDITLINE_FLAGS"] = { "LIBS": [env["editline_libname"]] }
+ env["EDITLINE_FLAGS"].update(editline_flags)
conf.Finish()
# Avahi
avahi_conf_env = conf_env.Clone()
avahi_flags = {}
if env.get("avahi_libdir", None) :
- avahi_flags["LIBPATH"] = [env["avahi_libdir"]]
+ avahi_flags["LIBPATH"] = [env["avahi_libdir"]]
if env.get("avahi_includedir", None) :
- avahi_flags["CPPPATH"] = [env["avahi_includedir"]]
+ avahi_flags["CPPPATH"] = [env["avahi_includedir"]]
avahi_conf_env.MergeFlags(avahi_flags)
conf = Configure(avahi_conf_env)
if env.get("try_avahi", True) and conf.CheckCHeader("avahi-client/client.h") and conf.CheckLib("avahi-client") and conf.CheckLib("avahi-common") :
- env["HAVE_AVAHI"] = True
- env["AVAHI_FLAGS"] = { "LIBS": ["avahi-client", "avahi-common"] }
- env["AVAHI_FLAGS"].update(avahi_flags)
+ env["HAVE_AVAHI"] = True
+ env["AVAHI_FLAGS"] = { "LIBS": ["avahi-client", "avahi-common"] }
+ env["AVAHI_FLAGS"].update(avahi_flags)
conf.Finish()
# Qt
if env["qt"] :
- env["QTDIR"] = env["qt"]
+ env["QTDIR"] = env["qt"]
-# Check for OS X Secure Transport
-if not env.get("openssl_force_bundled", False) and env["PLATFORM"] == "darwin" and env["target"] == "native" :
- env["HAVE_SECURETRANSPORT"] = True
-else :
- env["HAVE_SECURETRANSPORT"] = False
+################################################################################
+# TLS backend selection
+################################################################################
+env["OPENSSL_FLAGS"] = {}
+if env.get("tls_backend") == "native" :
+ if env["PLATFORM"] == "win32" :
+ env["HAVE_SCHANNEL"] = True
+ elif env["PLATFORM"] == "darwin" and env["target"] == "native":
+ env["HAVE_SECURETRANSPORT"] = True
+ elif env["target"] in ("iphone-device", "iphone-simulator", "xcode", "android") :
+ env["tls_backend"] = "openssl_bundled"
+ else :
+ env["tls_backend"] = "openssl"
# OpenSSL
-openssl_env = conf_env.Clone()
-if env.get("openssl_force_bundled", False) or env["target"] in ("iphone-device", "iphone-simulator", "xcode", "android") :
- env["OPENSSL_BUNDLED"] = True
- env["HAVE_OPENSSL"] = True
-elif not env["HAVE_SECURETRANSPORT"] :
- use_openssl = bool(env["openssl"])
- openssl_prefix = ""
- if isinstance(env["openssl"], str) :
- openssl_prefix = env["openssl"]
- openssl_flags = {}
- if openssl_prefix :
- openssl_include = env.get("openssl_include", None)
- openssl_libdir = env.get("openssl_libdir", None)
- if openssl_include:
- openssl_flags = {"CPPPATH":[openssl_include]}
- else:
- openssl_flags = { "CPPPATH": [os.path.join(openssl_prefix, "include")] }
- if openssl_libdir:
- openssl_flags["LIBPATH"] = [openssl_libdir]
- env["OPENSSL_DIR"] = openssl_prefix
- elif env["PLATFORM"] == "win32" :
- openssl_flags["LIBPATH"] = [os.path.join(openssl_prefix, "lib", "VC")]
- env["OPENSSL_DIR"] = openssl_prefix
- else :
- openssl_flags["LIBPATH"] = [os.path.join(openssl_prefix, "lib")]
- openssl_env.MergeFlags(openssl_flags)
-
- openssl_conf = Configure(openssl_env)
- if use_openssl and openssl_conf.CheckCHeader("openssl/ssl.h") :
- env["HAVE_OPENSSL"] = 1
- env["OPENSSL_FLAGS"] = openssl_flags
- openssl_libnames = env.get("openssl_libnames", None)
- if openssl_libnames:
- env["OPENSSL_FLAGS"]["LIBS"] = openssl_libnames.split(',')
- elif env["PLATFORM"] == "win32" :
- env["OPENSSL_FLAGS"]["LIBS"] = ["libeay32MD", "ssleay32MD"]
- else:
- env["OPENSSL_FLAGS"]["LIBS"] = ["ssl", "crypto"]
- if env["PLATFORM"] == "darwin" :
- if platform.mac_ver()[0].startswith("10.5") :
- env["OPENSSL_FLAGS"]["FRAMEWORKS"] = ["Security"]
- else :
- env["OPENSSL_FLAGS"] = {}
- if env["PLATFORM"] == "win32" :
- # If we're compiling for Windows and OpenSSL isn't being used, use Schannel
- env["HAVE_SCHANNEL"] = True
-
- openssl_conf.Finish()
+if env.get("tls_backend") == "openssl_bundled" :
+ env["OPENSSL_BUNDLED"] = True
+ env["HAVE_OPENSSL"] = True
+elif env.get("tls_backend") == "openssl" :
+ openssl_env = conf_env.Clone()
+ use_openssl = bool(env["openssl"])
+ openssl_prefix = ""
+ if isinstance(env["openssl"], str) :
+ openssl_prefix = env["openssl"]
+ openssl_flags = {}
+ if openssl_prefix :
+ openssl_include = env.get("openssl_include")
+ openssl_libdir = env.get("openssl_libdir")
+ if openssl_include:
+ openssl_flags = {"CPPPATH":[openssl_include]}
+ else:
+ openssl_flags = { "CPPPATH": [os.path.join(openssl_prefix, "include")] }
+ if openssl_libdir:
+ openssl_flags["LIBPATH"] = [openssl_libdir]
+ env["OPENSSL_DIR"] = openssl_prefix
+ elif env["PLATFORM"] == "win32" :
+ openssl_flags["LIBPATH"] = [os.path.join(openssl_prefix, "lib", "VC")]
+ env["OPENSSL_DIR"] = openssl_prefix
+ else :
+ openssl_flags["LIBPATH"] = [os.path.join(openssl_prefix, "lib")]
+ openssl_env.MergeFlags(openssl_flags)
+
+ openssl_conf = Configure(openssl_env)
+ if use_openssl and openssl_conf.CheckCHeader("openssl/ssl.h") :
+ env["HAVE_OPENSSL"] = 1
+ env["OPENSSL_FLAGS"] = openssl_flags
+ openssl_libnames = env.get("openssl_libnames")
+ if openssl_libnames:
+ env["OPENSSL_FLAGS"]["LIBS"] = openssl_libnames.split(',')
+ elif env["PLATFORM"] == "win32" :
+ env["OPENSSL_FLAGS"]["LIBS"] = ["libeay32MD", "ssleay32MD"]
+ else:
+ env["OPENSSL_FLAGS"]["LIBS"] = ["ssl", "crypto"]
+ if env["PLATFORM"] == "darwin" :
+ if platform.mac_ver()[0].startswith("10.5") :
+ env["OPENSSL_FLAGS"]["FRAMEWORKS"] = ["Security"]
+ openssl_conf.Finish()
if env["PLATFORM"] == "win32" :
- # On Windows link to secur32. It is needed by Swiften/SASL/WindowsAuthentication
- env.Append(LIBS = ["secur32"])
+ # On Windows link to secur32. It is needed by Swiften/SASL/WindowsAuthentication
+ env.Append(LIBS = ["secur32"])
#Hunspell
hunspell_env = conf_env.Clone()
hunspell_prefix = isinstance(env.get("hunspell_prefix", False), str) and env["hunspell_prefix"] or ""
hunspell_flags = {}
if hunspell_prefix :
- hunspell_flags = {"CPPPATH":[os.path.join(hunspell_prefix, "include")], "LIBPATH":[os.path.join(hunspell_prefix, "lib")]}
+ hunspell_flags = {"CPPPATH":[os.path.join(hunspell_prefix, "include")], "LIBPATH":[os.path.join(hunspell_prefix, "lib")]}
hunspell_env.MergeFlags(hunspell_flags)
env["HAVE_HUNSPELL"] = 0;
if env.get("hunspell_enable", False) :
- hunspell_conf = Configure(hunspell_env)
- if hunspell_conf.CheckCXXHeader("hunspell/hunspell.hxx") and hunspell_conf.CheckLib("hunspell") :
- env["HAVE_HUNSPELL"] = 1
- hunspell_flags["LIBS"] = ["hunspell"]
- env["HUNSPELL_FLAGS"] = hunspell_flags
- hunspell_conf.Finish()
+ hunspell_conf = Configure(hunspell_env)
+ if hunspell_conf.CheckCXXHeader("hunspell/hunspell.hxx") and hunspell_conf.CheckLib("hunspell") :
+ env["HAVE_HUNSPELL"] = 1
+ hunspell_flags["LIBS"] = ["hunspell"]
+ env["HUNSPELL_FLAGS"] = hunspell_flags
+ hunspell_conf.Finish()
# Bonjour
if env["PLATFORM"] == "darwin" and env["target"] == "native" :
- env["HAVE_BONJOUR"] = 1
+ env["HAVE_BONJOUR"] = 1
elif env.get("bonjour", False) :
- bonjour_env = conf_env.Clone()
- bonjour_conf = Configure(bonjour_env)
- bonjour_flags = {}
- if env.get("bonjour") != True :
- bonjour_prefix = env["bonjour"]
- bonjour_flags["CPPPATH"] = [os.path.join(bonjour_prefix, "include")]
- bonjour_flags["LIBPATH"] = [os.path.join(bonjour_prefix, "lib", "win32")]
- bonjour_env.MergeFlags(bonjour_flags)
- if bonjour_conf.CheckCHeader("dns_sd.h") and bonjour_conf.CheckLib("dnssd") :
- env["HAVE_BONJOUR"] = 1
- env["BONJOUR_FLAGS"] = bonjour_flags
- env["BONJOUR_FLAGS"]["LIBS"] = ["dnssd"]
- bonjour_conf.Finish()
+ bonjour_env = conf_env.Clone()
+ bonjour_conf = Configure(bonjour_env)
+ bonjour_flags = {}
+ if env.get("bonjour") != True :
+ bonjour_prefix = env["bonjour"]
+ bonjour_flags["CPPPATH"] = [os.path.join(bonjour_prefix, "include")]
+ bonjour_flags["LIBPATH"] = [os.path.join(bonjour_prefix, "lib", "win32")]
+ bonjour_env.MergeFlags(bonjour_flags)
+ if bonjour_conf.CheckCHeader("dns_sd.h") and bonjour_conf.CheckLib("dnssd") :
+ env["HAVE_BONJOUR"] = 1
+ env["BONJOUR_FLAGS"] = bonjour_flags
+ env["BONJOUR_FLAGS"]["LIBS"] = ["dnssd"]
+ bonjour_conf.Finish()
# Cocoa & IOKit
if env["PLATFORM"] == "darwin" :
- cocoa_conf = Configure(conf_env)
- if cocoa_conf.CheckCHeader("IOKit/IOKitLib.h") :
- env["HAVE_IOKIT"] = True
- cocoa_conf.Finish()
+ cocoa_conf = Configure(conf_env)
+ if cocoa_conf.CheckCHeader("IOKit/IOKitLib.h") :
+ env["HAVE_IOKIT"] = True
+ cocoa_conf.Finish()
# Qt
try :
- myenv = env.Clone()
- myenv.Tool("qt4", toolpath = ["#/BuildTools/SCons/Tools"])
- env["HAVE_QT"] = True
+ myenv = env.Clone()
+ myenv.Tool("qt4", toolpath = ["#/BuildTools/SCons/Tools"])
+ env["HAVE_QT"] = True
except SCons.Errors.StopError:
- env["HAVE_QT"] = False
+ env["HAVE_QT"] = False
except Exception as e:
- print "Info: %s" % str(e)
- env["HAVE_QT"] = False
+ print "Info: %s" % str(e)
+ env["HAVE_QT"] = False
################################################################################
# DocBook setup
################################################################################
if env.get("docbook_xml") :
- env["DOCBOOK_XML_DIR"] = env["docbook_xml"]
+ env["DOCBOOK_XML_DIR"] = env["docbook_xml"]
if env.get("docbook_xsl") :
- env["DOCBOOK_XSL_DIR"] = env["docbook_xsl"]
+ env["DOCBOOK_XSL_DIR"] = env["docbook_xsl"]
################################################################################
@@ -633,11 +674,11 @@ if env.get("docbook_xsl") :
################################################################################
try:
- if env.Dir("#/.git").exists() :
- if not env.GetOption("clean") and env.get("install_git_hooks", True) :
- env.Install("#/.git/hooks", Glob("#/BuildTools/Git/Hooks/*"))
+ if env.Dir("#/.git").exists() :
+ if not env.GetOption("clean") and env.get("install_git_hooks", True) :
+ env.Install("#/.git/hooks", Glob("#/BuildTools/Git/Hooks/*"))
except TypeError:
- print "You seem to be using Swift in a Git submodule. Not installing hooks."
+ print "You seem to be using Swift in a Git submodule. Not installing hooks."
################################################################################
@@ -645,23 +686,23 @@ except TypeError:
################################################################################
if ARGUMENTS.get("replace_pragma_once", False) :
- env.Tool("ReplacePragmaOnce", toolpath = ["#/BuildTools/SCons/Tools"])
-
- def relpath(path, start) :
- i = len(os.path.commonprefix([path, start]))
- return path[i+1:]
-
- for actual_root, dirs, files in os.walk(root) :
- if "3rdParty" in actual_root :
- continue
- for file in files :
- if not file.endswith(".h") :
- continue
- include = relpath(os.path.join(actual_root, file), root)
- env.ReplacePragmaOnce("#/include/" + include, "#/" + include)
- env.Append(CPPPATH = ["#/include"])
+ env.Tool("ReplacePragmaOnce", toolpath = ["#/BuildTools/SCons/Tools"])
+
+ def relpath(path, start) :
+ i = len(os.path.commonprefix([path, start]))
+ return path[i+1:]
+
+ for actual_root, dirs, files in os.walk(root) :
+ if "3rdParty" in actual_root :
+ continue
+ for file in files :
+ if not file.endswith(".h") :
+ continue
+ include = relpath(os.path.join(actual_root, file), root)
+ env.ReplacePragmaOnce("#/include/" + include, "#/" + include)
+ env.Append(CPPPATH = ["#/include"])
else :
- env.Append(CPPPATH = [root])
+ env.Append(CPPPATH = [root])
################################################################################
@@ -669,29 +710,29 @@ else :
################################################################################
if ARGUMENTS.get("dump_trace", False) :
- env.SetOption("no_exec", True)
- env["TEST"] = True
- env["BOOST_BUILD_BCP"] = True
- env.Decider(lambda x, y, z : True)
- SCons.Node.Python.Value.changed_since_last_build = (lambda x, y, z: True)
+ env.SetOption("no_exec", True)
+ env["TEST"] = True
+ env["BOOST_BUILD_BCP"] = True
+ env.Decider(lambda x, y, z : True)
+ SCons.Node.Python.Value.changed_since_last_build = (lambda x, y, z: True)
# Modules
modules = []
if os.path.isdir(Dir("#/3rdParty").abspath) :
- for dir in os.listdir(Dir("#/3rdParty").abspath) :
- full_dir = os.path.join(Dir("#/3rdParty").abspath, dir)
- if not os.path.isdir(full_dir) :
- continue
- sconscript = os.path.join(full_dir, "SConscript")
- if os.path.isfile(sconscript) :
- modules.append("3rdParty/" + dir)
+ for dir in os.listdir(Dir("#/3rdParty").abspath) :
+ full_dir = os.path.join(Dir("#/3rdParty").abspath, dir)
+ if not os.path.isdir(full_dir) :
+ continue
+ sconscript = os.path.join(full_dir, "SConscript")
+ if os.path.isfile(sconscript) :
+ modules.append("3rdParty/" + dir)
for dir in os.listdir(Dir("#").abspath) :
- full_dir = os.path.join(Dir("#").abspath, dir)
- if not os.path.isdir(full_dir) :
- continue
- sconscript = os.path.join(full_dir, "SConscript")
- if os.path.isfile(sconscript) :
- modules.append(dir)
+ full_dir = os.path.join(Dir("#").abspath, dir)
+ if not os.path.isdir(full_dir) :
+ continue
+ sconscript = os.path.join(full_dir, "SConscript")
+ if os.path.isfile(sconscript) :
+ modules.append(dir)
# QA comes last
modules.remove("QA")
@@ -700,13 +741,13 @@ modules.append("QA")
# Flags
env["PROJECTS"] = [m for m in modules if m not in ["Documentation", "QA", "SwifTools"] and not m.startswith("3rdParty")]
for stage in ["flags", "build"] :
- env["SCONS_STAGE"] = stage
- SConscript(dirs = map(lambda x : root + "/" + x, modules))
+ env["SCONS_STAGE"] = stage
+ SConscript(dirs = map(lambda x : root + "/" + x, modules))
# SLOCCount
if ARGUMENTS.get("sloccount", False) :
- for project in env["PROJECTS"] :
- env.SLOCCount("#/" + project)
+ for project in env["PROJECTS"] :
+ env.SLOCCount("#/" + project)
################################################################################
@@ -719,11 +760,11 @@ print " -------------------"
parsers = []
if env.get("HAVE_LIBXML", 0):
- parsers.append("LibXML")
+ parsers.append("LibXML")
if env.get("HAVE_EXPAT", 0):
- parsers.append("Expat")
- if env.get("EXPAT_BUNDLED", False) :
- parsers.append("(Bundled)")
+ parsers.append("Expat")
+ if env.get("EXPAT_BUNDLED", False) :
+ parsers.append("(Bundled)")
print " Projects: " + ' '.join(env["PROJECTS"])
print ""
print " XML Parsers: " + ' '.join(parsers)
@@ -731,3 +772,8 @@ print " XML Parsers: " + ' '.join(parsers)
print " TLS Support: " + (env.get("HAVE_OPENSSL",0) and "OpenSSL" or env.get("HAVE_SECURETRANSPORT",0) and "Secure Transport" or env.get("HAVE_SCHANNEL", 0) and "Schannel" or "Disabled")
print " DNSSD Support: " + (env.get("HAVE_BONJOUR") and "Bonjour" or (env.get("HAVE_AVAHI") and "Avahi" or "Disabled"))
print
+
+if not GetOption("help") and not env.get("HAVE_OPENSSL", 0) and not env.get("HAVE_SCHANNEL", 0) and not env.get("HAVE_SECURETRANSPORT", 0):
+ print "Error: A working TLS backend is required. Please check the documentation for more information."
+ Exit(1)
+
diff --git a/BuildTools/SCons/Tools/AppBundle.py b/BuildTools/SCons/Tools/AppBundle.py
index f1072f5..337e83f 100644
--- a/BuildTools/SCons/Tools/AppBundle.py
+++ b/BuildTools/SCons/Tools/AppBundle.py
@@ -1,64 +1,72 @@
import SCons.Util, os.path
+from datetime import date
def generate(env) :
- def createAppBundle(env, bundle, version = "1.0", resources = [], frameworks = [], info = {}, handlesXMPPURIs = False) :
- bundleDir = bundle + ".app"
- bundleContentsDir = bundleDir + "/Contents"
- resourcesDir = bundleContentsDir + "/Resources"
- frameworksDir = bundleContentsDir + "/Frameworks"
- env.Install(bundleContentsDir + "/MacOS", bundle)
- env.WriteVal(bundleContentsDir + "/PkgInfo", env.Value("APPL\77\77\77\77"))
+ def createAppBundle(env, bundle, version = "1.0", resources = [], frameworks = [], info = {}, handlesXMPPURIs = False, sparklePublicDSAKey = None) :
+ env.Tool("InstallWithSymLinks", toolpath = ["#/BuildTools/SCons/Tools"])
- infoDict = {
- "CFBundleDevelopmentRegion" : "English",
- "CFBundleExecutable" : bundle,
- "CFBundleIdentifier" : "im.swift." + bundle,
- "CFBundleInfoDictionaryVersion" : "6.0",
- "CFBundleName" : bundle,
- "CFBundlePackageType" : "APPL",
- "CFBundleSignature": "\77\77\77\77",
- "CFBundleVersion" : version,
- "CFBundleIconFile" : bundle,
- "NSPrincipalClass" : "NSApplication",
- "NSHumanReadableCopyright" : unichr(0xA9) + " 2010 Swift Development Team.\nAll Rights Reserved."
- }
- infoDict.update(info)
+ bundleDir = bundle + ".app"
+ bundleContentsDir = bundleDir + "/Contents"
+ resourcesDir = bundleContentsDir + "/Resources"
+ frameworksDir = bundleContentsDir + "/Frameworks"
+ env.Install(bundleContentsDir + "/MacOS", bundle)
+ env.WriteVal(bundleContentsDir + "/PkgInfo", env.Value("APPL\77\77\77\77"))
- plist = """<?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
- <plist version="1.0">
- <dict>
- """
- for key, value in infoDict.items() :
- plist += "<key>" + key + "</key>\n"
- plist += "<string>" + value.encode("utf-8") + "</string>\n"
- if handlesXMPPURIs :
- plist += """<key>CFBundleURLTypes</key>
+ infoDict = {
+ "CFBundleDevelopmentRegion" : "English",
+ "CFBundleExecutable" : bundle,
+ "CFBundleIdentifier" : "im.swift." + bundle,
+ "CFBundleInfoDictionaryVersion" : "6.0",
+ "CFBundleName" : bundle,
+ "CFBundlePackageType" : "APPL",
+ "CFBundleSignature": "\77\77\77\77",
+ "CFBundleVersion" : version,
+ "CFBundleIconFile" : bundle,
+ "NSPrincipalClass" : "NSApplication",
+ "NSHumanReadableCopyright" : "(c) 2010-%d Isode Ltd.\nAll Rights Reserved." % date.today().year
+ }
+ infoDict.update(info)
+
+ plist = """<?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <plist version="1.0">
+ <dict>
+ """
+ for key, value in infoDict.items() :
+ plist += "<key>" + key + "</key>\n"
+ plist += "<string>" + value.encode("utf-8") + "</string>\n"
+ if handlesXMPPURIs :
+ plist += """<key>CFBundleURLTypes</key>
<array>
- <dict>
- <key>CFBundleURLName</key>
- <string>XMPP URL</string>
- <key>CFBundleURLSchemes</key>
- <array>
- <string>xmpp</string>
- </array>
- </dict>
+ <dict>
+ <key>CFBundleURLName</key>
+ <string>XMPP URL</string>
+ <key>CFBundleURLSchemes</key>
+ <array>
+ <string>xmpp</string>
+ </array>
+ </dict>
</array>\n"""
- plist += """</dict>
- </plist>
- """
- env.WriteVal(bundleContentsDir + "/Info.plist", env.Value(plist))
- for (target, resource) in resources.items() :
- env.Install(os.path.join(resourcesDir, target), resource)
+ if sparklePublicDSAKey :
+ plist += "<key>SUPublicDSAKeyFile</key>"
+ plist += "<string>" + sparklePublicDSAKey.name.encode("utf-8") + "</string>"
+ env.Install(resourcesDir, sparklePublicDSAKey)
+ plist += """</dict>
+ </plist>
+ """
+ env.WriteVal(bundleContentsDir + "/Info.plist", env.Value(plist))
+
+ for (target, resource) in resources.items() :
+ env.Install(os.path.join(resourcesDir, target), resource)
- for framework in frameworks :
- env.Install(frameworksDir, framework)
+ for framework in frameworks :
+ env.InstallWithSymLinks(frameworksDir, framework)
- return env.Dir(bundleDir)
+ return env.Dir(bundleDir)
- env.AddMethod(createAppBundle, "AppBundle")
+ env.AddMethod(createAppBundle, "AppBundle")
def exists(env) :
- return env["PLATFORM"] == "darwin"
+ return env["PLATFORM"] == "darwin"
diff --git a/BuildTools/SCons/Tools/BuildVersion.py b/BuildTools/SCons/Tools/BuildVersion.py
index b15448a..7968282 100644
--- a/BuildTools/SCons/Tools/BuildVersion.py
+++ b/BuildTools/SCons/Tools/BuildVersion.py
@@ -3,16 +3,16 @@ import SCons.Util
import Version
def generate(env) :
- def createBuildVersion(env, target, project) :
- buildVersion = """#pragma once
+ def createBuildVersion(env, target, project) :
+ buildVersion = """#pragma once
static const char* buildVersion = \"%(buildVersion)s\";\n
#define SWIFT_VERSION_STRING \"%(buildVersion)s\";\n
""" % { "buildVersion" : Version.getBuildVersion(env.Dir("#").abspath, project) }
- env.WriteVal(target, env.Value(buildVersion))
+ env.WriteVal(target, env.Value(buildVersion))
- env.AddMethod(createBuildVersion, "BuildVersion")
+ env.AddMethod(createBuildVersion, "BuildVersion")
def exists(env) :
- return true
+ return true
diff --git a/BuildTools/SCons/Tools/DoxyGen.py b/BuildTools/SCons/Tools/DoxyGen.py
index 79af1c9..66a9111 100644
--- a/BuildTools/SCons/Tools/DoxyGen.py
+++ b/BuildTools/SCons/Tools/DoxyGen.py
@@ -1,26 +1,26 @@
import SCons.Util, os
def generate(env) :
- def modify_targets(target, source, env) :
- target = [env.File("html/index.html")]
- return target, source
+ def modify_targets(target, source, env) :
+ target = [env.File("html/index.html")]
+ return target, source
- def generate_actions(source, target, env, for_signature) :
- if env.WhereIs("$DOXYGEN") and env.WhereIs("$DOT") :
- return [SCons.Action.Action("$DOXYGEN $SOURCE", cmdstr = "$DOXYCOMSTR")]
- else :
- return []
+ def generate_actions(source, target, env, for_signature) :
+ if env.WhereIs("$DOXYGEN") and env.WhereIs("$DOT") :
+ return [SCons.Action.Action("$DOXYGEN $SOURCE", cmdstr = "$DOXYCOMSTR")]
+ else :
+ return []
- env["DOXYGEN"] = "doxygen"
- # FIXME: For some reason, things go incredibly slow (at least on OS X)
- # when not doing this. Some environment flag is having an effect on
- # this; find out which
- env["ENV"] = os.environ
- env["DOT"] = "dot"
- env["BUILDERS"]["DoxyGen"] = SCons.Builder.Builder(
- emitter = modify_targets,
- generator = generate_actions,
- single_source = True)
+ env["DOXYGEN"] = "doxygen"
+ # FIXME: For some reason, things go incredibly slow (at least on OS X)
+ # when not doing this. Some environment flag is having an effect on
+ # this; find out which
+ env["ENV"] = os.environ
+ env["DOT"] = "dot"
+ env["BUILDERS"]["DoxyGen"] = SCons.Builder.Builder(
+ emitter = modify_targets,
+ generator = generate_actions,
+ single_source = True)
def exists(env) :
- return True
+ return True
diff --git a/BuildTools/SCons/Tools/Flags.py b/BuildTools/SCons/Tools/Flags.py
index 0768181..fe0cfcc 100644
--- a/BuildTools/SCons/Tools/Flags.py
+++ b/BuildTools/SCons/Tools/Flags.py
@@ -1,13 +1,13 @@
import SCons.Util
def generate(env) :
- def useFlags(env, flags) :
- for flag in flags :
- if flag in env :
- env[flag] = env[flag] + flags[flag]
- else :
- env[flag] = flags[flag]
- env.AddMethod(useFlags, "UseFlags")
+ def useFlags(env, flags) :
+ for flag in flags :
+ if flag in env :
+ env[flag] = env[flag] + flags[flag]
+ else :
+ env[flag] = flags[flag]
+ env.AddMethod(useFlags, "UseFlags")
def exists(env) :
- return True
+ return True
diff --git a/BuildTools/SCons/Tools/InstallWithSymLinks.py b/BuildTools/SCons/Tools/InstallWithSymLinks.py
new file mode 100644
index 0000000..23d12ed
--- /dev/null
+++ b/BuildTools/SCons/Tools/InstallWithSymLinks.py
@@ -0,0 +1,114 @@
+"""SCons.Tool.install
+
+Tool-specific initialization for the install tool.
+
+There normally shouldn't be any need to import this module directly.
+It will usually be imported through the generic SCons.Tool.Tool()
+selection method.
+"""
+
+#
+# Copyright (c) 2001 - 2015 The SCons Foundation
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+
+from SCons.Script import Action, Builder
+from SCons.Node import FS
+import shutil
+import stat
+import os
+from os import path
+
+class CopytreeError(EnvironmentError):
+ pass
+
+# This is a patched version of shutil.copytree from python 2.5. It
+# doesn't fail if the dir exists, which regular copytree does
+# (annoyingly). Note the XXX comment in the docstring.
+def scons_copytree(src, dst, symlinks=False):
+ """Recursively copy a directory tree using copy2().
+
+ The destination directory must not already exist.
+ If exception(s) occur, an CopytreeError is raised with a list of reasons.
+
+ If the optional symlinks flag is true, symbolic links in the
+ source tree result in symbolic links in the destination tree; if
+ it is false, the contents of the files pointed to by symbolic
+ links are copied.
+
+ XXX Consider this example code rather than the ultimate tool.
+
+ """
+ names = os.listdir(src)
+ # garyo@genarts.com fix: check for dir before making dirs.
+ if not os.path.exists(dst):
+ os.makedirs(dst)
+ errors = []
+ for name in names:
+ srcname = os.path.join(src, name)
+ dstname = os.path.join(dst, name)
+ try:
+ if symlinks and os.path.islink(srcname):
+ linkto = os.readlink(srcname)
+ os.symlink(linkto, dstname)
+ elif os.path.isdir(srcname):
+ scons_copytree(srcname, dstname, symlinks)
+ else:
+ shutil.copy2(srcname, dstname)
+ # XXX What about devices, sockets etc.?
+ except (IOError, os.error), why:
+ errors.append((srcname, dstname, str(why)))
+ # catch the CopytreeError from the recursive copytree so that we can
+ # continue with other files
+ except CopytreeError, err:
+ errors.extend(err.args[0])
+ try:
+ shutil.copystat(src, dst)
+ except WindowsError:
+ # can't copy file access times on Windows
+ pass
+ except OSError, why:
+ errors.extend((src, dst, str(why)))
+ if errors:
+ raise CopytreeError, errors
+
+
+def symlinkBuilderImpl(target, source, env):
+ lnk = target[0].abspath
+ src = source[0].abspath
+ lnkdir,lnkname = path.split(lnk)
+ srcdir,srcname = path.split(src)
+
+ scons_copytree(src, os.path.join(lnk, srcname), True)
+
+ return None
+
+def symlinkBuilderPrinter(target, source, env):
+ lnk = path.basename(target[0].abspath)
+ src = path.basename(source[0].abspath)
+ return 'INSTALL PRESERVING SYMLINKS ' + target[0].get_internal_path()
+
+def generate(env) :
+ symlinkBuilder = Builder(action = Action(symlinkBuilderImpl, symlinkBuilderPrinter), target_factory = FS.Entry, source_factory = FS.Entry)
+ env.Append(BUILDERS = {'InstallWithSymLinks' : symlinkBuilder})
+
+def exists(env) :
+ return True \ No newline at end of file
diff --git a/BuildTools/SCons/Tools/Nib.py b/BuildTools/SCons/Tools/Nib.py
index 91eb064..cf5b0dc 100644
--- a/BuildTools/SCons/Tools/Nib.py
+++ b/BuildTools/SCons/Tools/Nib.py
@@ -1,12 +1,12 @@
import SCons.Util
def generate(env) :
- env["IBTOOL"] = "ibtool"
- env["BUILDERS"]["Nib"] = SCons.Builder.Builder(
- action = SCons.Action.Action("$IBTOOL --errors --warnings --notices --output-format human-readable-text --compile $TARGET $SOURCE", cmdstr = "$NIBCOMSTR"),
- suffix = ".nib",
- src_suffix = ".xib",
- single_source = True)
+ env["IBTOOL"] = "ibtool"
+ env["BUILDERS"]["Nib"] = SCons.Builder.Builder(
+ action = SCons.Action.Action("$IBTOOL --errors --warnings --notices --output-format human-readable-text --compile $TARGET $SOURCE", cmdstr = "$NIBCOMSTR"),
+ suffix = ".nib",
+ src_suffix = ".xib",
+ single_source = True)
def exists(env) :
- return env["PLATFORM"] == "darwin"
+ return env["PLATFORM"] == "darwin"
diff --git a/BuildTools/SCons/Tools/ReplacePragmaOnce.py b/BuildTools/SCons/Tools/ReplacePragmaOnce.py
index 3df0f41..cb49bbb 100644
--- a/BuildTools/SCons/Tools/ReplacePragmaOnce.py
+++ b/BuildTools/SCons/Tools/ReplacePragmaOnce.py
@@ -1,25 +1,25 @@
import SCons.Util, os.path
def generate(env) :
- root = env.Dir("#").abspath
- def relpath(path, start) :
- i = len(os.path.commonprefix([path, start]))
- return path[i+1:]
+ root = env.Dir("#").abspath
+ def relpath(path, start) :
+ i = len(os.path.commonprefix([path, start]))
+ return path[i+1:]
- def replacePragmaOnce(env, target, source) :
- guard = relpath(source[0].abspath, root).replace("/", "_").replace(".", "_").upper()
- data = source[0].get_contents()
- f = open(str(target[0]), 'wb')
- if "#pragma once" in data :
- f.write(data.replace("#pragma once", "#ifndef %(guard)s\n#define %(guard)s" % {"guard": guard}))
- f.write("\n#endif\n")
- else :
- f.write(data)
- f.close()
+ def replacePragmaOnce(env, target, source) :
+ guard = relpath(source[0].abspath, root).replace("/", "_").replace(".", "_").upper()
+ data = source[0].get_contents()
+ f = open(str(target[0]), 'wb')
+ if "#pragma once" in data :
+ f.write(data.replace("#pragma once", "#ifndef %(guard)s\n#define %(guard)s" % {"guard": guard}))
+ f.write("\n#endif\n")
+ else :
+ f.write(data)
+ f.close()
- env["BUILDERS"]["ReplacePragmaOnce"] = SCons.Builder.Builder(
- action = SCons.Action.Action(replacePragmaOnce, cmdstr = "$GENCOMSTR"),
- single_source = True)
+ env["BUILDERS"]["ReplacePragmaOnce"] = SCons.Builder.Builder(
+ action = SCons.Action.Action(replacePragmaOnce, cmdstr = "$GENCOMSTR"),
+ single_source = True)
def exists(env) :
- return True
+ return True
diff --git a/BuildTools/SCons/Tools/SLOCCount.py b/BuildTools/SCons/Tools/SLOCCount.py
index 682a797..be31672 100644
--- a/BuildTools/SCons/Tools/SLOCCount.py
+++ b/BuildTools/SCons/Tools/SLOCCount.py
@@ -1,17 +1,17 @@
import SCons.Util, os.path, os
def generate(env) :
- def createSLOCCount(env, source) :
- myenv = env.Clone()
- myenv["ENV"]["HOME"] = os.environ["HOME"]
- source = myenv.Dir(source)
- target = myenv.File("#/" + source.path + ".sloccount")
- # FIXME: There's probably a better way to force building the .sc
- if os.path.exists(target.abspath) :
- os.unlink(target.abspath)
- return myenv.Command(target, source, [SCons.Action.Action("sloccount --duplicates --wide --details " + source.path + " | grep -v qrc_ > $TARGET", cmdstr = "$GENCOMSTR")])
+ def createSLOCCount(env, source) :
+ myenv = env.Clone()
+ myenv["ENV"]["HOME"] = os.environ["HOME"]
+ source = myenv.Dir(source)
+ target = myenv.File("#/" + source.path + ".sloccount")
+ # FIXME: There's probably a better way to force building the .sc
+ if os.path.exists(target.abspath) :
+ os.unlink(target.abspath)
+ return myenv.Command(target, source, [SCons.Action.Action("sloccount --duplicates --wide --details " + source.path + " | grep -v qrc_ > $TARGET", cmdstr = "$GENCOMSTR")])
- env.AddMethod(createSLOCCount, "SLOCCount")
+ env.AddMethod(createSLOCCount, "SLOCCount")
def exists(env) :
- return True
+ return True
diff --git a/BuildTools/SCons/Tools/Test.py b/BuildTools/SCons/Tools/Test.py
index 1eee4f6..72acb22 100644
--- a/BuildTools/SCons/Tools/Test.py
+++ b/BuildTools/SCons/Tools/Test.py
@@ -1,53 +1,53 @@
import SCons.Util, os
def generate(env) :
- def registerTest(env, target, type = "unit", is_checker = False) :
- if env["TEST_TYPE"] == "all" or env["TEST_TYPE"] == type :
- if SCons.Util.is_List(target) :
- cmd = target[0].abspath
- else :
- cmd = target.abspath
- params = ""
-
- # Special support for unittest checker
- if is_checker and env.get("checker_report", False) :
- params = " --xml > " + os.path.join(target[0].dir.path, "checker-report.xml")
-
- ignore_prefix = ""
- if env.get("TEST_IGNORE_RESULT", False) :
- ignore_prefix = "-"
-
- # Set environment variables for running the test
- test_env = env.Clone()
- for i in ["HOME", "USERPROFILE", "APPDATA", "ASAN_OPTIONS", "LSAN_OPTIONS", "SWIFT_NETWORK_TEST_IPV4", "SWIFT_NETWORK_TEST_IPV6"]:
- if os.environ.get(i, "") :
- test_env["ENV"][i] = os.environ[i]
- if env["target"] == "android" :
- test_env["ENV"]["PATH"] = env["android_sdk_bin"] + ";" + test_env["ENV"]["PATH"]
- else :
- if test_env["PLATFORM"] == "darwin" :
- test_env["ENV"]["DYLD_FALLBACK_LIBRARY_PATH"] = ":".join(map(lambda x : str(x), test_env.get("LIBPATH", [])))
- elif test_env["PLATFORM"] == "win32" :
- test_env["ENV"]["PATH"] = ";".join(map(lambda x : str(x), test_env.get("LIBRUNPATH", []))) + ";" + test_env["ENV"]["PATH"]
-
-
- # Run the test
- if env["target"] == "android":
- exec_name = os.path.basename(cmd)
- test_env.Command("**dummy**", target, SCons.Action.Action(
- ["adb shell mount -o rw,remount /system",
- "adb push " + cmd + " /system/bin/" + exec_name,
- "adb shell SWIFT_CLIENTTEST_JID=\"" + os.getenv("SWIFT_CLIENTTEST_JID") + "\" SWIFT_CLIENTTEST_PASS=\"" + os.getenv("SWIFT_CLIENTTEST_PASS") + "\" " + env.get("TEST_RUNNER", "") + "/system/bin/" + exec_name], cmdstr = "$TESTCOMSTR"))
- else :
- test_env.Command("**dummy**", target,
- SCons.Action.Action(ignore_prefix + env.get("TEST_RUNNER", "") + cmd + " " + params, cmdstr = "$TESTCOMSTR"))
-
- def registerScriptTests(env, scripts, name, type) :
- if env["TEST_TYPE"] == "all" or env["TEST_TYPE"] == type :
- pass
-
- env.AddMethod(registerTest, "Test")
- env.AddMethod(registerScriptTests, "ScriptTests")
+ def registerTest(env, target, type = "unit", is_checker = False) :
+ if env["TEST_TYPE"] == "all" or env["TEST_TYPE"] == type :
+ if SCons.Util.is_List(target) :
+ cmd = target[0].abspath
+ else :
+ cmd = target.abspath
+ params = ""
+
+ # Special support for unittest checker
+ if is_checker and env.get("checker_report", False) :
+ params = " --xml > " + os.path.join(target[0].dir.path, "checker-report.xml")
+
+ ignore_prefix = ""
+ if env.get("TEST_IGNORE_RESULT", False) :
+ ignore_prefix = "-"
+
+ # Set environment variables for running the test
+ test_env = env.Clone()
+ for i in ["HOME", "USERPROFILE", "APPDATA", "ASAN_OPTIONS", "LSAN_OPTIONS", "SWIFT_NETWORK_TEST_IPV4", "SWIFT_NETWORK_TEST_IPV6"]:
+ if os.environ.get(i, "") :
+ test_env["ENV"][i] = os.environ[i]
+ if env["target"] == "android" :
+ test_env["ENV"]["PATH"] = env["android_sdk_bin"] + ";" + test_env["ENV"]["PATH"]
+ else :
+ if test_env["PLATFORM"] == "darwin" :
+ test_env["ENV"]["DYLD_FALLBACK_LIBRARY_PATH"] = ":".join(map(lambda x : str(x), test_env.get("LIBPATH", [])))
+ elif test_env["PLATFORM"] == "win32" :
+ test_env["ENV"]["PATH"] = ";".join(map(lambda x : str(x), test_env.get("LIBRUNPATH", []))) + ";" + test_env["ENV"]["PATH"]
+
+
+ # Run the test
+ if env["target"] == "android":
+ exec_name = os.path.basename(cmd)
+ test_env.Command("**dummy**", target, SCons.Action.Action(
+ ["adb shell mount -o rw,remount /system",
+ "adb push " + cmd + " /system/bin/" + exec_name,
+ "adb shell SWIFT_CLIENTTEST_JID=\"" + os.getenv("SWIFT_CLIENTTEST_JID") + "\" SWIFT_CLIENTTEST_PASS=\"" + os.getenv("SWIFT_CLIENTTEST_PASS") + "\" " + env.get("TEST_RUNNER", "") + "/system/bin/" + exec_name], cmdstr = "$TESTCOMSTR"))
+ else :
+ test_env.Command("**dummy**", target,
+ SCons.Action.Action(ignore_prefix + env.get("TEST_RUNNER", "") + cmd + " " + params, cmdstr = "$TESTCOMSTR"))
+
+ def registerScriptTests(env, scripts, name, type) :
+ if env["TEST_TYPE"] == "all" or env["TEST_TYPE"] == type :
+ pass
+
+ env.AddMethod(registerTest, "Test")
+ env.AddMethod(registerScriptTests, "ScriptTests")
def exists(env) :
- return True
+ return True
diff --git a/BuildTools/SCons/Tools/WindowsBundle.py b/BuildTools/SCons/Tools/WindowsBundle.py
index ef77acb..20d41ff 100644
--- a/BuildTools/SCons/Tools/WindowsBundle.py
+++ b/BuildTools/SCons/Tools/WindowsBundle.py
@@ -4,119 +4,119 @@ import re
import shutil
def which(program_name):
- if hasattr(shutil, "which"):
- return shutil.which(program_name)
- else:
- path = os.getenv('PATH')
- for p in path.split(os.path.pathsep):
- p = os.path.join(p,program_name)
- if os.path.exists(p) and os.access(p,os.X_OK):
- return p
+ if hasattr(shutil, "which"):
+ return shutil.which(program_name)
+ else:
+ path = os.getenv('PATH')
+ for p in path.split(os.path.pathsep):
+ p = os.path.join(p,program_name)
+ if os.path.exists(p) and os.access(p,os.X_OK):
+ return p
def generate(env) :
- def captureWinDeployQtMapping(release = True):
- p = False
-
- qt_bin_folder = ""
- if "QTDIR" in env:
- qt_bin_folder = env["QTDIR"] + "\\bin;"
-
- environ = {"PATH": qt_bin_folder + os.getenv("PATH"), "TEMP": os.getenv("TEMP"), "TMP": os.getenv("TMP")}
-
- if release:
- p = subprocess.Popen(['windeployqt', '--release', '--dry-run', '--list', 'mapping', 'Swift.exe'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environ)
- else:
- p = subprocess.Popen(['windeployqt', '--debug', '--dry-run', '--list', 'mapping', 'Swift.exe'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environ)
-
- if p:
- stdout, stderr = p.communicate()
-
- mappings = []
-
- p = re.compile(ur'"([^\"]*)" "([^\"]*)"')
-
- matches = re.findall(p, stdout)
- for match in matches:
- mappings.append(match)
- return mappings
- else:
- return False
-
- def createWindowsBundleManual(env, bundle, resources = {}, qtplugins = {}, qtlibs = [], qtversion = '4') :
- all_files = []
- all_files += env.Install(bundle, bundle + ".exe")
- for lib in qtlibs :
- all_files += env.Install(bundle, os.path.join(env["QTDIR"], "bin", lib + ".dll"))
- plugins_suffix = '4'
- if qtversion == '5' :
- plugins_suffix = ''
- for plugin_type in qtplugins:
- all_files += env.Install(os.path.join(bundle, plugin_type), [os.path.join(env["QTDIR"], "plugins", plugin_type, "q" + plugin + plugins_suffix + ".dll") for plugin in qtplugins[plugin_type]])
- for dir, resourceFiles in resources.items() :
- for resource in resourceFiles :
- e = env.Entry(resource)
- if e.isdir() :
- for subresource in env.Glob(str(e) + "/*") :
- all_files += env.Install(os.path.join(bundle, dir, e.name), subresource)
- else :
- all_files += env.Install(os.path.join(bundle, dir), resource)
- return all_files
-
- # This version of uses windeployqt tool
- def createWindowsBundleWithWinDeployQt(env, bundle, resources = {}, qtplugins = {}, qtlibs = [], qtversion = '4') :
- assert(qtversion == '5')
- all_files = []
-
- # add swift executable
- all_files += env.Install(bundle, bundle + ".exe")
-
- # adding resources (swift sounds/images/translations)
- for dir, resourceFiles in resources.items() :
- for resource in resourceFiles :
- e = env.Entry(resource)
- if e.isdir() :
- for subresource in env.Glob(str(e) + "/*") :
- all_files += env.Install(os.path.join(bundle, dir, e.name), subresource)
- else :
- all_files += env.Install(os.path.join(bundle, dir), resource)
-
- qtmappings = captureWinDeployQtMapping()
- assert(qtmappings)
-
- # handle core DLLs
- qt_corelib_regex = re.compile(ur".*bin.*\\(.*)\.dll")
-
- for qtlib in qtlibs:
- if qtlib.startswith("Qt5"):
- (src_path, target_path) = next(((src_path, target_path) for (src_path, target_path) in qtmappings if qt_corelib_regex.match(src_path) and qt_corelib_regex.match(src_path).group(1) == qtlib), (None, None))
- if src_path != None:
- all_files += env.Install(bundle, src_path)
-
- # handle core dependencies
- for (src_path, target_path) in qtmappings:
- if qt_corelib_regex.match(src_path) and not qt_corelib_regex.match(src_path).group(1).startswith("Qt5"):
- all_files += env.Install(bundle, src_path)
-
- # handle plugins
- qt_plugin_regex = re.compile(ur".*plugins.*\\(.*)\\(.*)\.dll")
- for (src_path, target_path) in qtmappings:
- if qt_plugin_regex.match(src_path):
- plugin_folder, filename = qt_plugin_regex.match(src_path).groups()
- try:
- if plugin_folder in ["audio"] or filename[1:] in qtplugins[plugin_folder]:
- all_files += env.Install(os.path.join(bundle, plugin_folder), src_path)
- except:
- pass
- return all_files
-
- def createWindowsBundle(env, bundle, resources = {}, qtplugins = {}, qtlibs = [], qtversion = '4'):
- if which("windeployqt.exe"):
- return createWindowsBundleWithWinDeployQt(env, bundle, resources, qtplugins, qtlibs, qtversion)
- else:
- return createWindowsBundleManual(env, bundle, resources, qtplugins, qtlibs, qtversion)
-
- env.AddMethod(createWindowsBundle, "WindowsBundle")
+ def captureWinDeployQtMapping(release = True):
+ p = False
+
+ qt_bin_folder = ""
+ if "QTDIR" in env:
+ qt_bin_folder = env["QTDIR"] + "\\bin;"
+
+ environ = {"PATH": qt_bin_folder + os.getenv("PATH"), "TEMP": os.getenv("TEMP"), "TMP": os.getenv("TMP")}
+
+ if release:
+ p = subprocess.Popen(['windeployqt', '--release', '--dry-run', '--list', 'mapping', 'Swift.exe'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environ)
+ else:
+ p = subprocess.Popen(['windeployqt', '--debug', '--dry-run', '--list', 'mapping', 'Swift.exe'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environ)
+
+ if p:
+ stdout, stderr = p.communicate()
+
+ mappings = []
+
+ p = re.compile(ur'"([^\"]*)" "([^\"]*)"')
+
+ matches = re.findall(p, stdout)
+ for match in matches:
+ mappings.append(match)
+ return mappings
+ else:
+ return False
+
+ def createWindowsBundleManual(env, bundle, resources = {}, qtplugins = {}, qtlibs = [], qtversion = '4') :
+ all_files = []
+ all_files += env.Install(bundle, bundle + ".exe")
+ for lib in qtlibs :
+ all_files += env.Install(bundle, os.path.join(env["QTDIR"], "bin", lib + ".dll"))
+ plugins_suffix = '4'
+ if qtversion == '5' :
+ plugins_suffix = ''
+ for plugin_type in qtplugins:
+ all_files += env.Install(os.path.join(bundle, plugin_type), [os.path.join(env["QTDIR"], "plugins", plugin_type, "q" + plugin + plugins_suffix + ".dll") for plugin in qtplugins[plugin_type]])
+ for dir, resourceFiles in resources.items() :
+ for resource in resourceFiles :
+ e = env.Entry(resource)
+ if e.isdir() :
+ for subresource in env.Glob(str(e) + "/*") :
+ all_files += env.Install(os.path.join(bundle, dir, e.name), subresource)
+ else :
+ all_files += env.Install(os.path.join(bundle, dir), resource)
+ return all_files
+
+ # This version of uses windeployqt tool
+ def createWindowsBundleWithWinDeployQt(env, bundle, resources = {}, qtplugins = {}, qtlibs = [], qtversion = '4') :
+ assert(qtversion == '5')
+ all_files = []
+
+ # add swift executable
+ all_files += env.Install(bundle, bundle + ".exe")
+
+ # adding resources (swift sounds/images/translations)
+ for dir, resourceFiles in resources.items() :
+ for resource in resourceFiles :
+ e = env.Entry(resource)
+ if e.isdir() :
+ for subresource in env.Glob(str(e) + "/*") :
+ all_files += env.Install(os.path.join(bundle, dir, e.name), subresource)
+ else :
+ all_files += env.Install(os.path.join(bundle, dir), resource)
+
+ qtmappings = captureWinDeployQtMapping()
+ assert(qtmappings)
+
+ # handle core DLLs
+ qt_corelib_regex = re.compile(ur".*bin.*\\(.*)\.dll")
+
+ for qtlib in qtlibs:
+ if qtlib.startswith("Qt5"):
+ (src_path, target_path) = next(((src_path, target_path) for (src_path, target_path) in qtmappings if qt_corelib_regex.match(src_path) and qt_corelib_regex.match(src_path).group(1) == qtlib), (None, None))
+ if src_path != None:
+ all_files += env.Install(bundle, src_path)
+
+ # handle core dependencies
+ for (src_path, target_path) in qtmappings:
+ if qt_corelib_regex.match(src_path) and not qt_corelib_regex.match(src_path).group(1).startswith("Qt5"):
+ all_files += env.Install(bundle, src_path)
+
+ # handle plugins
+ qt_plugin_regex = re.compile(ur".*plugins.*\\(.*)\\(.*)\.dll")
+ for (src_path, target_path) in qtmappings:
+ if qt_plugin_regex.match(src_path):
+ plugin_folder, filename = qt_plugin_regex.match(src_path).groups()
+ try:
+ if plugin_folder in ["audio"] or filename[1:] in qtplugins[plugin_folder]:
+ all_files += env.Install(os.path.join(bundle, plugin_folder), src_path)
+ except:
+ pass
+ return all_files
+
+ def createWindowsBundle(env, bundle, resources = {}, qtplugins = {}, qtlibs = [], qtversion = '4'):
+ if which("windeployqt.exe"):
+ return createWindowsBundleWithWinDeployQt(env, bundle, resources, qtplugins, qtlibs, qtversion)
+ else:
+ return createWindowsBundleManual(env, bundle, resources, qtplugins, qtlibs, qtversion)
+
+ env.AddMethod(createWindowsBundle, "WindowsBundle")
def exists(env) :
- return env["PLATFORM"] == "win32"
+ return env["PLATFORM"] == "win32"
diff --git a/BuildTools/SCons/Tools/WriteVal.py b/BuildTools/SCons/Tools/WriteVal.py
index 4e8d3bb..ad77a99 100644
--- a/BuildTools/SCons/Tools/WriteVal.py
+++ b/BuildTools/SCons/Tools/WriteVal.py
@@ -1,15 +1,15 @@
import SCons.Util
def generate(env) :
- def replacePragmaOnce(env, target, source) :
- f = open(str(target[0]), 'wb')
- f.write(source[0].get_contents())
- f.close()
+ def replacePragmaOnce(env, target, source) :
+ f = open(str(target[0]), 'wb')
+ f.write(source[0].get_contents())
+ f.close()
- env["BUILDERS"]["WriteVal"] = SCons.Builder.Builder(
- action = SCons.Action.Action(replacePragmaOnce, cmdstr = "$GENCOMSTR"),
- single_source = True)
+ env["BUILDERS"]["WriteVal"] = SCons.Builder.Builder(
+ action = SCons.Action.Action(replacePragmaOnce, cmdstr = "$GENCOMSTR"),
+ single_source = True)
def exists(env) :
- return True
+ return True
diff --git a/BuildTools/SCons/Tools/nsis.py b/BuildTools/SCons/Tools/nsis.py
index f5b2905..393beb8 100644
--- a/BuildTools/SCons/Tools/nsis.py
+++ b/BuildTools/SCons/Tools/nsis.py
@@ -6,34 +6,34 @@ nsisIncludes_re = re.compile(r'^\s*!include (translations-\S*)', re.M)
"""
TODO:
- - Extract the target from the nsis file
- - When a target is provided use the output function
+ - Extract the target from the nsis file
+ - When a target is provided use the output function
"""
def generate(env) :
- """Add Builders and construction variables for qt to an Environment."""
- Builder = SCons.Builder.Builder
+ """Add Builders and construction variables for qt to an Environment."""
+ Builder = SCons.Builder.Builder
- env['NSIS_MAKENSIS'] = 'makensis'
- env['NSIS_OPTIONS'] = ["/V2"]
- def winToLocalReformat(path) :
- return os.path.join(*path.split("\\"))
- def scanNsisContent(node, env, path, arg):
- contents = node.get_contents()
- includes = nsisFiles_re.findall(contents) + nsisIncludes_re.findall(contents)
- includes = [ winToLocalReformat(include) for include in includes ]
- return filter(lambda x: x.rfind('*')==-1, includes)
- nsisscanner = env.Scanner(name = 'nsisfile',
- function = scanNsisContent,
- argument = None,
- skeys = ['.nsi'])
- nsisbuilder = Builder(
- action = SCons.Action.Action('$NSIS_MAKENSIS $NSIS_OPTIONS $SOURCE', cmdstr = '$NSISCOMSTR'),
- source_scanner = nsisscanner,
- single_source = True
- )
- env.Append( BUILDERS={'Nsis' : nsisbuilder} )
+ env['NSIS_MAKENSIS'] = 'makensis'
+ env['NSIS_OPTIONS'] = ["/V2"]
+ def winToLocalReformat(path) :
+ return os.path.join(*path.split("\\"))
+ def scanNsisContent(node, env, path, arg):
+ contents = node.get_contents()
+ includes = nsisFiles_re.findall(contents) + nsisIncludes_re.findall(contents)
+ includes = [ winToLocalReformat(include) for include in includes ]
+ return filter(lambda x: x.rfind('*')==-1, includes)
+ nsisscanner = env.Scanner(name = 'nsisfile',
+ function = scanNsisContent,
+ argument = None,
+ skeys = ['.nsi'])
+ nsisbuilder = Builder(
+ action = SCons.Action.Action('$NSIS_MAKENSIS $NSIS_OPTIONS $SOURCE', cmdstr = '$NSISCOMSTR'),
+ source_scanner = nsisscanner,
+ single_source = True
+ )
+ env.Append( BUILDERS={'Nsis' : nsisbuilder} )
def exists(env) :
- return True
+ return True
diff --git a/BuildTools/SCons/Tools/qt4.py b/BuildTools/SCons/Tools/qt4.py
index ec33b97..b965e06 100644
--- a/BuildTools/SCons/Tools/qt4.py
+++ b/BuildTools/SCons/Tools/qt4.py
@@ -47,24 +47,24 @@ import SCons.Util
import SCons.SConf
class ToolQtWarning(SCons.Warnings.Warning):
- pass
+ pass
class GeneratedMocFileNotIncluded(ToolQtWarning):
- pass
+ pass
class QtdirNotFound(ToolQtWarning):
- pass
+ pass
SCons.Warnings.enableWarningClass(ToolQtWarning)
qrcinclude_re = re.compile(r'<file (alias=\"[^\"]*\")?>([^<]*)</file>', re.M)
def transformToWinePath(path) :
- return os.popen('winepath -w "%s"'%path).read().strip().replace('\\','/')
+ return os.popen('winepath -w "%s"'%path).read().strip().replace('\\','/')
header_extensions = [".h", ".hxx", ".hpp", ".hh"]
if SCons.Util.case_sensitive_suffixes('.h', '.H'):
- header_extensions.append('.H')
+ header_extensions.append('.H')
# TODO: The following two lines will work when integrated back to SCons
# TODO: Meanwhile the third line will do the work
#cplusplus = __import__('c++', globals(), locals(), [])
@@ -72,519 +72,522 @@ if SCons.Util.case_sensitive_suffixes('.h', '.H'):
cxx_suffixes = [".c", ".cxx", ".cpp", ".cc"]
def checkMocIncluded(target, source, env):
- moc = target[0]
- cpp = source[0]
- # looks like cpp.includes is cleared before the build stage :-(
- # not really sure about the path transformations (moc.cwd? cpp.cwd?) :-/
- path = SCons.Defaults.CScan.path_function(env, moc.cwd)
- includes = SCons.Defaults.CScan(cpp, env, path)
- if not moc in includes:
- SCons.Warnings.warn(
- GeneratedMocFileNotIncluded,
- "Generated moc file '%s' is not included by '%s'" %
- (str(moc), str(cpp)))
+ moc = target[0]
+ cpp = source[0]
+ # looks like cpp.includes is cleared before the build stage :-(
+ # not really sure about the path transformations (moc.cwd? cpp.cwd?) :-/
+ path = SCons.Defaults.CScan.path_function(env, moc.cwd)
+ includes = SCons.Defaults.CScan(cpp, env, path)
+ if not moc in includes:
+ SCons.Warnings.warn(
+ GeneratedMocFileNotIncluded,
+ "Generated moc file '%s' is not included by '%s'" %
+ (str(moc), str(cpp)))
def find_file(filename, paths, node_factory):
- for dir in paths:
- node = node_factory(filename, dir)
- if node.rexists():
- return node
- return None
+ for dir in paths:
+ node = node_factory(filename, dir)
+ if node.rexists():
+ return node
+ return None
class _Automoc:
- """
- Callable class, which works as an emitter for Programs, SharedLibraries and
- StaticLibraries.
- """
-
- def __init__(self, objBuilderName):
- self.objBuilderName = objBuilderName
-
- def __call__(self, target, source, env):
- """
- Smart autoscan function. Gets the list of objects for the Program
- or Lib. Adds objects and builders for the special qt files.
- """
- try:
- if int(env.subst('$QT4_AUTOSCAN')) == 0:
- return target, source
- except ValueError:
- pass
- try:
- debug = int(env.subst('$QT4_DEBUG'))
- except ValueError:
- debug = 0
-
- # some shortcuts used in the scanner
- splitext = SCons.Util.splitext
- objBuilder = getattr(env, self.objBuilderName)
-
- # some regular expressions:
- # Q_OBJECT detection
- q_object_search = re.compile(r'[^A-Za-z0-9]Q_OBJECT[^A-Za-z0-9]')
- # cxx and c comment 'eater'
- #comment = re.compile(r'(//.*)|(/\*(([^*])|(\*[^/]))*\*/)')
- # CW: something must be wrong with the regexp. See also bug #998222
- # CURRENTLY THERE IS NO TEST CASE FOR THAT
-
- # The following is kind of hacky to get builders working properly (FIXME)
- objBuilderEnv = objBuilder.env
- objBuilder.env = env
- mocBuilderEnv = env.Moc4.env
- env.Moc4.env = env
-
- # make a deep copy for the result; MocH objects will be appended
- out_sources = source[:]
-
- for obj in source:
- if isinstance(obj,basestring): # big kludge!
- print "scons: qt4: '%s' MAYBE USING AN OLD SCONS VERSION AND NOT CONVERTED TO 'File'. Discarded." % str(obj)
- continue
- if not obj.has_builder():
- # binary obj file provided
- if debug:
- print "scons: qt: '%s' seems to be a binary. Discarded." % str(obj)
- continue
- cpp = obj.sources[0]
- if not splitext(str(cpp))[1] in cxx_suffixes:
- if debug:
- print "scons: qt: '%s' is no cxx file. Discarded." % str(cpp)
- # c or fortran source
- continue
- #cpp_contents = comment.sub('', cpp.get_contents())
- try:
- cpp_contents = cpp.get_contents()
- except: continue # may be an still not generated source
- h=None
- for h_ext in header_extensions:
- # try to find the header file in the corresponding source
- # directory
- hname = splitext(cpp.name)[0] + h_ext
- h = find_file(hname, (cpp.get_dir(),), env.File)
- if h:
- if debug:
- print "scons: qt: Scanning '%s' (header of '%s')" % (str(h), str(cpp))
- #h_contents = comment.sub('', h.get_contents())
- h_contents = h.get_contents()
- break
- if not h and debug:
- print "scons: qt: no header for '%s'." % (str(cpp))
- if h and q_object_search.search(h_contents):
- # h file with the Q_OBJECT macro found -> add moc_cpp
- moc_cpp = env.Moc4(h)
- moc_o = objBuilder(moc_cpp)
- out_sources.append(moc_o)
- #moc_cpp.target_scanner = SCons.Defaults.CScan
- if debug:
- print "scons: qt: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(h), str(moc_cpp))
- if cpp and q_object_search.search(cpp_contents):
- # cpp file with Q_OBJECT macro found -> add moc
- # (to be included in cpp)
- moc = env.Moc4(cpp)
- env.Ignore(moc, moc)
- if debug:
- print "scons: qt: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(cpp), str(moc))
- #moc.source_scanner = SCons.Defaults.CScan
- # restore the original env attributes (FIXME)
- objBuilder.env = objBuilderEnv
- env.Moc4.env = mocBuilderEnv
-
- return (target, out_sources)
+ """
+ Callable class, which works as an emitter for Programs, SharedLibraries and
+ StaticLibraries.
+ """
+
+ def __init__(self, objBuilderName):
+ self.objBuilderName = objBuilderName
+
+ def __call__(self, target, source, env):
+ """
+ Smart autoscan function. Gets the list of objects for the Program
+ or Lib. Adds objects and builders for the special qt files.
+ """
+ try:
+ if int(env.subst('$QT4_AUTOSCAN')) == 0:
+ return target, source
+ except ValueError:
+ pass
+ try:
+ debug = int(env.subst('$QT4_DEBUG'))
+ except ValueError:
+ debug = 0
+
+ # some shortcuts used in the scanner
+ splitext = SCons.Util.splitext
+ objBuilder = getattr(env, self.objBuilderName)
+
+ # some regular expressions:
+ # Q_OBJECT detection
+ q_object_search = re.compile(r'[^A-Za-z0-9]Q_OBJECT[^A-Za-z0-9]')
+ # cxx and c comment 'eater'
+ #comment = re.compile(r'(//.*)|(/\*(([^*])|(\*[^/]))*\*/)')
+ # CW: something must be wrong with the regexp. See also bug #998222
+ # CURRENTLY THERE IS NO TEST CASE FOR THAT
+
+ # The following is kind of hacky to get builders working properly (FIXME)
+ objBuilderEnv = objBuilder.env
+ objBuilder.env = env
+ mocBuilderEnv = env.Moc4.env
+ env.Moc4.env = env
+
+ # make a deep copy for the result; MocH objects will be appended
+ out_sources = source[:]
+
+ for obj in source:
+ if isinstance(obj,basestring): # big kludge!
+ print "scons: qt4: '%s' MAYBE USING AN OLD SCONS VERSION AND NOT CONVERTED TO 'File'. Discarded." % str(obj)
+ continue
+ if not obj.has_builder():
+ # binary obj file provided
+ if debug:
+ print "scons: qt: '%s' seems to be a binary. Discarded." % str(obj)
+ continue
+ cpp = obj.sources[0]
+ if not splitext(str(cpp))[1] in cxx_suffixes:
+ if debug:
+ print "scons: qt: '%s' is no cxx file. Discarded." % str(cpp)
+ # c or fortran source
+ continue
+ #cpp_contents = comment.sub('', cpp.get_contents())
+ try:
+ cpp_contents = cpp.get_contents()
+ except: continue # may be an still not generated source
+ h=None
+ for h_ext in header_extensions:
+ # try to find the header file in the corresponding source
+ # directory
+ hname = splitext(cpp.name)[0] + h_ext
+ h = find_file(hname, (cpp.get_dir(),), env.File)
+ if h:
+ if debug:
+ print "scons: qt: Scanning '%s' (header of '%s')" % (str(h), str(cpp))
+ #h_contents = comment.sub('', h.get_contents())
+ h_contents = h.get_contents()
+ break
+ if not h and debug:
+ print "scons: qt: no header for '%s'." % (str(cpp))
+ if h and q_object_search.search(h_contents):
+ # h file with the Q_OBJECT macro found -> add moc_cpp
+ moc_cpp = env.Moc4(h)
+ moc_o = objBuilder(moc_cpp)
+ out_sources.append(moc_o)
+ #moc_cpp.target_scanner = SCons.Defaults.CScan
+ if debug:
+ print "scons: qt: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(h), str(moc_cpp))
+ if cpp and q_object_search.search(cpp_contents):
+ # cpp file with Q_OBJECT macro found -> add moc
+ # (to be included in cpp)
+ moc = env.Moc4(cpp)
+ env.Ignore(moc, moc)
+ if debug:
+ print "scons: qt: found Q_OBJECT macro in '%s', moc'ing to '%s'" % (str(cpp), str(moc))
+ #moc.source_scanner = SCons.Defaults.CScan
+ # restore the original env attributes (FIXME)
+ objBuilder.env = objBuilderEnv
+ env.Moc4.env = mocBuilderEnv
+
+ return (target, out_sources)
AutomocShared = _Automoc('SharedObject')
AutomocStatic = _Automoc('StaticObject')
def _detect(env):
- """Not really safe, but fast method to detect the QT library"""
- if 'QTDIR' in env :
- return env['QTDIR']
-
- if 'QTDIR' in os.environ :
- return os.environ['QTDIR']
-
- moc = None
- if env["qt5"]:
- moc = env.WhereIs('moc-qt5') or env.WhereIs('moc5') or env.WhereIs('moc')
- else :
- moc = env.WhereIs('moc-qt4') or env.WhereIs('moc4') or env.WhereIs('moc')
- if moc:
- # Test whether the moc command we found is real, or whether it is just the qtchooser dummy.
- p = subprocess.Popen([moc, "-v"], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- p.communicate()
- if p.returncode == 0:
- import sys
- if sys.platform == "darwin" :
- return ""
- QTDIR = os.path.dirname(os.path.dirname(moc))
- return QTDIR
-
- raise SCons.Errors.StopError(
- QtdirNotFound,
- "Could not detect Qt 4 installation")
- return None
+ """Not really safe, but fast method to detect the QT library"""
+ if 'QTDIR' in env :
+ return env['QTDIR']
+
+ if 'QTDIR' in os.environ :
+ return os.environ['QTDIR']
+
+ moc = None
+ if env["qt5"]:
+ moc = env.WhereIs('moc-qt5') or env.WhereIs('moc5') or env.WhereIs('moc')
+ else :
+ moc = env.WhereIs('moc-qt4') or env.WhereIs('moc4') or env.WhereIs('moc')
+ if moc:
+ # Test whether the moc command we found is real, or whether it is just the qtchooser dummy.
+ p = subprocess.Popen([moc, "-v"], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env["ENV"])
+ p.communicate()
+ if p.returncode == 0:
+ import sys
+ if sys.platform == "darwin" :
+ return ""
+ QTDIR = os.path.dirname(os.path.dirname(moc))
+ return QTDIR
+
+ raise SCons.Errors.StopError(
+ QtdirNotFound,
+ "Could not detect Qt 4 installation")
+ return None
def generate(env):
- """Add Builders and construction variables for qt to an Environment."""
-
- def locateQt4Command(env, command, qtdir) :
- if len(qtdir) == 0 :
- qtdir = "/usr"
- if env["qt5"]:
- suffixes = [
- '-qt5',
- '-qt5.exe',
- '5',
- '5.exe',
- '',
- '.exe',
- ]
- else :
- suffixes = [
- '-qt4',
- '-qt4.exe',
- '4',
- '4.exe',
- '',
- '.exe',
- ]
- triedPaths = []
- for suffix in suffixes :
- fullpath = os.path.join(qtdir,'bin',command + suffix)
- if os.access(fullpath, os.X_OK) :
- return fullpath
- triedPaths.append(fullpath)
-
- fullpath = env.Detect([command+'-qt4', command+'4', command])
- if not (fullpath is None) : return fullpath
-
- raise Exception("Qt4 command '" + command + "' not found. Tried: " + ', '.join(triedPaths))
-
-
- CLVar = SCons.Util.CLVar
- Action = SCons.Action.Action
- Builder = SCons.Builder.Builder
- splitext = SCons.Util.splitext
-
- env['QTDIR'] = _detect(env)
- # TODO: 'Replace' should be 'SetDefault'
-# env.SetDefault(
- env.Replace(
- QTDIR = _detect(env),
- # TODO: This is not reliable to QTDIR value changes but needed in order to support '-qt4' variants
- QT4_MOC = locateQt4Command(env,'moc', env['QTDIR']),
- QT4_UIC = locateQt4Command(env,'uic', env['QTDIR']),
- QT4_RCC = locateQt4Command(env,'rcc', env['QTDIR']),
- QT4_LUPDATE = locateQt4Command(env,'lupdate', env['QTDIR']),
- QT4_LRELEASE = locateQt4Command(env,'lrelease', env['QTDIR']),
- QT4_LIB = '', # KLUDGE to avoid linking qt3 library
-
- QT4_AUTOSCAN = 1, # Should the qt tool try to figure out, which sources are to be moc'ed?
-
- # Some QT specific flags. I don't expect someone wants to
- # manipulate those ...
- QT4_UICFLAGS = CLVar(''),
- QT4_MOCFROMHFLAGS = CLVar(''),
- QT4_MOCFROMCXXFLAGS = CLVar('-i'),
- QT4_QRCFLAGS = '',
-
- # suffixes/prefixes for the headers / sources to generate
- QT4_UISUFFIX = '.ui',
- QT4_UICDECLPREFIX = 'ui_',
- QT4_UICDECLSUFFIX = '.h',
- QT4_MOCHPREFIX = 'moc_',
- QT4_MOCHSUFFIX = '$CXXFILESUFFIX',
- QT4_MOCCXXPREFIX = '',
- QT4_MOCCXXSUFFIX = '.moc',
- QT4_QRCSUFFIX = '.qrc',
- QT4_QRCCXXSUFFIX = '$CXXFILESUFFIX',
- QT4_QRCCXXPREFIX = 'qrc_',
- QT4_MOCCPPPATH = [],
- QT4_MOCINCFLAGS = '$( ${_concat("-I", QT4_MOCCPPPATH, INCSUFFIX, __env__, RDirs)} $)',
-
- # Commands for the qt support ...
- QT4_UICCOM = '$QT4_UIC $QT4_UICFLAGS -o $TARGET $SOURCE',
- # FIXME: The -DBOOST_TT_HAS_OPERATOR_HPP_INCLUDED flag is a hack to work
- # around an issue in Qt
- # See https://bugreports.qt-project.org/browse/QTBUG-22829
- QT4_MOCFROMHCOM = '$QT4_MOC -DBOOST_TT_HAS_OPERATOR_HPP_INCLUDED $QT4_MOCFROMHFLAGS $QT4_MOCINCFLAGS -o $TARGET $SOURCE',
- QT4_MOCFROMCXXCOM = [
- '$QT4_MOC -DBOOST_TT_HAS_OPERATOR_HPP_INCLUDED $QT4_MOCFROMCXXFLAGS $QT4_MOCINCFLAGS -o $TARGET $SOURCE',
- Action(checkMocIncluded,None)],
- QT4_LUPDATECOM = '$QT4_LUPDATE $SOURCE -ts $TARGET',
- QT4_LRELEASECOM = '$QT4_LRELEASE -silent $SOURCE -qm $TARGET',
- QT4_RCCCOM = '$QT4_RCC $QT4_QRCFLAGS -name $SOURCE $SOURCE -o $TARGET',
- )
- if len(env["QTDIR"]) > 0 :
- env.Replace(QT4_LIBPATH = os.path.join('$QTDIR', 'lib'))
-
- # Translation builder
- tsbuilder = Builder(
- action = SCons.Action.Action('$QT4_LUPDATECOM'), #,'$QT4_LUPDATECOMSTR'),
- multi=1
- )
- env.Append( BUILDERS = { 'Ts': tsbuilder } )
- qmbuilder = Builder(
- action = SCons.Action.Action('$QT4_LRELEASECOM', cmdstr = '$QT4_LRELEASECOMSTR'),
- src_suffix = '.ts',
- suffix = '.qm',
- single_source = True
- )
- env.Append( BUILDERS = { 'Qm': qmbuilder } )
-
- # Resource builder
- def scanResources(node, env, path, arg):
- # I've being careful on providing names relative to the qrc file
- # If that was not needed that code could be simplified a lot
- def recursiveFiles(basepath, path) :
- result = []
- for item in os.listdir(os.path.join(basepath, path)) :
- itemPath = os.path.join(path, item)
- if os.path.isdir(os.path.join(basepath, itemPath)) :
- result += recursiveFiles(basepath, itemPath)
- else:
- result.append(itemPath)
- return result
- contents = node.get_contents()
- includes = [included[1] for included in qrcinclude_re.findall(contents)]
- qrcpath = os.path.dirname(node.path)
- dirs = [included for included in includes if os.path.isdir(os.path.join(qrcpath,included))]
- # dirs need to include files recursively
- for dir in dirs :
- includes.remove(dir)
- includes+=recursiveFiles(qrcpath,dir)
- return includes
- qrcscanner = SCons.Scanner.Scanner(name = 'qrcfile',
- function = scanResources,
- argument = None,
- skeys = ['.qrc'])
- qrcbuilder = Builder(
- action = SCons.Action.Action('$QT4_RCCCOM', cmdstr = '$QT4_RCCCOMSTR'),
- source_scanner = qrcscanner,
- src_suffix = '$QT4_QRCSUFFIX',
- suffix = '$QT4_QRCCXXSUFFIX',
- prefix = '$QT4_QRCCXXPREFIX',
- single_source = True
- )
- env.Append( BUILDERS = { 'Qrc': qrcbuilder } )
-
- # Interface builder
- uic4builder = Builder(
- action = SCons.Action.Action('$QT4_UICCOM', cmdstr = '$QT4_UICCOMSTR'),
- src_suffix='$QT4_UISUFFIX',
- suffix='$QT4_UICDECLSUFFIX',
- prefix='$QT4_UICDECLPREFIX',
- single_source = True
- #TODO: Consider the uiscanner on new scons version
- )
- env['BUILDERS']['Uic4'] = uic4builder
-
- # Metaobject builder
- mocBld = Builder(action={}, prefix={}, suffix={})
- for h in header_extensions:
- act = SCons.Action.Action('$QT4_MOCFROMHCOM', cmdstr = '$QT4_MOCFROMHCOMSTR')
- mocBld.add_action(h, act)
- mocBld.prefix[h] = '$QT4_MOCHPREFIX'
- mocBld.suffix[h] = '$QT4_MOCHSUFFIX'
- for cxx in cxx_suffixes:
- act = SCons.Action.Action('$QT4_MOCFROMCXXCOM', cmdstr = '$QT4_MOCFROMCXXCOMSTR')
- mocBld.add_action(cxx, act)
- mocBld.prefix[cxx] = '$QT4_MOCCXXPREFIX'
- mocBld.suffix[cxx] = '$QT4_MOCCXXSUFFIX'
- env['BUILDERS']['Moc4'] = mocBld
-
- # er... no idea what that was for
- static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
- static_obj.src_builder.append('Uic4')
- shared_obj.src_builder.append('Uic4')
-
- # We use the emitters of Program / StaticLibrary / SharedLibrary
- # to scan for moc'able files
- # We can't refer to the builders directly, we have to fetch them
- # as Environment attributes because that sets them up to be called
- # correctly later by our emitter.
- env.AppendUnique(PROGEMITTER =[AutomocStatic],
- SHLIBEMITTER=[AutomocShared],
- LIBEMITTER =[AutomocStatic],
- # Of course, we need to link against the qt libraries
- LIBPATH=["$QT4_LIBPATH"],
- LIBS=['$QT4_LIB'])
-
- # TODO: Does dbusxml2cpp need an adapter
- env.AddMethod(enable_modules, "EnableQt4Modules")
+ """Add Builders and construction variables for qt to an Environment."""
+
+ def locateQt4Command(env, command, qtdir) :
+ if len(qtdir) == 0 :
+ qtdir = "/usr"
+ if env["qt5"]:
+ suffixes = [
+ '-qt5',
+ '-qt5.exe',
+ '5',
+ '5.exe',
+ '',
+ '.exe',
+ ]
+ else :
+ suffixes = [
+ '-qt4',
+ '-qt4.exe',
+ '4',
+ '4.exe',
+ '',
+ '.exe',
+ ]
+ triedPaths = []
+ for suffix in suffixes :
+ fullpath = os.path.join(qtdir,'bin',command + suffix)
+ if os.access(fullpath, os.X_OK) :
+ return fullpath
+ triedPaths.append(fullpath)
+
+ fullpath = env.Detect([command+'-qt4', command+'4', command])
+ if not (fullpath is None) : return fullpath
+
+ raise Exception("Qt4 command '" + command + "' not found. Tried: " + ', '.join(triedPaths))
+
+
+ CLVar = SCons.Util.CLVar
+ Action = SCons.Action.Action
+ Builder = SCons.Builder.Builder
+ splitext = SCons.Util.splitext
+
+ env['QTDIR'] = _detect(env)
+ # TODO: 'Replace' should be 'SetDefault'
+# env.SetDefault(
+ env.Replace(
+ QTDIR = _detect(env),
+ # TODO: This is not reliable to QTDIR value changes but needed in order to support '-qt4' variants
+ QT4_MOC = locateQt4Command(env,'moc', env['QTDIR']),
+ QT4_UIC = locateQt4Command(env,'uic', env['QTDIR']),
+ QT4_RCC = locateQt4Command(env,'rcc', env['QTDIR']),
+ QT4_LUPDATE = locateQt4Command(env,'lupdate', env['QTDIR']),
+ QT4_LRELEASE = locateQt4Command(env,'lrelease', env['QTDIR']),
+ QT4_LIB = '', # KLUDGE to avoid linking qt3 library
+
+ QT4_AUTOSCAN = 1, # Should the qt tool try to figure out, which sources are to be moc'ed?
+
+ # Some QT specific flags. I don't expect someone wants to
+ # manipulate those ...
+ QT4_UICFLAGS = CLVar(''),
+ QT4_MOCFROMHFLAGS = CLVar(''),
+ QT4_MOCFROMCXXFLAGS = CLVar('-i'),
+ QT4_QRCFLAGS = '--compress 9 --threshold 5',
+
+ # suffixes/prefixes for the headers / sources to generate
+ QT4_UISUFFIX = '.ui',
+ QT4_UICDECLPREFIX = 'ui_',
+ QT4_UICDECLSUFFIX = '.h',
+ QT4_MOCHPREFIX = 'moc_',
+ QT4_MOCHSUFFIX = '$CXXFILESUFFIX',
+ QT4_MOCCXXPREFIX = '',
+ QT4_MOCCXXSUFFIX = '.moc',
+ QT4_QRCSUFFIX = '.qrc',
+ QT4_QRCCXXSUFFIX = '$CXXFILESUFFIX',
+ QT4_QRCCXXPREFIX = 'qrc_',
+ QT4_MOCCPPPATH = [],
+ QT4_MOCINCFLAGS = '$( ${_concat("-I", QT4_MOCCPPPATH, INCSUFFIX, __env__, RDirs)} $)',
+
+ # Commands for the qt support ...
+ QT4_UICCOM = '$QT4_UIC $QT4_UICFLAGS -o $TARGET $SOURCE',
+ # FIXME: The -DBOOST_TT_HAS_OPERATOR_HPP_INCLUDED flag is a hack to work
+ # around an issue in Qt
+ # See https://bugreports.qt-project.org/browse/QTBUG-22829
+ QT4_MOCFROMHCOM = '$QT4_MOC -DBOOST_TT_HAS_OPERATOR_HPP_INCLUDED $QT4_MOCFROMHFLAGS $QT4_MOCINCFLAGS -o $TARGET $SOURCE',
+ QT4_MOCFROMCXXCOM = [
+ '$QT4_MOC -DBOOST_TT_HAS_OPERATOR_HPP_INCLUDED $QT4_MOCFROMCXXFLAGS $QT4_MOCINCFLAGS -o $TARGET $SOURCE',
+ Action(checkMocIncluded,None)],
+ QT4_LUPDATECOM = '$QT4_LUPDATE $SOURCE -ts $TARGET',
+ QT4_LRELEASECOM = '$QT4_LRELEASE -silent $SOURCE -qm $TARGET',
+ QT4_RCCCOM = '$QT4_RCC $QT4_QRCFLAGS -name $SOURCE $SOURCE -o $TARGET',
+ )
+ if len(env["QTDIR"]) > 0 :
+ env.Replace(QT4_LIBPATH = os.path.join('$QTDIR', 'lib'))
+
+ # Translation builder
+ tsbuilder = Builder(
+ action = SCons.Action.Action('$QT4_LUPDATECOM'), #,'$QT4_LUPDATECOMSTR'),
+ multi=1
+ )
+ env.Append( BUILDERS = { 'Ts': tsbuilder } )
+ qmbuilder = Builder(
+ action = SCons.Action.Action('$QT4_LRELEASECOM', cmdstr = '$QT4_LRELEASECOMSTR'),
+ src_suffix = '.ts',
+ suffix = '.qm',
+ single_source = True
+ )
+ env.Append( BUILDERS = { 'Qm': qmbuilder } )
+
+ # Resource builder
+ def scanResources(node, env, path, arg):
+ # I've being careful on providing names relative to the qrc file
+ # If that was not needed that code could be simplified a lot
+ def recursiveFiles(basepath, path) :
+ result = []
+ for item in os.listdir(os.path.join(basepath, path)) :
+ itemPath = os.path.join(path, item)
+ if os.path.isdir(os.path.join(basepath, itemPath)) :
+ result += recursiveFiles(basepath, itemPath)
+ else:
+ result.append(itemPath)
+ return result
+ contents = node.get_contents()
+ includes = [included[1] for included in qrcinclude_re.findall(contents)]
+ qrcpath = os.path.dirname(node.path)
+ dirs = [included for included in includes if os.path.isdir(os.path.join(qrcpath,included))]
+ # dirs need to include files recursively
+ for dir in dirs :
+ includes.remove(dir)
+ includes+=recursiveFiles(qrcpath,dir)
+ return includes
+ qrcscanner = SCons.Scanner.Scanner(name = 'qrcfile',
+ function = scanResources,
+ argument = None,
+ skeys = ['.qrc'])
+ qrcbuilder = Builder(
+ action = SCons.Action.Action('$QT4_RCCCOM', cmdstr = '$QT4_RCCCOMSTR'),
+ source_scanner = qrcscanner,
+ src_suffix = '$QT4_QRCSUFFIX',
+ suffix = '$QT4_QRCCXXSUFFIX',
+ prefix = '$QT4_QRCCXXPREFIX',
+ single_source = True
+ )
+ env.Append( BUILDERS = { 'Qrc': qrcbuilder } )
+
+ # Interface builder
+ uic4builder = Builder(
+ action = SCons.Action.Action('$QT4_UICCOM', cmdstr = '$QT4_UICCOMSTR'),
+ src_suffix='$QT4_UISUFFIX',
+ suffix='$QT4_UICDECLSUFFIX',
+ prefix='$QT4_UICDECLPREFIX',
+ single_source = True
+ #TODO: Consider the uiscanner on new scons version
+ )
+ env['BUILDERS']['Uic4'] = uic4builder
+
+ # Metaobject builder
+ mocBld = Builder(action={}, prefix={}, suffix={})
+ for h in header_extensions:
+ act = SCons.Action.Action('$QT4_MOCFROMHCOM', cmdstr = '$QT4_MOCFROMHCOMSTR')
+ mocBld.add_action(h, act)
+ mocBld.prefix[h] = '$QT4_MOCHPREFIX'
+ mocBld.suffix[h] = '$QT4_MOCHSUFFIX'
+ for cxx in cxx_suffixes:
+ act = SCons.Action.Action('$QT4_MOCFROMCXXCOM', cmdstr = '$QT4_MOCFROMCXXCOMSTR')
+ mocBld.add_action(cxx, act)
+ mocBld.prefix[cxx] = '$QT4_MOCCXXPREFIX'
+ mocBld.suffix[cxx] = '$QT4_MOCCXXSUFFIX'
+ env['BUILDERS']['Moc4'] = mocBld
+
+ # er... no idea what that was for
+ static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
+ static_obj.src_builder.append('Uic4')
+ shared_obj.src_builder.append('Uic4')
+
+ # We use the emitters of Program / StaticLibrary / SharedLibrary
+ # to scan for moc'able files
+ # We can't refer to the builders directly, we have to fetch them
+ # as Environment attributes because that sets them up to be called
+ # correctly later by our emitter.
+ env.AppendUnique(PROGEMITTER =[AutomocStatic],
+ SHLIBEMITTER=[AutomocShared],
+ LIBEMITTER =[AutomocStatic],
+ # Of course, we need to link against the qt libraries
+ LIBPATH=["$QT4_LIBPATH"],
+ LIBS=['$QT4_LIB'])
+
+ # TODO: Does dbusxml2cpp need an adapter
+ env.AddMethod(enable_modules, "EnableQt4Modules")
def enable_modules(self, modules, debug=False, crosscompiling=False, version='4') :
- import sys
-
- validModules = [
- 'QtCore',
- 'QtGui',
- 'QtOpenGL',
- 'Qt3Support',
- 'QtAssistant',
- 'QtScript',
- 'QtDBus',
- 'QtSql',
- # The next modules have not been tested yet so, please
- # maybe they require additional work on non Linux platforms
- 'QtNetwork',
- 'QtSvg',
- 'QtTest',
- 'QtXml',
- 'QtXmlPatterns',
- 'QtUiTools',
- 'QtDesigner',
- 'QtDesignerComponents',
- 'QtWebKit',
- 'QtHelp',
- 'QtScript',
-
- # Qt5 modules
- 'QtWidgets',
- 'QtMultimedia',
- 'QtWebKitWidgets',
- 'QtWebChannel',
- ]
- if sys.platform != "win32" and sys.platform != "darwin" and not crosscompiling :
- validModules += ['QtX11Extras']
- staticModules = [
- 'QtUiTools',
- ]
- invalidModules=[]
- for module in modules:
- if module not in validModules :
- invalidModules.append(module)
- if invalidModules :
- raise Exception("Modules %s are not Qt4 modules. Valid Qt4 modules are: %s"% (
- str(invalidModules),str(validModules)))
-
- moduleDefines = {
- 'QtScript' : ['QT_SCRIPT_LIB'],
- 'QtSvg' : ['QT_SVG_LIB'],
- 'Qt3Support' : ['QT_QT3SUPPORT_LIB','QT3_SUPPORT'],
- 'QtSql' : ['QT_SQL_LIB'],
- 'QtXml' : ['QT_XML_LIB'],
- 'QtOpenGL' : ['QT_OPENGL_LIB'],
- 'QtGui' : ['QT_GUI_LIB'],
- 'QtWidgets' : ['QT_WIDGETS_LIB'],
- 'QtWebKitWidgets' : [],
- 'QtNetwork' : ['QT_NETWORK_LIB'],
- 'QtCore' : ['QT_CORE_LIB'],
- }
- for module in modules :
- try : self.AppendUnique(CPPDEFINES=moduleDefines[module])
- except: pass
- debugSuffix = ''
-
-
- include_flag = "-I"
- if os.path.basename(self["CC"]) in ("gcc", "clang"):
- include_flag = "-isystem"
-
-
- if sys.platform != "win32" and sys.platform != "darwin" and not crosscompiling :
- if self["qt"]:
- # The user specified qt path in config.py and we are going to use the
- # installation under that location.
- UsePkgConfig = False
- else:
- # The user did not specify a qt path in config py and we are going to
- # ask pkg-config for the correct flags.
- UsePkgConfig = True
- if not UsePkgConfig:
- if debug : debugSuffix = '_debug'
- if version == '4' :
- self.AppendUnique(CPPFLAGS = [include_flag + os.path.join("$QTDIR", "include", "phonon")])
- for module in modules :
- module_str = module
- if not version == '4' :
- module_str = module_str.replace('Qt', 'Qt5')
- self.AppendUnique(LIBS=[module_str+debugSuffix])
- self.AppendUnique(LIBPATH=[os.path.join("$QTDIR","lib")])
- self.AppendUnique(CPPFLAGS = [include_flag + os.path.join("$QTDIR","include")])
- self.AppendUnique(CPPFLAGS = [include_flag + os.path.join("$QTDIR","include", module)])
- self["QT4_MOCCPPPATH"] = self["CPPPATH"]
- return
- else:
- test_conf = self.Configure()
- modules_str = " ".join(modules)
- if not version == '4' :
- modules_str = modules_str.replace('Qt', 'Qt5')
-
- # Check if Qt is registered at pkg-config
- ret = test_conf.TryAction('pkg-config --exists \'%s\'' % modules_str)[0]
- if ret != 1:
- test_conf.Finish()
- raise Exception('Qt installation is missing packages. The following are required: %s' % modules_str)
- return
- test_conf.env.ParseConfig("pkg-config --cflags --libs " + modules_str)
- self.AppendUnique(LIBS=test_conf.env["LIBS"], LIBPATH=test_conf.env["LIBPATH"], CPPPATH=test_conf.env["CPPPATH"])
- self["QT4_MOCCPPPATH"] = self["CPPPATH"]
- test_conf.Finish()
- return
-
- if sys.platform == "win32" or crosscompiling :
- if crosscompiling:
- transformedQtdir = transformToWinePath(self['QTDIR'])
- self['QT4_MOC'] = "QTDIR=%s %s"%( transformedQtdir, self['QT4_MOC'])
- self.AppendUnique(CPPPATH=[os.path.join("$QTDIR","include")])
- try: modules.remove("QtDBus")
- except: pass
- if debug : debugSuffix = 'd'
- if "QtAssistant" in modules:
- self.AppendUnique(CPPPATH=[os.path.join("$QTDIR","include","QtAssistant")])
- modules.remove("QtAssistant")
- modules.append("QtAssistantClient")
- if version == '4' :
- # FIXME: Phonon Hack
- self.AppendUnique(LIBS=['phonon'+debugSuffix+version])
- self.AppendUnique(LIBS=[lib+debugSuffix+version for lib in modules if lib not in staticModules])
- else :
- self.AppendUnique(LIBS=[lib.replace('Qt', 'Qt5') + debugSuffix for lib in modules if lib not in staticModules])
- self.PrependUnique(LIBS=[lib+debugSuffix for lib in modules if lib in staticModules])
- if 'QtOpenGL' in modules:
- self.AppendUnique(LIBS=['opengl32'])
- elif version == '5' :
- self.Append(CPPDEFINES = ["QT_NO_OPENGL"])
- self.AppendUnique(CPPPATH=[ '$QTDIR/include/'])
- self.AppendUnique(CPPPATH=[ '$QTDIR/include/'+module for module in modules])
- if crosscompiling :
- self["QT4_MOCCPPPATH"] = [
- path.replace('$QTDIR', transformedQtdir)
- for path in self['CPPPATH'] ]
- else :
- self["QT4_MOCCPPPATH"] = self["CPPPATH"]
- self.AppendUnique(LIBPATH=[os.path.join('$QTDIR','lib')])
- self.PrependUnique(LIBS=["shell32"])
- return
-
- if sys.platform=="darwin" :
- if debug : debugSuffix = 'd'
-
- if len(self["QTDIR"]) > 0 :
- self.AppendUnique(LIBPATH=[os.path.join('$QTDIR','lib')])
- self.AppendUnique(LINKFLAGS="-F$QTDIR/lib")
- self.AppendUnique(CPPFLAGS="-iframework$QTDIR/lib")
- self.AppendUnique(LINKFLAGS="-L$QTDIR/lib") #TODO clean!
-
- # FIXME: Phonon Hack
- if version == '4' :
- self.Append(LINKFLAGS=['-framework', "phonon"])
-
- for module in modules :
- if module in staticModules :
- self.AppendUnique(LIBS=[module+debugSuffix]) # TODO: Add the debug suffix
- self.AppendUnique(LIBPATH=[os.path.join("$QTDIR","lib")])
- else :
- if len(self["QTDIR"]) > 0 :
- self.Append(CPPFLAGS = [include_flag + os.path.join("$QTDIR", "lib", module + ".framework", "Versions", version, "Headers")])
- else :
- self.Append(CPPFLAGS = [include_flag + os.path.join("/Library/Frameworks", module + ".framework", "Versions", version, "Headers")])
- self.Append(LINKFLAGS=['-framework', module])
- if 'QtOpenGL' in modules:
- self.AppendUnique(LINKFLAGS="-F/System/Library/Frameworks")
- self.Append(LINKFLAGS=['-framework', 'AGL']) #TODO ughly kludge to avoid quotes
- self.Append(LINKFLAGS=['-framework', 'OpenGL'])
- self["QT4_MOCCPPPATH"] = self["CPPPATH"]
+ import sys
+
+ validModules = [
+ 'QtCore',
+ 'QtGui',
+ 'QtOpenGL',
+ 'Qt3Support',
+ 'QtAssistant',
+ 'QtScript',
+ 'QtDBus',
+ 'QtSql',
+ # The next modules have not been tested yet so, please
+ # maybe they require additional work on non Linux platforms
+ 'QtNetwork',
+ 'QtSvg',
+ 'QtTest',
+ 'QtXml',
+ 'QtXmlPatterns',
+ 'QtUiTools',
+ 'QtDesigner',
+ 'QtDesignerComponents',
+ 'QtWebKit',
+ 'QtHelp',
+ 'QtScript',
+
+ # Qt5 modules
+ 'QtWidgets',
+ 'QtMultimedia',
+ 'QtWebKitWidgets',
+ 'QtWebChannel',
+ ]
+ if sys.platform != "win32" and sys.platform != "darwin" and not crosscompiling :
+ validModules += ['QtX11Extras']
+ staticModules = [
+ 'QtUiTools',
+ ]
+ invalidModules=[]
+ for module in modules:
+ if module not in validModules :
+ invalidModules.append(module)
+ if invalidModules :
+ raise Exception("Modules %s are not Qt4 modules. Valid Qt4 modules are: %s"% (
+ str(invalidModules),str(validModules)))
+
+ moduleDefines = {
+ 'QtScript' : ['QT_SCRIPT_LIB'],
+ 'QtSvg' : ['QT_SVG_LIB'],
+ 'Qt3Support' : ['QT_QT3SUPPORT_LIB','QT3_SUPPORT'],
+ 'QtSql' : ['QT_SQL_LIB'],
+ 'QtXml' : ['QT_XML_LIB'],
+ 'QtOpenGL' : ['QT_OPENGL_LIB'],
+ 'QtGui' : ['QT_GUI_LIB'],
+ 'QtWidgets' : ['QT_WIDGETS_LIB'],
+ 'QtWebKitWidgets' : [],
+ 'QtNetwork' : ['QT_NETWORK_LIB'],
+ 'QtCore' : ['QT_CORE_LIB'],
+ }
+ for module in modules :
+ try : self.AppendUnique(CPPDEFINES=moduleDefines[module])
+ except: pass
+ debugSuffix = ''
+
+
+ include_flag = "-I"
+ if os.path.basename(self["CC"]) in ("gcc", "clang"):
+ include_flag = "-isystem"
+
+
+ if sys.platform != "win32" and sys.platform != "darwin" and not crosscompiling :
+ if self["qt"]:
+ # The user specified qt path in config.py and we are going to use the
+ # installation under that location.
+ UsePkgConfig = False
+ else:
+ # The user did not specify a qt path in config py and we are going to
+ # ask pkg-config for the correct flags.
+ UsePkgConfig = True
+ if not UsePkgConfig:
+ if debug : debugSuffix = '_debug'
+ if version == '4' :
+ self.AppendUnique(CPPFLAGS = [include_flag + os.path.join("$QTDIR", "include", "phonon")])
+ for module in modules :
+ module_str = module
+ if not version == '4' :
+ module_str = module_str.replace('Qt', 'Qt5')
+ self.AppendUnique(LIBS=[module_str+debugSuffix])
+ self.AppendUnique(LIBPATH=[os.path.join("$QTDIR","lib")])
+ self.AppendUnique(CPPFLAGS = [include_flag + os.path.join("$QTDIR","include")])
+ self.AppendUnique(CPPFLAGS = [include_flag + os.path.join("$QTDIR","include", module)])
+ self["QT4_MOCCPPPATH"] = self["CPPPATH"]
+ return
+ else:
+ test_conf = self.Configure()
+ modules_str = " ".join(modules)
+ if not version == '4' :
+ modules_str = modules_str.replace('Qt', 'Qt5')
+
+ # Check if Qt is registered at pkg-config
+ ret = test_conf.TryAction('pkg-config --exists \'%s\'' % modules_str)[0]
+ if ret != 1:
+ test_conf.Finish()
+ raise Exception('Qt installation is missing packages. The following are required: %s' % modules_str)
+ return
+
+ def parse_conf_as_system(env, cmd, unique=1):
+ return env.MergeFlags(cmd.replace("-I/", include_flag + "/"), unique)
+
+ test_conf.env.ParseConfig("pkg-config --cflags --libs " + modules_str, parse_conf_as_system)
+ self["QT4_MOCCPPPATH"] = self["CPPPATH"]
+ test_conf.Finish()
+ return
+
+ if sys.platform == "win32" or crosscompiling :
+ if crosscompiling:
+ transformedQtdir = transformToWinePath(self['QTDIR'])
+ self['QT4_MOC'] = "QTDIR=%s %s"%( transformedQtdir, self['QT4_MOC'])
+ self.AppendUnique(CPPPATH=[os.path.join("$QTDIR","include")])
+ try: modules.remove("QtDBus")
+ except: pass
+ if debug : debugSuffix = 'd'
+ if "QtAssistant" in modules:
+ self.AppendUnique(CPPPATH=[os.path.join("$QTDIR","include","QtAssistant")])
+ modules.remove("QtAssistant")
+ modules.append("QtAssistantClient")
+ if version == '4' :
+ # FIXME: Phonon Hack
+ self.AppendUnique(LIBS=['phonon'+debugSuffix+version])
+ self.AppendUnique(LIBS=[lib+debugSuffix+version for lib in modules if lib not in staticModules])
+ else :
+ self.AppendUnique(LIBS=[lib.replace('Qt', 'Qt5') + debugSuffix for lib in modules if lib not in staticModules])
+ self.PrependUnique(LIBS=[lib+debugSuffix for lib in modules if lib in staticModules])
+ if 'QtOpenGL' in modules:
+ self.AppendUnique(LIBS=['opengl32'])
+ elif version == '5' :
+ self.Append(CPPDEFINES = ["QT_NO_OPENGL"])
+ self.AppendUnique(CPPPATH=[ '$QTDIR/include/'])
+ self.AppendUnique(CPPPATH=[ '$QTDIR/include/'+module for module in modules])
+ if crosscompiling :
+ self["QT4_MOCCPPPATH"] = [
+ path.replace('$QTDIR', transformedQtdir)
+ for path in self['CPPPATH'] ]
+ else :
+ self["QT4_MOCCPPPATH"] = self["CPPPATH"]
+ self.AppendUnique(LIBPATH=[os.path.join('$QTDIR','lib')])
+ self.PrependUnique(LIBS=["shell32"])
+ return
+
+ if sys.platform=="darwin" :
+ if debug : debugSuffix = 'd'
+
+ if len(self["QTDIR"]) > 0 :
+ self.AppendUnique(LIBPATH=[os.path.join('$QTDIR','lib')])
+ self.AppendUnique(LINKFLAGS="-F$QTDIR/lib")
+ self.AppendUnique(CPPFLAGS=["-iframework$QTDIR/lib", include_flag + os.path.join("$QTDIR", "include")])
+ self.Append(LINKFLAGS="-Wl,-rpath,$QTDIR/lib")
+
+ # FIXME: Phonon Hack
+ if version == '4' :
+ self.Append(LINKFLAGS=['-framework', "phonon"])
+
+ for module in modules :
+ if module in staticModules :
+ self.AppendUnique(LIBS=[module+debugSuffix]) # TODO: Add the debug suffix
+ self.AppendUnique(LIBPATH=[os.path.join("$QTDIR","lib")])
+ else :
+ if len(self["QTDIR"]) > 0 :
+ self.Append(CPPFLAGS = [include_flag + os.path.join("$QTDIR", "lib", module + ".framework", "Headers")])
+ else :
+ self.Append(CPPFLAGS = [include_flag + os.path.join("/Library/Frameworks", module + ".framework", "Headers")])
+ self.Append(LINKFLAGS=['-framework', module])
+ if 'QtOpenGL' in modules:
+ self.AppendUnique(LINKFLAGS="-F/System/Library/Frameworks")
+ self.Append(LINKFLAGS=['-framework', 'AGL']) #TODO ughly kludge to avoid quotes
+ self.Append(LINKFLAGS=['-framework', 'OpenGL'])
+ self["QT4_MOCCPPPATH"] = self["CPPPATH"]
def exists(env):
- return _detect(env)
+ return _detect(env)
diff --git a/BuildTools/SCons/Tools/textfile.py b/BuildTools/SCons/Tools/textfile.py
index b290125..89f8963 100644
--- a/BuildTools/SCons/Tools/textfile.py
+++ b/BuildTools/SCons/Tools/textfile.py
@@ -25,23 +25,23 @@
__doc__ = """
Textfile/Substfile builder for SCons.
- Create file 'target' which typically is a textfile. The 'source'
- may be any combination of strings, Nodes, or lists of same. A
- 'linesep' will be put between any part written and defaults to
- os.linesep.
-
- The only difference between the Textfile builder and the Substfile
- builder is that strings are converted to Value() nodes for the
- former and File() nodes for the latter. To insert files in the
- former or strings in the latter, wrap them in a File() or Value(),
- respectively.
-
- The values of SUBST_DICT first have any construction variables
- expanded (its keys are not expanded). If a value of SUBST_DICT is
- a python callable function, it is called and the result is expanded
- as the value. Values are substituted in a "random" order; if any
- substitution could be further expanded by another subsitition, it
- is unpredictible whether the expansion will occur.
+ Create file 'target' which typically is a textfile. The 'source'
+ may be any combination of strings, Nodes, or lists of same. A
+ 'linesep' will be put between any part written and defaults to
+ os.linesep.
+
+ The only difference between the Textfile builder and the Substfile
+ builder is that strings are converted to Value() nodes for the
+ former and File() nodes for the latter. To insert files in the
+ former or strings in the latter, wrap them in a File() or Value(),
+ respectively.
+
+ The values of SUBST_DICT first have any construction variables
+ expanded (its keys are not expanded). If a value of SUBST_DICT is
+ a python callable function, it is called and the result is expanded
+ as the value. Values are substituted in a "random" order; if any
+ substitution could be further expanded by another subsitition, it
+ is unpredictible whether the expansion will occur.
"""
__revision__ = "src/engine/SCons/Tool/textfile.py 5357 2011/09/09 21:31:03 bdeegan"
@@ -56,117 +56,117 @@ from SCons.Node.Python import Value
from SCons.Util import is_String, is_Sequence, is_Dict
def _do_subst(node, subs):
- """
- Fetch the node contents and replace all instances of the keys with
- their values. For example, if subs is
- {'%VERSION%': '1.2345', '%BASE%': 'MyProg', '%prefix%': '/bin'},
- then all instances of %VERSION% in the file will be replaced with
- 1.2345 and so forth.
- """
- contents = node.get_text_contents()
- if not subs: return contents
- for (k,v) in subs:
- contents = re.sub(k, v, contents)
- return contents
+ """
+ Fetch the node contents and replace all instances of the keys with
+ their values. For example, if subs is
+ {'%VERSION%': '1.2345', '%BASE%': 'MyProg', '%prefix%': '/bin'},
+ then all instances of %VERSION% in the file will be replaced with
+ 1.2345 and so forth.
+ """
+ contents = node.get_text_contents()
+ if not subs: return contents
+ for (k,v) in subs:
+ contents = re.sub(k, v, contents)
+ return contents
def _action(target, source, env):
- # prepare the line separator
- linesep = env['LINESEPARATOR']
- if linesep is None:
- linesep = os.linesep
- elif is_String(linesep):
- pass
- elif isinstance(linesep, Value):
- linesep = linesep.get_text_contents()
- else:
- raise SCons.Errors.UserError(
- 'unexpected type/class for LINESEPARATOR: %s'
- % repr(linesep), None)
-
- # create a dictionary to use for the substitutions
- if 'SUBST_DICT' not in env:
- subs = None # no substitutions
- else:
- d = env['SUBST_DICT']
- if is_Dict(d):
- d = list(d.items())
- elif is_Sequence(d):
- pass
- else:
- raise SCons.Errors.UserError('SUBST_DICT must be dict or sequence')
- subs = []
- for (k,v) in d:
- if callable(v):
- v = v()
- if is_String(v):
- v = env.subst(v)
- else:
- v = str(v)
- subs.append((k,v))
-
- # write the file
- try:
- fd = open(target[0].get_path(), "wb")
- except (OSError,IOError), e:
- raise SCons.Errors.UserError("Can't write target file %s" % target[0])
- # separate lines by 'linesep' only if linesep is not empty
- lsep = None
- for s in source:
- if lsep: fd.write(lsep)
- fd.write(_do_subst(s, subs))
- lsep = linesep
- fd.close()
+ # prepare the line separator
+ linesep = env['LINESEPARATOR']
+ if linesep is None:
+ linesep = os.linesep
+ elif is_String(linesep):
+ pass
+ elif isinstance(linesep, Value):
+ linesep = linesep.get_text_contents()
+ else:
+ raise SCons.Errors.UserError(
+ 'unexpected type/class for LINESEPARATOR: %s'
+ % repr(linesep), None)
+
+ # create a dictionary to use for the substitutions
+ if 'SUBST_DICT' not in env:
+ subs = None # no substitutions
+ else:
+ d = env['SUBST_DICT']
+ if is_Dict(d):
+ d = list(d.items())
+ elif is_Sequence(d):
+ pass
+ else:
+ raise SCons.Errors.UserError('SUBST_DICT must be dict or sequence')
+ subs = []
+ for (k,v) in d:
+ if callable(v):
+ v = v()
+ if is_String(v):
+ v = env.subst(v)
+ else:
+ v = str(v)
+ subs.append((k,v))
+
+ # write the file
+ try:
+ fd = open(target[0].get_path(), "wb")
+ except (OSError,IOError), e:
+ raise SCons.Errors.UserError("Can't write target file %s" % target[0])
+ # separate lines by 'linesep' only if linesep is not empty
+ lsep = None
+ for s in source:
+ if lsep: fd.write(lsep)
+ fd.write(_do_subst(s, subs))
+ lsep = linesep
+ fd.close()
def _strfunc(target, source, env):
- return "Creating '%s'" % target[0]
+ return "Creating '%s'" % target[0]
def _convert_list_R(newlist, sources):
- for elem in sources:
- if is_Sequence(elem):
- _convert_list_R(newlist, elem)
- elif isinstance(elem, Node):
- newlist.append(elem)
- else:
- newlist.append(Value(elem))
+ for elem in sources:
+ if is_Sequence(elem):
+ _convert_list_R(newlist, elem)
+ elif isinstance(elem, Node):
+ newlist.append(elem)
+ else:
+ newlist.append(Value(elem))
def _convert_list(target, source, env):
- if len(target) != 1:
- raise SCons.Errors.UserError("Only one target file allowed")
- newlist = []
- _convert_list_R(newlist, source)
- return target, newlist
+ if len(target) != 1:
+ raise SCons.Errors.UserError("Only one target file allowed")
+ newlist = []
+ _convert_list_R(newlist, source)
+ return target, newlist
_common_varlist = ['SUBST_DICT', 'LINESEPARATOR']
_text_varlist = _common_varlist + ['TEXTFILEPREFIX', 'TEXTFILESUFFIX']
_text_builder = SCons.Builder.Builder(
- action = SCons.Action.Action(_action, _strfunc, varlist = _text_varlist),
- source_factory = Value,
- emitter = _convert_list,
- prefix = '$TEXTFILEPREFIX',
- suffix = '$TEXTFILESUFFIX',
- )
+ action = SCons.Action.Action(_action, _strfunc, varlist = _text_varlist),
+ source_factory = Value,
+ emitter = _convert_list,
+ prefix = '$TEXTFILEPREFIX',
+ suffix = '$TEXTFILESUFFIX',
+ )
_subst_varlist = _common_varlist + ['SUBSTFILEPREFIX', 'TEXTFILESUFFIX']
_subst_builder = SCons.Builder.Builder(
- action = SCons.Action.Action(_action, _strfunc, varlist = _subst_varlist),
- source_factory = SCons.Node.FS.File,
- emitter = _convert_list,
- prefix = '$SUBSTFILEPREFIX',
- suffix = '$SUBSTFILESUFFIX',
- src_suffix = ['.in'],
- )
+ action = SCons.Action.Action(_action, _strfunc, varlist = _subst_varlist),
+ source_factory = SCons.Node.FS.File,
+ emitter = _convert_list,
+ prefix = '$SUBSTFILEPREFIX',
+ suffix = '$SUBSTFILESUFFIX',
+ src_suffix = ['.in'],
+ )
def generate(env):
- env['LINESEPARATOR'] = os.linesep
- env['BUILDERS']['MyTextfile'] = _text_builder
- env['TEXTFILEPREFIX'] = ''
- env['TEXTFILESUFFIX'] = '.txt'
- env['BUILDERS']['MySubstfile'] = _subst_builder
- env['SUBSTFILEPREFIX'] = ''
- env['SUBSTFILESUFFIX'] = ''
+ env['LINESEPARATOR'] = os.linesep
+ env['BUILDERS']['MyTextfile'] = _text_builder
+ env['TEXTFILEPREFIX'] = ''
+ env['TEXTFILESUFFIX'] = '.txt'
+ env['BUILDERS']['MySubstfile'] = _subst_builder
+ env['SUBSTFILEPREFIX'] = ''
+ env['SUBSTFILESUFFIX'] = ''
def exists(env):
- return 1
+ return 1
# Local Variables:
# tab-width:4
diff --git a/BuildTools/SCons/Tools/wix.py b/BuildTools/SCons/Tools/wix.py
index 705d249..907b6d9 100644
--- a/BuildTools/SCons/Tools/wix.py
+++ b/BuildTools/SCons/Tools/wix.py
@@ -3,49 +3,49 @@ import SCons.Util
from subprocess import call
def generate(env) :
- wixPath = env.get("wix_bindir", "")
- if len(wixPath) > 0 and wixPath[-1] != "\\":
- wixPath += "\\"
- env['WIX_HEAT'] = wixPath + 'heat.exe'
- env['WIX_HEAT_OPTIONS'] = '-nologo -ag -sfrag -suid -template fragment -dr ProgramFilesFolder'
- env['WIX_CANDLE'] = wixPath + 'candle.exe'
- env['WIX_CANDLE_OPTIONS'] = '-nologo'
- env['WIX_LIGHT'] = wixPath + 'light.exe'
- env['WIX_LIGHT_OPTIONS'] = '-nologo -ext WixUIExtension'
-
- def WiX_IncludeScanner(source, env, path, arg):
- wixIncludeRegexp = re.compile(r'^\s*\<\?include (\S+.wxs)\s*\?\>\S*', re.M)
- contents = source.get_contents()
- includes = wixIncludeRegexp.findall(contents)
- return [ "" + include for include in includes ]
-
- heat_builder = SCons.Builder.Builder(
- action = '"$WIX_HEAT" dir "$WIX_SOURCE_OBJECT_DIR" -cg Files $WIX_HEAT_OPTIONS -o ${TARGET} -t Swift\\Packaging\\WiX\\include.xslt',
- suffix = '.wxi')
-
-
- candle_scanner = env.Scanner(name = 'wixincludefile',
- function = WiX_IncludeScanner,
- argument = None,
- skeys = ['.wxs'])
-
- candle_builder = SCons.Builder.Builder(
- action = '"$WIX_CANDLE" $WIX_CANDLE_OPTIONS ${SOURCES} -o ${TARGET}',
- src_suffix = '.wxs',
- suffix = '.wixobj',
- source_scanner = candle_scanner,
- src_builder = heat_builder)
-
-
- light_builder = SCons.Builder.Builder(
- action = '"$WIX_LIGHT" $WIX_LIGHT_OPTIONS -b "$WIX_SOURCE_OBJECT_DIR" ${SOURCES} -o ${TARGET}',
- src_suffix = '.wixobj',
- src_builder = candle_builder)
-
- env['BUILDERS']['WiX_Heat'] = heat_builder
- env['BUILDERS']['WiX_Candle'] = candle_builder
- env['BUILDERS']['WiX_Light'] = light_builder
+ wixPath = env.get("wix_bindir", "")
+ if len(wixPath) > 0 and wixPath[-1] != "\\":
+ wixPath += "\\"
+ env['WIX_HEAT'] = wixPath + 'heat.exe'
+ env['WIX_HEAT_OPTIONS'] = '-nologo -ag -sfrag -suid -template fragment -dr ProgramFilesFolder'
+ env['WIX_CANDLE'] = wixPath + 'candle.exe'
+ env['WIX_CANDLE_OPTIONS'] = '-nologo'
+ env['WIX_LIGHT'] = wixPath + 'light.exe'
+ env['WIX_LIGHT_OPTIONS'] = '-nologo -ext WixUIExtension'
+
+ def WiX_IncludeScanner(source, env, path, arg):
+ wixIncludeRegexp = re.compile(r'^\s*\<\?include (\S+.wxs)\s*\?\>\S*', re.M)
+ contents = source.get_contents()
+ includes = wixIncludeRegexp.findall(contents)
+ return [ "" + include for include in includes ]
+
+ heat_builder = SCons.Builder.Builder(
+ action = '"$WIX_HEAT" dir "$WIX_SOURCE_OBJECT_DIR" -cg Files $WIX_HEAT_OPTIONS -o ${TARGET} -t Swift\\Packaging\\WiX\\include.xslt',
+ suffix = '.wxi')
+
+
+ candle_scanner = env.Scanner(name = 'wixincludefile',
+ function = WiX_IncludeScanner,
+ argument = None,
+ skeys = ['.wxs'])
+
+ candle_builder = SCons.Builder.Builder(
+ action = '"$WIX_CANDLE" $WIX_CANDLE_OPTIONS ${SOURCES} -o ${TARGET}',
+ src_suffix = '.wxs',
+ suffix = '.wixobj',
+ source_scanner = candle_scanner,
+ src_builder = heat_builder)
+
+
+ light_builder = SCons.Builder.Builder(
+ action = '"$WIX_LIGHT" $WIX_LIGHT_OPTIONS -b "$WIX_SOURCE_OBJECT_DIR" ${SOURCES} -o ${TARGET}',
+ src_suffix = '.wixobj',
+ src_builder = candle_builder)
+
+ env['BUILDERS']['WiX_Heat'] = heat_builder
+ env['BUILDERS']['WiX_Candle'] = candle_builder
+ env['BUILDERS']['WiX_Light'] = light_builder
def exists(env) :
- return True
+ return True
diff --git a/BuildTools/SCons/Version.py b/BuildTools/SCons/Version.py
index 6482664..d34c2a7 100644
--- a/BuildTools/SCons/Version.py
+++ b/BuildTools/SCons/Version.py
@@ -1,68 +1,68 @@
import subprocess, os, datetime, re, os.path
def getGitBuildVersion(root, project) :
- tag = git("describe --tags --exact --match \"" + project + "-*\"", root)
- if tag :
- return tag.rstrip()[len(project)+1:]
- tag = git("describe --tags --match \"" + project + "-*\"", root)
- if tag :
- m = re.match(project + "-(.*)-(.*)-(.*)", tag)
- if m :
- return m.group(1) + "-dev" + m.group(2)
- return None
+ tag = git("describe --tags --exact --match \"" + project + "-*\"", root)
+ if tag :
+ return tag.rstrip()[len(project)+1:]
+ tag = git("describe --tags --match \"" + project + "-*\"", root)
+ if tag :
+ m = re.match(project + "-(.*)-(.*)-(.*)", tag)
+ if m :
+ return m.group(1) + "-dev" + m.group(2)
+ return None
def git(cmd, root) :
- full_cmd = "git " + cmd
- p = subprocess.Popen(full_cmd, cwd=root, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(os.name != "nt"))
- gitVersion = p.stdout.read()
- # error = p.stderr.read()
- # if error:
- # print "Git error: " + error
- p.stdin.close()
- if p.wait() == 0 :
- return gitVersion
- return None
+ full_cmd = "git " + cmd
+ p = subprocess.Popen(full_cmd, cwd=root, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=(os.name != "nt"))
+ gitVersion = p.stdout.read()
+ # error = p.stderr.read()
+ # if error:
+ # print "Git error: " + error
+ p.stdin.close()
+ if p.wait() == 0 :
+ return gitVersion
+ return None
def getBuildVersion(root, project) :
- versionFilename = os.path.join(root, "VERSION." + project)
- if os.path.isfile(versionFilename) :
- f = open(versionFilename)
- version = f.read().strip()
- f.close()
- return version
+ versionFilename = os.path.join(root, "VERSION." + project)
+ if os.path.isfile(versionFilename) :
+ f = open(versionFilename)
+ version = f.read().strip()
+ f.close()
+ return version
- gitVersion = getGitBuildVersion(root, project)
- if gitVersion :
- return gitVersion
+ gitVersion = getGitBuildVersion(root, project)
+ if gitVersion :
+ return gitVersion
- return datetime.date.today().strftime("%Y%m%d")
+ return datetime.date.today().strftime("%Y%m%d")
def convertToWindowsVersion(version) :
- version_match = re.match("(\d+)\.(\d+)(.*)", version)
- major = version_match and int(version_match.group(1)) or 0
- minor = version_match and int(version_match.group(2)) or 0
- if version_match and len(version_match.group(3)) == 0 :
- patch = 60000
- else :
- match = re.match("^beta(\d+)(.*)", version_match.group(3))
- build_string = ""
- if match :
- patch = 1000*int(match.group(1))
- build_string = match.group(2)
- else :
- rc_match = re.match("^rc(\d+)(.*)", version_match.group(3))
- if rc_match :
- patch = 10000*int(rc_match.group(1))
- build_string = rc_match.group(2)
- else :
- patch = 0
- alpha_match = re.match("^alpha(.*)", version_match.group(3))
- if alpha_match :
- build_string = alpha_match.group(1)
+ version_match = re.match("(\d+)\.(\d+)(.*)", version)
+ major = version_match and int(version_match.group(1)) or 0
+ minor = version_match and int(version_match.group(2)) or 0
+ if version_match and len(version_match.group(3)) == 0 :
+ patch = 60000
+ else :
+ match = re.match("^beta(\d+)(.*)", version_match.group(3))
+ build_string = ""
+ if match :
+ patch = 1000*int(match.group(1))
+ build_string = match.group(2)
+ else :
+ rc_match = re.match("^rc(\d+)(.*)", version_match.group(3))
+ if rc_match :
+ patch = 10000*int(rc_match.group(1))
+ build_string = rc_match.group(2)
+ else :
+ patch = 0
+ alpha_match = re.match("^alpha(.*)", version_match.group(3))
+ if alpha_match :
+ build_string = alpha_match.group(1)
- if len(build_string) > 0 :
- build_match = re.match("^-dev(\d+)", build_string)
- if build_match :
- patch += int(build_match.group(1))
+ if len(build_string) > 0 :
+ build_match = re.match("^-dev(\d+)", build_string)
+ if build_match :
+ patch += int(build_match.group(1))
- return (major, minor, patch)
+ return (major, minor, patch)
diff --git a/BuildTools/UpdateDebianChangelog.py b/BuildTools/UpdateDebianChangelog.py
index 0693461..1d0e3ea 100755
--- a/BuildTools/UpdateDebianChangelog.py
+++ b/BuildTools/UpdateDebianChangelog.py
@@ -14,28 +14,28 @@ project = ""
last_version = ""
m = re.match("([\w-]+) \((.*)-\d+\)", last_version_line)
if m :
- project = m.group(1)
- last_version = m.group(2)
+ project = m.group(1)
+ last_version = m.group(2)
if project == "" :
- project="swift-im"
+ project="swift-im"
if "dev" in version :
- distribution = "development"
+ distribution = "development"
elif "beta" in version or "rc" in version :
- distribution = "beta development"
+ distribution = "beta development"
else :
- distribution = "release beta development"
+ distribution = "release beta development"
if last_version != version :
- changelog = open(sys.argv[1])
- changelog_data = changelog.read()
- changelog.close()
- changelog = open(sys.argv[1], "w")
- changelog.write(project + " (" + version + "-1)" + " " + distribution + "; urgency=low\n\n")
- changelog.write(" * Upstream development snapshot\n\n")
- changelog.write(" -- Swift Package Maintainer <packages@swift.im> " + email.utils.formatdate() + "\n")
- changelog.write("\n")
- changelog.write(changelog_data)
- changelog.close()
+ changelog = open(sys.argv[1])
+ changelog_data = changelog.read()
+ changelog.close()
+ changelog = open(sys.argv[1], "w")
+ changelog.write(project + " (" + version + "-1)" + " " + distribution + "; urgency=low\n\n")
+ changelog.write(" * Upstream development snapshot\n\n")
+ changelog.write(" -- Swift Package Maintainer <packages@swift.im> " + email.utils.formatdate() + "\n")
+ changelog.write("\n")
+ changelog.write(changelog_data)
+ changelog.close()
diff --git a/BuildTools/scons2ninja.py b/BuildTools/scons2ninja.py
index 5d084cd..6c77c88 100755
--- a/BuildTools/scons2ninja.py
+++ b/BuildTools/scons2ninja.py
@@ -24,202 +24,202 @@ SCONS_ARGS = ' '.join(sys.argv[1:])
BINARY_FLAGS = ["-framework", "-arch", "-x", "--output-format", "-isystem", "-include"]
if sys.platform == 'win32' :
- LIB_PREFIX = ""
- LIB_SUFFIX = ""
- EXE_SUFFIX = ".exe"
+ LIB_PREFIX = ""
+ LIB_SUFFIX = ""
+ EXE_SUFFIX = ".exe"
else :
- LIB_PREFIX = "lib"
- LIB_SUFFIX = ".a"
- EXE_SUFFIX = ""
+ LIB_PREFIX = "lib"
+ LIB_SUFFIX = ".a"
+ EXE_SUFFIX = ""
def is_regexp(x) :
- return 'match' in dir(x)
+ return 'match' in dir(x)
def is_list(l) :
- return type(l) is list
+ return type(l) is list
def escape(s) :
- return s.replace(' ', '$ ').replace(':', '$:')
+ return s.replace(' ', '$ ').replace(':', '$:')
def quote_spaces(s) :
- if ' ' in s :
- return '"' + s + '"'
- else :
- return s
+ if ' ' in s :
+ return '"' + s + '"'
+ else :
+ return s
def to_list(l) :
- if not l :
- return []
- if is_list(l) :
- return l
- return [l]
+ if not l :
+ return []
+ if is_list(l) :
+ return l
+ return [l]
def partition(l, f) :
- x = []
- y = []
- for v in l :
- if f(v) :
- x.append(v)
- else :
- y.append(v)
- return (x, y)
+ x = []
+ y = []
+ for v in l :
+ if f(v) :
+ x.append(v)
+ else :
+ y.append(v)
+ return (x, y)
def get_unary_flags(prefix, flags) :
- return [x[len(prefix):] for x in flags if x.lower().startswith(prefix.lower())]
+ return [x[len(prefix):] for x in flags if x.lower().startswith(prefix.lower())]
def extract_unary_flags(prefix, flags) :
- f1, f2 = partition(flags, lambda x : x.lower().startswith(prefix.lower()))
- return ([f[len(prefix):] for f in f1], f2)
+ f1, f2 = partition(flags, lambda x : x.lower().startswith(prefix.lower()))
+ return ([f[len(prefix):] for f in f1], f2)
def extract_unary_flag(prefix, flags) :
- flag, flags = extract_unary_flags(prefix, flags)
- return (flag[0], flags)
+ flag, flags = extract_unary_flags(prefix, flags)
+ return (flag[0], flags)
def extract_binary_flag(prefix, flags) :
- i = flags.index(prefix)
- flag = flags[i + 1]
- del flags[i]
- del flags[i]
- return (flag, flags)
+ i = flags.index(prefix)
+ flag = flags[i + 1]
+ del flags[i]
+ del flags[i]
+ return (flag, flags)
def get_non_flags(flags) :
- skip = False
- result = []
- for f in flags :
- if skip :
- skip = False
- elif f in BINARY_FLAGS :
- skip = True
- elif not f.startswith("/") and not f.startswith("-") :
- result.append(f)
- return result
+ skip = False
+ result = []
+ for f in flags :
+ if skip :
+ skip = False
+ elif f in BINARY_FLAGS :
+ skip = True
+ elif not f.startswith("/") and not f.startswith("-") :
+ result.append(f)
+ return result
def extract_non_flags(flags) :
- non_flags = get_non_flags(flags)
- return (non_flags, filter(lambda x : x not in non_flags, flags))
+ non_flags = get_non_flags(flags)
+ return (non_flags, filter(lambda x : x not in non_flags, flags))
def get_dependencies(target, build_targets) :
- result = []
- queue = list(dependencies.get(target, []))
- while len(queue) > 0 :
- n = queue.pop()
- # Filter out Value() results
- if n in build_targets or os.path.exists(n) :
- result.append(n)
- queue += list(dependencies.get(n, []))
- return result
+ result = []
+ queue = list(dependencies.get(target, []))
+ while len(queue) > 0 :
+ n = queue.pop()
+ # Filter out Value() results
+ if n in build_targets or os.path.exists(n) :
+ result.append(n)
+ queue += list(dependencies.get(n, []))
+ return result
def get_built_libs(libs, libpaths, outputs) :
- canonical_outputs = [os.path.abspath(p) for p in outputs]
- result = []
- for libpath in libpaths :
- for lib in libs :
- lib_libpath = os.path.join(libpath, LIB_PREFIX + lib + LIB_SUFFIX)
- if os.path.abspath(lib_libpath) in canonical_outputs :
- result.append(lib_libpath)
- return result
+ canonical_outputs = [os.path.abspath(p) for p in outputs]
+ result = []
+ for libpath in libpaths :
+ for lib in libs :
+ lib_libpath = os.path.join(libpath, LIB_PREFIX + lib + LIB_SUFFIX)
+ if os.path.abspath(lib_libpath) in canonical_outputs :
+ result.append(lib_libpath)
+ return result
def parse_tool_command(line) :
- command = shlex.split(line, False, False if sys.platform == 'win32' else True)
- flags = command[1:]
- tool = os.path.splitext(os.path.basename(command[0]))[0]
- if tool.startswith('clang++') or tool.startswith('g++') :
- tool = "cxx"
- elif tool.startswith('clang') or tool.startswith('gcc') :
- tool = "cc"
- if tool in ["cc", "cxx"] and not "-c" in flags :
- tool = "glink"
- tool = tool.replace('-qt4', '')
- return tool, command, flags
+ command = shlex.split(line, False, False if sys.platform == 'win32' else True)
+ flags = command[1:]
+ tool = os.path.splitext(os.path.basename(command[0]))[0]
+ if tool.startswith('clang++') or tool.startswith('g++') :
+ tool = "cxx"
+ elif tool.startswith('clang') or tool.startswith('gcc') :
+ tool = "cc"
+ if tool in ["cc", "cxx"] and not "-c" in flags :
+ tool = "glink"
+ tool = tool.replace('-qt4', '')
+ return tool, command, flags
def rglob(pattern, root = '.') :
- return [os.path.join(path, f) for path, dirs, files in os.walk(root) for f in fnmatch.filter(files, pattern)]
+ return [os.path.join(path, f) for path, dirs, files in os.walk(root) for f in fnmatch.filter(files, pattern)]
################################################################################
# Helper for building Ninja files
################################################################################
class NinjaBuilder :
- def __init__(self) :
- self._header = ""
- self.variables = ""
- self.rules = ""
- self._build = ""
- self.pools = ""
- self._flags = {}
- self.targets = []
-
- def header(self, text) :
- self._header += text + "\n"
-
- def rule(self, name, **kwargs) :
- self.rules += "rule " + name + "\n"
- for k, v in kwargs.iteritems() :
- self.rules += " " + str(k) + " = " + str(v) + "\n"
- self.rules += "\n"
-
- def pool(self, name, **kwargs) :
- self.pools += "pool " + name + "\n"
- for k, v in kwargs.iteritems() :
- self.pools += " " + str(k) + " = " + str(v) + "\n"
- self.pools += "\n"
-
- def variable(self, name, value) :
- self.variables += str(name) + " = " + str(value) + "\n"
-
- def build(self, target, rule, sources = None, **kwargs) :
- self._build += "build " + self.to_string(target) + ": " + rule
- if sources :
- self._build += " " + self.to_string(sources)
- if 'deps' in kwargs and kwargs['deps'] :
- self._build += " | " + self.to_string(kwargs["deps"])
- if 'order_deps' in kwargs :
- self._build += " || " + self.to_string(kwargs['order_deps'])
- self._build += "\n"
- for var, value in kwargs.iteritems() :
- if var in ['deps', 'order_deps'] :
- continue
- value = self.to_string(value, quote = True)
- if var.endswith("flags") :
- value = self.get_flags_variable(var, value)
- self._build += " " + var + " = " + value + "\n"
- self.targets += to_list(target)
-
- def header_targets(self) :
- return [x for x in self.targets if x.endswith('.h') or x.endswith('.hh')]
-
- def serialize(self) :
- result = ""
- result += self._header + "\n"
- result += self.variables + "\n"
- for prefix in self._flags.values() :
- for k, v in prefix.iteritems() :
- result += v + " = " + k + "\n"
- result += "\n"
- result += self.pools + "\n"
- result += self.rules + "\n"
- result += self._build + "\n"
- return result
-
- def to_string(self, lst, quote = False) :
- if is_list(lst) :
- if quote :
- return ' '.join([quote_spaces(x) for x in lst])
- else :
- return ' '.join([escape(x) for x in lst])
- if is_regexp(lst) :
- return ' '.join([escape(x) for x in self.targets if lst.match(x)])
- return escape(lst)
-
- def get_flags_variable(self, flags_type, flags) :
- if len(flags) == 0 :
- return ''
- if flags_type not in self._flags :
- self._flags[flags_type] = {}
- type_flags = self._flags[flags_type]
- if flags not in type_flags :
- type_flags[flags] = flags_type + "_" + str(len(type_flags))
- return "$" + type_flags[flags]
+ def __init__(self) :
+ self._header = ""
+ self.variables = ""
+ self.rules = ""
+ self._build = ""
+ self.pools = ""
+ self._flags = {}
+ self.targets = []
+
+ def header(self, text) :
+ self._header += text + "\n"
+
+ def rule(self, name, **kwargs) :
+ self.rules += "rule " + name + "\n"
+ for k, v in kwargs.iteritems() :
+ self.rules += " " + str(k) + " = " + str(v) + "\n"
+ self.rules += "\n"
+
+ def pool(self, name, **kwargs) :
+ self.pools += "pool " + name + "\n"
+ for k, v in kwargs.iteritems() :
+ self.pools += " " + str(k) + " = " + str(v) + "\n"
+ self.pools += "\n"
+
+ def variable(self, name, value) :
+ self.variables += str(name) + " = " + str(value) + "\n"
+
+ def build(self, target, rule, sources = None, **kwargs) :
+ self._build += "build " + self.to_string(target) + ": " + rule
+ if sources :
+ self._build += " " + self.to_string(sources)
+ if 'deps' in kwargs and kwargs['deps'] :
+ self._build += " | " + self.to_string(kwargs["deps"])
+ if 'order_deps' in kwargs :
+ self._build += " || " + self.to_string(kwargs['order_deps'])
+ self._build += "\n"
+ for var, value in kwargs.iteritems() :
+ if var in ['deps', 'order_deps'] :
+ continue
+ value = self.to_string(value, quote = True)
+ if var.endswith("flags") :
+ value = self.get_flags_variable(var, value)
+ self._build += " " + var + " = " + value + "\n"
+ self.targets += to_list(target)
+
+ def header_targets(self) :
+ return [x for x in self.targets if x.endswith('.h') or x.endswith('.hh')]
+
+ def serialize(self) :
+ result = ""
+ result += self._header + "\n"
+ result += self.variables + "\n"
+ for prefix in self._flags.values() :
+ for k, v in prefix.iteritems() :
+ result += v + " = " + k + "\n"
+ result += "\n"
+ result += self.pools + "\n"
+ result += self.rules + "\n"
+ result += self._build + "\n"
+ return result
+
+ def to_string(self, lst, quote = False) :
+ if is_list(lst) :
+ if quote :
+ return ' '.join([quote_spaces(x) for x in lst])
+ else :
+ return ' '.join([escape(x) for x in lst])
+ if is_regexp(lst) :
+ return ' '.join([escape(x) for x in self.targets if lst.match(x)])
+ return escape(lst)
+
+ def get_flags_variable(self, flags_type, flags) :
+ if len(flags) == 0 :
+ return ''
+ if flags_type not in self._flags :
+ self._flags[flags_type] = {}
+ type_flags = self._flags[flags_type]
+ if flags not in type_flags :
+ type_flags[flags] = flags_type + "_" + str(len(type_flags))
+ return "$" + type_flags[flags]
################################################################################
@@ -231,7 +231,7 @@ scons_cmd = "scons"
scons_dependencies = ['SConstruct'] + rglob('SConscript')
def ninja_custom_command(ninja, line) :
- return False
+ return False
CONFIGURATION_FILE = '.scons2ninja.conf'
execfile(CONFIGURATION_FILE)
@@ -248,104 +248,104 @@ ninja = NinjaBuilder()
ninja.pool('scons_pool', depth = 1)
if sys.platform == 'win32' :
- ninja.rule('cl',
- deps = 'msvc',
- command = '$cl /showIncludes $clflags -c $in /Fo$out',
- description = 'CXX $out')
-
- ninja.rule('link',
- command = '$link $in $linkflags $libs /out:$out',
- description = 'LINK $out')
-
- ninja.rule('link_mt',
- command = '$link $in $linkflags $libs /out:$out ; $mt $mtflags',
- description = 'LINK $out')
-
- ninja.rule('lib',
- command = '$lib $libflags /out:$out $in',
- description = 'AR $out')
-
- ninja.rule('rc',
- command = '$rc $rcflags /Fo$out $in',
- description = 'RC $out')
-
- # SCons doesn't touch files if they didn't change, which makes
- # ninja rebuild the file over and over again. There's no touch on Windows :(
- # Could implement it with a script, but for now, delete the file if
- # this problem occurs. I'll fix it if it occurs too much.
- ninja.rule('scons',
- command = scons_cmd + " ${scons_args} $out",
- pool = 'scons_pool',
- description = 'GEN $out')
-
- ninja.rule('install', command = 'cmd /c copy $in $out')
- ninja.rule('run', command = '$in')
+ ninja.rule('cl',
+ deps = 'msvc',
+ command = '$cl /showIncludes $clflags -c $in /Fo$out',
+ description = 'CXX $out')
+
+ ninja.rule('link',
+ command = '$link $in $linkflags $libs /out:$out',
+ description = 'LINK $out')
+
+ ninja.rule('link_mt',
+ command = '$link $in $linkflags $libs /out:$out ; $mt $mtflags',
+ description = 'LINK $out')
+
+ ninja.rule('lib',
+ command = '$lib $libflags /out:$out $in',
+ description = 'AR $out')
+
+ ninja.rule('rc',
+ command = '$rc $rcflags /Fo$out $in',
+ description = 'RC $out')
+
+ # SCons doesn't touch files if they didn't change, which makes
+ # ninja rebuild the file over and over again. There's no touch on Windows :(
+ # Could implement it with a script, but for now, delete the file if
+ # this problem occurs. I'll fix it if it occurs too much.
+ ninja.rule('scons',
+ command = scons_cmd + " ${scons_args} $out",
+ pool = 'scons_pool',
+ description = 'GEN $out')
+
+ ninja.rule('install', command = 'cmd /c copy $in $out')
+ ninja.rule('run', command = '$in')
else :
- ninja.rule('cxx',
- deps = 'gcc',
- depfile = '$out.d',
- command = '$cxx -MMD -MF $out.d $cxxflags -c $in -o $out',
- description = 'CXX $out')
+ ninja.rule('cxx',
+ deps = 'gcc',
+ depfile = '$out.d',
+ command = '$cxx -MMD -MF $out.d $cxxflags -c $in -o $out',
+ description = 'CXX $out')
- ninja.rule('cc',
- deps = 'gcc',
- depfile = '$out.d',
- command = '$cc -MMD -MF $out.d $ccflags -c $in -o $out',
- description = 'CC $out')
+ ninja.rule('cc',
+ deps = 'gcc',
+ depfile = '$out.d',
+ command = '$cc -MMD -MF $out.d $ccflags -c $in -o $out',
+ description = 'CC $out')
- ninja.rule('link',
- command = '$glink -o $out $in $linkflags',
- description = 'LINK $out')
+ ninja.rule('link',
+ command = '$glink -o $out $in $linkflags',
+ description = 'LINK $out')
- ninja.rule('ar',
- command = 'ar $arflags $out $in && ranlib $out',
- description = 'AR $out')
+ ninja.rule('ar',
+ command = 'ar $arflags $out $in && ranlib $out',
+ description = 'AR $out')
- # SCons doesn't touch files if they didn't change, which makes
- # ninja rebuild the file over and over again. Touching solves this.
- ninja.rule('scons',
- command = scons_cmd + " $out && touch $out",
- pool = 'scons_pool',
- description = 'GEN $out')
+ # SCons doesn't touch files if they didn't change, which makes
+ # ninja rebuild the file over and over again. Touching solves this.
+ ninja.rule('scons',
+ command = scons_cmd + " $out && touch $out",
+ pool = 'scons_pool',
+ description = 'GEN $out')
- ninja.rule('install', command = 'install $in $out')
- ninja.rule('run', command = './$in')
+ ninja.rule('install', command = 'install $in $out')
+ ninja.rule('run', command = './$in')
ninja.rule('moc',
- command = '$moc $mocflags -o $out $in',
- description = 'MOC $out')
+ command = '$moc $mocflags -o $out $in',
+ description = 'MOC $out')
ninja.rule('rcc',
- command = '$rcc $rccflags -name $name -o $out $in',
- description = 'RCC $out')
+ command = '$rcc $rccflags -name $name -o $out $in',
+ description = 'RCC $out')
ninja.rule('uic',
- command = '$uic $uicflags -o $out $in',
- description = 'UIC $out')
+ command = '$uic $uicflags -o $out $in',
+ description = 'UIC $out')
ninja.rule('lrelease',
- command = '$lrelease $lreleaseflags $in -qm $out',
- description = 'LRELEASE $out')
+ command = '$lrelease $lreleaseflags $in -qm $out',
+ description = 'LRELEASE $out')
ninja.rule('ibtool',
- command = '$ibtool $ibtoolflags --compile $out $in',
- description = 'IBTOOL $out')
+ command = '$ibtool $ibtoolflags --compile $out $in',
+ description = 'IBTOOL $out')
ninja.rule('dsymutil',
- command = '$dsymutil $dsymutilflags -o $out $in',
- description = 'DSYMUTIL $out')
+ command = '$dsymutil $dsymutilflags -o $out $in',
+ description = 'DSYMUTIL $out')
ninja.rule('generator',
- command = "python " + SCRIPT + " ${scons_args}",
- depfile = ".scons2ninja.deps",
- pool = 'scons_pool',
- generator = '1',
- description = 'Regenerating build.ninja')
+ command = "python " + SCRIPT + " ${scons_args}",
+ depfile = ".scons2ninja.deps",
+ pool = 'scons_pool',
+ generator = '1',
+ description = 'Regenerating build.ninja')
ninja.rule('sdef',
- command = 'sdef $in | sdp -fh --basename $basename -o $outdir',
- description = 'SDEF $out')
+ command = 'sdef $in | sdp -fh --basename $basename -o $outdir',
+ description = 'SDEF $out')
################################################################################
# Build Statements
@@ -365,235 +365,237 @@ stage = 'preamble'
skip_nth_line = -1
stack = ['.']
for line in f.stdout :
- line = line.rstrip()
-
- # Skip lines if requested from previous command
- if skip_nth_line >= 0 :
- skip_nth_line -= 1
- if skip_nth_line == 0 :
- continue
-
- if line.startswith('scons: done building targets') :
- break
-
- if stage == "preamble" :
- # Pass all lines from the SCons configuration step to output
- if re.match("^scons: Building targets ...", line) :
- stage = "build"
- else :
- print line
-
- elif stage == "build" :
- if line.startswith('+-') :
- stage = "dependencies"
- elif re.match("^Using tempfile", line) :
- # Ignore response files from MSVS
- skip_nth_line = 2
- else :
- build_lines.append(line)
-
- # Already detect targets that will need 'mt'
- tool, _, flags = parse_tool_command(line)
- if tool == 'mt' :
- target = get_unary_flags("-outputresource:", flags)[0]
- target = target[0:target.index(';')]
- mtflags[target] = flags
-
- elif stage == "dependencies" :
- if not re.match('^[\s|]+\+\-', line) :
- # Work around bug in SCons that splits output over multiple lines
- continue
-
- level = line.index('+-') / 2
- filename = line[level*2+2:]
- if filename.startswith('[') :
- filename = filename[1:-1]
-
- # Check if we use the 'fixed' format which escapes filenamenames
- if filename.startswith('\'') and filename.endswith('\'') :
- filename = eval(filename)
-
- if level < len(stack) :
- stack = stack[0:level]
- elif level > len(stack) :
- if level != len(stack) + 1 :
- raise Exception("Internal Error" )
- stack.append(previous_filename)
-
- # Skip absolute paths
- if not os.path.isabs(filename) :
- target = stack[-1]
- if target not in dependencies :
- dependencies[target] = []
- dependencies[target].append(filename)
- previous_filename = filename
+ line = line.rstrip()
+
+ # Skip lines if requested from previous command
+ if skip_nth_line >= 0 :
+ skip_nth_line -= 1
+ if skip_nth_line == 0 :
+ continue
+
+ if line.startswith('scons: done building targets') :
+ break
+
+ if stage == "preamble" :
+ # Pass all lines from the SCons configuration step to output
+ if re.match("^scons: Building targets ...", line) :
+ stage = "build"
+ else :
+ print line
+
+ elif stage == "build" :
+ if line.startswith('+-') :
+ stage = "dependencies"
+ elif re.match("^Using tempfile", line) :
+ # Ignore response files from MSVS
+ skip_nth_line = 2
+ else :
+ build_lines.append(line)
+
+ # Already detect targets that will need 'mt'
+ tool, _, flags = parse_tool_command(line)
+ if tool == 'mt' :
+ target = get_unary_flags("-outputresource:", flags)[0]
+ target = target[0:target.index(';')]
+ mtflags[target] = flags
+
+ elif stage == "dependencies" :
+ if not re.match('^[\s|]+\+\-', line) :
+ # Work around bug in SCons that splits output over multiple lines
+ continue
+
+ level = line.index('+-') / 2
+ filename = line[level*2+2:]
+ if filename.startswith('[') :
+ filename = filename[1:-1]
+
+ # Check if we use the 'fixed' format which escapes filenamenames
+ if filename.startswith('\'') and filename.endswith('\'') :
+ filename = eval(filename)
+
+ if level < len(stack) :
+ stack = stack[0:level]
+ elif level > len(stack) :
+ if level != len(stack) + 1 :
+ raise Exception("Internal Error" )
+ stack.append(previous_filename)
+
+ # Skip absolute paths
+ if not os.path.isabs(filename) :
+ target = stack[-1]
+ if target not in dependencies :
+ dependencies[target] = []
+ dependencies[target].append(filename)
+ previous_filename = filename
if f.wait() != 0 :
- print "Error calling '" + scons_generate_cmd + "'"
- print f.stderr.read()
- exit(-1)
+ print "Error calling '" + scons_generate_cmd + "'"
+ print f.stderr.read()
+ exit(-1)
# Pass 2: Parse build rules
tools = {}
for line in build_lines :
- # Custom python function
- m = re.match('^(\w+)\(\[([^\]]*)\]', line)
- if m :
- out = [x[1:-1] for x in m.group(2).split(',')]
- for x in out :
- # 'Note' = To be more correct, deps should also include $scons_dependencies,
- # but this regenerates a bit too often, so leaving it out for now.
- ninja.build(x, 'scons', None, deps = sorted(get_dependencies(x, ninja.targets)))
- continue
-
-
- # TextFile
- m = re.match("^Creating '([^']+)'", line)
- if m :
- out = m.group(1)
- # Note: To be more correct, deps should also include $scons_dependencies,
- # but this regenerates a bit too often, so leaving it out for now.
- ninja.build(out, 'scons', None, deps = sorted(get_dependencies(out, ninja.targets)))
- continue
-
- # Install
- m = re.match('^Install file: "(.*)" as "(.*)"', line)
- if m :
- ninja.build(m.group(2), 'install', m.group(1))
- continue
-
- m = re.match('^Install directory: "(.*)" as "(.*)"', line)
- if m :
- for source in rglob('*', m.group(1)) :
- if os.path.isdir(source) :
- continue
- target = os.path.join(m.group(2), os.path.relpath(source, m.group(1)))
- ninja.build(target, 'install', source)
- continue
-
- # Tools
- tool, command, flags = parse_tool_command(line)
- tools[tool] = command[0]
-
- ############################################################
- # clang/gcc tools
- ############################################################
-
- if tool == 'cc':
- out, flags = extract_binary_flag("-o", flags)
- files, flags = extract_non_flags(flags)
- ninja.build(out, 'cc', files, order_deps = '_generated_headers', ccflags = flags)
-
- elif tool == 'cxx':
- out, flags = extract_binary_flag("-o", flags)
- files, flags = extract_non_flags(flags)
- ninja.build(out, 'cxx', files, order_deps = '_generated_headers', cxxflags = flags)
-
- elif tool == 'glink':
- out, flags = extract_binary_flag("-o", flags)
- files, flags = extract_non_flags(flags)
- libs = get_unary_flags('-l', flags)
- libpaths = get_unary_flags("-L", flags)
- deps = get_built_libs(libs, libpaths, ninja.targets)
- ninja.build(out, 'link', files, deps = sorted(deps), linkflags = flags)
-
- elif tool == 'ar':
- objects, flags = partition(flags, lambda x: x.endswith('.o'))
- libs, flags = partition(flags, lambda x: x.endswith('.a'))
- out = libs[0]
- ninja.build(out, 'ar', objects, arflags = flags)
-
- elif tool == 'ranlib':
- pass
-
-
- ############################################################
- # MSVC tools
- ############################################################
-
- elif tool == 'cl':
- out, flags = extract_unary_flag("/Fo", flags)
- files, flags = extract_non_flags(flags)
- ninja.build(out, 'cl', files, order_deps = '_generated_headers', clflags = flags)
-
- elif tool == 'lib':
- out, flags = extract_unary_flag("/out:", flags)
- files, flags = extract_non_flags(flags)
- ninja.build(out, 'lib', files, libflags = flags)
-
- elif tool == 'link':
- objects, flags = partition(flags, lambda x: x.endswith('.obj') or x.endswith('.res'))
- out, flags = extract_unary_flag("/out:", flags)
- libs, flags = partition(flags, lambda x: not x.startswith("/") and x.endswith(".lib"))
- libpaths = get_unary_flags("/libpath:", flags)
- deps = get_built_libs(libs, libpaths, ninja.targets)
- if out in mtflags :
- ninja.build(out, 'link_mt', objects, deps = sorted(deps),
- libs = libs, linkflags = flags, mtflags = mtflags[out])
- else :
- ninja.build(out, 'link', objects, deps = sorted(deps),
- libs = libs, linkflags = flags)
-
- elif tool == 'rc':
- out, flags = extract_unary_flag("/fo", flags)
- files, flags = extract_non_flags(flags)
- ninja.build(out, 'rc', files[0], order_deps = '_generated_headers', rcflags = flags)
-
- elif tool == 'mt':
- # Already handled
- pass
-
- ############################################################
- # Qt tools
- ############################################################
-
- elif tool == 'moc':
- out, flags = extract_binary_flag("-o", flags)
- files, flags = extract_non_flags(flags)
- ninja.build(out, 'moc', files, mocflags = flags)
-
- elif tool == 'uic':
- out, flags = extract_binary_flag("-o", flags)
- files, flags = extract_non_flags(flags)
- ninja.build(out, 'uic', files, uicflags = flags)
-
- elif tool == 'lrelease':
- out, flags = extract_binary_flag("-qm", flags)
- files, flags = extract_non_flags(flags)
- ninja.build(out, 'lrelease', files, lreleaseflags = flags)
-
- elif tool == 'rcc':
- out, flags = extract_binary_flag("-o", flags)
- name, flags = extract_binary_flag("-name", flags)
- files, flags = extract_non_flags(flags)
- deps = list(set(get_dependencies(out, ninja.targets)) - set(files))
- ninja.build(out, 'rcc', files, deps = sorted(deps), name = name, rccflags = flags)
-
- ############################################################
- # OS X tools
- ############################################################
-
- elif tool == 'ibtool':
- out, flags = extract_binary_flag("--compile", flags)
- files, flags = extract_non_flags(flags)
- ninja.build(out, 'ibtool', files, ibtoolflags = flags)
-
- elif tool == 'dsymutil':
- out, flags = extract_binary_flag("-o", flags)
- files, flags = extract_non_flags(flags)
- ninja.build(out, 'dsymutil', files, dsymutilflags = flags)
-
- elif tool == 'sdef' :
- source = flags[0];
- outdir, flags = extract_binary_flag("-o", flags)
- basename, flags = extract_binary_flag("--basename", flags)
- ninja.build(os.path.join(outdir, basename + ".h"), 'sdef', [source],
- basename = basename,
- outdir = outdir)
-
-
- elif not ninja_custom_command(ninja, line) :
- raise Exception("Unknown tool: '" + line + "'")
+ # Custom python function
+ m = re.match('^(\w+)\(\[([^\]]*)\]', line)
+ if m :
+ out = [x[1:-1] for x in m.group(2).split(',')]
+ for x in out :
+ # 'Note' = To be more correct, deps should also include $scons_dependencies,
+ # but this regenerates a bit too often, so leaving it out for now.
+ ninja.build(x, 'scons', None, deps = sorted(get_dependencies(x, ninja.targets)))
+ continue
+
+
+ # TextFile
+ m = re.match("^Creating '([^']+)'", line)
+ if m :
+ out = m.group(1)
+ # Note: To be more correct, deps should also include $scons_dependencies,
+ # but this regenerates a bit too often, so leaving it out for now.
+ ninja.build(out, 'scons', None, deps = sorted(get_dependencies(out, ninja.targets)))
+ continue
+
+ # Install
+ m = re.match('^Install file: "(.*)" as "(.*)"', line)
+ if m :
+ ninja.build(m.group(2), 'install', m.group(1))
+ continue
+
+ m = re.match('^Install directory: "(.*)" as "(.*)"', line)
+ if m :
+ for source in rglob('*', m.group(1)) :
+ if os.path.isdir(source) :
+ continue
+ target = os.path.join(m.group(2), os.path.relpath(source, m.group(1)))
+ ninja.build(target, 'install', source)
+ continue
+
+ # Tools
+ tool, command, flags = parse_tool_command(line)
+ tools[tool] = command[0]
+
+ ############################################################
+ # clang/gcc tools
+ ############################################################
+
+ if tool == 'cc':
+ out, flags = extract_binary_flag("-o", flags)
+ files, flags = extract_non_flags(flags)
+ ninja.build(out, 'cc', files, order_deps = '_generated_headers', ccflags = flags)
+
+ elif tool == 'cxx':
+ out, flags = extract_binary_flag("-o", flags)
+ files, flags = extract_non_flags(flags)
+ ninja.build(out, 'cxx', files, order_deps = '_generated_headers', cxxflags = flags)
+
+ elif tool == 'glink':
+ out, flags = extract_binary_flag("-o", flags)
+ files, flags = extract_non_flags(flags)
+ libs = get_unary_flags('-l', flags)
+ libpaths = get_unary_flags("-L", flags)
+ deps = get_built_libs(libs, libpaths, ninja.targets)
+ ninja.build(out, 'link', files, deps = sorted(deps), linkflags = flags)
+
+ elif tool == 'ar':
+ objects, flags = partition(flags, lambda x: x.endswith('.o'))
+ libs, flags = partition(flags, lambda x: x.endswith('.a'))
+ out = libs[0]
+ ninja.build(out, 'ar', objects, arflags = flags)
+
+ elif tool == 'ranlib':
+ pass
+
+
+ ############################################################
+ # MSVC tools
+ ############################################################
+
+ elif tool == 'cl':
+ out, flags = extract_unary_flag("/Fo", flags)
+ files, flags = extract_non_flags(flags)
+ ninja.build(out, 'cl', files, order_deps = '_generated_headers', clflags = flags)
+
+ elif tool == 'lib':
+ out, flags = extract_unary_flag("/out:", flags)
+ files, flags = extract_non_flags(flags)
+ ninja.build(out, 'lib', files, libflags = flags)
+
+ elif tool == 'link':
+ objects, flags = partition(flags, lambda x: x.endswith('.obj') or x.endswith('.res'))
+ out, flags = extract_unary_flag("/out:", flags)
+ libs, flags = partition(flags, lambda x: not x.startswith("/") and x.endswith(".lib"))
+ libpaths = get_unary_flags("/libpath:", flags)
+ deps = get_built_libs(libs, libpaths, ninja.targets)
+ if out in mtflags :
+ ninja.build(out, 'link_mt', objects, deps = sorted(deps),
+ libs = libs, linkflags = flags, mtflags = mtflags[out])
+ else :
+ ninja.build(out, 'link', objects, deps = sorted(deps),
+ libs = libs, linkflags = flags)
+
+ elif tool == 'rc':
+ out, flags = extract_unary_flag("/fo", flags)
+ files, flags = extract_non_flags(flags)
+ ninja.build(out, 'rc', files[0], order_deps = '_generated_headers', rcflags = flags)
+
+ elif tool == 'mt':
+ # Already handled
+ pass
+
+ ############################################################
+ # Qt tools
+ ############################################################
+
+ elif tool == 'moc':
+ out, flags = extract_binary_flag("-o", flags)
+ files, flags = extract_non_flags(flags)
+ ninja.build(out, 'moc', files, mocflags = flags)
+
+ elif tool == 'uic':
+ out, flags = extract_binary_flag("-o", flags)
+ files, flags = extract_non_flags(flags)
+ ninja.build(out, 'uic', files, uicflags = flags)
+
+ elif tool == 'lrelease':
+ out, flags = extract_binary_flag("-qm", flags)
+ files, flags = extract_non_flags(flags)
+ ninja.build(out, 'lrelease', files, lreleaseflags = flags)
+
+ elif tool == 'rcc':
+ out, flags = extract_binary_flag("-o", flags)
+ name, flags = extract_binary_flag("-name", flags)
+ compress, flags = extract_binary_flag("--compress", flags)
+ threshold, flags = extract_binary_flag("--threshold", flags)
+ files, flags = extract_non_flags(flags)
+ deps = list(set(get_dependencies(out, ninja.targets)) - set(files))
+ ninja.build(out, 'rcc', files, deps = sorted(deps), name = name, rccflags = ["--compress", compress, "--threshold", threshold])
+
+ ############################################################
+ # OS X tools
+ ############################################################
+
+ elif tool == 'ibtool':
+ out, flags = extract_binary_flag("--compile", flags)
+ files, flags = extract_non_flags(flags)
+ ninja.build(out, 'ibtool', files, ibtoolflags = flags)
+
+ elif tool == 'dsymutil':
+ out, flags = extract_binary_flag("-o", flags)
+ files, flags = extract_non_flags(flags)
+ ninja.build(out, 'dsymutil', files, dsymutilflags = flags)
+
+ elif tool == 'sdef' :
+ source = flags[0];
+ outdir, flags = extract_binary_flag("-o", flags)
+ basename, flags = extract_binary_flag("--basename", flags)
+ ninja.build(os.path.join(outdir, basename + ".h"), 'sdef', [source],
+ basename = basename,
+ outdir = outdir)
+
+
+ elif not ninja_custom_command(ninja, line) :
+ raise Exception("Unknown tool: '" + line + "'")
# Phony target for all generated headers, used as an order-only depency from all C/C++ sources
@@ -607,11 +609,11 @@ ninja.header("# This file is generated by " + SCRIPT)
ninja.variable("ninja_required_version", "1.3")
ninja.variable("scons_args", SCONS_ARGS)
for k, v in tools.iteritems() :
- ninja.variable(k, v)
+ ninja.variable(k, v)
# Extra customizations
if 'ninja_post' in dir() :
- ninja_post(ninja)
+ ninja_post(ninja)
################################################################################
diff --git a/COPYING.thirdparty b/COPYING.thirdparty
index be93dbc..0134aaa 100644
--- a/COPYING.thirdparty
+++ b/COPYING.thirdparty
@@ -6,6 +6,10 @@ Copyright (C) 2009-2012 Kevin Smith and Remko Tronçon
Resources
================
+============
+Silk Iconset
+============
+
These projects contain icons from http://www.famfamfam.com/lab/icons/silk/ under Creative Commons Attribution 3.0 License with the following requirements:
As an author, I would appreciate a reference to my authorship of the Silk icon set contents within a readme file or equivalent documentation for the software which includes the set or a subset of the icons contained within.
@@ -68,6 +72,104 @@ The rights granted under, and the subject matter referenced, in this License wer
--- END OF CREATE COMMONS ATTRIBUTION 3.0 LICENSE ---
+=========
+Lato Font
+=========
+
+Copyright (c) 2010-2015, Åukasz Dziedzic (dziedzic@typoland.com),
+with Reserved Font Name Lato.
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
================
Third-party code
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md
new file mode 100644
index 0000000..3e48510
--- /dev/null
+++ b/DEVELOPMENT.md
@@ -0,0 +1,229 @@
+# Swift Development Overview
+## Build System
+It is also possible to set frequently used configuration options in a `config.py`
+file in the project folder.
+Settings of particular interest are:
+- `qt` to set the path to a Qt installation
+- `cc`, `cxx`, `link` to set the C compiler, C++ compiler and linker to use
+- `cxxflags` to set additional flags to pass to the C++ compiler
+- `linkflags` to set additional flags to pass to the linker
+
+If you change anything in the configuration, or install previously missing dependencies, you might need to pass `force-configure=1` to SCons to force it to
+look for the dependencies again and not use cached information.
+
+It is also possible to only build Swiften or Sluift by passing explicit build targets to scons. For example `./scons Swiften` to only build Swiften.
+
+To install the build output on the system, simply run `./scons SWIFTEN_INSTALLDIR=/usr/local /usr/local
+
+Swift is written in cross-platform C++11. It is continuously tested with GCC, Clang and Visual Studio 2013.
+
+## Testing
+Swift has unit and integration tests. To run the unit tests, pass `test=unit`, and to run the integration tests, pass `test=system`, or pass `test=all` to run both.
+
+The integration tests require external setup and parameters to run.
+- `SWIFT_CLIENTTEST_JID=user@domain`
+- `SWIFT_CLIENTTEST_PASS=password`
+- `SWIFT_FILETRANSFERTEST_JID=user@domain`
+- `SWIFT_FILETRANSFERTEST_PASS=password`
+- `SWIFT_FILETRANSFERTEST2_JID=anotheruser@domain`
+- `SWIFT_FILETRANSFERTEST2_PASS=password`
+- `SWIFT_NETWORK_TEST_IPV4=0.0.0.0`
+
+Note: The unit and integration tests are build targets. When passing specific build targets to SCons the tests will not be build and run (even with `test=all`) unless the build targets for the tests are added as arguments to the `scons` call.
+
+## Packaging
+### Mac OS X
+The Mac OS X package consists of a disk image (.dmg) file containing an independently deployable **Swift.app** application bundle.
+
+For creating the Mac OS X package, i.e. the disk image, simply call `./scons.sh dist=1`. To additionally code sign the **Swift.app** application
+bundle, append `codesign_identity="Developer ID Application: Something here"` with your developer certificate identity to the `scons` command.
+
+**WARNING: Code signing has not been tested with third-party signed certificates yet!**
+
+### Windows
+The Windows package consist of a Widnows Installer (.msi) file. This is generated using the Windows Installer XML Toolset.
+
+For packaging use:
+- Microsoft VS 2013 Express
+- WiX
+- Download the C++ redistributable package from Microsoft and put it at `C:\Program Files (x86)\Common Files\Merge Modules\`
+- `config.py` should contain:
+ qt = "c:\\qt\\5.4.2"
+ vcredist = "C:\\Program Files (x86)\\Common Files\\Merge Modules\\vcredist_x86.exe"
+ debug = 1
+ optimize = 1
+ wix_bindir = "c:\\program files\\Windows Installer XML v3.5\\bin"
+- Run the following commands. Two scons runs are required as 'scons dist=1' requires the Swift.exe to be in place.
+```
+scons
+scons dist=1
+```
+
+To sign the resulting MSI file, append the `signtool_key_pfx` and `signtool_timestamp_url` parameters to the `scons dist=1` programm call, e.g.
+`scons dist=1 signtool_key_pfx=C:\Users\Swift\SwiftSPC.pfx signtool_timestamp_url=http://timestamp.verisign.com/scripts/timstamp.dll`.
+
+Notes:
+- The settings `debug = 1` and `optimize = 1` are **strictly required** if you use a precompiled Qt release from the Qt Project; otherwise you will get linker errors
+- On 64-bit Windows it's "Program Files (x86)" instead of "Program Files" in the
+ paths
+- Currently only 32-bit builds of the Swift client are supported
+
+## Automatic Software Updates
+Automatic software updates allow distribution of updates directly to the end users.
+This is useful for general feature updates, bug fixes and especially for security
+updates.
+
+### Automatic Software Updates for Mac OS X using Sparkle
+Swift supports integration with the software update framework [Sparkle](https://sparkle-project.org/) on OS X. For security reasons,
+Sparkle requires the application to be either code-signed or a bundled public DSA
+key. In case you do not code-sign, you can provide the path to the public DSA key
+to be bundled with the application bundle via the `sparkle_public_dsa_key` SCons
+argument.
+
+To build with Sparkle support, simply download Sparkle-1.14.0 and extract it to
+`3rdParty/Sparkle/Sparkle-1.14.0`. SCons will pick it up during configuration
+and build Swift with Sparkle support.
+
+The appcast URLs are specified in `Swift/QtUI/SwiftUpdateFeeds.h`.
+
+## Building Swiften for Android
+This section describes how to build Swiften for Android. It can then be used from any Android native code. This guide has been tested on OS X and Linux.
+
+### Prerequisites
+- Android SDK
+- Android NDK
+- Python
+- Other requirements that are obtained during this guide
+ - LDNS
+ - Unbound
+ - OpenSSL
+
+### Note on Supported Features
+File-transfer support has not been tested on Android. Link-local features are not supported under Android.
+
+### Supported Android NDK Level
+The minimal supported Android NDK API level is 14 (see --platform parameter of make-standalone-toolchain.sh).
+This is the NDK API level associated with Android 4.0. Higher Android NDK API levels however should work.
+
+### Preparation of Build Environment
+1. Fetch 3rd-party dependencies
+ 1. LDNS
+ ```
+ cd 3rdParty/Ldns
+ bash prepare_ldns.sh
+ ```
+ 2. Unbound
+ ```
+ cd 3rdParty/Unbound
+ bash prepare_unbound.sh
+ ```
+
+ 3. OpenSSL
+ ```
+ cd 3rdParty/OpenSSL
+ curl -O http://www.openssl.org/source/openssl-1.0.1j.tar.gz
+ tar -xf openssl-1.0.1j.tar.gz
+ mv openssl-1.0.1j openssl
+ ```
+
+2. Patch 3rd-party dependencies
+ ```
+ patch -p0 < 3rdParty/Ldns/01_andoird_compilation_fixes.diff
+ patch -p1 < 3rdParty/LibMiniUPnPc/01_android_compilation_fixes.diff
+ patch -p1 < 3rdParty/Unbound/01_android_fixes.diff
+ ```
+
+3. Create Android NDK Toolchain
+ ```
+ cd $ANDROID_NDK_ROOT (this is the folder where you extracted Android NDK)
+ bash ./build/tools/make-standalone-toolchain.sh --platform=android-14 --install-dir=$HOME/android-14-tc
+ ```
+
+### Configuring Swift Build
+1. Set config.py to (probably other paths, replace $NDK_TOOLCHAIN_INSTALL_DIR with the expanded path of the install dir used in the previous step):
+```
+android_toolchain=$NDK_TOOLCHAIN_INSTALL_DIR
+android_sdk_bin="/usr/local/bin"
+target = "android"
+unbound = 1
+```
+
+### Building
+Simply run `./scons test=none Swiften QA max_jobs=1`.
+
+### Testing
+Running Swift's test suite on Android requires a one time preparation of a testing environment.
+This creates an Android VM where the test will be deployed to and run on.
+
+1. Preparation of test environment (one time)
+ 1. Starting AVD (Android Device Manager) by running `android avd`
+ 2. Create a test VM by clicking the "Create..." button
+ 3. Fill out dialog
+ - AVD Name: swift_test
+ - Device: Nexus 4
+ - Target: Anything with API level equal or greater than your toolchain you build
+ - CPU/ABI: ARM (unless you build a different toolchain)
+ 4. Click "Ok" button
+ 5. Close AVD
+
+2. Running integration and unit tests
+ To run the unit tests you need to have an Android VM running while the test suite is running.
+ This requires to leave the command under step 2.1 running while you execute step 2.2.
+
+ Running the test suite on Android can take quite some time ( >30 minutes ) compared to a native run.
+ This is due to a) the slow transfer speed from host machine to VM (~ 2 MB/s) and and b) the test environment being emulated for an different CPU architecture.
+
+ 1. Start Android VM with resized /system partition:
+ `emulator -partition-size 2048 @swift_test`
+
+ 2. Run integration and unit tests (wait until the android boot screen is gone)
+ `env SWIFT_CLIENTTEST_JID="some jabber id" SWIFT_CLIENTTEST_PASS="password for the jabber id" ./scons test=all Swiften Swift/Controllers QA`
+
+## Building Swiften for iOS
+### Prerequisites
+- XCode
+- Python
+- Other requirements that are obtained during this guide
+ - OpenSSL
+
+### Supported Components
+- Swiften
+
+ Note: File-transfer support has not been tested on iOS. Link-local features are not supported under iOS.
+- Swift/Controllers
+
+### Preparation of Build Environment
+1. Fetch 3rd-party dependencies
+ 1. OpenSSL
+ ```
+ cd 3rdParty/OpenSSL
+ curl -O http://www.openssl.org/source/openssl-1.0.1j.tar.gz
+ tar -xf openssl-1.0.1j.tar.gz
+ mv openssl-1.0.1j openssl
+ ```
+
+### Building
+1. Switch to iOS directory
+ ```
+ cd BuildTools/iOS
+ ```
+
+2. Look up installed SDKs
+ ```
+ xcodebuild -showsdks
+ ```
+ Note: Here the iOS SDKs and iOS Simulator SDKs are of interest.
+
+3. Build Swiften (adjust the sdk parameter to one of the installed SDKs)
+ ```
+ xcodebuild build -arch i386 -sdk iphonesimulator8.1
+ ```
+
+ Note: When not specifying the architecture (-arch flag) XCode will try an universal build which is not supported.
+
+ Only specify one architecture at a time and if you require a universal lib you can create one using the `lipo` tool.
+
+4. The final libSwiften.a is located at `$SWIFT/build/current/Swiften/libSwiften.a`.
+
+### Testing
+Integration and unit tests are not supported on iOS.
diff --git a/Documentation/API/SConscript b/Documentation/API/SConscript
index df20b27..a8a8b1b 100644
--- a/Documentation/API/SConscript
+++ b/Documentation/API/SConscript
@@ -1,6 +1,6 @@
Import("env")
if "doc" in ARGUMENTS :
- myenv = env.Clone()
- myenv.Tool("DoxyGen", toolpath = ["#/BuildTools/SCons/Tools"])
- myenv.DoxyGen("Doxyfile")
+ myenv = env.Clone()
+ myenv.Tool("DoxyGen", toolpath = ["#/BuildTools/SCons/Tools"])
+ myenv.DoxyGen("Doxyfile")
diff --git a/Documentation/BuildingGenerics.txt b/Documentation/BuildingGenerics.txt
deleted file mode 100644
index 284cf45..0000000
--- a/Documentation/BuildingGenerics.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-To cause scons to search for dependencies instead of using cached results, add force-configure=1 to the commandline:
-scons force-configure=1
-
-Swift is usually built with Qt5. If you want to build it against Qt4, add the line
-qt5 = 0
-to your config.py. However, Qt4 support is no longer actively maintained.
diff --git a/Documentation/BuildingOnAndroid.txt b/Documentation/BuildingOnAndroid.txt
deleted file mode 100644
index 8a29895..0000000
--- a/Documentation/BuildingOnAndroid.txt
+++ /dev/null
@@ -1,97 +0,0 @@
-Prerequisites
--------------
-- Android SDK
-- Android NDK
-- Python
-- Other requirements that are obtained during this guide
- - LDNS
- - Unbound
- - OpenSSL
-
-Supported Components
---------------------
-- Swiften
- Note: File-transfer support has not been tested on Android. Link-local features are not supported under Android.
-
-Supported Android NDK Level
----------------------------
-The minimal supported Android NDK API level is 14 (see --platform parameter of make-standalone-toolchain.sh).
-This is the NDK API level associated with Android 4.0. Higher Android NDK API levels however should work.
-
-Preparation of Build Environment
---------------------------------
-1. Fetch 3rd-party dependencies
-
-1.1 LDNS
- cd 3rdParty/Ldns
- bash prepare_ldns.sh
-
-1.2 Unbound
- cd 3rdParty/Unbound
- bash prepare_unbound.sh
-
-1.3 OpenSSL
- cd 3rdParty/OpenSSL
- curl -O http://www.openssl.org/source/openssl-1.0.1j.tar.gz
- tar -xf openssl-1.0.1j.tar.gz
- mv openssl-1.0.1j openssl
-
-2. Patch 3rd-party dependencies
- patch -p0 < 3rdParty/Ldns/01_andoird_compilation_fixes.diff
- patch -p1 < 3rdParty/LibMiniUPnPc/01_android_compilation_fixes.diff
- patch -p1 < 3rdParty/Unbound/01_android_fixes.diff
-
-3. Create Android NDK Toolchain
- cd $ANDROID_NDK_ROOT (this is the folder where you extracted Android NDK)
- bash ./build/tools/make-standalone-toolchain.sh --platform=android-14 --install-dir=$HOME/android-14-tc
-
-Configuring Swift Build
------------------------
-1. Set config.py to (probably other paths, replace $NDK_TOOLCHAIN_INSTALL_DIR with the expanded path of the install dir used in the previous step):
- > android_toolchain=$NDK_TOOLCHAIN_INSTALL_DIR
- > android_sdk_bin="/usr/local/bin"
- > target = "android"
- > unbound = 1
-
-Building
---------
-./scons test=none Swiften Swift/Controllers QA max_jobs=1
-
-Testing
--------
-Running Swift's test suite on Android requires a one time preparation of a testing environment.
-This creates an Android VM where the test will be deployed to and run on.
-
-1. Preparation of test environment (one time)
-
-1.1 Starting AVD (Android Device Manager)
- android avd
-
-1.2 Create a test VM
- Click "Create..." button
-
-1.3 Fill out dialog
- AVD Name: swift_test
- Device: Nexus 4
- Target: Anything with API level equal or greater than your toolchain you build
- CPU/ABI: ARM (unless you build a different toolchain)
-
- Click "Ok" button
-
-1.4 Close AVD
-
-2. Running integration and unit tests
-
-To run the unit tests you need to have an Android VM running while the test suite is running.
-This requires to leave the command under step 2.1 running while you execute step 2.2.
-
-Running the test suite on Android can take quite some time ( >30 minutes ) compared to a native run.
-This is due to
- a) the slow transfer speed from host machine to VM (~ 2 MB/s) and
- b) the test environment being emulated for an different CPU architecture.
-
-2.1 Start Android VM with resized /system partition
- emulator -partition-size 2048 @swift_test
-
-2.2 Run integration and unit tests (wait until the android boot screen is gone)
- env SWIFT_CLIENTTEST_JID="some jabber id" SWIFT_CLIENTTEST_PASS="password for the jabber id" ./scons test=all Swiften Swift/Controllers QA
diff --git a/Documentation/BuildingOnIOS.txt b/Documentation/BuildingOnIOS.txt
deleted file mode 100644
index e310ca1..0000000
--- a/Documentation/BuildingOnIOS.txt
+++ /dev/null
@@ -1,44 +0,0 @@
-Prerequisites
-------------
-- XCode
-- Python
-- Other requirements that are obtained during this guide
- - OpenSSL
-
-Supported Components
---------------------
-- Swiften
- Note: File-transfer support has not been tested on iOS. Link-local features are not supported under iOS.
-- Swift/Controllers
-
-Preparation of Build Environment
---------------------------------
-1. Fetch 3rd-party dependencies
-
-1.1 OpenSSL
- cd 3rdParty/OpenSSL
- curl -O http://www.openssl.org/source/openssl-1.0.1j.tar.gz
- tar -xf openssl-1.0.1j.tar.gz
- mv openssl-1.0.1j openssl
-
-Building
---------
-1. Switch to iOS directory
- cd BuildTools/IOS
-
-2. Look up installed SDKs
- xcodebuild -showsdks
-
- Note: Here the iOS SDKs and iOS Simulator SDKs are of interest.
-
-3. Build Swiften (adjust the sdk parameter to one of the installed SDKs)
- xcodebuild build -arch i386 -sdk iphonesimulator8.1
-
- Note: When not specifying the architecture (-arch flag) XCode will try an universal build which is not supported.
- Only specify one architecture at a time and if you require a universal lib you can create one using the lipo tool.
-
-4. The final libSwiften.a is located at $SWIFT/build/current/Swiften/libSwiften.a.
-
-Testing
--------
-Integration and unit tests are not supported on iOS.
diff --git a/Documentation/BuildingOnUnix.txt b/Documentation/BuildingOnUnix.txt
deleted file mode 100644
index b9f31ea..0000000
--- a/Documentation/BuildingOnUnix.txt
+++ /dev/null
@@ -1,35 +0,0 @@
-Prerequisites
-------------
-- GCC
-- Python
-- OpenSSL (and development package)
-- Qt Open Source Edition (and development package. Optional; not needed for Swiften)
-
-Building
---------
-- Swift uses Qt5 for the UI and on Unix-like platforms it is automatically detected
- using pkg-config.
- - The dependencies can be installed by running ./BuildTools/InstallSwiftDependencies.sh
-- Run
- ./scons
-- To build only a subdir, add the path as a target to scons. E.g., for Swift:
- ./scons Swift
-
-Running tests
--------------
-If you want to run the unit tests (only interesting if you're doing development work)
-- Run
- ./scons test=unit
- for running the unit tests.
-
-Installing
-----------
-- To install swift in /usr/local, run
- ./scons SWIFT_INSTALLDIR=/usr/local /usr/local
-
-Swiften-only
-------------
-- To compile just Swiften, add Swiften to the end of the scons command
- ./scons Swiften
-- To compile and install only Swiften, use SWIFTEN_INSTALLDIR
- ./scons SWIFTEN_INSTALLDIR=/usr/local /usr/local
diff --git a/Documentation/BuildingOnWindows.txt b/Documentation/BuildingOnWindows.txt
deleted file mode 100644
index d296241..0000000
--- a/Documentation/BuildingOnWindows.txt
+++ /dev/null
@@ -1,66 +0,0 @@
-Prerequisites
-------------
-- Microsoft Visual C++ Express Edition
-- Windows SDK
-- Python (2.5 <= version < 3)
-- OpenSSL
- * OpenSSL is optional - without it the Windows platform crypto will be used
- * Download and extract the Windows binary version of OpenSSL from
- http://www.slproweb.com/products/Win32OpenSSL.html
-- Qt Open Source Edition (optional; not needed for Swiften)
-
-Building Qt for Microsoft Visual C++
-------------------------------------
-- These steps are optional - the pre-packaged Qt is fine
-- From the 'Visual C++' 'Programs' group, launch the Visual C++ command prompt
-- Go to the dir where you installed Qt
-- Configure Qt:
- configure
-- Build Qt:
- nmake
-
-Building Swift
---------------
-- From the 'Visual C++' 'Programs' group, launch the Visual C++ command prompt
-- Go to the Swift source dir
-- Create a file 'config.py' with the following contents, reflecting your local
- setup:
- openssl = "path\to\openssl" #optional
- qt = "path\to\qt"
-- Run 'scons'
-- To build only a subdir, add the path as a target to scons. E.g., for Swift:
- scons Swift
-
-Running tests
--------------
-- Run
- scons test=unit
- for running the unit tests, or
- scons test=all
- for running all tests.
-
-Packaging Swift
----------------
-For packaging use:
-- Microsoft Visual C++ Express 2008 or Microsoft VS 2013 Express
-- No OpenSSL
-- WiX
-- Download the C++ redistributable package from Microsoft and put it at C:\Program Files (x86)\Common Files\Merge Modules\
-- config.py should contain:
- qt = "c:\\qt\\5.4.2"
- vcredist = "C:\\Program Files (x86)\\Common Files\\Merge Modules\\vcredist_x86.exe"
- debug = 1
- optimize = 1
- wix_bindir = "c:\\program files\\Windows Installer XML v3.5\\bin"
-- run the following commands. Two scons runs are required as 'scons dist=1' requires the Swift.exe to be in place.
- scons
- scons dist=1
-
-Notes
------
-- The settings debug = 1 and optimize = 1 are strictly required if you use
- a precompiled Qt release from the Qt Project; otherwise you will get linker
- errors
-- On 64-bit Windows it's "Program Files (x86)" instead of "Program Files" in the
- paths
-- Currently only 32-bit builds of the Swift client are supported
diff --git a/Documentation/SConscript b/Documentation/SConscript
index 161cd83..e2f6393 100644
--- a/Documentation/SConscript
+++ b/Documentation/SConscript
@@ -1,4 +1,4 @@
Import("env")
if env["SCONS_STAGE"] == "build" :
- SConscript(dirs = ["SwiftenDevelopersGuide", "SwiftUserGuide", "API", "SwiftAPI"])
+ SConscript(dirs = ["SwiftenDevelopersGuide", "SwiftUserGuide", "API", "SwiftAPI"])
diff --git a/Documentation/SwiftAPI/SConscript b/Documentation/SwiftAPI/SConscript
index df20b27..a8a8b1b 100644
--- a/Documentation/SwiftAPI/SConscript
+++ b/Documentation/SwiftAPI/SConscript
@@ -1,6 +1,6 @@
Import("env")
if "doc" in ARGUMENTS :
- myenv = env.Clone()
- myenv.Tool("DoxyGen", toolpath = ["#/BuildTools/SCons/Tools"])
- myenv.DoxyGen("Doxyfile")
+ myenv = env.Clone()
+ myenv.Tool("DoxyGen", toolpath = ["#/BuildTools/SCons/Tools"])
+ myenv.DoxyGen("Doxyfile")
diff --git a/Documentation/SwiftUserGuide/SConscript b/Documentation/SwiftUserGuide/SConscript
index 50f60bc..1577b83 100644
--- a/Documentation/SwiftUserGuide/SConscript
+++ b/Documentation/SwiftUserGuide/SConscript
@@ -11,5 +11,5 @@ import sys, re, os.path
################################################################################
if "doc" in ARGUMENTS :
- env.DocBook("Swift Users Guide.xml")
+ env.DocBook("Swift Users Guide.xml")
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 356a115..d928db8 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot2.cpp
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot2.cpp
@@ -1,10 +1,11 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <iostream>
+
#include <boost/bind.hpp>
#include <Swiften/Swiften.h>
@@ -18,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 8334b2f..470753d 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot3.cpp
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot3.cpp
@@ -1,10 +1,11 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <iostream>
+
#include <boost/bind.hpp>
#include <Swiften/Swiften.h>
@@ -13,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 1432677..9ab7864 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot4.cpp
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot4.cpp
@@ -1,11 +1,12 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
//...
#include <iostream>
+
#include <boost/bind.hpp>
#include <Swiften/Swiften.h>
@@ -14,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;
- }
-
- 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 handleConnected() {
+ // Request the roster
+ GetRosterRequest::ref rosterRequest =
+ GetRosterRequest::create(client->getIQRouter());
+ rosterRequest->onResponse.connect(
+ bind(&EchoBot::handleRosterReceived, this, _2));
+ rosterRequest->send();
+ }
- void handleConnected() {
- // Request the roster
- GetRosterRequest::ref rosterRequest =
- GetRosterRequest::create(client->getIQRouter());
- rosterRequest->onResponse.connect(
- bind(&EchoBot::handleRosterReceived, this, _2));
- rosterRequest->send();
- }
+ 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 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 handleMessageReceived(Message::ref message) {
+ // Echo back the incoming message
+ message->setTo(message->getFrom());
+ message->setFrom(JID());
+ client->sendMessage(message);
+ }
- private:
- Client* client;
- ClientXMLTracer* tracer;
- //...
+ 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 ace3b7f..3475a6c 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot5.cpp
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot5.cpp
@@ -1,11 +1,12 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
//...
#include <iostream>
+
#include <boost/bind.hpp>
#include <Swiften/Swiften.h>
@@ -14,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;
- //...
- }
- //...
-
- 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 handleConnected() {
+ // Request the roster
+ GetRosterRequest::ref rosterRequest =
+ GetRosterRequest::create(client->getIQRouter());
+ rosterRequest->onResponse.connect(
+ bind(&EchoBot::handleRosterReceived, this, _2));
+ rosterRequest->send();
+ }
- void handleConnected() {
- // Request the roster
- GetRosterRequest::ref rosterRequest =
- GetRosterRequest::create(client->getIQRouter());
- rosterRequest->onResponse.connect(
- bind(&EchoBot::handleRosterReceived, this, _2));
- rosterRequest->send();
- }
+ 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 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 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;
+ //...
+ 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 609b005..e1d5528 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot6.cpp
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot6.cpp
@@ -1,13 +1,14 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
//...
#include <iostream>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Swiften.h>
@@ -19,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;
+ //...
+ }
+ //...
- ~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);
- }
- }
+ 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 handleConnected() {
- // Request the roster
- GetRosterRequest::ref rosterRequest =
- GetRosterRequest::create(client->getIQRouter());
- rosterRequest->onResponse.connect(
- bind(&EchoBot::handleRosterReceived, this, _2));
- rosterRequest->send();
- }
+ void handleConnected() {
+ // Request the roster
+ GetRosterRequest::ref rosterRequest =
+ GetRosterRequest::create(client->getIQRouter());
+ rosterRequest->onResponse.connect(
+ bind(&EchoBot::handleRosterReceived, this, _2));
+ rosterRequest->send();
+ }
- 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 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());
- //...
- 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 handleMessageReceived(Message::ref message) {
+ //...
+ // Echo back the incoming message
+ message->setTo(message->getFrom());
+ message->setFrom(JID());
+ //...
+ if (!message->getPayload<EchoPayload>()) {
+ std::shared_ptr<EchoPayload> echoPayload = std::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;
+ //...
+ 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 ad51eb9..16d7e4e 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoComponent.cpp
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoComponent.cpp
@@ -1,10 +1,11 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <iostream>
+
#include <boost/bind.hpp>
#include <Swiften/Swiften.h>
@@ -13,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;
+ }
- ~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);
- }
- }
+ 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 handleConnected() {
- }
+ void handleConnected() {
+ }
- void handleMessageReceived(Message::ref message) {
- // Echo back the incoming message
- message->setTo(message->getFrom());
- message->setFrom(jid);
- component->sendMessage(message);
- }
+ 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;
+ 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..faf1080 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadSerializer.h
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadSerializer.h
@@ -1,19 +1,20 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Swiften.h>
#include "EchoPayload.h"
+#include <Swiften/Swiften.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(std::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/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/SConscript b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/SConscript
index 5d27b70..268ab9a 100644
--- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/SConscript
+++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/SConscript
@@ -7,30 +7,11 @@ example_env.UseFlags(example_env["SWIFTEN_DEP_FLAGS"])
# Precompile Swiften header
# This is useful to slightly speed up compilation.
# if example_env["PLATFORM"] == "win32":
-# example_env.WriteVal("Swiften.cpp", example_env.Value("#include <Swiften/Swiften.h>\n"))
-# example_env["PCH"] = example_env.PCH("Swiften.cpp")[0]
-# example_env["PCHSTOP"] = "Swiften/Swiften.h"
+# example_env.WriteVal("Swiften.cpp", example_env.Value("#include <Swiften/Swiften.h>\n"))
+# example_env["PCH"] = example_env.PCH("Swiften.cpp")[0]
+# example_env["PCHSTOP"] = "Swiften/Swiften.h"
for i in range(1,7) :
- example_env.Program("EchoBot" + str(i), ["EchoBot" + str(i) + ".cpp"])
+ example_env.Program("EchoBot" + str(i), ["EchoBot" + str(i) + ".cpp"])
+example_env.Program("EchoBot0x", "EchoBot0x.cpp")
example_env.Program("EchoComponent", "EchoComponent.cpp")
-
-# C++0x
-cpp0x = False
-cpp0x_env = example_env.Clone()
-if env["PLATFORM"] == "win32" :
- if int(env["MSVS_VERSION"].split(".")[0]) >= 10 :
- cpp0x = True
-elif env["PLATFORM"] == "hpux" :
- pass
-elif env["PLATFORM"] == "sunos" :
- pass
-else :
- if env["CCVERSION"].split(".") >= ["4", "5", "0"] :
- # Temporarily disabling c++0x mode because of problems with boost::thread
- # on some platforms
- #cpp0x = True
- cpp0x_env.Replace(CXXFLAGS = [flag for flag in env["CXXFLAGS"] if flag != "-Werror"])
- cpp0x_env.Append(CXXFLAGS = ["-std=c++0x"])
-if cpp0x :
- cpp0x_env.Program("EchoBot0x", "EchoBot0x.cpp")
diff --git a/Documentation/SwiftenDevelopersGuide/SConscript b/Documentation/SwiftenDevelopersGuide/SConscript
index ba0eb0b..ac7c67a 100644
--- a/Documentation/SwiftenDevelopersGuide/SConscript
+++ b/Documentation/SwiftenDevelopersGuide/SConscript
@@ -9,89 +9,89 @@ env.Tool("DocBook", toolpath = ["#/BuildTools/DocBook/SCons"])
import sys, re, os.path
def generateDocBookCode(env, target, source) :
- # Strips empty lines from the beginning & end of a program
- def stripEmptyLines(program) :
- programLines = program.split('\n')
- newProgramLines = []
- inProgram = False
- for line in programLines :
- if not re.match("^\s*$", line) or inProgram :
- inProgram = True
- newProgramLines.append(line)
- return '\n'.join(newProgramLines).rstrip()
+ # Strips empty lines from the beginning & end of a program
+ def stripEmptyLines(program) :
+ programLines = program.split('\n')
+ newProgramLines = []
+ inProgram = False
+ for line in programLines :
+ if not re.match("^\s*$", line) or inProgram :
+ inProgram = True
+ newProgramLines.append(line)
+ return '\n'.join(newProgramLines).rstrip()
- def createCallouts(program, calloutPrefix) :
- newProgramLines = []
- calloutLines = []
- nextID = 0
- for line in program.split("\n") :
- # FIXME: Takes the largest match
- m = re.match(".*\/* \(\*\) (.*) \*/.*", line)
- if m :
- cobID = "cob-" + calloutPrefix + "-" + str(nextID)
- coID = "co-" + calloutPrefix + "-" + str(nextID)
- nextID += 1
- line = re.sub("/\*.*\*/", "]]><co id=\"%(cobID)s\" linkends=\"%(coID)s\"/><![CDATA[" % {"cobID" : cobID, "coID" : coID}, line)
- calloutLines.append("<callout arearefs=\"%(cobID)s\" id=\"%(coID)s\"><para>%(text)s</para></callout>" % {"cobID": cobID, "coID": coID, "text": m.group(1)})
- newProgramLines.append(line)
- callouts = ""
- if len(calloutLines) > 0 :
- callouts = "<calloutlist>" + "\n".join(calloutLines) + "</calloutlist>"
- return ("\n".join(newProgramLines), callouts)
+ def createCallouts(program, calloutPrefix) :
+ newProgramLines = []
+ calloutLines = []
+ nextID = 0
+ for line in program.split("\n") :
+ # FIXME: Takes the largest match
+ m = re.match(".*\/* \(\*\) (.*) \*/.*", line)
+ if m :
+ cobID = "cob-" + calloutPrefix + "-" + str(nextID)
+ coID = "co-" + calloutPrefix + "-" + str(nextID)
+ nextID += 1
+ line = re.sub("/\*.*\*/", "]]><co id=\"%(cobID)s\" linkends=\"%(coID)s\"/><![CDATA[" % {"cobID" : cobID, "coID" : coID}, line)
+ calloutLines.append("<callout arearefs=\"%(cobID)s\" id=\"%(coID)s\"><para>%(text)s</para></callout>" % {"cobID": cobID, "coID": coID, "text": m.group(1)})
+ newProgramLines.append(line)
+ callouts = ""
+ if len(calloutLines) > 0 :
+ callouts = "<calloutlist>" + "\n".join(calloutLines) + "</calloutlist>"
+ return ("\n".join(newProgramLines), callouts)
- # Parse program
- filename = source[0].abspath
- filenameBase = os.path.basename(filename).replace(".cpp", "")
- inputfile = open(filename)
- program = ""
- programs = {}
- programName = ""
- inEllipsis = False
- for line in inputfile.readlines() :
- if inEllipsis :
- if "//..." in line :
- inEllipsis = False
- else :
- if line.startswith("/*") or line.startswith(" *") :
- continue
- if "//..." in line :
- inEllipsis = True
- line = line.replace("//...", "]]>&#x2026;<![CDATA[")
- else :
- m = re.match("^/// (.*)", line)
- if m :
- if programName :
- programs[programName] = program
- program = ""
- programName = m.group(1).strip().replace(" ", "")
- continue
- line = re.sub("\t", " ", line)
- program += line
- programs[programName] = program
- inputfile.close()
+ # Parse program
+ filename = source[0].abspath
+ filenameBase = os.path.basename(filename).replace(".cpp", "")
+ inputfile = open(filename)
+ program = ""
+ programs = {}
+ programName = ""
+ inEllipsis = False
+ for line in inputfile.readlines() :
+ if inEllipsis :
+ if "//..." in line :
+ inEllipsis = False
+ else :
+ if line.startswith("/*") or line.startswith(" *") :
+ continue
+ if "//..." in line :
+ inEllipsis = True
+ line = line.replace("//...", "]]>&#x2026;<![CDATA[")
+ else :
+ m = re.match("^/// (.*)", line)
+ if m :
+ if programName :
+ programs[programName] = program
+ program = ""
+ programName = m.group(1).strip().replace(" ", "")
+ continue
+ line = re.sub("\t", " ", line)
+ program += line
+ programs[programName] = program
+ inputfile.close()
- for programName, program in programs.items() :
- program = stripEmptyLines(program)
- (program, callouts) = createCallouts(program, filenameBase + "-" + programName)
+ for programName, program in programs.items() :
+ program = stripEmptyLines(program)
+ (program, callouts) = createCallouts(program, filenameBase + "-" + programName)
- document = "<foo><programlisting><![CDATA[" + program + "]]></programlisting>" + callouts + "</foo>"
+ document = "<foo><programlisting><![CDATA[" + program + "]]></programlisting>" + callouts + "</foo>"
- # Generate code
- output = open(target[0].abspath, 'w')
- output.write(document)
- output.close()
+ # Generate code
+ output = open(target[0].abspath, 'w')
+ output.write(document)
+ output.close()
################################################################################
if "doc" in ARGUMENTS :
- env.DocBook("Swiften Developers Guide.xml")
+ env.DocBook("Swiften Developers Guide.xml")
sources = []
for i in range(1, 7) :
- sources.append("Examples/EchoBot/EchoBot" + str(i) + ".cpp")
+ sources.append("Examples/EchoBot/EchoBot" + str(i) + ".cpp")
sources.append("Examples/EchoBot/EchoBot0x.cpp")
sources += ["Examples/EchoBot/" + i for i in ["EchoPayloadParserFactory.h", "EchoPayloadSerializer.h", "EchoPayload.h", "EchoComponent.cpp"]]
for source in sources :
- env.Command(source + ".xml", source, Action(generateDocBookCode, cmdstr = "$GENCOMSTR"))
+ env.Command(source + ".xml", source, Action(generateDocBookCode, cmdstr = "$GENCOMSTR"))
SConscript(dirs = ["Examples"])
diff --git a/Limber/SConscript b/Limber/SConscript
index 13bc0df..7aca509 100644
--- a/Limber/SConscript
+++ b/Limber/SConscript
@@ -1,30 +1,30 @@
Import("env")
if env["SCONS_STAGE"] == "flags" :
- env["LIMBER_FLAGS"] = {
- "LIBPATH": [Dir(".")],
- "LIBS": ["Limber"],
- }
+ env["LIMBER_FLAGS"] = {
+ "LIBPATH": [Dir(".")],
+ "LIBS": ["Limber"],
+ }
elif env["SCONS_STAGE"] == "build" :
- libenv = env.Clone()
- libenv.UseFlags(env["SWIFTEN_FLAGS"])
- libenv.UseFlags(env["SWIFTEN_DEP_FLAGS"])
- libenv.StaticLibrary("Limber", [
- "Server/ServerFromClientSession.cpp",
- "Server/ServerSession.cpp",
- "Server/ServerStanzaRouter.cpp",
- "Server/SimpleUserRegistry.cpp",
- "Server/UserRegistry.cpp",
- ])
+ libenv = env.Clone()
+ libenv.UseFlags(env["SWIFTEN_FLAGS"])
+ libenv.UseFlags(env["SWIFTEN_DEP_FLAGS"])
+ libenv.StaticLibrary("Limber", [
+ "Server/ServerFromClientSession.cpp",
+ "Server/ServerSession.cpp",
+ "Server/ServerStanzaRouter.cpp",
+ "Server/SimpleUserRegistry.cpp",
+ "Server/UserRegistry.cpp",
+ ])
- myenv = env.Clone()
- myenv.BuildVersion("BuildVersion.h", project = "limber")
- myenv.UseFlags(env["LIMBER_FLAGS"])
- myenv.UseFlags(env["SWIFTEN_FLAGS"])
- myenv.UseFlags(env["SWIFTEN_DEP_FLAGS"])
- myenv.Program("limber", ["main.cpp"])
+ myenv = env.Clone()
+ myenv.BuildVersion("BuildVersion.h", project = "limber")
+ myenv.UseFlags(env["LIMBER_FLAGS"])
+ myenv.UseFlags(env["SWIFTEN_FLAGS"])
+ myenv.UseFlags(env["SWIFTEN_DEP_FLAGS"])
+ myenv.Program("limber", ["main.cpp"])
- env.Append(UNITTEST_SOURCES = [
- File("Server/UnitTest/ServerStanzaRouterTest.cpp"),
- ])
+ env.Append(UNITTEST_SOURCES = [
+ File("Server/UnitTest/ServerStanzaRouterTest.cpp"),
+ ])
diff --git a/Limber/Server/ServerFromClientSession.cpp b/Limber/Server/ServerFromClientSession.cpp
index 052ea9b..f2a3659 100644
--- a/Limber/Server/ServerFromClientSession.cpp
+++ b/Limber/Server/ServerFromClientSession.cpp
@@ -1,119 +1,121 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Limber/Server/ServerFromClientSession.h"
+#include <Limber/Server/ServerFromClientSession.h>
+
+#include <memory>
-#include <boost/smart_ptr/make_shared.hpp>
#include <boost/bind.hpp>
-#include "Swiften/Elements/ProtocolHeader.h"
-#include "Limber/Server/UserRegistry.h"
-#include "Swiften/Network/Connection.h"
-#include "Swiften/StreamStack/XMPPLayer.h"
-#include "Swiften/Elements/StreamFeatures.h"
-#include "Swiften/Elements/ResourceBind.h"
-#include "Swiften/Elements/StartSession.h"
-#include "Swiften/Elements/IQ.h"
-#include "Swiften/Elements/AuthSuccess.h"
-#include "Swiften/Elements/AuthFailure.h"
-#include "Swiften/Elements/AuthRequest.h"
-#include "Swiften/SASL/PLAINMessage.h"
+#include <Swiften/Elements/AuthFailure.h>
+#include <Swiften/Elements/AuthRequest.h>
+#include <Swiften/Elements/AuthSuccess.h>
+#include <Swiften/Elements/IQ.h>
+#include <Swiften/Elements/ProtocolHeader.h>
+#include <Swiften/Elements/ResourceBind.h>
+#include <Swiften/Elements/StartSession.h>
+#include <Swiften/Elements/StreamFeatures.h>
+#include <Swiften/Network/Connection.h>
+#include <Swiften/SASL/PLAINMessage.h>
+#include <Swiften/StreamStack/XMPPLayer.h>
+
+#include <Limber/Server/UserRegistry.h>
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,
+ std::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();
- }
- }
- }
+void ServerFromClientSession::handleElement(std::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(std::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(std::make_shared<AuthSuccess>());
+ user_ = plainMessage.getAuthenticationID();
+ authenticated_ = true;
+ getXMPPLayer()->resetParser();
+ }
+ else {
+ getXMPPLayer()->writeElement(std::shared_ptr<AuthFailure>(new AuthFailure));
+ finishSession(AuthenticationFailedError);
+ }
+ }
+ }
+ else {
+ getXMPPLayer()->writeElement(std::shared_ptr<AuthFailure>(new AuthFailure));
+ finishSession(NoSupportedAuthMechanismsError);
+ }
+ }
+ else if (IQ* iq = dynamic_cast<IQ*>(element.get())) {
+ if (std::shared_ptr<ResourceBind> resourceBind = iq->getPayload<ResourceBind>()) {
+ setRemoteJID(JID(user_, getLocalJID().getDomain(), resourceBind->getResource()));
+ std::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);
+ std::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 8b03569..6aea194 100644
--- a/Limber/Server/ServerFromClientSession.h
+++ b/Limber/Server/ServerFromClientSession.h
@@ -1,62 +1,62 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/enable_shared_from_this.hpp>
+#include <memory>
#include <string>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/Session/Session.h>
+#include <boost/signals2.hpp>
+
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/JID/JID.h>
#include <Swiften/Network/Connection.h>
-#include <Swiften/Base/ByteArray.h>
+#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,
+ std::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory,
+ UserRegistry* userRegistry);
+
+ boost::signals2::signal<void ()> onSessionStarted;
+ void setAllowSASLEXTERNAL();
+
+ private:
+ void handleElement(std::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.cpp b/Limber/Server/ServerSession.cpp
index 5f07619..a18a60f 100644
--- a/Limber/Server/ServerSession.cpp
+++ b/Limber/Server/ServerSession.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Limber/Server/ServerSession.h"
+#include <Limber/Server/ServerSession.h>
namespace Swift {
diff --git a/Limber/Server/ServerSession.h b/Limber/Server/ServerSession.h
index 4296e16..0b39d7c 100644
--- a/Limber/Server/ServerSession.h
+++ b/Limber/Server/ServerSession.h
@@ -1,23 +1,23 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#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(std::shared_ptr<Stanza>) = 0;
+ };
}
diff --git a/Limber/Server/ServerStanzaRouter.cpp b/Limber/Server/ServerStanzaRouter.cpp
index 02ddb4d..b7ccca8 100644
--- a/Limber/Server/ServerStanzaRouter.cpp
+++ b/Limber/Server/ServerStanzaRouter.cpp
@@ -1,74 +1,76 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Limber/Server/ServerStanzaRouter.h"
-#include "Limber/Server/ServerSession.h"
+#include <Limber/Server/ServerStanzaRouter.h>
-#include <cassert>
#include <algorithm>
+#include <cassert>
+
#include <Swiften/Base/Algorithm.h>
+#include <Limber/Server/ServerSession.h>
+
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());
+bool ServerStanzaRouter::routeStanza(std::shared_ptr<Stanza> stanza) {
+ 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 5f0ad31..04192ba 100644
--- a/Limber/Server/ServerStanzaRouter.h
+++ b/Limber/Server/ServerStanzaRouter.h
@@ -1,30 +1,30 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
#include <map>
+#include <memory>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/Stanza.h>
+#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(std::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 2fb2d9e..4f39030 100644
--- a/Limber/Server/SimpleUserRegistry.cpp
+++ b/Limber/Server/SimpleUserRegistry.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Limber/Server/SimpleUserRegistry.h"
+#include <Limber/Server/SimpleUserRegistry.h>
namespace Swift {
@@ -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 bcf194d..9963b2c 100644
--- a/Limber/Server/SimpleUserRegistry.h
+++ b/Limber/Server/SimpleUserRegistry.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,22 +7,23 @@
#pragma once
#include <map>
+#include <string>
#include <Swiften/JID/JID.h>
-#include <string>
-#include "Limber/Server/UserRegistry.h"
+
+#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();
+
+ 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;
- };
+ private:
+ std::map<JID, SafeByteArray> users;
+ };
}
diff --git a/Limber/Server/UnitTest/ServerStanzaRouterTest.cpp b/Limber/Server/UnitTest/ServerStanzaRouterTest.cpp
index a300b85..5f34d92 100644
--- a/Limber/Server/UnitTest/ServerStanzaRouterTest.cpp
+++ b/Limber/Server/UnitTest/ServerStanzaRouterTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,144 +7,145 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include "Swiften/Elements/Message.h"
-#include "Limber/Server/ServerStanzaRouter.h"
-#include "Limber/Server/ServerSession.h"
+#include <Swiften/Elements/Message.h>
+
+#include <Limber/Server/ServerSession.h>
+#include <Limber/Server/ServerStanzaRouter.h>
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:
+ std::shared_ptr<Message> createMessageTo(const std::string& recipient) {
+ std::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(std::shared_ptr<Stanza> stanza) {
+ sentStanzas.push_back(stanza);
+ }
+
+ JID jid;
+ int priority;
+ std::vector< std::shared_ptr<Stanza> > sentStanzas;
+ };
};
CPPUNIT_TEST_SUITE_REGISTRATION(ServerStanzaRouterTest);
diff --git a/Limber/Server/UserRegistry.cpp b/Limber/Server/UserRegistry.cpp
index 51e5129..bd5d189 100644
--- a/Limber/Server/UserRegistry.cpp
+++ b/Limber/Server/UserRegistry.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Limber/Server/UserRegistry.h"
+#include <Limber/Server/UserRegistry.h>
namespace Swift {
diff --git a/Limber/Server/UserRegistry.h b/Limber/Server/UserRegistry.h
index d7da38b..98b3e99 100644
--- a/Limber/Server/UserRegistry.h
+++ b/Limber/Server/UserRegistry.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,15 +7,16 @@
#pragma once
#include <string>
+
#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 9c060ad..26cb8d6 100644
--- a/Limber/main.cpp
+++ b/Limber/main.cpp
@@ -1,104 +1,106 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
#include <string>
+
#include <boost/bind.hpp>
-#include <boost/shared_ptr.hpp>
-#include "Swiften/Elements/IQ.h"
-#include "Swiften/Elements/RosterPayload.h"
-#include "Swiften/Elements/VCard.h"
-#include "Swiften/Base/IDGenerator.h"
-#include "Swiften/EventLoop/EventLoop.h"
-#include "Swiften/EventLoop/SimpleEventLoop.h"
-#include "Swiften/EventLoop/EventOwner.h"
-#include "Swiften/Elements/Stanza.h"
-#include "Swiften/Network/ConnectionServer.h"
-#include "Swiften/Network/BoostConnection.h"
-#include "Swiften/Network/BoostIOServiceThread.h"
-#include "Swiften/Network/BoostConnectionServer.h"
-#include "Limber/Server/SimpleUserRegistry.h"
-#include "Limber/Server/ServerFromClientSession.h"
-#include "Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h"
-#include "Swiften/Parser/PlatformXMLParserFactory.h"
-#include "Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h"
+#include <Swiften/Base/IDGenerator.h>
+#include <Swiften/Elements/IQ.h>
+#include <Swiften/Elements/RosterPayload.h>
+#include <Swiften/Elements/Stanza.h>
+#include <Swiften/Elements/VCard.h>
+#include <Swiften/EventLoop/EventLoop.h>
+#include <Swiften/EventLoop/EventOwner.h>
+#include <Swiften/EventLoop/SimpleEventLoop.h>
+#include <Swiften/Network/BoostConnection.h>
+#include <Swiften/Network/BoostConnectionServer.h>
+#include <Swiften/Network/BoostIOServiceThread.h>
+#include <Swiften/Network/ConnectionServer.h>
+#include <Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h>
+#include <Swiften/Parser/PlatformXMLParserFactory.h>
+#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+
+#include <Limber/Server/ServerFromClientSession.h>
+#include <Limber/Server/SimpleUserRegistry.h>
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(std::shared_ptr<Connection> c) {
+ std::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(std::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(std::shared_ptr<ToplevelElement> element, std::shared_ptr<ServerFromClientSession> session) {
+ std::shared_ptr<Stanza> stanza(std::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 (std::shared_ptr<IQ> iq = std::dynamic_pointer_cast<IQ>(stanza)) {
+ if (iq->getPayload<RosterPayload>()) {
+ session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), std::make_shared<RosterPayload>()));
+ }
+ if (iq->getPayload<VCard>()) {
+ if (iq->getType() == IQ::Get) {
+ std::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_;
+ std::shared_ptr<BoostConnectionServer> serverFromClientConnectionServer_;
+ std::vector< std::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..4b43635 100644
--- a/QA/Checker/IO.cpp
+++ b/QA/Checker/IO.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 (unsigned char i : s) {
+ 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 (unsigned char i : s) {
+ 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 (int i : s) {
+ 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 (size_t i : s) {
+ 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/SConscript b/QA/Checker/SConscript
index 13dec62..f8a3ce4 100644
--- a/QA/Checker/SConscript
+++ b/QA/Checker/SConscript
@@ -1,17 +1,23 @@
+import os
+
Import("env")
if env["TEST"] :
- if env["SCONS_STAGE"] == "flags" :
- env["CHECKER_FLAGS"] = {
- "CPPPATH" : ["#/3rdParty/HippoMocks"],
- "LIBS": ["Checker"],
- "LIBPATH": [Dir(".")],
- "LINKFLAGS": env["PLATFORM"] == "win32" and ["/SUBSYSTEM:CONSOLE"] or []
- }
+ if env["SCONS_STAGE"] == "flags" :
+ env["CHECKER_FLAGS"] = {
+ "LIBS": ["Checker"],
+ "LIBPATH": [Dir(".")],
+ "LINKFLAGS": env["PLATFORM"] == "win32" and ["/SUBSYSTEM:CONSOLE"] or []
+ }
+
+ if os.path.basename(env["CC"]) in ("clang", "gcc"):
+ env["CHECKER_FLAGS"]["CPPFLAGS"] = ["-isystem" + Dir("#/3rdParty/HippoMocks").abspath]
+ else :
+ env["CHECKER_FLAGS"]["CPPPATH"] = ["#/3rdParty/HippoMocks"]
- if env["SCONS_STAGE"] == "build" :
- checker_env = env.Clone()
- checker_env.UseFlags(env["SWIFTEN_FLAGS"])
- checker_env.UseFlags(env["BOOST_FLAGS"])
- checker_env.UseFlags(env["CPPUNIT_FLAGS"])
- checker_env.Library("Checker", ["checker.cpp", "IO.cpp"])
+ if env["SCONS_STAGE"] == "build" :
+ checker_env = env.Clone()
+ checker_env.UseFlags(env["SWIFTEN_FLAGS"])
+ checker_env.UseFlags(env["BOOST_FLAGS"])
+ checker_env.UseFlags(env["CPPUNIT_FLAGS"])
+ checker_env.Library("Checker", ["checker.cpp", "IO.cpp"])
diff --git a/QA/Checker/checker.cpp b/QA/Checker/checker.cpp
index 2cb00d3..f1186cc 100644
--- a/QA/Checker/checker.cpp
+++ b/QA/Checker/checker.cpp
@@ -1,86 +1,87 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <string>
-#include <cppunit/ui/text/TestRunner.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <cppunit/XmlOutputter.h>
-#include <cppunit/TextTestResult.h>
+
#include <cppunit/BriefTestProgressListener.h>
-#include <cppunit/TextTestProgressListener.h>
#include <cppunit/TextOutputter.h>
+#include <cppunit/TextTestProgressListener.h>
+#include <cppunit/TextTestResult.h>
+#include <cppunit/XmlOutputter.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <cppunit/ui/text/TestRunner.h>
#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/CrossDistributionTest/VagrantCrossDistributionTest.py b/QA/CrossDistributionTest/VagrantCrossDistributionTest.py
new file mode 100755
index 0000000..3530fe5
--- /dev/null
+++ b/QA/CrossDistributionTest/VagrantCrossDistributionTest.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python
+
+# Required Python libraries:
+#
+# pip install python-vagrant tqdm
+#
+# Purpose of this script:
+#
+# This script tests
+# a) InstallSwiftDependencies.sh installs all required packages for Swift and Swiften on system and
+# b) all Swift projects build successfully on the system and their tests pass.
+
+from tqdm import tqdm
+from time import sleep
+import sys
+import vagrant
+
+testSystems = [
+ "bento/ubuntu-16.04",
+ "bento/ubuntu-15.04",
+ "bento/debian-8.5",
+ "bento/opensuse-leap-42.1",
+ "bento/fedora-24",
+ "Sabayon/spinbase-amd64"
+]
+
+progressBar = tqdm(testSystems)
+
+successfulSystems = []
+failedSystems = []
+
+for testSystem in progressBar :
+ v = vagrant.Vagrant(quiet_stdout=False)
+ try :
+ progressBar.set_description("create Vagrantfile for %s" % testSystem)
+ with open('Vagrantfile', 'w') as vagrantfile :
+ vagrantfile.write("""
+Vagrant.configure("2") do |config|
+ config.vm.box = "%s"
+
+ config.ssh.insert_key = false
+
+ config.vm.provider "virtualbox" do |v|
+ v.memory = 4096
+ v.cpus = 2
+ end
+
+ # This is needed because Fedora only comes with Python 3 and Ansible needs Python 2
+ # on the target system for some features.
+ if config.vm.box.include? "fedora"
+ config.vm.provision "shell", inline: "sudo dnf install -y python2 python2-dnf libselinux-python"
+ end
+
+ if config.vm.box.include? "Sabayon"
+ config.vm.provision "shell", inline: "sudo equo update && sudo env ACCEPT_LICENSE=* equo install dev-vcs/git sys-apps/lsb-release"
+ end
+
+ config.vm.synced_folder "../..", "/home/vagrant/swift-host", type: "rsync"
+ config.vm.synced_folder ".", "/vagrant", type: "rsync"
+
+ config.vm.provision "ansible" do |ansible|
+ #ansible.verbose = "vvv"
+ ansible.playbook = "playbook.yml"
+ end
+end""" % testSystem)
+
+ progressBar.set_description("vagrant up")
+ v.up(testSystem, provision=True )
+
+ progressBar.set_description("start building swift on %s" % testSystem)
+ # unset QTDIR is needed, because Fedora 24 sets QTDIR to Qt 3, even though Qt 5 is installed.
+ # SCons will pick up the Qt installation from QTDIR if QTDIR is set.
+ v._call_vagrant_command(["ssh", "-c", "cd /home/vagrant/swift && unset QTDIR && ./scons test=unit -j 2"])
+
+ progressBar.set_description("vagrant destory %s" % testSystem)
+ v.destroy()
+ successfulSystems.append(testSystem)
+ except :
+ e = sys.exc_info()[0]
+ print("Exception: %s" % e)
+ progressBar.set_description("vagrant destory %s" % testSystem)
+ v.destroy()
+ failedSystems.append(testSystem)
+
+for system in successfulSystems:
+ print("SUCCESS: %s" % system)
+for system in failedSystems:
+ print("FAILED: %s" % system)
+
+exit(len(failedSystems)) \ No newline at end of file
diff --git a/QA/CrossDistributionTest/playbook.yml b/QA/CrossDistributionTest/playbook.yml
new file mode 100644
index 0000000..aa4b8f5
--- /dev/null
+++ b/QA/CrossDistributionTest/playbook.yml
@@ -0,0 +1,33 @@
+- hosts: all
+ tasks:
+ - name: Install required packages via apt
+ apt: name=git state=latest update_cache=yes
+ become: true
+ when: ansible_distribution == 'Debian' or ansible_distribution == 'Ubuntu'
+ - name: Install required packages via dnf
+ dnf: name={{item}} state=latest
+ with_items:
+ - git
+ - redhat-lsb
+ become: true
+ when: ansible_distribution == 'CentOS' or ansible_distribution == 'Red Hat Enterprise Linux' or ansible_distribution == 'RedHat' or ansible_distribution == 'Fedora'
+ - name: 'Install required packages via zypper'
+ zypper: name={{item}} state=latest
+ with_items:
+ - git-core
+ - lsb-release
+ become: true
+ when: ansible_distribution == 'openSUSE Leap'
+ - name: Clone git from host working directory
+ git: repo=/home/vagrant/swift-host dest=/home/vagrant/swift
+
+ - name: 'Install Swift dependencies for openSUSE Leap'
+ shell: ./BuildTools/InstallSwiftDependencies.sh --non-interactive chdir=/home/vagrant/swift
+ become: true
+ when: ansible_distribution == 'openSUSE Leap'
+ - name: 'Install Swift dependencies'
+ environment:
+ ACCEPT_LICENSE: '*'
+ shell: yes | ./BuildTools/InstallSwiftDependencies.sh chdir=/home/vagrant/swift
+ become: true
+ when: ansible_distribution != 'openSUSE Leap'
diff --git a/QA/SConscript b/QA/SConscript
index 5c626e3..b4125cf 100644
--- a/QA/SConscript
+++ b/QA/SConscript
@@ -1,4 +1,4 @@
SConscript(dirs = [
- "Checker",
- "UnitTest"
- ])
+ "Checker",
+ "UnitTest"
+ ])
diff --git a/QA/UnitTest/SConscript b/QA/UnitTest/SConscript
index 0cacc7c..1874f99 100644
--- a/QA/UnitTest/SConscript
+++ b/QA/UnitTest/SConscript
@@ -3,27 +3,27 @@ import os
Import("env")
if env["TEST"] :
- if env["SCONS_STAGE"] == "flags" :
- env["UNITTEST_SOURCES"] = []
- env["UNITTEST_OBJECTS"] = []
- if env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
- myenv.UseFlags(env.get("CHECKER_FLAGS",""))
- myenv.UseFlags(env.get("INJECTED_UNITTEST_FLAGS","")) # So things that piggy-back our build system can piggy-back our test system too
- myenv.UseFlags(env.get("SLIMBER_FLAGS",""))
- myenv.UseFlags(env.get("SWIFT_CONTROLLERS_FLAGS",""))
- myenv.UseFlags(env.get("SWIFTOOLS_FLAGS",""))
- myenv.UseFlags(env.get("LIMBER_FLAGS",""))
- myenv.UseFlags(env.get("SWIFTEN_FLAGS",""))
- myenv.UseFlags(env.get("CPPUNIT_FLAGS",""))
- myenv.UseFlags(env.get("SWIFTEN_DEP_FLAGS", ""))
- if env.get("HAVE_LIBXML") :
- myenv.Append(CPPDEFINES = ["HAVE_LIBXML"])
- if env.get("HAVE_EXPAT") :
- myenv.Append(CPPDEFINES = ["HAVE_EXPAT"])
- if env["TEST_CREATE_LIBRARIES"] :
- lib = myenv.StaticLibrary("Swift_UnitTests", env["UNITTEST_SOURCES"] + env["UNITTEST_OBJECTS"])
- myenv.Program("checker", lib)
- else :
- checker = myenv.Program("checker", env["UNITTEST_SOURCES"] + env["UNITTEST_OBJECTS"])
- myenv.Test(checker, is_checker = True)
+ if env["SCONS_STAGE"] == "flags" :
+ env["UNITTEST_SOURCES"] = []
+ env["UNITTEST_OBJECTS"] = []
+ if env["SCONS_STAGE"] == "build" :
+ myenv = env.Clone()
+ myenv.UseFlags(env.get("CHECKER_FLAGS",""))
+ myenv.UseFlags(env.get("INJECTED_UNITTEST_FLAGS","")) # So things that piggy-back our build system can piggy-back our test system too
+ myenv.UseFlags(env.get("SLIMBER_FLAGS",""))
+ myenv.UseFlags(env.get("SWIFT_CONTROLLERS_FLAGS",""))
+ myenv.UseFlags(env.get("SWIFTOOLS_FLAGS",""))
+ myenv.UseFlags(env.get("LIMBER_FLAGS",""))
+ myenv.UseFlags(env.get("SWIFTEN_FLAGS",""))
+ myenv.UseFlags(env.get("CPPUNIT_FLAGS",""))
+ myenv.UseFlags(env.get("SWIFTEN_DEP_FLAGS", ""))
+ if env.get("HAVE_LIBXML") :
+ myenv.Append(CPPDEFINES = ["HAVE_LIBXML"])
+ if env.get("HAVE_EXPAT") :
+ myenv.Append(CPPDEFINES = ["HAVE_EXPAT"])
+ if env["TEST_CREATE_LIBRARIES"] :
+ lib = myenv.StaticLibrary("Swift_UnitTests", env["UNITTEST_SOURCES"] + env["UNITTEST_OBJECTS"])
+ myenv.Program("checker", lib)
+ else :
+ checker = myenv.Program("checker", env["UNITTEST_SOURCES"] + env["UNITTEST_OBJECTS"])
+ myenv.Test(checker, is_checker = True)
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/README.md b/README.md
new file mode 100644
index 0000000..d67dc74
--- /dev/null
+++ b/README.md
@@ -0,0 +1,86 @@
+# Swift - An elegant, secure, adaptable and intuitive XMPP Client
+
+__NOTE: Please download any releases from https://swift.im/releases.html, or as a Git checkout. The tarballs provided by GitHub will not build correctly.__
+
+## Quick Start
+Simply run `./scons Swift` on Linux, or `./scons Swift qt=/Users/username/Qt_installation_path/Qt/5.4.2/5.4/clang_64` on Mac OS X or `scons.bat Swift qt=C:\path\to\qt` on Windows to build Swift.
+
+This document only covers the general structure, project dependencies and building the Swift GUI application.
+More detailed information on building components, development, testing and packaging can be found in DEVELOPMENT.md.
+
+## Components
+* Swiften: A cross-platform C++ XMPP library.
+* Swift: A Qt-based cross-platform desktop GUI client based on Swiften.
+* Sluift: A XMPP scripting environment based on Lua and Swiften.
+* Limber: A XMPP proxy server proxying zero-configuration (XEP-0174) to a
+connected XMPP client.
+* Slimber: Qt and Cocoa frontends for Limber.
+* SwiftTools: A collection of utilities for Swift.
+
+## Supported Platforms
+Swift is known to work on Windows, Mac OS X, Linux and other Unix-like systems. However, we do not test the whole range of operating systems, especailly the huge amount of Linux and Unix-like systems.
+Swiften further has support for Android and iOS.
+
+Platforms we officially test our releases on are listed below. We only test on default configurations and default desktops environments on Linux distributions.
+
+* Swift
+ * Windows 7 to Windows 10
+ * Mac OS X 10.10 and Mac OS X 10.11
+ * Ubuntu 14.04 ( Trusty Tahr ) and Ubuntu 16.04 ( Xenial Xerus )
+ * Debian 8 ( jessie )
+
+## External Dependencies
+The Swift repository includes some third party dependencies in the 3rdParty directory
+to easy development. Third party dependencies not included are listed below:
+
+* OpenSSL is required when building Swiften on Linux or Android
+* Qt 5 is required by Swift; **Qt up to version Qt 5.5 is supported**
+* Python (2.5 <= version < 3)
+
+## General Build Instructions
+The Swift projects use the SCons build system for build configuration and Build
+execution. SCons is one of the included third party dependencies.
+
+To build all Swift components simply run SCons. On Mac OS X and Linux you run the `./scons` command. On Windows you run the `scons.bat` command in a Visual Studio developer shell.
+
+On multi-processor systems, i.e. most desktop and server machines, you can use the `-j NUMBER_OF_PARALLEL_TASKS` flag, or pass the `max_jobs=1` to the `scons` command to speed up build time. The `max_jobs=1` argument will set the number of parallel tasks to the number of CPU cores available. Note that each parallel task increases the memory requirements for the overall build process.
+
+## Platform Specific Instructions
+### Mac OS X
+#### Prerequisites
+- XCode (C++ 11 compiler) or Clang
+- Qt 5: The binary release of Qt provided on https://www.qt.io/download-open-source/ works just fine.
+
+#### Building Swift
+
+After installing Qt, simply run `./scons qt=/Users/username/Qt_installation_path/Qt/5.4.2/5.4/clang_64 Swift` to build Swift. Afterwards you can find a runnable app bundle at `Swift/QtUI/Swift.app`.
+
+### Windows
+#### Prerequisites
+- Microsoft Visual Studio 2013 Express or later (C++11)
+- Windows SDK
+- Python (2.5 <= version < 3)
+- Qt Open Source Edition
+
+A binary release of Qt can be obtained from https://www.qt.io/download-open-source/. Make sure it matches the Visual Studio version you have installed.
+
+#### Building Swift
+
+From the 'Visual C++' 'Programs' group, launch the Visual C++ command prompt, go to your checked out Swift directory and run `scons.bat qt=C:\path\to\qt Swift` to build Swift.
+
+To start Swift, simply change to `Swift/QtUI` and run `Swift.exe`.
+
+### Unix / Linux
+#### Prerequisites
+On Linux Swift mainly depends on Qt and OpenSSL.
+To install all required dependencies take a look at `./BuildTools/InstallSwiftDependencies.sh`. It is a script that supports various Linux distributions and will install the required system packages for building and running Swift.
+
+On Unix/Linux SCons will use `pkg-config` to determine the compiler and linker flags for Qt 5.
+
+Note: The Qt that comes with your Linux distribution might not be up to date and may have issues with some desktop environments.
+
+#### Building Swift
+To build Swift, simply open a terminal, go to the project root and run `./scons Swift`. Afterwards you can start Swift by running `./Swift/QtUI/swift-im`.
+
+#### Installing Swift
+To install Swift on the system (e.g. in the `/usr/local` directory), run `./scons SWIFT_INSTALLDIR=/usr/local /usr/local` in the Swift project folder.
diff --git a/README.txt b/README.txt
deleted file mode 100644
index 54e71f2..0000000
--- a/README.txt
+++ /dev/null
@@ -1 +0,0 @@
-See Documentation/* for build instructions.
diff --git a/SConstruct b/SConstruct
index 15f6dd0..1cf0bd8 100644
--- a/SConstruct
+++ b/SConstruct
@@ -1,5 +1,5 @@
variant_dir = SConscript("BuildTools/SCons/SConscript.boot")
if variant_dir :
- SConscript("BuildTools/SCons/SConstruct", variant_dir = variant_dir, src_dir = ".")
+ SConscript("BuildTools/SCons/SConstruct", variant_dir = variant_dir, src_dir = ".")
else :
- SConscript("BuildTools/SCons/SConstruct")
+ SConscript("BuildTools/SCons/SConstruct")
diff --git a/Slimber/CLI/DummyMenulet.cpp b/Slimber/CLI/DummyMenulet.cpp
index 25f28e5..78c6ddf 100644
--- a/Slimber/CLI/DummyMenulet.cpp
+++ b/Slimber/CLI/DummyMenulet.cpp
@@ -1,8 +1,7 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Slimber/CLI/DummyMenulet.h"
-
+#include <Slimber/CLI/DummyMenulet.h>
diff --git a/Slimber/CLI/DummyMenulet.h b/Slimber/CLI/DummyMenulet.h
index ec1c7ca..4b37df6 100644
--- a/Slimber/CLI/DummyMenulet.h
+++ b/Slimber/CLI/DummyMenulet.h
@@ -1,36 +1,36 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Slimber/Menulet.h"
+#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/SConscript b/Slimber/CLI/SConscript
index e17996d..9dfa174 100644
--- a/Slimber/CLI/SConscript
+++ b/Slimber/CLI/SConscript
@@ -8,6 +8,6 @@ myenv.UseFlags(env["SWIFTEN_FLAGS"])
myenv.UseFlags(env["SWIFTEN_DEP_FLAGS"])
myenv.Program("slimber", [
- "main.cpp",
- "DummyMenulet.cpp",
- ])
+ "main.cpp",
+ "DummyMenulet.cpp",
+ ])
diff --git a/Slimber/CLI/main.cpp b/Slimber/CLI/main.cpp
index 6f55301..26f88d0 100644
--- a/Slimber/CLI/main.cpp
+++ b/Slimber/CLI/main.cpp
@@ -1,21 +1,22 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/EventLoop/SimpleEventLoop.h>
-#include "Slimber/CLI/DummyMenulet.h"
-#include "Slimber/MainController.h"
+
+#include <Slimber/CLI/DummyMenulet.h>
+#include <Slimber/MainController.h>
using namespace Swift;
int main() {
- SimpleEventLoop eventLoop;
-
- DummyMenulet menulet;
- MainController controller(&menulet, &eventLoop);
+ SimpleEventLoop eventLoop;
+
+ DummyMenulet menulet;
+ MainController controller(&menulet, &eventLoop);
- eventLoop.run();
- return 0;
+ eventLoop.run();
+ return 0;
}
diff --git a/Slimber/Cocoa/CocoaController.mm b/Slimber/Cocoa/CocoaController.mm
index da1df98..7d17948 100644
--- a/Slimber/Cocoa/CocoaController.mm
+++ b/Slimber/Cocoa/CocoaController.mm
@@ -1,29 +1,29 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Slimber/Cocoa/CocoaController.h>
-#include <Slimber/MainController.h>
#include <Slimber/Cocoa/CocoaMenulet.h>
#include <Slimber/Cocoa/main.h>
+#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 887fdf9..0dc06f5 100644
--- a/Slimber/Cocoa/CocoaMenulet.h
+++ b/Slimber/Cocoa/CocoaMenulet.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,26 +7,27 @@
#pragma once
#include <Cocoa/Cocoa.h>
+
#include <Slimber/Menulet.h>
#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 6013b05..a05843e 100644
--- a/Slimber/Cocoa/CocoaMenulet.mm
+++ b/Slimber/Cocoa/CocoaMenulet.mm
@@ -1,85 +1,82 @@
/*
- * Copyright (c) 2012-2013 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Slimber/Cocoa/CocoaMenulet.h"
-
-#pragma GCC diagnostic ignored "-Wold-style-cast"
+#include <Slimber/Cocoa/CocoaMenulet.h>
#include <boost/function.hpp>
+#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:
- [NSString stringWithUTF8String: icon.c_str()] 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:
- [NSString stringWithUTF8String: name.c_str()]
- action: NULL keyEquivalent: @""];
- if (!icon.empty()) {
- NSString* path = [[NSBundle mainBundle] pathForResource:
- [NSString stringWithUTF8String: icon.c_str()] 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: nullptr 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/SConscript b/Slimber/Cocoa/SConscript
index 441dc27..8f3c104 100644
--- a/Slimber/Cocoa/SConscript
+++ b/Slimber/Cocoa/SConscript
@@ -8,22 +8,22 @@ myenv.MergeFlags(env["SWIFTEN_FLAGS"])
myenv.MergeFlags(env["SWIFTEN_DEP_FLAGS"])
myenv.Program("Slimber", [
- "main.mm",
- "CocoaController.mm",
- "CocoaMenulet.mm",
- ])
+ "main.mm",
+ "CocoaController.mm",
+ "CocoaMenulet.mm",
+ ])
myenv.Nib("MainMenu")
myenv.AppBundle("Slimber", resources = { "": [
- "MainMenu.nib",
- "../Resources/Slimber.icns",
- "../Resources/Credits.html",
- "../Resources/Online.png",
- "../Resources/Offline.png",
- "../Resources/UsersOnline.png",
- "../Resources/UsersOffline.png"
- ]}, info = {
- "NSMainNibFile" : "MainMenu",
- "LSUIElement" : "1",
- })
+ "MainMenu.nib",
+ "../Resources/Slimber.icns",
+ "../Resources/Credits.html",
+ "../Resources/Online.png",
+ "../Resources/Offline.png",
+ "../Resources/UsersOnline.png",
+ "../Resources/UsersOffline.png"
+ ]}, info = {
+ "NSMainNibFile" : "MainMenu",
+ "LSUIElement" : "1",
+ })
diff --git a/Slimber/Cocoa/main.mm b/Slimber/Cocoa/main.mm
index 167c1ab..c5495af 100644
--- a/Slimber/Cocoa/main.mm
+++ b/Slimber/Cocoa/main.mm
@@ -1,13 +1,20 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Slimber/Cocoa/main.h>
+
#include <Cocoa/Cocoa.h>
-#include "Slimber/Cocoa/main.h"
#include <Swiften/EventLoop/Cocoa/CocoaEventLoop.h>
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 f3a6aa3..ff2edc4 100644
--- a/Slimber/FileVCardCollection.cpp
+++ b/Slimber/FileVCardCollection.cpp
@@ -1,44 +1,45 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Slimber/FileVCardCollection.h"
+#include <Slimber/FileVCardCollection.h>
+
+#include <memory>
-#include <boost/smart_ptr/make_shared.hpp>
#include <boost/filesystem/fstream.hpp>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/Elements/VCard.h>
-#include <Swiften/Serializer/PayloadSerializers/VCardSerializer.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h>
#include <Swiften/Parser/PayloadParsers/VCardParser.h>
+#include <Swiften/Serializer/PayloadSerializers/VCardSerializer.h>
namespace Swift {
FileVCardCollection::FileVCardCollection(boost::filesystem::path dir) : vcardsPath(dir) {
}
-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>();
- }
+std::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 std::dynamic_pointer_cast<VCard>(parser.getPayload());
+ }
+ else {
+ return std::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();
+void FileVCardCollection::setOwnVCard(std::shared_ptr<VCard> v) {
+ 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 6d8f5e9..ff4a91b 100644
--- a/Slimber/FileVCardCollection.h
+++ b/Slimber/FileVCardCollection.h
@@ -1,25 +1,26 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/filesystem.hpp>
-#include "Slimber/VCardCollection.h"
+#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);
+ std::shared_ptr<VCard> getOwnVCard() const;
+ void setOwnVCard(std::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 7e75a05..ec5f2cd 100644
--- a/Slimber/LinkLocalPresenceManager.cpp
+++ b/Slimber/LinkLocalPresenceManager.cpp
@@ -1,109 +1,108 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Slimber/LinkLocalPresenceManager.h"
+#include <Slimber/LinkLocalPresenceManager.h>
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
-#include <Swiften/Elements/RosterPayload.h>
#include <Swiften/Elements/Presence.h>
+#include <Swiften/Elements/RosterPayload.h>
+#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
namespace Swift {
LinkLocalPresenceManager::LinkLocalPresenceManager(LinkLocalServiceBrowser* browser) : browser(browser) {
- browser->onServiceAdded.connect(
- boost::bind(&LinkLocalPresenceManager::handleServiceAdded, this, _1));
- browser->onServiceChanged.connect(
- boost::bind(&LinkLocalPresenceManager::handleServiceChanged, this, _1));
- browser->onServiceRemoved.connect(
- boost::bind(&LinkLocalPresenceManager::handleServiceRemoved, this, _1));
+ 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>();
+ for (const auto& 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));
+ std::shared_ptr<RosterPayload> roster(new RosterPayload());
+ roster->addItem(getRosterItem(service));
+ onRosterChanged(roster);
+ onPresenceChanged(getPresence(service));
}
void LinkLocalPresenceManager::handleServiceChanged(const LinkLocalService& service) {
- onPresenceChanged(getPresence(service));
+ 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);
+ std::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;
+std::shared_ptr<RosterPayload> LinkLocalPresenceManager::getRoster() const {
+ std::shared_ptr<RosterPayload> roster(new RosterPayload());
+ for (const auto& 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<std::shared_ptr<Presence> > LinkLocalPresenceManager::getAllPresence() const {
+ std::vector<std::shared_ptr<Presence> > result;
+ for (const auto& service : browser->getServices()) {
+ result.push_back(getPresence(service));
+ }
+ return result;
}
RosterItemPayload LinkLocalPresenceManager::getRosterItem(const LinkLocalService& service) const {
- return RosterItemPayload(service.getJID(), getRosterName(service), RosterItemPayload::Both);
+ return RosterItemPayload(service.getJID(), getRosterName(service), RosterItemPayload::Both);
}
std::string LinkLocalPresenceManager::getRosterName(const LinkLocalService& service) const {
- LinkLocalServiceInfo info = service.getInfo();
- if (!info.getNick().empty()) {
- return info.getNick();
- }
- else if (!info.getFirstName().empty()) {
- std::string result = info.getFirstName();
- if (!info.getLastName().empty()) {
- result += " " + info.getLastName();
- }
- return result;
- }
- else if (!info.getLastName().empty()) {
- return info.getLastName();
- }
- return "";
+ 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;
+std::shared_ptr<Presence> LinkLocalPresenceManager::getPresence(const LinkLocalService& service) const {
+ std::shared_ptr<Presence> presence(new Presence());
+ presence->setFrom(service.getJID());
+ switch (service.getInfo().getStatus()) {
+ case LinkLocalServiceInfo::Available:
+ presence->setShow(StatusShow::Online);
+ break;
+ case LinkLocalServiceInfo::Away:
+ presence->setShow(StatusShow::Away);
+ break;
+ 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 3738319..c3e7ddc 100644
--- a/Slimber/LinkLocalPresenceManager.h
+++ b/Slimber/LinkLocalPresenceManager.h
@@ -1,46 +1,47 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/boost_bsignals.h>
+#include <memory>
+#include <string>
+
+#include <boost/signals2.hpp>
#include <Swiften/Elements/RosterItemPayload.h>
-#include <string>
#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::signals2::trackable {
+ public:
+ LinkLocalPresenceManager(LinkLocalServiceBrowser*);
- boost::shared_ptr<RosterPayload> getRoster() const;
- std::vector<boost::shared_ptr<Presence> > getAllPresence() const;
+ std::shared_ptr<RosterPayload> getRoster() const;
+ std::vector<std::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::signals2::signal<void (std::shared_ptr<RosterPayload>)> onRosterChanged;
+ boost::signals2::signal<void (std::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;
+ std::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 54ad222..cd36132 100644
--- a/Slimber/MainController.cpp
+++ b/Slimber/MainController.cpp
@@ -1,127 +1,127 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Slimber/MainController.h"
+#include <Slimber/MainController.h>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
-#include <iostream>
-#include <Swiften/Base/foreach.h>
-#include <SwifTools/Application/PlatformApplicationPathProvider.h>
+#include <Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h>
#include <Swiften/LinkLocal/LinkLocalService.h>
#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
-#include <Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h>
-#include "Slimber/Server.h"
-#include "Slimber/FileVCardCollection.h"
-#include "Slimber/MenuletController.h"
-#include "Slimber/Menulet.h"
+
+#include <Slimber/FileVCardCollection.h>
+#include <Slimber/Menulet.h>
+#include <Slimber/MenuletController.h>
+#include <Slimber/Server.h>
+
+#include <SwifTools/Application/PlatformApplicationPathProvider.h>
using namespace Swift;
MainController::MainController(Menulet* menulet, EventLoop* eventLoop) {
- dnsSDQuerier = PlatformDNSSDQuerierFactory(eventLoop).createQuerier();
- assert(dnsSDQuerier);
+ 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;
+ for (const auto& service : linkLocalServiceBrowser->getServices()) {
+ std::string description = service.getDescription();
+ if (description != service.getName()) {
+ description += " (" + service.getName() + ")";
+ }
+ names.push_back(description);
+ }
+ menuletController->setUserNames(names);
}
void MainController::handleServerStopped(boost::optional<ServerError> error) {
- if (error) {
- std::string message;
- switch (error->getType()) {
- case ServerError::C2SPortConflict:
- message = std::string("Error: Port ") + boost::lexical_cast<std::string>(server->getClientToServerPort()) + std::string(" in use");
- break;
- case ServerError::C2SError:
- message = std::string("Local connection server error");
- break;
- case ServerError::LinkLocalPortConflict:
- message = std::string("Error: Port ") + boost::lexical_cast<std::string>(server->getLinkLocalPort()) + std::string(" in use");
- break;
- case ServerError::LinkLocalError:
- message = std::string("External connection server error");
- break;
- }
- menuletController->setXMPPStatus(message, MenuletController::Offline);
- }
- else {
- menuletController->setXMPPStatus("XMPP Server Not Running", MenuletController::Offline);
- }
+ 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 ecb81ba..9989b4d 100644
--- a/Slimber/MainController.h
+++ b/Slimber/MainController.h
@@ -1,45 +1,46 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/optional.hpp>
-#include "Slimber/ServerError.h"
+#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:
+ std::shared_ptr<Swift::DNSSDQuerier> dnsSDQuerier;
+ Swift::LinkLocalServiceBrowser* linkLocalServiceBrowser;
+ Swift::VCardCollection* vCardCollection;
+ Swift::Server* server;
+ MenuletController* menuletController;
};
diff --git a/Slimber/Menulet.cpp b/Slimber/Menulet.cpp
index 5ab4273..3e449f8 100644
--- a/Slimber/Menulet.cpp
+++ b/Slimber/Menulet.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Slimber/Menulet.h"
+#include <Slimber/Menulet.h>
Menulet::~Menulet() {
}
diff --git a/Slimber/Menulet.h b/Slimber/Menulet.h
index a5c7bde..4c06754 100644
--- a/Slimber/Menulet.h
+++ b/Slimber/Menulet.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,19 +7,20 @@
#pragma once
#include <string>
-#include <Swiften/Base/boost_bsignals.h>
+
+#include <boost/signals2.hpp>
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::signals2::signal<void ()> onRestartClicked;
};
diff --git a/Slimber/MenuletController.cpp b/Slimber/MenuletController.cpp
index 078275b..5ea5bc9 100644
--- a/Slimber/MenuletController.cpp
+++ b/Slimber/MenuletController.cpp
@@ -1,55 +1,53 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Slimber/MenuletController.h"
+#include <Slimber/MenuletController.h>
-#include <Swiften/Base/foreach.h>
#include <string>
-#include "Slimber/Menulet.h"
-#include <iostream>
+#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:");
+ for (const auto& user : linkLocalUsers) {
+ menulet->addItem(std::string(" ") + user);
+ }
+ }
+ menulet->addSeparator();
+ menulet->addItem(xmppStatusMessage, (xmppStatus == Online ? "Online" : "Offline"));
+ menulet->addSeparator();
+ menulet->addAboutItem();
+ menulet->addSeparator();
+ menulet->addRestartItem();
+ menulet->addExitItem();
}
diff --git a/Slimber/MenuletController.h b/Slimber/MenuletController.h
index 7885ad1..3c05ed2 100644
--- a/Slimber/MenuletController.h
+++ b/Slimber/MenuletController.h
@@ -1,39 +1,39 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
#include <vector>
-#include <boost/signal.hpp>
-#include <string>
+#include <boost/signals2.hpp>
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::signals2::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 27fc803..301661e 100644
--- a/Slimber/Qt/QtAboutDialog.cpp
+++ b/Slimber/Qt/QtAboutDialog.cpp
@@ -1,37 +1,37 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Slimber/Qt/QtAboutDialog.h"
+#include <Slimber/Qt/QtAboutDialog.h>
#include <QCoreApplication>
-#include <QVBoxLayout>
#include <QLabel>
#include <QPixmap>
+#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.cpp b/Slimber/Qt/QtMenulet.cpp
index ba3d004..5d0d276 100644
--- a/Slimber/Qt/QtMenulet.cpp
+++ b/Slimber/Qt/QtMenulet.cpp
@@ -1,8 +1,7 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Slimber/Qt/QtMenulet.h"
-
+#include <Slimber/Qt/QtMenulet.h>
diff --git a/Slimber/Qt/QtMenulet.h b/Slimber/Qt/QtMenulet.h
index d6a7a4d..fa17d21 100644
--- a/Slimber/Qt/QtMenulet.h
+++ b/Slimber/Qt/QtMenulet.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,75 +8,75 @@
#include <QCoreApplication>
#include <QMenu>
-#include <QString>
-#include <QSystemTrayIcon>
#include <QObject>
#include <QPixmap>
#include <QPointer>
+#include <QString>
+#include <QSystemTrayIcon>
-#include "Slimber/Menulet.h"
-#include "Slimber/Qt/QtAboutDialog.h"
+#include <Slimber/Menulet.h>
+#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/SConscript b/Slimber/Qt/SConscript
index 0e7bdea..8328f8c 100644
--- a/Slimber/Qt/SConscript
+++ b/Slimber/Qt/SConscript
@@ -15,11 +15,11 @@ myenv.UseFlags(env.get("AVAHI_FLAGS", ""))
myenv.UseFlags(myenv["PLATFORM_FLAGS"])
if myenv.get("HAVE_ICU") :
- myenv.MergeFlags(env["ICU_FLAGS"])
- myenv.Append(CPPDEFINES = ["HAVE_ICU"])
+ myenv.MergeFlags(env["ICU_FLAGS"])
+ myenv.Append(CPPDEFINES = ["HAVE_ICU"])
if myenv.get("HAVE_LIBIDN") :
- myenv.MergeFlags(env["LIBIDN_FLAGS"])
- myenv.Append(CPPDEFINES = ["HAVE_LIBIDN"])
+ myenv.MergeFlags(env["LIBIDN_FLAGS"])
+ myenv.Append(CPPDEFINES = ["HAVE_LIBIDN"])
myenv.Tool("qt4", toolpath = ["#/BuildTools/SCons/Tools"])
myenv.Tool("nsis", toolpath = ["#/BuildTools/SCons/Tools"])
@@ -27,41 +27,39 @@ myenv.Tool("nsis", toolpath = ["#/BuildTools/SCons/Tools"])
qt4modules = ['QtCore', 'QtGui']
if myenv["qt5"] :
- qt_version = '5'
- qt4modules += ['QtWidgets']
+ qt_version = '5'
+ qt4modules += ['QtWidgets']
else :
- qt_version = '4'
+ qt_version = '4'
myenv.EnableQt4Modules(qt4modules, debug = False, version = qt_version)
-myenv.Append(CPPPATH = ["."])
-
if env["PLATFORM"] == "win32" :
- myenv.Append(LINKFLAGS = ["/SUBSYSTEM:WINDOWS"])
- myenv.Append(LIBS = "qtmain")
+ myenv.Append(LINKFLAGS = ["/SUBSYSTEM:WINDOWS"])
+ myenv.Append(LIBS = "qtmain")
myenv.BuildVersion("BuildVersion.h", project = "slimber")
sources = [
- "main.cpp",
- "QtMenulet.cpp",
- "QtAboutDialog.cpp",
- myenv.Qrc("Slimber.qrc"),
- ]
+ "main.cpp",
+ "QtMenulet.cpp",
+ "QtAboutDialog.cpp",
+ myenv.Qrc("Slimber.qrc"),
+ ]
#if env["PLATFORM"] == "win32" :
-# myenv.RES("../resources/Windows/Slimber.rc")
-# sources += ["../resources/Windows/Slimber.res"]
+# myenv.RES("../resources/Windows/Slimber.rc")
+# sources += ["../resources/Windows/Slimber.res"]
if env["PLATFORM"] == "win32" :
- slimberProgram = myenv.Program("Slimber", sources)
+ slimberProgram = myenv.Program("Slimber", sources)
else :
- slimberProgram = myenv.Program("slimber", sources)
+ slimberProgram = myenv.Program("slimber", sources)
if env["PLATFORM"] == "win32" :
- if "dist" in COMMAND_LINE_TARGETS or env.GetOption("clean") :
- myenv.WindowsBundle("Slimber", resources = {}, qtlibs = ["QtCore4", "QtGui4"])
- myenv.Append(NSIS_OPTIONS = [
- "/DmsvccRedistributableDir=\"" + env["vcredist"] + "\"",
- "/DbuildDate=" + datetime.date.today().strftime("%Y%m%d")
- ])
- #myenv.Nsis("../Packaging/nsis/slimber.nsi")
+ if "dist" in COMMAND_LINE_TARGETS or env.GetOption("clean") :
+ myenv.WindowsBundle("Slimber", resources = {}, qtlibs = ["QtCore4", "QtGui4"])
+ myenv.Append(NSIS_OPTIONS = [
+ "/DmsvccRedistributableDir=\"" + env["vcredist"] + "\"",
+ "/DbuildDate=" + datetime.date.today().strftime("%Y%m%d")
+ ])
+ #myenv.Nsis("../Packaging/nsis/slimber.nsi")
diff --git a/Slimber/Qt/main.cpp b/Slimber/Qt/main.cpp
index 5415d05..8fbfbb6 100644
--- a/Slimber/Qt/main.cpp
+++ b/Slimber/Qt/main.cpp
@@ -1,35 +1,36 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <QApplication>
#include <QCoreApplication>
-#include <QSystemTrayIcon>
#include <QMessageBox>
+#include <QSystemTrayIcon>
-#include "QtMenulet.h"
-#include "Slimber/MainController.h"
#include <Swiften/EventLoop/Qt/QtEventLoop.h>
+
+#include <Slimber/MainController.h>
#include <Slimber/Qt/BuildVersion.h>
+#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/SConscript b/Slimber/SConscript
index ff4f57d..a41fe0b 100644
--- a/Slimber/SConscript
+++ b/Slimber/SConscript
@@ -4,18 +4,18 @@ Import("env")
env["BUILD_SLIMBER"] = True
if env["PLATFORM"] == "win32" :
- if not env.get("HAVE_BONJOUR") and "Slimber" in env["PROJECTS"] :
- env["PROJECTS"].remove("Slimber")
+ if not env.get("HAVE_BONJOUR") and "Slimber" in env["PROJECTS"] :
+ env["PROJECTS"].remove("Slimber")
elif env["PLATFORM"] != "darwin" :
- if not env.get("HAVE_AVAHI", False) and "Slimber" in env["PROJECTS"] :
- env["PROJECTS"].remove("Slimber")
+ if not env.get("HAVE_AVAHI", False) and "Slimber" in env["PROJECTS"] :
+ env["PROJECTS"].remove("Slimber")
if not "Slimber" in env["PROJECTS"] and env["SCONS_STAGE"] == "flags" :
- print "Bonjour missing. Not building Slimber."
+ print "Bonjour missing. Not building Slimber."
if not env.get("HAVE_QT", False) and "Slimber" in env["PROJECTS"] :
- print "Qt missing. Not building Slimber."
- env["PROJECTS"].remove("Slimber")
+ print "Qt missing. Not building Slimber."
+ env["PROJECTS"].remove("Slimber")
if "Slimber" in env["PROJECTS"] :
@@ -23,42 +23,42 @@ if "Slimber" in env["PROJECTS"] :
# Flags
################################################################################
- if env["SCONS_STAGE"] == "flags" :
- env["SLIMBER_FLAGS"] = {
- "LIBPATH": [Dir(".")],
- "LIBS": ["Slimber"]
- }
+ if env["SCONS_STAGE"] == "flags" :
+ env["SLIMBER_FLAGS"] = {
+ "LIBPATH": [Dir(".")],
+ "LIBS": ["Slimber"]
+ }
################################################################################
# Build
################################################################################
- if env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
- myenv.UseFlags(env["LIMBER_FLAGS"])
- myenv.MergeFlags(env["BOOST_FLAGS"])
- myenv.MergeFlags(env["SWIFTEN_FLAGS"])
- myenv.MergeFlags(env["SWIFTEN_DEP_FLAGS"])
- myenv.StaticLibrary("Slimber", [
- "LinkLocalPresenceManager.cpp",
- "FileVCardCollection.cpp",
- "VCardCollection.cpp",
- "Server.cpp",
- "MainController.cpp",
- "MenuletController.cpp",
- "Menulet.cpp"
- ])
+ if env["SCONS_STAGE"] == "build" :
+ myenv = env.Clone()
+ myenv.UseFlags(env["LIMBER_FLAGS"])
+ myenv.MergeFlags(env["BOOST_FLAGS"])
+ myenv.MergeFlags(env["SWIFTEN_FLAGS"])
+ myenv.MergeFlags(env["SWIFTEN_DEP_FLAGS"])
+ myenv.StaticLibrary("Slimber", [
+ "LinkLocalPresenceManager.cpp",
+ "FileVCardCollection.cpp",
+ "VCardCollection.cpp",
+ "Server.cpp",
+ "MainController.cpp",
+ "MenuletController.cpp",
+ "Menulet.cpp"
+ ])
- env["SLIMBER_VERSION"] = "0.9.9." + datetime.date.today().strftime("%Y%m%d")
+ env["SLIMBER_VERSION"] = "0.9.9." + datetime.date.today().strftime("%Y%m%d")
- env.Append(UNITTEST_SOURCES = [
- File("UnitTest/LinkLocalPresenceManagerTest.cpp"),
- File("UnitTest/MenuletControllerTest.cpp")
- ])
+ env.Append(UNITTEST_SOURCES = [
+ File("UnitTest/LinkLocalPresenceManagerTest.cpp"),
+ File("UnitTest/MenuletControllerTest.cpp")
+ ])
- SConscript("CLI/SConscript")
- if env["PLATFORM"] == "darwin" :
- SConscript("Cocoa/SConscript")
- else :
- SConscript("Qt/SConscript")
+ SConscript("CLI/SConscript")
+ if env["PLATFORM"] == "darwin" :
+ SConscript("Cocoa/SConscript")
+ else :
+ SConscript("Qt/SConscript")
diff --git a/Slimber/Server.cpp b/Slimber/Server.cpp
index b78e701..3bc3112 100644
--- a/Slimber/Server.cpp
+++ b/Slimber/Server.cpp
@@ -1,438 +1,439 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Slimber/Server.h"
+#include <Slimber/Server.h>
+#include <cassert>
#include <string>
+
#include <boost/bind.hpp>
-#include <iostream>
-
-#include "Swiften/Base/String.h"
-#include "Swiften/LinkLocal/LinkLocalConnector.h"
-#include "Swiften/Network/Connection.h"
-#include "Swiften/Session/SessionTracer.h"
-#include "Swiften/Elements/ToplevelElement.h"
-#include "Swiften/Elements/Presence.h"
-#include "Swiften/Elements/RosterPayload.h"
-#include "Swiften/Network/BoostConnection.h"
-#include "Swiften/Network/BoostConnectionServer.h"
-#include "Swiften/Session/SessionTracer.h"
-#include "Swiften/Elements/IQ.h"
-#include "Swiften/Elements/VCard.h"
-#include "Limber/Server/UserRegistry.h"
-#include "Swiften/Session/Session.h"
-#include <Swiften/Base/foreach.h>
-#include <string>
-#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
-#include <Swiften/LinkLocal/OutgoingLinkLocalSession.h>
+
+#include <Swiften/Base/Log.h>
+#include <Swiften/Base/String.h>
+#include <Swiften/Elements/IQ.h>
+#include <Swiften/Elements/Presence.h>
+#include <Swiften/Elements/RosterPayload.h>
+#include <Swiften/Elements/ToplevelElement.h>
+#include <Swiften/Elements/VCard.h>
#include <Swiften/LinkLocal/IncomingLinkLocalSession.h>
+#include <Swiften/LinkLocal/LinkLocalConnector.h>
#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
+#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
+#include <Swiften/LinkLocal/OutgoingLinkLocalSession.h>
+#include <Swiften/Network/BoostConnection.h>
+#include <Swiften/Network/BoostConnectionServer.h>
+#include <Swiften/Network/Connection.h>
#include <Swiften/Network/ConnectionServer.h>
-#include "Slimber/VCardCollection.h"
-#include "Slimber/LinkLocalPresenceManager.h"
-#include "Limber/Server/ServerFromClientSession.h"
+#include <Swiften/Session/Session.h>
+#include <Swiften/Session/SessionTracer.h>
+
+#include <Limber/Server/ServerFromClientSession.h>
+#include <Limber/Server/UserRegistry.h>
+
+#include <Slimber/LinkLocalPresenceManager.h>
+#include <Slimber/VCardCollection.h>
namespace Swift {
Server::Server(
- int clientConnectionPort,
- int linkLocalConnectionPort,
- LinkLocalServiceBrowser* linkLocalServiceBrowser,
- VCardCollection* vCardCollection,
- 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(nullptr),
+ 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 = nullptr;
+
+ if (serverFromClientSession) {
+ serverFromClientSession->finishSession();
+ }
+ serverFromClientSession.reset();
+ for (auto&& session : linkLocalSessions) {
+ session->finishSession();
+ }
+ linkLocalSessions.clear();
+ for (auto&& connector : connectors) {
+ connector->cancel();
+ }
+ connectors.clear();
+ tracers.clear();
+
+ if (serverFromNetworkConnectionServer) {
+ serverFromNetworkConnectionServer->stop();
+ for (auto&& connection : serverFromNetworkConnectionServerSignalConnections) {
+ connection.disconnect();
+ }
+ serverFromNetworkConnectionServerSignalConnections.clear();
+ serverFromNetworkConnectionServer.reset();
+ }
+ if (serverFromClientConnectionServer) {
+ serverFromClientConnectionServer->stop();
+ for (auto&& 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();
+void Server::handleNewClientConnection(std::shared_ptr<Connection> connection) {
+ if (serverFromClientSession) {
+ connection->disconnect();
+ }
+ serverFromClientSession = std::shared_ptr<ServerFromClientSession>(
+ new ServerFromClientSession(idGenerator.generateID(), connection,
+ &payloadParserFactories, &payloadSerializers, &xmlParserFactory, &userRegistry));
+ serverFromClientSession->setAllowSASLEXTERNAL();
+ serverFromClientSession->onSessionStarted.connect(
+ boost::bind(&Server::handleSessionStarted, this));
+ serverFromClientSession->onElementReceived.connect(
+ boost::bind(&Server::handleElementReceived, this, _1,
+ serverFromClientSession));
+ serverFromClientSession->onSessionFinished.connect(
+ boost::bind(&Server::handleSessionFinished, this,
+ serverFromClientSession));
+ //tracers.push_back(std::shared_ptr<SessionTracer>(
+ // new SessionTracer(serverFromClientSession)));
+ serverFromClientSession->startSession();
}
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();
+void Server::handleSessionFinished(std::shared_ptr<ServerFromClientSession>) {
+ 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));
- }
- }
- }
+void Server::handleElementReceived(std::shared_ptr<ToplevelElement> element, std::shared_ptr<ServerFromClientSession> session) {
+ std::shared_ptr<Stanza> stanza = std::dynamic_pointer_cast<Stanza>(element);
+ if (!stanza) {
+ return;
+ }
+
+ stanza->setFrom(session->getRemoteJID());
+ if (!stanza->getTo().isValid()) {
+ stanza->setTo(session->getLocalJID());
+ }
+
+ if (std::shared_ptr<Presence> presence = std::dynamic_pointer_cast<Presence>(stanza)) {
+ if (presence->getType() == Presence::Available) {
+ if (!linkLocalServiceRegistered) {
+ linkLocalServiceRegistered = true;
+ linkLocalServiceBrowser->registerService(
+ session->getRemoteJID().toBare().toString(),
+ linkLocalConnectionPort, getLinkLocalServiceInfo(presence));
+ }
+ else {
+ linkLocalServiceBrowser->updateService(
+ getLinkLocalServiceInfo(presence));
+ }
+ lastPresence = presence;
+ }
+ else {
+ unregisterService();
+ }
+ }
+ else if (!stanza->getTo().isValid() || stanza->getTo() == session->getLocalJID() || stanza->getTo() == session->getRemoteJID().toBare()) {
+ if (std::shared_ptr<IQ> iq = std::dynamic_pointer_cast<IQ>(stanza)) {
+ if (iq->getPayload<RosterPayload>()) {
+ if (iq->getType() == IQ::Get) {
+ session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), presenceManager->getRoster()));
+ rosterRequested = true;
+ for (const auto& presence : presenceManager->getAllPresence()) {
+ session->sendElement(presence);
+ }
+ }
+ else {
+ session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::Forbidden, ErrorPayload::Cancel));
+ }
+ }
+ if (std::shared_ptr<VCard> vcard = iq->getPayload<VCard>()) {
+ if (iq->getType() == IQ::Get) {
+ session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), vCardCollection->getOwnVCard()));
+ }
+ else {
+ vCardCollection->setOwnVCard(vcard);
+ session->sendElement(IQ::createResult(iq->getFrom(), iq->getID()));
+ if (lastPresence) {
+ linkLocalServiceBrowser->updateService(getLinkLocalServiceInfo(lastPresence));
+ }
+ }
+ }
+ else {
+ session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::FeatureNotImplemented, ErrorPayload::Cancel));
+ }
+ }
+ }
+ else {
+ JID toJID = stanza->getTo();
+ std::shared_ptr<Session> outgoingSession =
+ getLinkLocalSessionForJID(toJID);
+ if (outgoingSession) {
+ outgoingSession->sendElement(stanza);
+ }
+ else {
+ boost::optional<LinkLocalService> service =
+ presenceManager->getServiceForJID(toJID);
+ if (service) {
+ std::shared_ptr<LinkLocalConnector> connector =
+ getLinkLocalConnectorForJID(toJID);
+ if (!connector) {
+ connector = std::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);
+void Server::handleNewLinkLocalConnection(std::shared_ptr<Connection> connection) {
+ std::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());
+void Server::handleLinkLocalSessionFinished(std::shared_ptr<Session> session) {
+ //std::cout << "Link local session from " << session->getRemoteJID() << " ended" << std::endl;
+ linkLocalSessions.erase(
+ std::remove(linkLocalSessions.begin(), linkLocalSessions.end(), session),
+ linkLocalSessions.end());
}
-void Server::handleLinkLocalElementReceived(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);
- }
+void Server::handleLinkLocalElementReceived(std::shared_ptr<ToplevelElement> element, std::shared_ptr<Session> session) {
+ if (std::shared_ptr<Stanza> stanza = std::dynamic_pointer_cast<Stanza>(element)) {
+ JID fromJID = session->getRemoteJID();
+ if (!presenceManager->getServiceForJID(fromJID.toBare())) {
+ return; // TODO: Send error back
+ }
+ stanza->setFrom(fromJID);
+ serverFromClientSession->sendElement(stanza);
+ }
}
-void Server::handleConnectFinished(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());
+void Server::handleConnectFinished(std::shared_ptr<LinkLocalConnector> connector, bool error) {
+ if (error) {
+ SWIFT_LOG(warning) << "Error connecting" << std::endl;
+ // TODO: Send back queued stanzas
+ }
+ else {
+ std::shared_ptr<OutgoingLinkLocalSession> outgoingSession(
+ new OutgoingLinkLocalSession(
+ selfJID, connector->getService().getJID(), connector->getConnection(),
+ &payloadParserFactories, &payloadSerializers, &xmlParserFactory));
+ for (const auto& element : connector->getQueuedElements()) {
+ outgoingSession->queueElement(element);
+ }
+ registerLinkLocalSession(outgoingSession);
+ }
+ connectors.erase(std::remove(connectors.begin(), connectors.end(), connector), connectors.end());
}
-void Server::registerLinkLocalSession(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();
+void Server::registerLinkLocalSession(std::shared_ptr<Session> session) {
+ session->onSessionFinished.connect(
+ boost::bind(&Server::handleLinkLocalSessionFinished, this, session));
+ session->onElementReceived.connect(
+ boost::bind(&Server::handleLinkLocalElementReceived, this, _1, session));
+ linkLocalSessions.push_back(session);
+ //tracers.push_back(std::make_shared<SessionTracer>(session));
+ session->startSession();
}
-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>();
+std::shared_ptr<Session> Server::getLinkLocalSessionForJID(const JID& jid) {
+ for (const auto& session : linkLocalSessions) {
+ if (session->getRemoteJID() == jid) {
+ return session;
+ }
+ }
+ return std::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>();
+std::shared_ptr<LinkLocalConnector> Server::getLinkLocalConnectorForJID(const JID& jid) {
+ for (const auto& connector : connectors) {
+ if (connector->getService().getJID() == jid) {
+ return connector;
+ }
+ }
+ return std::shared_ptr<LinkLocalConnector>();
}
void Server::handleServiceRegistered(const DNSSDServiceID& service) {
- selfJID = JID(service.getName());
+ 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);
- }
+void Server::handleRosterChanged(std::shared_ptr<RosterPayload> roster) {
+ if (rosterRequested) {
+ assert(serverFromClientSession);
+ std::shared_ptr<IQ> iq = IQ::createRequest(
+ IQ::Set, serverFromClientSession->getRemoteJID(),
+ idGenerator.generateID(), roster);
+ iq->setFrom(serverFromClientSession->getRemoteJID().toBare());
+ serverFromClientSession->sendElement(iq);
+ }
}
-void Server::handlePresenceChanged(boost::shared_ptr<Presence> presence) {
- if (rosterRequested) {
- serverFromClientSession->sendElement(presence);
- }
+void Server::handlePresenceChanged(std::shared_ptr<Presence> 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 Server::getLinkLocalServiceInfo(std::shared_ptr<Presence> presence) {
+ LinkLocalServiceInfo info;
+ std::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 ef3b298..4842cd9 100644
--- a/Slimber/Server.h
+++ b/Slimber/Server.h
@@ -1,123 +1,126 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/optional.hpp>
+#include <memory>
#include <vector>
-#include "Swiften/Network/BoostIOServiceThread.h"
-#include "Swiften/Network/BoostConnectionServer.h"
-#include "Limber/Server/UserRegistry.h"
-#include "Swiften/Base/IDGenerator.h"
-#include "Swiften/Parser/PlatformXMLParserFactory.h"
-#include "Limber/Server/ServerFromClientSession.h"
-#include "Swiften/JID/JID.h"
-#include "Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h"
-#include "Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h"
-#include "Swiften/LinkLocal/LinkLocalServiceInfo.h"
-#include "Slimber/ServerError.h"
+#include <boost/optional.hpp>
+
+#include <Swiften/Base/IDGenerator.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
+#include <Swiften/Network/BoostConnectionServer.h>
+#include <Swiften/Network/BoostIOServiceThread.h>
+#include <Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h>
+#include <Swiften/Parser/PlatformXMLParserFactory.h>
+#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+
+#include <Limber/Server/ServerFromClientSession.h>
+#include <Limber/Server/UserRegistry.h>
+
+#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::signals2::signal<void (bool)> onSelfConnected;
+ boost::signals2::signal<void (boost::optional<ServerError>)> onStopped;
+
+ private:
+ void stop(boost::optional<ServerError>);
+
+ void handleNewClientConnection(std::shared_ptr<Connection> c);
+ void handleSessionStarted();
+ void handleSessionFinished(std::shared_ptr<ServerFromClientSession>);
+ void handleElementReceived(std::shared_ptr<ToplevelElement> element, std::shared_ptr<ServerFromClientSession> session);
+ void handleRosterChanged(std::shared_ptr<RosterPayload> roster);
+ void handlePresenceChanged(std::shared_ptr<Presence> presence);
+ void handleServiceRegistered(const DNSSDServiceID& service);
+ void handleNewLinkLocalConnection(std::shared_ptr<Connection> connection);
+ void handleLinkLocalSessionFinished(std::shared_ptr<Session> session);
+ void handleLinkLocalElementReceived(std::shared_ptr<ToplevelElement> element, std::shared_ptr<Session> session);
+ void handleConnectFinished(std::shared_ptr<LinkLocalConnector> connector, bool error);
+ void handleClientConnectionServerStopped(
+ boost::optional<BoostConnectionServer::Error>);
+ void handleLinkLocalConnectionServerStopped(
+ boost::optional<BoostConnectionServer::Error>);
+ std::shared_ptr<Session> getLinkLocalSessionForJID(const JID& jid);
+ std::shared_ptr<LinkLocalConnector> getLinkLocalConnectorForJID(const JID& jid);
+ void registerLinkLocalSession(std::shared_ptr<Session> session);
+ void unregisterService();
+ LinkLocalServiceInfo getLinkLocalServiceInfo(std::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;
+ std::shared_ptr<BoostConnectionServer> serverFromClientConnectionServer;
+ std::vector<boost::signals2::connection> serverFromClientConnectionServerSignalConnections;
+ std::shared_ptr<ServerFromClientSession> serverFromClientSession;
+ std::shared_ptr<Presence> lastPresence;
+ JID selfJID;
+ std::shared_ptr<BoostConnectionServer> serverFromNetworkConnectionServer;
+ std::vector<boost::signals2::connection> serverFromNetworkConnectionServerSignalConnections;
+ std::vector< std::shared_ptr<Session> > linkLocalSessions;
+ std::vector< std::shared_ptr<LinkLocalConnector> > connectors;
+ std::vector< std::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 9a7adf0..c8e7700 100644
--- a/Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp
+++ b/Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp
@@ -1,261 +1,264 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <map>
+
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/bind.hpp>
-#include <map>
#include <Swiften/Elements/Presence.h>
-#include <Swiften/Elements/RosterPayload.h>
#include <Swiften/Elements/RosterItemPayload.h>
-#include "Slimber/LinkLocalPresenceManager.h"
-#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
-#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
-#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
+#include <Swiften/Elements/RosterPayload.h>
+#include <Swiften/EventLoop/DummyEventLoop.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h>
+#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h>
-#include <Swiften/EventLoop/DummyEventLoop.h>
+#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
+#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
+
+#include <Slimber/LinkLocalPresenceManager.h>
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 = std::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");
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland");
+ addService("rabbit@teaparty");
+ updateServicePresence("rabbit@teaparty", LinkLocalServiceInfo::Away, "Partying");
+
+ std::vector<std::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() {
+ std::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland", "Alice");
+ addService("rabbit@teaparty", "Rabbit");
+
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
+
+ addService("alice@wonderland");
+ addService("queen@garden");
+
+ CPPUNIT_ASSERT(!testling->getServiceForJID(JID("rabbit@teaparty")));
+ }
+
+ private:
+ std::shared_ptr<LinkLocalPresenceManager> createTestling() {
+ std::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(std::shared_ptr<RosterPayload> payload) {
+ rosterChanges.push_back(payload);
+ }
+
+ void handlePresenceChanged(std::shared_ptr<Presence> presence) {
+ presenceChanges.push_back(presence);
+ }
+
+ private:
+ DummyEventLoop* eventLoop;
+ std::shared_ptr<FakeDNSSDQuerier> querier;
+ LinkLocalServiceBrowser* browser;
+ std::vector< std::shared_ptr<RosterPayload> > rosterChanges;
+ std::vector< std::shared_ptr<Presence> > presenceChanges;
};
CPPUNIT_TEST_SUITE_REGISTRATION(LinkLocalPresenceManagerTest);
diff --git a/Slimber/UnitTest/MenuletControllerTest.cpp b/Slimber/UnitTest/MenuletControllerTest.cpp
index 39e4c07..e3b46ab 100644
--- a/Slimber/UnitTest/MenuletControllerTest.cpp
+++ b/Slimber/UnitTest/MenuletControllerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,149 +7,149 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include "Slimber/Menulet.h"
-#include "Slimber/MenuletController.h"
+#include <Slimber/Menulet.h>
+#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.cpp b/Slimber/VCardCollection.cpp
index 15c27b6..b2de6c5 100644
--- a/Slimber/VCardCollection.cpp
+++ b/Slimber/VCardCollection.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Slimber/VCardCollection.h"
+#include <Slimber/VCardCollection.h>
namespace Swift {
diff --git a/Slimber/VCardCollection.h b/Slimber/VCardCollection.h
index 0e7d27f..50147ec 100644
--- a/Slimber/VCardCollection.h
+++ b/Slimber/VCardCollection.h
@@ -1,21 +1,21 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#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 std::shared_ptr<VCard> getOwnVCard() const = 0;
+ virtual void setOwnVCard(std::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 113e07b..ef0b1a4 100644
--- a/Sluift/Console.cpp
+++ b/Sluift/Console.cpp
@@ -1,21 +1,25 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/Console.h>
-#include <lua.hpp>
-#include <stdexcept>
+
+#include <cctype>
#include <iostream>
-#include <boost/optional.hpp>
-#include <boost/lexical_cast.hpp>
+#include <stdexcept>
+
#include <boost/algorithm/string/predicate.hpp>
+#include <boost/lexical_cast.hpp>
#include <boost/numeric/conversion/cast.hpp>
+#include <boost/optional.hpp>
+
+#include <lua.hpp>
+
+#include <Sluift/Lua/LuaUtils.h>
#include <Sluift/Terminal.h>
#include <Sluift/tokenize.h>
-#include <Sluift/Lua/LuaUtils.h>
-#include <cctype>
using namespace Swift;
@@ -24,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 b53a167..6ed6f58 100644
--- a/Sluift/Console.h
+++ b/Sluift/Console.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,35 +7,38 @@
#pragma once
#include <string>
+
#include <boost/optional/optional.hpp>
-#include <Sluift/Completer.h>
+
#include <Swiften/Base/Override.h>
+#include <Sluift/Completer.h>
+
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 8d1aac8..206ced6 100644
--- a/Sluift/EditlineTerminal.cpp
+++ b/Sluift/EditlineTerminal.cpp
@@ -1,78 +1,81 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/EditlineTerminal.h>
-#include <boost/optional.hpp>
-#include <iostream>
-#include <editline/readline.h>
-#include <boost/numeric/conversion/cast.hpp>
#include <cassert>
-#include <vector>
#include <cstring>
+#include <iostream>
+#include <vector>
+
+#include <boost/numeric/conversion/cast.hpp>
+#include <boost/optional.hpp>
+
+#include <editline/readline.h>
#include <Swiften/Base/Platform.h>
+
#include <Sluift/Completer.h>
using namespace Swift;
-static EditlineTerminal* globalInstance = NULL;
+static EditlineTerminal* globalInstance = nullptr;
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 nullptr;
+ }
+ 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
}
@@ -80,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 3608096..ec4cf63 100644
--- a/Sluift/EditlineTerminal.h
+++ b/Sluift/EditlineTerminal.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,19 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+
#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 35f1a72..f6797b0 100644
--- a/Sluift/ElementConvertors/BodyConvertor.cpp
+++ b/Sluift/ElementConvertors/BodyConvertor.cpp
@@ -1,13 +1,15 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/BodyConvertor.h>
+#include <memory>
+
#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+
#include <Sluift/Lua/LuaUtils.h>
using namespace Swift;
@@ -18,18 +20,18 @@ BodyConvertor::BodyConvertor() : GenericLuaElementConvertor<Body>("body") {
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;
+std::shared_ptr<Body> BodyConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<Body> result = std::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");
- }
+void BodyConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
diff --git a/Sluift/ElementConvertors/BodyConvertor.h b/Sluift/ElementConvertors/BodyConvertor.h
index c9d922b..64ff4d0 100644
--- a/Sluift/ElementConvertors/BodyConvertor.h
+++ b/Sluift/ElementConvertors/BodyConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,19 +7,19 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Body.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/Body.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 std::shared_ptr<Body> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::shared_ptr<Body>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/CarbonsReceivedConvertor.cpp b/Sluift/ElementConvertors/CarbonsReceivedConvertor.cpp
new file mode 100644
index 0000000..cfd55f3
--- /dev/null
+++ b/Sluift/ElementConvertors/CarbonsReceivedConvertor.cpp
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Sluift/ElementConvertors/CarbonsReceivedConvertor.h>
+
+#include <memory>
+#include <lua.hpp>
+
+#include <Swiften/Elements/Forwarded.h>
+
+#include <Sluift/LuaElementConvertors.h>
+
+using namespace Swift;
+
+CarbonsReceivedConvertor::CarbonsReceivedConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<CarbonsReceived>("carbons_received"),
+ convertors(convertors) {
+}
+
+CarbonsReceivedConvertor::~CarbonsReceivedConvertor() {
+}
+
+std::shared_ptr<CarbonsReceived> CarbonsReceivedConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<CarbonsReceived> result = std::make_shared<CarbonsReceived>();
+ lua_getfield(L, -1, "payload");
+ if (!lua_isnil(L, -1)) {
+ std::shared_ptr<Forwarded> payload = std::dynamic_pointer_cast<Forwarded>(convertors->convertFromLuaUntyped(L, -1, "payload"));
+ if (!!payload) {
+ result->setForwarded(payload);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
+}
+
+void CarbonsReceivedConvertor::doConvertToLua(lua_State* L, std::shared_ptr<CarbonsReceived> payload) {
+ lua_createtable(L, 0, 0);
+ if (convertors->convertToLuaUntyped(L, payload->getForwarded()) > 0) {
+ lua_setfield(L, -2, "payload");
+
+ }
+}
+
+boost::optional<LuaElementConvertor::Documentation> CarbonsReceivedConvertor::getDocumentation() const {
+ return Documentation(
+ "CarbonsReceived",
+ "This table has the following fields:\n\n"
+ "- `payload`: @{Forwarded}\n"
+ );
+}
diff --git a/Sluift/ElementConvertors/CarbonsReceivedConvertor.h b/Sluift/ElementConvertors/CarbonsReceivedConvertor.h
new file mode 100644
index 0000000..f18f699
--- /dev/null
+++ b/Sluift/ElementConvertors/CarbonsReceivedConvertor.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/CarbonsReceived.h>
+
+#include <Sluift/GenericLuaElementConvertor.h>
+
+namespace Swift {
+ class LuaElementConvertors;
+
+ class CarbonsReceivedConvertor : public GenericLuaElementConvertor<CarbonsReceived> {
+ public:
+ CarbonsReceivedConvertor(LuaElementConvertors* convertors);
+ virtual ~CarbonsReceivedConvertor();
+
+ virtual std::shared_ptr<CarbonsReceived> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::shared_ptr<CarbonsReceived>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+
+ private:
+ LuaElementConvertors* convertors;
+ };
+}
+
diff --git a/Sluift/ElementConvertors/CarbonsSentConvertor.cpp b/Sluift/ElementConvertors/CarbonsSentConvertor.cpp
new file mode 100644
index 0000000..45851d2
--- /dev/null
+++ b/Sluift/ElementConvertors/CarbonsSentConvertor.cpp
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Sluift/ElementConvertors/CarbonsSentConvertor.h>
+
+#include <memory>
+#include <lua.hpp>
+
+#include <Swiften/Elements/Forwarded.h>
+
+#include <Sluift/LuaElementConvertors.h>
+
+using namespace Swift;
+
+CarbonsSentConvertor::CarbonsSentConvertor(LuaElementConvertors* convertors) :
+ GenericLuaElementConvertor<CarbonsSent>("carbons_sent"),
+ convertors(convertors) {
+}
+
+CarbonsSentConvertor::~CarbonsSentConvertor() {
+}
+
+std::shared_ptr<CarbonsSent> CarbonsSentConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<CarbonsSent> result = std::make_shared<CarbonsSent>();
+ lua_getfield(L, -1, "payload");
+ if (!lua_isnil(L, -1)) {
+ std::shared_ptr<Forwarded> payload = std::dynamic_pointer_cast<Forwarded>(convertors->convertFromLuaUntyped(L, -1, "payload"));
+ if (!!payload) {
+ result->setForwarded(payload);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
+}
+
+void CarbonsSentConvertor::doConvertToLua(lua_State* L, std::shared_ptr<CarbonsSent> payload) {
+ lua_createtable(L, 0, 0);
+ if (convertors->convertToLuaUntyped(L, payload->getForwarded()) > 0) {
+ lua_setfield(L, -2, "payload");
+ }
+}
+
+boost::optional<LuaElementConvertor::Documentation> CarbonsSentConvertor::getDocumentation() const {
+ return Documentation(
+ "CarbonsSent",
+ "This table has the following fields:\n\n"
+ "- `payload`: @{Forwarded}\n"
+ );
+}
diff --git a/Sluift/ElementConvertors/CarbonsSentConvertor.h b/Sluift/ElementConvertors/CarbonsSentConvertor.h
new file mode 100644
index 0000000..a36a6a8
--- /dev/null
+++ b/Sluift/ElementConvertors/CarbonsSentConvertor.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/CarbonsSent.h>
+
+#include <Sluift/GenericLuaElementConvertor.h>
+
+namespace Swift {
+ class LuaElementConvertors;
+
+ class CarbonsSentConvertor : public GenericLuaElementConvertor<CarbonsSent> {
+ public:
+ CarbonsSentConvertor(LuaElementConvertors* convertors);
+ virtual ~CarbonsSentConvertor();
+
+ virtual std::shared_ptr<CarbonsSent> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::shared_ptr<CarbonsSent>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+
+ private:
+ LuaElementConvertors* convertors;
+ };
+}
+
diff --git a/Sluift/ElementConvertors/CommandConvertor.cpp b/Sluift/ElementConvertors/CommandConvertor.cpp
index c9fc952..de7a439 100644
--- a/Sluift/ElementConvertors/CommandConvertor.cpp
+++ b/Sluift/ElementConvertors/CommandConvertor.cpp
@@ -1,16 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/CommandConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/Base/foreach.h>
+#include <lua.hpp>
+
#include <Sluift/Lua/Check.h>
#include <Sluift/Lua/Value.h>
#include <Sluift/LuaElementConvertors.h>
@@ -18,179 +19,177 @@
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;
+std::shared_ptr<Command> CommandConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<Command> result = std::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);
+ 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);
+ 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 (std::shared_ptr<Form> form = std::dynamic_pointer_cast<Form>(convertors->convertFromLuaUntyped(L, -1, "form"))) {
+ result->setForm(form);
+ }
+ }
+ lua_pop(L, 1);
+
+ return result;
}
-void CommandConvertor::doConvertToLua(lua_State* L, 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");
- }
+void CommandConvertor::doConvertToLua(lua_State* L, std::shared_ptr<Command> payload) {
+ Lua::Table result;
+ if (!payload->getNode().empty()) {
+ result["node"] = Lua::valueRef(payload->getNode());
+ }
+ if (!payload->getSessionID().empty()) {
+ result["session_id"] = Lua::valueRef(payload->getSessionID());
+ }
+ switch (payload->getStatus()) {
+ case Command::Executing: result["status"] = Lua::valueRef("executing"); break;
+ case Command::Completed: result["status"] = Lua::valueRef("completed"); break;
+ case Command::Canceled: result["status"] = Lua::valueRef("canceled"); break;
+ case Command::NoStatus: break;
+ }
+
+ if (!payload->getNotes().empty()) {
+ std::vector<Lua::Value> notes;
+ for (const auto& note : payload->getNotes()) {
+ Lua::Table noteTable;
+ if (!note.note.empty()) {
+ noteTable["note"] = Lua::valueRef(note.note);
+ }
+ switch (note.type) {
+ case Command::Note::Info: noteTable["type"] = Lua::valueRef("info"); break;
+ case Command::Note::Warn: noteTable["type"] = Lua::valueRef("warn"); break;
+ case Command::Note::Error: noteTable["type"] = Lua::valueRef("error"); break;
+ }
+ notes.push_back(noteTable);
+ }
+ result["notes"] = Lua::valueRef(notes);
+ }
+
+ if (payload->getAction() != Command::NoAction) {
+ result["action"] = Lua::valueRef(convertActionToString(payload->getAction()));
+ }
+
+ if (payload->getExecuteAction() != Command::NoAction) {
+ result["execute_action"] = Lua::valueRef(convertActionToString(payload->getAction()));
+ }
+
+ if (!payload->getAvailableActions().empty()) {
+ std::vector<Lua::Value> availableActions;
+ for (const auto& action : payload->getAvailableActions()) {
+ if (action != Command::NoAction) {
+ availableActions.push_back(convertActionToString(action));
+ }
+ }
+ result["available_actions"] = Lua::valueRef(availableActions);
+ }
+
+ Lua::pushValue(L, result);
+
+ if (payload->getForm()) {
+ bool result = convertors->convertToLuaUntyped(L, payload->getForm());
+ assert(result);
+ lua_setfield(L, -2, "form");
+ }
}
diff --git a/Sluift/ElementConvertors/CommandConvertor.h b/Sluift/ElementConvertors/CommandConvertor.h
index 868fe5e..1b0d481 100644
--- a/Sluift/ElementConvertors/CommandConvertor.h
+++ b/Sluift/ElementConvertors/CommandConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,22 +7,22 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Command.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/Command.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 std::shared_ptr<Command> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::shared_ptr<Command>) SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/DOMElementConvertor.cpp b/Sluift/ElementConvertors/DOMElementConvertor.cpp
index 6ed214d..b957686 100644
--- a/Sluift/ElementConvertors/DOMElementConvertor.cpp
+++ b/Sluift/ElementConvertors/DOMElementConvertor.cpp
@@ -1,159 +1,159 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/DOMElementConvertor.h>
-#include <iostream>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/RawXMLPayload.h>
-#include <Swiften/Serializer/PayloadSerializer.h>
-#include <Sluift/Lua/Check.h>
-#include <Sluift/Lua/LuaUtils.h>
-#include <Swiften/Parser/XMLParserClient.h>
-#include <Swiften/Parser/XMLParser.h>
-#include <Swiften/Parser/AttributeMap.h>
#include <Swiften/Parser/Attribute.h>
+#include <Swiften/Parser/AttributeMap.h>
+#include <Swiften/Parser/XMLParser.h>
+#include <Swiften/Parser/XMLParserClient.h>
+#include <Swiften/Serializer/PayloadSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+#include <Swiften/Serializer/XML/XMLTextNode.h>
+
+#include <Sluift/Lua/Check.h>
#include <Sluift/Lua/Debug.h>
+#include <Sluift/Lua/LuaUtils.h>
using namespace Swift;
namespace {
- class ParserClient : public XMLParserClient {
- public:
- ParserClient(lua_State* L) : L(L), currentIndex(1) {
- }
-
- virtual void handleStartElement(
- const std::string& element, const std::string& ns,
- const AttributeMap& attributes) SWIFTEN_OVERRIDE {
- lua_checkstack(L, 6);
- lua_pushnumber(L, currentIndex);
- lua_newtable(L);
- lua_pushstring(L, element.c_str());
- lua_setfield(L, -2, "tag");
- if (!ns.empty()) {
- lua_pushstring(L, ns.c_str());
- lua_setfield(L, -2, "ns");
- }
- if (!attributes.getEntries().empty()) {
- lua_newtable(L);
- int i = 1;
- foreach(const AttributeMap::Entry& entry, attributes.getEntries()) {
- 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;
+ for (const auto& entry : attributes.getEntries()) {
+ lua_pushnumber(L, i);
+ lua_newtable(L);
+ lua_pushstring(L, entry.getAttribute().getName().c_str());
+ lua_setfield(L, -2, "name");
+ if (!entry.getAttribute().getNamespace().empty()) {
+ lua_pushstring(L, entry.getAttribute().getNamespace().c_str());
+ lua_setfield(L, -2, "ns");
+ }
+ lua_pushstring(L, entry.getValue().c_str());
+ lua_setfield(L, -2, "value");
+ lua_settable(L, -3);
+ ++i;
+ }
+ lua_setfield(L, -2, "attributes");
+ }
+
+ indexStack.push_back(currentIndex);
+ currentIndex = 1;
+ lua_newtable(L);
+ }
+
+ virtual void handleEndElement(
+ const std::string&, const std::string&) SWIFTEN_OVERRIDE {
+ lua_setfield(L, -2, "children");
+ lua_settable(L, -3);
+ currentIndex = indexStack.back();
+ indexStack.pop_back();
+ currentIndex++;
+ }
+
+ 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(std::make_shared<XMLTextNode>(lua_tostring(L, -1)));
+ }
+ else if (lua_istable(L, -1)) {
+ element.addNode(std::make_shared<XMLRawTextNode>(serializeElement(L)));
+ }
+ lua_pop(L, 1); // value
+ }
+ }
+ lua_pop(L, 1); // children
+
+ return element.serialize();
+ }
}
DOMElementConvertor::DOMElementConvertor() {
@@ -162,40 +162,40 @@ DOMElementConvertor::DOMElementConvertor() {
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());
+std::shared_ptr<Element> DOMElementConvertor::convertFromLua(lua_State* L, int index, const std::string& type) {
+ if (!lua_istable(L, index) || type != "dom") {
+ return std::shared_ptr<Payload>();
+ }
+ return std::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, std::shared_ptr<Element> element) {
+ // Serialize payload to XML
+ std::shared_ptr<Payload> payload = std::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);
+ std::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 610dbff..7b1ba58 100644
--- a/Sluift/ElementConvertors/DOMElementConvertor.h
+++ b/Sluift/ElementConvertors/DOMElementConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,22 +7,22 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Parser/PlatformXMLParserFactory.h>
+#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
#include <Sluift/LuaElementConvertor.h>
-#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
-#include <Swiften/Parser/PlatformXMLParserFactory.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 std::shared_ptr<Element> convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE;
+ virtual boost::optional<std::string> convertToLua(lua_State*, std::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 c95da93..75e6706 100644
--- a/Sluift/ElementConvertors/DefaultElementConvertor.cpp
+++ b/Sluift/ElementConvertors/DefaultElementConvertor.cpp
@@ -1,14 +1,15 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/DefaultElementConvertor.h>
-#include <iostream>
-#include <typeinfo>
#include <string>
+#include <typeinfo>
+
+#include <Swiften/Base/Log.h>
using namespace Swift;
@@ -18,13 +19,13 @@ DefaultElementConvertor::DefaultElementConvertor() {
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::shared_ptr<Element> DefaultElementConvertor::convertFromLua(lua_State*, int, const std::string& type) {
+ SWIFT_LOG(warning) << "Unable to convert type '" << type << "'" << std::endl;
+ return std::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;
+boost::optional<std::string> DefaultElementConvertor::convertToLua(lua_State*, std::shared_ptr<Element>) {
+ // 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..4aec300 100644
--- a/Sluift/ElementConvertors/DefaultElementConvertor.h
+++ b/Sluift/ElementConvertors/DefaultElementConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::shared_ptr<Element> convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE;
+ virtual boost::optional<std::string> convertToLua(lua_State*, std::shared_ptr<Element>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/DelayConvertor.cpp b/Sluift/ElementConvertors/DelayConvertor.cpp
index a17e114..f23e137 100644
--- a/Sluift/ElementConvertors/DelayConvertor.cpp
+++ b/Sluift/ElementConvertors/DelayConvertor.cpp
@@ -1,17 +1,21 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/DelayConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Sluift/Lua/Check.h>
+
+#include <lua.hpp>
+
#include <Swiften/Base/DateTime.h>
+#include <Sluift/Lua/Check.h>
+
using namespace Swift;
DelayConvertor::DelayConvertor() : GenericLuaElementConvertor<Delay>("delay") {
@@ -20,28 +24,28 @@ DelayConvertor::DelayConvertor() : GenericLuaElementConvertor<Delay>("delay") {
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;
+std::shared_ptr<Delay> DelayConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<Delay> result = std::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");
+void DelayConvertor::doConvertToLua(lua_State* L, std::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");
}
diff --git a/Sluift/ElementConvertors/DelayConvertor.h b/Sluift/ElementConvertors/DelayConvertor.h
index 6cee7de..b9f72f2 100644
--- a/Sluift/ElementConvertors/DelayConvertor.h
+++ b/Sluift/ElementConvertors/DelayConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,17 +7,17 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Delay.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/Delay.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 std::shared_ptr<Delay> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::shared_ptr<Delay>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/DiscoInfoConvertor.cpp b/Sluift/ElementConvertors/DiscoInfoConvertor.cpp
index d9a408e..2aa4a77 100644
--- a/Sluift/ElementConvertors/DiscoInfoConvertor.cpp
+++ b/Sluift/ElementConvertors/DiscoInfoConvertor.cpp
@@ -1,14 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/DiscoInfoConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
+
+#include <lua.hpp>
+
#include <Sluift/Lua/LuaUtils.h>
using namespace Swift;
@@ -19,98 +22,98 @@ DiscoInfoConvertor::DiscoInfoConvertor() : GenericLuaElementConvertor<DiscoInfo>
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;
+std::shared_ptr<DiscoInfo> DiscoInfoConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<DiscoInfo> result = std::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
+void DiscoInfoConvertor::doConvertToLua(lua_State* L, std::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
}
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 7c5009f..34f8237 100644
--- a/Sluift/ElementConvertors/DiscoInfoConvertor.h
+++ b/Sluift/ElementConvertors/DiscoInfoConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,18 +7,18 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/DiscoInfo.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/DiscoInfo.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 std::shared_ptr<DiscoInfo> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 6ec944a..c15a0f8 100644
--- a/Sluift/ElementConvertors/DiscoItemsConvertor.cpp
+++ b/Sluift/ElementConvertors/DiscoItemsConvertor.cpp
@@ -1,14 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/DiscoItemsConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
+
+#include <lua.hpp>
+
#include <Sluift/Lua/LuaUtils.h>
using namespace Swift;
@@ -19,50 +22,50 @@ DiscoItemsConvertor::DiscoItemsConvertor() : GenericLuaElementConvertor<DiscoIte
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;
+std::shared_ptr<DiscoItems> DiscoItemsConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<DiscoItems> result = std::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");
- }
+void DiscoItemsConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
diff --git a/Sluift/ElementConvertors/DiscoItemsConvertor.h b/Sluift/ElementConvertors/DiscoItemsConvertor.h
index 5e3a86c..a77b948 100644
--- a/Sluift/ElementConvertors/DiscoItemsConvertor.h
+++ b/Sluift/ElementConvertors/DiscoItemsConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,17 +7,17 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/DiscoItems.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/DiscoItems.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 std::shared_ptr<DiscoItems> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::shared_ptr<DiscoItems>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/ElementConvertors.ipp b/Sluift/ElementConvertors/ElementConvertors.ipp
index 7d25e86..a81c9cf 100644
--- a/Sluift/ElementConvertors/ElementConvertors.ipp
+++ b/Sluift/ElementConvertors/ElementConvertors.ipp
@@ -1,87 +1,87 @@
/*
- * Copyright (c) 2013-2014 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Sluift/ElementConvertors/PubSubRetractConvertor.h>
+#include <Sluift/ElementConvertors/IsodeIQDelegationConvertor.h>
+#include <Sluift/ElementConvertors/PubSubAffiliationConvertor.h>
#include <Sluift/ElementConvertors/PubSubAffiliationsConvertor.h>
-#include <Sluift/ElementConvertors/PubSubPublishConvertor.h>
-#include <Sluift/ElementConvertors/PubSubItemsConvertor.h>
-#include <Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h>
-#include <Sluift/ElementConvertors/PubSubEventRedirectConvertor.h>
-#include <Sluift/ElementConvertors/UserTuneConvertor.h>
#include <Sluift/ElementConvertors/PubSubConfigureConvertor.h>
-#include <Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h>
-#include <Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h>
-#include <Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h>
-#include <Sluift/ElementConvertors/UserLocationConvertor.h>
-#include <Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h>
-#include <Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h>
+#include <Sluift/ElementConvertors/PubSubCreateConvertor.h>
#include <Sluift/ElementConvertors/PubSubDefaultConvertor.h>
+#include <Sluift/ElementConvertors/PubSubEventAssociateConvertor.h>
#include <Sluift/ElementConvertors/PubSubEventCollectionConvertor.h>
-#include <Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h>
-#include <Sluift/ElementConvertors/PubSubEventRetractConvertor.h>
-#include <Sluift/ElementConvertors/PubSubItemConvertor.h>
-#include <Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h>
+#include <Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h>
#include <Sluift/ElementConvertors/PubSubEventDeleteConvertor.h>
-#include <Sluift/ElementConvertors/PubSubCreateConvertor.h>
-#include <Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h>
+#include <Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h>
+#include <Sluift/ElementConvertors/PubSubEventItemConvertor.h>
#include <Sluift/ElementConvertors/PubSubEventItemsConvertor.h>
+#include <Sluift/ElementConvertors/PubSubEventPurgeConvertor.h>
+#include <Sluift/ElementConvertors/PubSubEventRedirectConvertor.h>
+#include <Sluift/ElementConvertors/PubSubEventRetractConvertor.h>
+#include <Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h>
+#include <Sluift/ElementConvertors/PubSubItemConvertor.h>
+#include <Sluift/ElementConvertors/PubSubItemsConvertor.h>
#include <Sluift/ElementConvertors/PubSubOptionsConvertor.h>
-#include <Sluift/ElementConvertors/PubSubEventItemConvertor.h>
-#include <Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h>
-#include <Sluift/ElementConvertors/IsodeIQDelegationConvertor.h>
#include <Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.h>
-#include <Sluift/ElementConvertors/PubSubEventPurgeConvertor.h>
-#include <Sluift/ElementConvertors/PubSubAffiliationConvertor.h>
-#include <Sluift/ElementConvertors/PubSubSubscribeConvertor.h>
-#include <Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h>
+#include <Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h>
+#include <Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h>
#include <Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.h>
-#include <Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h>
-#include <Sluift/ElementConvertors/PubSubEventAssociateConvertor.h>
+#include <Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h>
+#include <Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h>
+#include <Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h>
+#include <Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h>
+#include <Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h>
+#include <Sluift/ElementConvertors/PubSubPublishConvertor.h>
+#include <Sluift/ElementConvertors/PubSubRetractConvertor.h>
+#include <Sluift/ElementConvertors/PubSubSubscribeConvertor.h>
+#include <Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h>
#include <Sluift/ElementConvertors/PubSubSubscriptionConvertor.h>
+#include <Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h>
+#include <Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h>
#include <Sluift/ElementConvertors/SecurityLabelConvertor.h>
-#include <Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h>
+#include <Sluift/ElementConvertors/UserLocationConvertor.h>
+#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>(this));
- convertors.push_back(boost::make_shared<PubSubEventRedirectConvertor>(this));
- convertors.push_back(boost::make_shared<UserTuneConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubConfigureConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubEventDisassociateConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubOwnerAffiliationsConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubOwnerConfigureConvertor>(this));
- convertors.push_back(boost::make_shared<UserLocationConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubSubscribeOptionsConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubOwnerSubscriptionsConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubDefaultConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubEventCollectionConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubEventSubscriptionConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubEventRetractConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubItemConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubUnsubscribeConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubEventDeleteConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubCreateConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubOwnerPurgeConvertor>(this));
- 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>(this));
- convertors.push_back(boost::make_shared<IsodeIQDelegationConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubOwnerAffiliationConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubEventPurgeConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubAffiliationConvertor>(this));
- 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>(this));
- convertors.push_back(boost::make_shared<PubSubSubscriptionConvertor>(this));
- convertors.push_back(boost::make_shared<SecurityLabelConvertor>(this));
- convertors.push_back(boost::make_shared<PubSubEventConfigurationConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubRetractConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubAffiliationsConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubPublishConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubItemsConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubOwnerRedirectConvertor>());
+ convertors.push_back(std::make_shared<PubSubEventRedirectConvertor>());
+ convertors.push_back(std::make_shared<UserTuneConvertor>());
+ convertors.push_back(std::make_shared<PubSubConfigureConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubEventDisassociateConvertor>());
+ convertors.push_back(std::make_shared<PubSubOwnerAffiliationsConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubOwnerConfigureConvertor>(this));
+ convertors.push_back(std::make_shared<UserLocationConvertor>());
+ convertors.push_back(std::make_shared<PubSubSubscribeOptionsConvertor>());
+ convertors.push_back(std::make_shared<PubSubOwnerSubscriptionsConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubDefaultConvertor>());
+ convertors.push_back(std::make_shared<PubSubEventCollectionConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubEventSubscriptionConvertor>());
+ convertors.push_back(std::make_shared<PubSubEventRetractConvertor>());
+ convertors.push_back(std::make_shared<PubSubItemConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubUnsubscribeConvertor>());
+ convertors.push_back(std::make_shared<PubSubEventDeleteConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubCreateConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubOwnerPurgeConvertor>());
+ convertors.push_back(std::make_shared<PubSubEventItemsConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubOptionsConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubEventItemConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubOwnerSubscriptionConvertor>());
+ convertors.push_back(std::make_shared<IsodeIQDelegationConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubOwnerAffiliationConvertor>());
+ convertors.push_back(std::make_shared<PubSubEventPurgeConvertor>());
+ convertors.push_back(std::make_shared<PubSubAffiliationConvertor>());
+ convertors.push_back(std::make_shared<PubSubSubscribeConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubOwnerDeleteConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubOwnerDefaultConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubSubscriptionsConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubEventAssociateConvertor>());
+ convertors.push_back(std::make_shared<PubSubSubscriptionConvertor>(this));
+ convertors.push_back(std::make_shared<SecurityLabelConvertor>());
+ convertors.push_back(std::make_shared<PubSubEventConfigurationConvertor>(this));
}
diff --git a/Sluift/ElementConvertors/FormConvertor.cpp b/Sluift/ElementConvertors/FormConvertor.cpp
index be1015c..90fd9fe 100644
--- a/Sluift/ElementConvertors/FormConvertor.cpp
+++ b/Sluift/ElementConvertors/FormConvertor.cpp
@@ -1,343 +1,343 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/FormConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <sstream>
+
+#include <boost/assign/list_of.hpp>
#include <boost/numeric/conversion/cast.hpp>
+
+#include <lua.hpp>
+
#include <Sluift/Lua/Check.h>
#include <Sluift/Lua/Value.h>
-#include <Swiften/Base/foreach.h>
-#include <boost/assign/list_of.hpp>
-#include <sstream>
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(std::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;
+ for (const auto& option : field->getOptions()) {
+ Lua::Table luaOption = boost::assign::map_list_of
+ ("label", Lua::valueRef(option.label))
+ ("value", Lua::valueRef(option.value));
+ options.push_back(luaOption);
+ }
+ luaField["options"] = valueRef(options);
+ }
+ return luaField;
+ }
+
+ Lua::Array convertFieldListToLua(const std::vector< std::shared_ptr<FormField> >& fieldList) {
+ Lua::Array fields;
+ for (auto&& field : fieldList) {
+ fields.push_back(convertFieldToLua(field));
+ }
+ return fields;
+ }
+
+
+ std::shared_ptr<FormField> convertFieldFromLua(lua_State* L) {
+ std::shared_ptr<FormField> result = std::make_shared<FormField>();
+ FormField::Type fieldType = FormField::UnknownType;
+ boost::optional<std::string> type = Lua::getStringField(L, -1, "type");
+ if (type) {
+ if (*type == "boolean") {
+ fieldType = FormField::BooleanType;
+ }
+ if (*type == "fixed") {
+ fieldType = FormField::FixedType;
+ }
+ if (*type == "hidden") {
+ fieldType = FormField::HiddenType;
+ }
+ if (*type == "list-single") {
+ fieldType = FormField::ListSingleType;
+ }
+ if (*type == "text-multi") {
+ fieldType = FormField::TextMultiType;
+ }
+ if (*type == "text-private") {
+ fieldType = FormField::TextPrivateType;
+ }
+ if (*type == "text-single") {
+ 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< std::shared_ptr<FormField> > convertFieldListFromLua(lua_State* L) {
+ std::vector< std::shared_ptr<FormField> > result;
+ for (lua_pushnil(L); lua_next(L, -2);) {
+ result.push_back(convertFieldFromLua(L));
+ lua_pop(L, 1);
+ }
+ return result;
+ }
+
+ std::shared_ptr<Form> convertFormFromLua(lua_State* L) {
+ std::shared_ptr<Form> result = std::make_shared<Form>();
+ if (boost::optional<std::string> title = Lua::getStringField(L, -1, "title")) {
+ result->setTitle(*title);
+ }
+ if (boost::optional<std::string> instructions = Lua::getStringField(L, -1, "instructions")) {
+ result->setInstructions(*instructions);
+ }
+ if (boost::optional<std::string> type = Lua::getStringField(L, -1, "type")) {
+ Form::Type formType = Form::FormType;
+ if (*type == "submit") {
+ formType = Form::SubmitType;
+ }
+ else if (*type == "cancel") {
+ formType = Form::CancelType;
+ }
+ else if (*type == "result") {
+ formType = Form::ResultType;
+ }
+ result->setType(formType);
+ }
+
+ lua_getfield(L, -1, "fields");
+ if (lua_istable(L, -1)) {
+ for (auto&& formField : convertFieldListFromLua(L)) {
+ result->addField(formField);
+ }
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, -1, "reported_fields");
+ if (lua_istable(L, -1)) {
+ for (auto&& formField : convertFieldListFromLua(L)) {
+ result->addReportedField(formField);
+ }
+ }
+ lua_pop(L, 1);
+
+ lua_getfield(L, -1, "items");
+ if (lua_istable(L, -1)) {
+ for (lua_pushnil(L); lua_next(L, -2);) {
+ result->addItem(convertFieldListFromLua(L));
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+
+ return result;
+ }
+
+ void convertFormToLua(lua_State* L, std::shared_ptr<Form> payload) {
+ std::string type;
+ switch (payload->getType()) {
+ case Form::FormType: type = "form"; break;
+ case Form::SubmitType: type = "submit"; break;
+ case Form::CancelType: type = "cancel"; break;
+ case Form::ResultType: type = "result"; break;
+ }
+
+ Lua::Table result = boost::assign::map_list_of("type", Lua::valueRef(type));
+ if (!payload->getTitle().empty()) {
+ result["title"] = Lua::valueRef(payload->getTitle());
+ }
+ if (!payload->getInstructions().empty()) {
+ result["instructions"] = Lua::valueRef(payload->getInstructions());
+ }
+ result["fields"] = valueRef(convertFieldListToLua(payload->getFields()));
+ if (!payload->getReportedFields().empty()) {
+ result["reported_fields"] = valueRef(convertFieldListToLua(payload->getReportedFields()));
+ }
+
+ if (!payload->getItems().empty()) {
+ Lua::Array luaItems;
+ for (const auto& item : payload->getItems()) {
+ if (!item.empty()) {
+ luaItems.push_back(convertFieldListToLua(item));
+ }
+ }
+ result["items"] = valueRef(luaItems);
+ }
+
+ Lua::pushValue(L, result);
+
+ lua_newtable(L);
+ lua_pushcfunction(L, formIndex);
+ lua_setfield(L, -2, "__index");
+ lua_pushcfunction(L, formNewIndex);
+ lua_setfield(L, -2, "__newindex");
+ lua_setmetatable(L, -2);
+ }
+
+ int createSubmission(lua_State* L) {
+ std::shared_ptr<Form> form = convertFormFromLua(L);
+
+ // Remove all redundant elements
+ form->setInstructions("");
+ form->setTitle("");
+ form->clearItems();
+ form->clearReportedFields();
+ std::vector< std::shared_ptr<FormField> > fields(form->getFields());
+ form->clearFields();
+ for (auto&& field : fields) {
+ if (field->getType() == FormField::FixedType) {
+ continue;
+ }
+ field->clearOptions();
+ field->setLabel("");
+ field->setType(FormField::UnknownType);
+ field->setDescription("");
+ form->addField(field);
+ }
+ form->setType(Form::SubmitType);
+
+ // Convert back
+ convertFormToLua(L, form);
+ Lua::registerTableToString(L, -1);
+
+ return 1;
+ }
}
FormConvertor::FormConvertor() : GenericLuaElementConvertor<Form>("form") {
@@ -346,14 +346,14 @@ FormConvertor::FormConvertor() : GenericLuaElementConvertor<Form>("form") {
FormConvertor::~FormConvertor() {
}
-boost::shared_ptr<Form> FormConvertor::doConvertFromLua(lua_State* L) {
- return convertFormFromLua(L);
+std::shared_ptr<Form> FormConvertor::doConvertFromLua(lua_State* L) {
+ return convertFormFromLua(L);
}
-void FormConvertor::doConvertToLua(lua_State* L, boost::shared_ptr<Form> payload) {
- convertFormToLua(L, payload);
+void FormConvertor::doConvertToLua(lua_State* L, std::shared_ptr<Form> 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 3c1542f..b32a940 100644
--- a/Sluift/ElementConvertors/FormConvertor.h
+++ b/Sluift/ElementConvertors/FormConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,17 +7,17 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Form.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/Form.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 std::shared_ptr<Form> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::shared_ptr<Form>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/ForwardedConvertor.cpp b/Sluift/ElementConvertors/ForwardedConvertor.cpp
index a6ec79c..b353eea 100644
--- a/Sluift/ElementConvertors/ForwardedConvertor.cpp
+++ b/Sluift/ElementConvertors/ForwardedConvertor.cpp
@@ -1,72 +1,74 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Sluift/ElementConvertors/ForwardedConvertor.h>
+
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+
#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Sluift/ElementConvertors/ForwardedConvertor.h>
-#include <Sluift/LuaElementConvertors.h>
+
#include <Swiften/Elements/Delay.h>
#include <Swiften/Elements/IQ.h>
-#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/Message.h>
+#include <Swiften/Elements/Presence.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <Sluift/LuaElementConvertors.h>
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;
+std::shared_ptr<Forwarded> ForwardedConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<Forwarded> result = std::make_shared<Forwarded>();
+ lua_getfield(L, -1, "delay");
+ if (!lua_isnil(L, -1)) {
+ std::shared_ptr<Delay> delay = std::dynamic_pointer_cast<Delay>(convertors->convertFromLuaUntyped(L, -1, "delay"));
+ if (!!delay) {
+ result->setDelay(delay);
+ }
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "stanza");
+ if (!lua_isnil(L, -1)) {
+ std::shared_ptr<Stanza> stanza = std::dynamic_pointer_cast<Stanza>(convertors->convertFromLua(L, -1));
+ 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");
- }
- }
+void ForwardedConvertor::doConvertToLua(lua_State* L, std::shared_ptr<Forwarded> payload) {
+ lua_createtable(L, 0, 0);
+ if (convertors->convertToLuaUntyped(L, payload->getDelay()) > 0) {
+ lua_setfield(L, -2, "delay");
+ }
+ std::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 a7d2586..a83b5f4 100644
--- a/Sluift/ElementConvertors/ForwardedConvertor.h
+++ b/Sluift/ElementConvertors/ForwardedConvertor.h
@@ -1,30 +1,31 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Sluift/GenericLuaElementConvertor.h>
#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Forwarded.h>
+#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 std::shared_ptr<Forwarded> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 e9119cb..67a4a2a 100644
--- a/Sluift/ElementConvertors/IQConvertor.cpp
+++ b/Sluift/ElementConvertors/IQConvertor.cpp
@@ -1,74 +1,75 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
-#include <lua.hpp>
#include <Sluift/ElementConvertors/IQConvertor.h>
-#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <memory>
+
+#include <lua.hpp>
+
+#include <Sluift/LuaElementConvertors.h>
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;
+std::shared_ptr<IQ> IQConvertor::doConvertFromLua(lua_State* L) {
+ std::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");
+void IQConvertor::doConvertToLua(lua_State* L, std::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");
}
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 b5351b7..859900a 100644
--- a/Sluift/ElementConvertors/IQConvertor.h
+++ b/Sluift/ElementConvertors/IQConvertor.h
@@ -1,33 +1,34 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Sluift/ElementConvertors/StanzaConvertor.h>
#include <Swiften/Base/Override.h>
#include <Swiften/Elements/IQ.h>
+#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 std::shared_ptr<IQ> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 c60a7aa..56b4a80 100644
--- a/Sluift/ElementConvertors/IsodeIQDelegationConvertor.cpp
+++ b/Sluift/ElementConvertors/IsodeIQDelegationConvertor.cpp
@@ -1,52 +1,50 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/IsodeIQDelegationConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <lua.hpp>
#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
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;
+std::shared_ptr<IsodeIQDelegation> IsodeIQDelegationConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<IsodeIQDelegation> result = std::make_shared<IsodeIQDelegation>();
+ lua_getfield(L, -1, "forward");
+ if (!lua_isnil(L, -1)) {
+ if (std::shared_ptr<Forwarded> payload = std::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");
- }
+void IsodeIQDelegationConvertor::doConvertToLua(lua_State* L, std::shared_ptr<IsodeIQDelegation> payload) {
+ 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 5af4944..f8b8c4a 100644
--- a/Sluift/ElementConvertors/IsodeIQDelegationConvertor.h
+++ b/Sluift/ElementConvertors/IsodeIQDelegationConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/IsodeIQDelegation.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/IsodeIQDelegation.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 std::shared_ptr<IsodeIQDelegation> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 25e4406..4fb8201 100644
--- a/Sluift/ElementConvertors/MAMFinConvertor.cpp
+++ b/Sluift/ElementConvertors/MAMFinConvertor.cpp
@@ -1,78 +1,81 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Sluift/ElementConvertors/MAMFinConvertor.h>
+
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+
#include <lua.hpp>
-#include <Sluift/ElementConvertors/MAMFinConvertor.h>
-#include <Sluift/LuaElementConvertors.h>
+
#include <Swiften/Elements/ResultSet.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <Sluift/LuaElementConvertors.h>
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;
+std::shared_ptr<MAMFin> MAMFinConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<MAMFin> result = std::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)) {
+ std::shared_ptr<ResultSet> resultSet = std::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");
- }
+void MAMFinConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 4021c00..371076a 100644
--- a/Sluift/ElementConvertors/MAMFinConvertor.h
+++ b/Sluift/ElementConvertors/MAMFinConvertor.h
@@ -1,29 +1,30 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Sluift/GenericLuaElementConvertor.h>
#include <Swiften/Base/Override.h>
#include <Swiften/Elements/MAMFin.h>
+#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 std::shared_ptr<MAMFin> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 d53fd9b..52337ce 100644
--- a/Sluift/ElementConvertors/MAMQueryConvertor.cpp
+++ b/Sluift/ElementConvertors/MAMQueryConvertor.cpp
@@ -1,85 +1,88 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Sluift/ElementConvertors/MAMQueryConvertor.h>
+
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+
#include <lua.hpp>
-#include <Sluift/ElementConvertors/MAMQueryConvertor.h>
-#include <Sluift/LuaElementConvertors.h>
+
#include <Swiften/Elements/Form.h>
#include <Swiften/Elements/ResultSet.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <Sluift/LuaElementConvertors.h>
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;
+std::shared_ptr<MAMQuery> MAMQueryConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<MAMQuery> result = std::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)) {
+ std::shared_ptr<Form> form = std::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)) {
+ std::shared_ptr<ResultSet> resultSet = std::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");
- }
+void MAMQueryConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 5169607..4ee119e 100644
--- a/Sluift/ElementConvertors/MAMQueryConvertor.h
+++ b/Sluift/ElementConvertors/MAMQueryConvertor.h
@@ -1,29 +1,30 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Sluift/GenericLuaElementConvertor.h>
#include <Swiften/Base/Override.h>
#include <Swiften/Elements/MAMQuery.h>
+#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 std::shared_ptr<MAMQuery> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 c163201..25b4c39 100644
--- a/Sluift/ElementConvertors/MAMResultConvertor.cpp
+++ b/Sluift/ElementConvertors/MAMResultConvertor.cpp
@@ -1,71 +1,73 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Sluift/ElementConvertors/MAMResultConvertor.h>
+
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+
#include <lua.hpp>
-#include <Sluift/ElementConvertors/MAMResultConvertor.h>
-#include <Sluift/LuaElementConvertors.h>
-#include <Swiften/Elements/Forwarded.h>
+#include <Swiften/Elements/Forwarded.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <Sluift/LuaElementConvertors.h>
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;
+std::shared_ptr<MAMResult> MAMResultConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<MAMResult> result = std::make_shared<MAMResult>();
+ lua_getfield(L, -1, "payload");
+ if (!lua_isnil(L, -1)) {
+ std::shared_ptr<Forwarded> payload = std::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");
- }
+void MAMResultConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 65d430a..a1b2564 100644
--- a/Sluift/ElementConvertors/MAMResultConvertor.h
+++ b/Sluift/ElementConvertors/MAMResultConvertor.h
@@ -1,29 +1,30 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Sluift/GenericLuaElementConvertor.h>
#include <Swiften/Base/Override.h>
#include <Swiften/Elements/MAMResult.h>
+#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 std::shared_ptr<MAMResult> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 d56e680..b7bf286 100644
--- a/Sluift/ElementConvertors/MessageConvertor.cpp
+++ b/Sluift/ElementConvertors/MessageConvertor.cpp
@@ -1,84 +1,85 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
-#include <lua.hpp>
#include <Sluift/ElementConvertors/MessageConvertor.h>
-#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <memory>
+
+#include <lua.hpp>
+
+#include <Sluift/LuaElementConvertors.h>
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;
+std::shared_ptr<Message> MessageConvertor::doConvertFromLua(lua_State* L) {
+ std::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");
+void MessageConvertor::doConvertToLua(lua_State* L, std::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");
}
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 f0da885..2031552 100644
--- a/Sluift/ElementConvertors/MessageConvertor.h
+++ b/Sluift/ElementConvertors/MessageConvertor.h
@@ -1,33 +1,34 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Sluift/ElementConvertors/StanzaConvertor.h>
#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Message.h>
+#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 std::shared_ptr<Message> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 4ab178c..abfac77 100644
--- a/Sluift/ElementConvertors/PresenceConvertor.cpp
+++ b/Sluift/ElementConvertors/PresenceConvertor.cpp
@@ -1,96 +1,97 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
-#include <lua.hpp>
#include <Sluift/ElementConvertors/PresenceConvertor.h>
-#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <memory>
+
+#include <lua.hpp>
+
+#include <Sluift/LuaElementConvertors.h>
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;
+std::shared_ptr<Presence> PresenceConvertor::doConvertFromLua(lua_State* L) {
+ std::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");
+void PresenceConvertor::doConvertToLua(lua_State* L, std::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");
}
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 fc4326e..11ec547 100644
--- a/Sluift/ElementConvertors/PresenceConvertor.h
+++ b/Sluift/ElementConvertors/PresenceConvertor.h
@@ -1,33 +1,34 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Sluift/ElementConvertors/StanzaConvertor.h>
#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Presence.h>
+#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 std::shared_ptr<Presence> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 c35488d..62a2b60 100644
--- a/Sluift/ElementConvertors/PubSubAffiliationConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubAffiliationConvertor.cpp
@@ -1,93 +1,88 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubAffiliationConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-
+#include <memory>
-
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-PubSubAffiliationConvertor::PubSubAffiliationConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubAffiliation>("pubsub_affiliation"),
- convertors(convertors) {
+PubSubAffiliationConvertor::PubSubAffiliationConvertor() :
+ 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;
+std::shared_ptr<PubSubAffiliation> PubSubAffiliationConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubAffiliation> result = std::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");
+void PubSubAffiliationConvertor::doConvertToLua(lua_State* L, std::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");
}
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 846dc38..456ef4e 100644
--- a/Sluift/ElementConvertors/PubSubAffiliationConvertor.h
+++ b/Sluift/ElementConvertors/PubSubAffiliationConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubAffiliation.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubAffiliation.h>
namespace Swift {
- class LuaElementConvertors;
-
- class PubSubAffiliationConvertor : public GenericLuaElementConvertor<PubSubAffiliation> {
- public:
- PubSubAffiliationConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubAffiliationConvertor();
+ class LuaElementConvertors;
- 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;
+ class PubSubAffiliationConvertor : public GenericLuaElementConvertor<PubSubAffiliation> {
+ public:
+ PubSubAffiliationConvertor();
+ virtual ~PubSubAffiliationConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<PubSubAffiliation> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 a338eda..c6ba09e 100644
--- a/Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp
@@ -1,79 +1,78 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubAffiliationsConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Sluift/LuaElementConvertors.h>
-#include <Swiften/Base/foreach.h>
+#include <lua.hpp>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <Sluift/LuaElementConvertors.h>
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);
- }
+std::shared_ptr<PubSubAffiliations> PubSubAffiliationsConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubAffiliations> result = std::make_shared<PubSubAffiliations>();
+ lua_getfield(L, -1, "node");
+ if (lua_isstring(L, -1)) {
+ result->setNode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ std::vector< std::shared_ptr<PubSubAffiliation> > items;
+ for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
+ lua_pushnumber(L, i + 1);
+ lua_gettable(L, -2);
+ if (!lua_isnil(L, -1)) {
+ if (std::shared_ptr<PubSubAffiliation> payload = std::dynamic_pointer_cast<PubSubAffiliation>(convertors->convertFromLuaUntyped(L, -1, "pubsub_affiliation"))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setAffiliations(items);
- }
- return result;
+ 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;
- }
- }
- }
- }
+void PubSubAffiliationsConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubAffiliations> payload) {
+ lua_createtable(L, 0, 0);
+ if (payload->getNode()) {
+ lua_pushstring(L, (*payload->getNode()).c_str());
+ lua_setfield(L, -2, "node");
+ }
+ if (!payload->getAffiliations().empty()) {
+ {
+ int i = 0;
+ for (auto&& item : payload->getAffiliations()) {
+ if (convertors->convertToLuaUntyped(L, item) > 0) {
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ ++i;
+ }
+ }
+ }
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubAffiliationsConvertor::getDocumentation() const {
- return Documentation(
- "PubSubAffiliations",
- "This table has the following fields:\n\n"
- "- `node`: string (Optional)\n"
- "- `affiliations`: array<@{PubSubAffiliation}>\n"
- );
+ 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 f398436..8ad38b2 100644
--- a/Sluift/ElementConvertors/PubSubAffiliationsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubAffiliationsConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubAffiliations.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubAffiliations.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 std::shared_ptr<PubSubAffiliations> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 be6b978..d8bf05d 100644
--- a/Sluift/ElementConvertors/PubSubConfigureConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubConfigureConvertor.cpp
@@ -1,52 +1,50 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubConfigureConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <lua.hpp>
#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
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;
+std::shared_ptr<PubSubConfigure> PubSubConfigureConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubConfigure> result = std::make_shared<PubSubConfigure>();
+ lua_getfield(L, -1, "data");
+ if (!lua_isnil(L, -1)) {
+ if (std::shared_ptr<Form> payload = std::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");
- }
+void PubSubConfigureConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubConfigure> payload) {
+ 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 4fc57b2..e41bb68 100644
--- a/Sluift/ElementConvertors/PubSubConfigureConvertor.h
+++ b/Sluift/ElementConvertors/PubSubConfigureConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubConfigure.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubConfigure.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 std::shared_ptr<PubSubConfigure> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 ac601d9..80553d5 100644
--- a/Sluift/ElementConvertors/PubSubCreateConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubCreateConvertor.cpp
@@ -1,60 +1,58 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubCreateConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <lua.hpp>
#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
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;
+std::shared_ptr<PubSubCreate> PubSubCreateConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubCreate> result = std::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 (std::shared_ptr<PubSubConfigure> payload = std::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");
- }
+void PubSubCreateConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 a4bf149..12c47da 100644
--- a/Sluift/ElementConvertors/PubSubCreateConvertor.h
+++ b/Sluift/ElementConvertors/PubSubCreateConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubCreate.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubCreate.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 std::shared_ptr<PubSubCreate> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 e0de984..8406913 100644
--- a/Sluift/ElementConvertors/PubSubDefaultConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubDefaultConvertor.cpp
@@ -1,77 +1,72 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubDefaultConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-
+#include <memory>
-
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-PubSubDefaultConvertor::PubSubDefaultConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubDefault>("pubsub_default"),
- convertors(convertors) {
+PubSubDefaultConvertor::PubSubDefaultConvertor() :
+ 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;
+std::shared_ptr<PubSubDefault> PubSubDefaultConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubDefault> result = std::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");
+void PubSubDefaultConvertor::doConvertToLua(lua_State* L, std::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");
}
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 9b6a01f..fbdbf95 100644
--- a/Sluift/ElementConvertors/PubSubDefaultConvertor.h
+++ b/Sluift/ElementConvertors/PubSubDefaultConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubDefault.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubDefault.h>
namespace Swift {
- class LuaElementConvertors;
-
- class PubSubDefaultConvertor : public GenericLuaElementConvertor<PubSubDefault> {
- public:
- PubSubDefaultConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubDefaultConvertor();
+ class LuaElementConvertors;
- 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;
+ class PubSubDefaultConvertor : public GenericLuaElementConvertor<PubSubDefault> {
+ public:
+ PubSubDefaultConvertor();
+ virtual ~PubSubDefaultConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<PubSubDefault> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 623ddc4..eb025a5 100644
--- a/Sluift/ElementConvertors/PubSubEventAssociateConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventAssociateConvertor.cpp
@@ -1,49 +1,44 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubEventAssociateConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-
+#include <memory>
-
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-PubSubEventAssociateConvertor::PubSubEventAssociateConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubEventAssociate>("pubsub_event_associate"),
- convertors(convertors) {
+PubSubEventAssociateConvertor::PubSubEventAssociateConvertor() :
+ 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;
+std::shared_ptr<PubSubEventAssociate> PubSubEventAssociateConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubEventAssociate> result = std::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");
+void PubSubEventAssociateConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubEventAssociate> payload) {
+ 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 6f4f3d8..975aa60 100644
--- a/Sluift/ElementConvertors/PubSubEventAssociateConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventAssociateConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubEventAssociate.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubEventAssociate.h>
namespace Swift {
- class LuaElementConvertors;
-
- class PubSubEventAssociateConvertor : public GenericLuaElementConvertor<PubSubEventAssociate> {
- public:
- PubSubEventAssociateConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubEventAssociateConvertor();
+ class LuaElementConvertors;
- 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;
+ class PubSubEventAssociateConvertor : public GenericLuaElementConvertor<PubSubEventAssociate> {
+ public:
+ PubSubEventAssociateConvertor();
+ virtual ~PubSubEventAssociateConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<PubSubEventAssociate> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 8fdfefa..721b1b4 100644
--- a/Sluift/ElementConvertors/PubSubEventCollectionConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventCollectionConvertor.cpp
@@ -1,73 +1,71 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubEventCollectionConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <lua.hpp>
#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
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;
+std::shared_ptr<PubSubEventCollection> PubSubEventCollectionConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubEventCollection> result = std::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 (std::shared_ptr<PubSubEventDisassociate> payload = std::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 (std::shared_ptr<PubSubEventAssociate> payload = std::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");
- }
+void PubSubEventCollectionConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 4226619..e8feada 100644
--- a/Sluift/ElementConvertors/PubSubEventCollectionConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventCollectionConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubEventCollection.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubEventCollection.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 std::shared_ptr<PubSubEventCollection> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 56f46ec..828a010 100644
--- a/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.cpp
@@ -1,60 +1,58 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <lua.hpp>
#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
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;
+std::shared_ptr<PubSubEventConfiguration> PubSubEventConfigurationConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubEventConfiguration> result = std::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 (std::shared_ptr<Form> payload = std::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");
- }
+void PubSubEventConfigurationConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 ce76da4..dd327d4 100644
--- a/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubEventConfiguration.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubEventConfiguration.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 std::shared_ptr<PubSubEventConfiguration> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 ae4374c..da7c849 100644
--- a/Sluift/ElementConvertors/PubSubEventConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventConvertor.cpp
@@ -1,37 +1,35 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubEventConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <lua.hpp>
#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
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;
+std::shared_ptr<PubSubEvent> PubSubEventConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubEvent> result = std::make_shared<PubSubEvent>();
+ if (std::shared_ptr<PubSubEventPayload> payload = std::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());
+void PubSubEventConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubEvent> event) {
+ convertors->convertToLua(L, event->getPayload());
}
diff --git a/Sluift/ElementConvertors/PubSubEventConvertor.h b/Sluift/ElementConvertors/PubSubEventConvertor.h
index 3bb4594..8b0cbec 100644
--- a/Sluift/ElementConvertors/PubSubEventConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,22 +7,22 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubEvent.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubEvent.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 std::shared_ptr<PubSubEvent> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::shared_ptr<PubSubEvent>) SWIFTEN_OVERRIDE;
- private:
- LuaElementConvertors* convertors;
- };
+ private:
+ LuaElementConvertors* convertors;
+ };
}
diff --git a/Sluift/ElementConvertors/PubSubEventDeleteConvertor.cpp b/Sluift/ElementConvertors/PubSubEventDeleteConvertor.cpp
index 29ead48..06fb3a2 100644
--- a/Sluift/ElementConvertors/PubSubEventDeleteConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventDeleteConvertor.cpp
@@ -1,60 +1,58 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubEventDeleteConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <lua.hpp>
#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
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;
+std::shared_ptr<PubSubEventDelete> PubSubEventDeleteConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubEventDelete> result = std::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 (std::shared_ptr<PubSubEventRedirect> payload = std::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");
- }
+void PubSubEventDeleteConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 e229781..ba2b0b8 100644
--- a/Sluift/ElementConvertors/PubSubEventDeleteConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventDeleteConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubEventDelete.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubEventDelete.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 std::shared_ptr<PubSubEventDelete> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 9ca8395..0ada5ce 100644
--- a/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.cpp
@@ -1,49 +1,44 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-
+#include <memory>
-
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-PubSubEventDisassociateConvertor::PubSubEventDisassociateConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubEventDisassociate>("pubsub_event_disassociate"),
- convertors(convertors) {
+PubSubEventDisassociateConvertor::PubSubEventDisassociateConvertor() :
+ 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;
+std::shared_ptr<PubSubEventDisassociate> PubSubEventDisassociateConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubEventDisassociate> result = std::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");
+void PubSubEventDisassociateConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubEventDisassociate> payload) {
+ 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 25a3863..0a1d678 100644
--- a/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubEventDisassociate.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubEventDisassociate.h>
namespace Swift {
- class LuaElementConvertors;
-
- class PubSubEventDisassociateConvertor : public GenericLuaElementConvertor<PubSubEventDisassociate> {
- public:
- PubSubEventDisassociateConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubEventDisassociateConvertor();
+ class LuaElementConvertors;
- 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;
+ class PubSubEventDisassociateConvertor : public GenericLuaElementConvertor<PubSubEventDisassociate> {
+ public:
+ PubSubEventDisassociateConvertor();
+ virtual ~PubSubEventDisassociateConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<PubSubEventDisassociate> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 43a64ff..ac86024 100644
--- a/Sluift/ElementConvertors/PubSubEventItemConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventItemConvertor.cpp
@@ -1,103 +1,102 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubEventItemConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Sluift/LuaElementConvertors.h>
-#include <Swiften/Base/foreach.h>
+#include <lua.hpp>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <Sluift/LuaElementConvertors.h>
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);
- }
+std::shared_ptr<PubSubEventItem> PubSubEventItemConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubEventItem> result = std::make_shared<PubSubEventItem>();
+ lua_getfield(L, -1, "node");
+ if (lua_isstring(L, -1)) {
+ result->setNode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "publisher");
+ if (lua_isstring(L, -1)) {
+ result->setPublisher(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "data");
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ std::vector< std::shared_ptr<Payload> > items;
+ for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
+ lua_pushnumber(L, i + 1);
+ lua_gettable(L, -2);
+ if (!lua_isnil(L, -1)) {
+ if (std::shared_ptr<Payload> payload = std::dynamic_pointer_cast<Payload>(convertors->convertFromLua(L, -1))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setData(items);
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "id");
- if (lua_isstring(L, -1)) {
- result->setID(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ 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");
- }
+void PubSubEventItemConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubEventItem> payload) {
+ lua_createtable(L, 0, 0);
+ if (payload->getNode()) {
+ lua_pushstring(L, (*payload->getNode()).c_str());
+ lua_setfield(L, -2, "node");
+ }
+ if (payload->getPublisher()) {
+ lua_pushstring(L, (*payload->getPublisher()).c_str());
+ lua_setfield(L, -2, "publisher");
+ }
+ if (!payload->getData().empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(payload->getData().size()), 0);
+ {
+ int i = 0;
+ for (auto&& item : payload->getData()) {
+ if (convertors->convertToLua(L, item) > 0) {
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ ++i;
+ }
+ }
+ }
+ lua_setfield(L, -2, "data");
+ }
+ if (payload->getID()) {
+ lua_pushstring(L, (*payload->getID()).c_str());
+ lua_setfield(L, -2, "id");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubEventItemConvertor::getDocumentation() const {
- return Documentation(
- "PubSubEventItem",
- "This table has the following fields:\n\n"
- "- `node`: string (Optional)\n"
- "- `publisher`: string (Optional)\n"
- "- `data`: array<element (table)>\n"
- "- `id`: string (Optional)\n"
- );
+ 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 c7dac83..6239b14 100644
--- a/Sluift/ElementConvertors/PubSubEventItemConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventItemConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubEventItem.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubEventItem.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 std::shared_ptr<PubSubEventItem> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 3287a6d..7a3cde1 100644
--- a/Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp
@@ -1,112 +1,111 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubEventItemsConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Sluift/LuaElementConvertors.h>
-#include <Swiften/Base/foreach.h>
+#include <lua.hpp>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <Sluift/LuaElementConvertors.h>
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);
- }
+std::shared_ptr<PubSubEventItems> PubSubEventItemsConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubEventItems> result = std::make_shared<PubSubEventItems>();
+ lua_getfield(L, -1, "node");
+ if (lua_isstring(L, -1)) {
+ result->setNode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "items");
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ std::vector< std::shared_ptr<PubSubEventItem> > items;
+ for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
+ lua_pushnumber(L, i + 1);
+ lua_gettable(L, -2);
+ if (!lua_isnil(L, -1)) {
+ if (std::shared_ptr<PubSubEventItem> payload = std::dynamic_pointer_cast<PubSubEventItem>(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_item"))) {
+ items.push_back(payload);
+ }
+ }
+ 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< std::shared_ptr<PubSubEventRetract> > items;
+ for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
+ lua_pushnumber(L, i + 1);
+ lua_gettable(L, -2);
+ if (!lua_isnil(L, -1)) {
+ if (std::shared_ptr<PubSubEventRetract> payload = std::dynamic_pointer_cast<PubSubEventRetract>(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_retract"))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setRetracts(items);
- }
- lua_pop(L, 1);
- return result;
+ 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");
- }
+void PubSubEventItemsConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubEventItems> payload) {
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ if (!payload->getItems().empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(payload->getItems().size()), 0);
+ {
+ int i = 0;
+ for (auto&& item : payload->getItems()) {
+ if (convertors->convertToLuaUntyped(L, item) > 0) {
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ ++i;
+ }
+ }
+ }
+ lua_setfield(L, -2, "items");
+ }
+ if (!payload->getRetracts().empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(payload->getRetracts().size()), 0);
+ {
+ int i = 0;
+ for (auto&& item : payload->getRetracts()) {
+ if (convertors->convertToLuaUntyped(L, item) > 0) {
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ ++i;
+ }
+ }
+ }
+ lua_setfield(L, -2, "retracts");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubEventItemsConvertor::getDocumentation() const {
- return Documentation(
- "PubSubEventItems",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- "- `items`: array<@{PubSubEventItem}>\n"
- "- `retracts`: array<@{PubSubEventRetract}>\n"
- );
+ 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 c409a3c..ea8942b 100644
--- a/Sluift/ElementConvertors/PubSubEventItemsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventItemsConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubEventItems.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubEventItems.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 std::shared_ptr<PubSubEventItems> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 e4604c0..223eedd 100644
--- a/Sluift/ElementConvertors/PubSubEventPurgeConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventPurgeConvertor.cpp
@@ -1,49 +1,44 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubEventPurgeConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-
+#include <memory>
-
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-PubSubEventPurgeConvertor::PubSubEventPurgeConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubEventPurge>("pubsub_event_purge"),
- convertors(convertors) {
+PubSubEventPurgeConvertor::PubSubEventPurgeConvertor() :
+ 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;
+std::shared_ptr<PubSubEventPurge> PubSubEventPurgeConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubEventPurge> result = std::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");
+void PubSubEventPurgeConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubEventPurge> payload) {
+ 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 39e571d..e3321b1 100644
--- a/Sluift/ElementConvertors/PubSubEventPurgeConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventPurgeConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubEventPurge.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubEventPurge.h>
namespace Swift {
- class LuaElementConvertors;
-
- class PubSubEventPurgeConvertor : public GenericLuaElementConvertor<PubSubEventPurge> {
- public:
- PubSubEventPurgeConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubEventPurgeConvertor();
+ class LuaElementConvertors;
- 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;
+ class PubSubEventPurgeConvertor : public GenericLuaElementConvertor<PubSubEventPurge> {
+ public:
+ PubSubEventPurgeConvertor();
+ virtual ~PubSubEventPurgeConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<PubSubEventPurge> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 3c0555e..673b320 100644
--- a/Sluift/ElementConvertors/PubSubEventRedirectConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventRedirectConvertor.cpp
@@ -1,49 +1,44 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubEventRedirectConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-
+#include <memory>
-
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-PubSubEventRedirectConvertor::PubSubEventRedirectConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubEventRedirect>("pubsub_event_redirect"),
- convertors(convertors) {
+PubSubEventRedirectConvertor::PubSubEventRedirectConvertor() :
+ 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;
+std::shared_ptr<PubSubEventRedirect> PubSubEventRedirectConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubEventRedirect> result = std::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");
+void PubSubEventRedirectConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubEventRedirect> payload) {
+ 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 90b9d49..b1f33d2 100644
--- a/Sluift/ElementConvertors/PubSubEventRedirectConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventRedirectConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubEventRedirect.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubEventRedirect.h>
namespace Swift {
- class LuaElementConvertors;
-
- class PubSubEventRedirectConvertor : public GenericLuaElementConvertor<PubSubEventRedirect> {
- public:
- PubSubEventRedirectConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubEventRedirectConvertor();
+ class LuaElementConvertors;
- 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;
+ class PubSubEventRedirectConvertor : public GenericLuaElementConvertor<PubSubEventRedirect> {
+ public:
+ PubSubEventRedirectConvertor();
+ virtual ~PubSubEventRedirectConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<PubSubEventRedirect> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 f4f1cfb..5981922 100644
--- a/Sluift/ElementConvertors/PubSubEventRetractConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventRetractConvertor.cpp
@@ -1,49 +1,44 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubEventRetractConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-
+#include <memory>
-
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-PubSubEventRetractConvertor::PubSubEventRetractConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubEventRetract>("pubsub_event_retract"),
- convertors(convertors) {
+PubSubEventRetractConvertor::PubSubEventRetractConvertor() :
+ 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;
+std::shared_ptr<PubSubEventRetract> PubSubEventRetractConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubEventRetract> result = std::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");
+void PubSubEventRetractConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubEventRetract> payload) {
+ 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 0e3b303..65aac36 100644
--- a/Sluift/ElementConvertors/PubSubEventRetractConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventRetractConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubEventRetract.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubEventRetract.h>
namespace Swift {
- class LuaElementConvertors;
-
- class PubSubEventRetractConvertor : public GenericLuaElementConvertor<PubSubEventRetract> {
- public:
- PubSubEventRetractConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubEventRetractConvertor();
+ class LuaElementConvertors;
- 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;
+ class PubSubEventRetractConvertor : public GenericLuaElementConvertor<PubSubEventRetract> {
+ public:
+ PubSubEventRetractConvertor();
+ virtual ~PubSubEventRetractConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<PubSubEventRetract> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 7eec64d..cab78d4 100644
--- a/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.cpp
@@ -1,107 +1,104 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <lua.hpp>
#include <Swiften/Base/DateTime.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
using namespace Swift;
-PubSubEventSubscriptionConvertor::PubSubEventSubscriptionConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubEventSubscription>("pubsub_event_subscription"),
- convertors(convertors) {
+PubSubEventSubscriptionConvertor::PubSubEventSubscriptionConvertor() :
+ 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;
+std::shared_ptr<PubSubEventSubscription> PubSubEventSubscriptionConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubEventSubscription> result = std::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");
+void PubSubEventSubscriptionConvertor::doConvertToLua(lua_State* L, std::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");
}
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 c254e34..0b3181b 100644
--- a/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h
+++ b/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubEventSubscription.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubEventSubscription.h>
namespace Swift {
- class LuaElementConvertors;
-
- class PubSubEventSubscriptionConvertor : public GenericLuaElementConvertor<PubSubEventSubscription> {
- public:
- PubSubEventSubscriptionConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubEventSubscriptionConvertor();
+ class LuaElementConvertors;
- 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;
+ class PubSubEventSubscriptionConvertor : public GenericLuaElementConvertor<PubSubEventSubscription> {
+ public:
+ PubSubEventSubscriptionConvertor();
+ virtual ~PubSubEventSubscriptionConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<PubSubEventSubscription> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 61aa17c..27fd4a3 100644
--- a/Sluift/ElementConvertors/PubSubItemConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubItemConvertor.cpp
@@ -1,81 +1,80 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubItemConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Sluift/LuaElementConvertors.h>
-#include <Swiften/Base/foreach.h>
+#include <lua.hpp>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <Sluift/LuaElementConvertors.h>
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);
- }
+std::shared_ptr<PubSubItem> PubSubItemConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubItem> result = std::make_shared<PubSubItem>();
+ lua_getfield(L, -1, "data");
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ std::vector< std::shared_ptr<Payload> > items;
+ for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
+ lua_pushnumber(L, i + 1);
+ lua_gettable(L, -2);
+ if (!lua_isnil(L, -1)) {
+ if (std::shared_ptr<Payload> payload = std::dynamic_pointer_cast<Payload>(convertors->convertFromLua(L, -1))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setData(items);
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "id");
- if (lua_isstring(L, -1)) {
- result->setID(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ 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");
+void PubSubItemConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubItem> payload) {
+ lua_createtable(L, 0, 0);
+ if (!payload->getData().empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(payload->getData().size()), 0);
+ {
+ int i = 0;
+ for (auto&& item : payload->getData()) {
+ if (convertors->convertToLua(L, item) > 0) {
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ ++i;
+ }
+ }
+ }
+ lua_setfield(L, -2, "data");
+ }
+ lua_pushstring(L, payload->getID().c_str());
+ lua_setfield(L, -2, "id");
}
boost::optional<LuaElementConvertor::Documentation> PubSubItemConvertor::getDocumentation() const {
- return Documentation(
- "PubSubItem",
- "This table has the following fields:\n\n"
- "- `data`: array<element (table)>\n"
- "- `id`: string\n"
- );
+ 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 334c15c..2772932 100644
--- a/Sluift/ElementConvertors/PubSubItemConvertor.h
+++ b/Sluift/ElementConvertors/PubSubItemConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubItem.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubItem.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 std::shared_ptr<PubSubItem> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 8ce1884..5fa1bd3 100644
--- a/Sluift/ElementConvertors/PubSubItemsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubItemsConvertor.cpp
@@ -1,97 +1,96 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubItemsConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Sluift/LuaElementConvertors.h>
-#include <Swiften/Base/foreach.h>
+#include <lua.hpp>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <Sluift/LuaElementConvertors.h>
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);
- }
+std::shared_ptr<PubSubItems> PubSubItemsConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubItems> result = std::make_shared<PubSubItems>();
+ lua_getfield(L, -1, "node");
+ if (lua_isstring(L, -1)) {
+ result->setNode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ std::vector< std::shared_ptr<PubSubItem> > items;
+ for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
+ lua_pushnumber(L, i + 1);
+ lua_gettable(L, -2);
+ if (!lua_isnil(L, -1)) {
+ if (std::shared_ptr<PubSubItem> payload = std::dynamic_pointer_cast<PubSubItem>(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setItems(items);
- }
- lua_getfield(L, -1, "maximum_items");
- if (lua_isnumber(L, -1)) {
- result->setMaximumItems(boost::numeric_cast<unsigned int>(lua_tonumber(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "subscription_id");
- if (lua_isstring(L, -1)) {
- result->setSubscriptionID(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ 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");
- }
+void PubSubItemsConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubItems> payload) {
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ if (!payload->getItems().empty()) {
+ {
+ int i = 0;
+ for (auto&& item : payload->getItems()) {
+ if (convertors->convertToLuaUntyped(L, item) > 0) {
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ ++i;
+ }
+ }
+ }
+ }
+ if (payload->getMaximumItems()) {
+ lua_pushnumber(L, (*payload->getMaximumItems()));
+ lua_setfield(L, -2, "maximum_items");
+ }
+ if (payload->getSubscriptionID()) {
+ lua_pushstring(L, (*payload->getSubscriptionID()).c_str());
+ lua_setfield(L, -2, "subscription_id");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubItemsConvertor::getDocumentation() const {
- return Documentation(
- "PubSubItems",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- "- `items`: array<@{PubSubItem}>\n"
- "- `maximum_items`: number (Optional)\n"
- "- `subscription_id`: string (Optional)\n"
- );
+ 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 801c2d8..56348b0 100644
--- a/Sluift/ElementConvertors/PubSubItemsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubItemsConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubItems.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubItems.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 std::shared_ptr<PubSubItems> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 dcb37a5..3582c63 100644
--- a/Sluift/ElementConvertors/PubSubOptionsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOptionsConvertor.cpp
@@ -1,78 +1,76 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubOptionsConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <lua.hpp>
#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
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;
+std::shared_ptr<PubSubOptions> PubSubOptionsConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubOptions> result = std::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 (std::shared_ptr<Form> payload = std::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");
- }
+void PubSubOptionsConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 8aacdbd..60d11cc 100644
--- a/Sluift/ElementConvertors/PubSubOptionsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOptionsConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubOptions.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubOptions.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 std::shared_ptr<PubSubOptions> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 bfcd4c4..15a800b 100644
--- a/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.cpp
@@ -1,93 +1,88 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-
+#include <memory>
-
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-PubSubOwnerAffiliationConvertor::PubSubOwnerAffiliationConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubOwnerAffiliation>("pubsub_owner_affiliation"),
- convertors(convertors) {
+PubSubOwnerAffiliationConvertor::PubSubOwnerAffiliationConvertor() :
+ 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;
+std::shared_ptr<PubSubOwnerAffiliation> PubSubOwnerAffiliationConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubOwnerAffiliation> result = std::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");
+void PubSubOwnerAffiliationConvertor::doConvertToLua(lua_State* L, std::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");
}
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 f16503f..9020482 100644
--- a/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubOwnerAffiliation.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubOwnerAffiliation.h>
namespace Swift {
- class LuaElementConvertors;
-
- class PubSubOwnerAffiliationConvertor : public GenericLuaElementConvertor<PubSubOwnerAffiliation> {
- public:
- PubSubOwnerAffiliationConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubOwnerAffiliationConvertor();
+ class LuaElementConvertors;
- 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;
+ class PubSubOwnerAffiliationConvertor : public GenericLuaElementConvertor<PubSubOwnerAffiliation> {
+ public:
+ PubSubOwnerAffiliationConvertor();
+ virtual ~PubSubOwnerAffiliationConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<PubSubOwnerAffiliation> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 85f9c3f..ee8a8cb 100644
--- a/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp
@@ -1,77 +1,76 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Sluift/LuaElementConvertors.h>
-#include <Swiften/Base/foreach.h>
+#include <lua.hpp>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <Sluift/LuaElementConvertors.h>
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);
- }
+std::shared_ptr<PubSubOwnerAffiliations> PubSubOwnerAffiliationsConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubOwnerAffiliations> result = std::make_shared<PubSubOwnerAffiliations>();
+ lua_getfield(L, -1, "node");
+ if (lua_isstring(L, -1)) {
+ result->setNode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ std::vector< std::shared_ptr<PubSubOwnerAffiliation> > items;
+ for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
+ lua_pushnumber(L, i + 1);
+ lua_gettable(L, -2);
+ if (!lua_isnil(L, -1)) {
+ if (std::shared_ptr<PubSubOwnerAffiliation> payload = std::dynamic_pointer_cast<PubSubOwnerAffiliation>(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_affiliation"))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setAffiliations(items);
- }
- return result;
+ 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;
- }
- }
- }
- }
+void PubSubOwnerAffiliationsConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubOwnerAffiliations> payload) {
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ if (!payload->getAffiliations().empty()) {
+ {
+ int i = 0;
+ for (auto&& item : payload->getAffiliations()) {
+ if (convertors->convertToLuaUntyped(L, item) > 0) {
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ ++i;
+ }
+ }
+ }
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubOwnerAffiliationsConvertor::getDocumentation() const {
- return Documentation(
- "PubSubOwnerAffiliations",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- "- `affiliations`: array<@{PubSubOwnerAffiliation}>\n"
- );
+ 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 63ed4a7..3026e2c 100644
--- a/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubOwnerAffiliations.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubOwnerAffiliations.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 std::shared_ptr<PubSubOwnerAffiliations> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 1c8c0fb..d179152 100644
--- a/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.cpp
@@ -1,62 +1,60 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <lua.hpp>
#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
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;
+std::shared_ptr<PubSubOwnerConfigure> PubSubOwnerConfigureConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubOwnerConfigure> result = std::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 (std::shared_ptr<Form> payload = std::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");
- }
+void PubSubOwnerConfigureConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 d02336d..4b39fdf 100644
--- a/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubOwnerConfigure.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubOwnerConfigure.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 std::shared_ptr<PubSubOwnerConfigure> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 9879be2..b2ff3de 100644
--- a/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.cpp
@@ -1,52 +1,50 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <lua.hpp>
#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
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;
+std::shared_ptr<PubSubOwnerDefault> PubSubOwnerDefaultConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubOwnerDefault> result = std::make_shared<PubSubOwnerDefault>();
+ lua_getfield(L, -1, "data");
+ if (!lua_isnil(L, -1)) {
+ if (std::shared_ptr<Form> payload = std::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");
- }
+void PubSubOwnerDefaultConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubOwnerDefault> payload) {
+ 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 932c3ae..ae0f018 100644
--- a/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubOwnerDefault.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubOwnerDefault.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 std::shared_ptr<PubSubOwnerDefault> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 e6e2b4f..3733d74 100644
--- a/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.cpp
@@ -1,60 +1,58 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <lua.hpp>
#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
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;
+std::shared_ptr<PubSubOwnerDelete> PubSubOwnerDeleteConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubOwnerDelete> result = std::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 (std::shared_ptr<PubSubOwnerRedirect> payload = std::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");
- }
+void PubSubOwnerDeleteConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 a48dcf9..54a2cf9 100644
--- a/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubOwnerDelete.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubOwnerDelete.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 std::shared_ptr<PubSubOwnerDelete> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 5b605bd..98c6355 100644
--- a/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.cpp
@@ -1,49 +1,44 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-
+#include <memory>
-
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-PubSubOwnerPurgeConvertor::PubSubOwnerPurgeConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubOwnerPurge>("pubsub_owner_purge"),
- convertors(convertors) {
+PubSubOwnerPurgeConvertor::PubSubOwnerPurgeConvertor() :
+ 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;
+std::shared_ptr<PubSubOwnerPurge> PubSubOwnerPurgeConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubOwnerPurge> result = std::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");
+void PubSubOwnerPurgeConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubOwnerPurge> payload) {
+ 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 45bba63..4696f45 100644
--- a/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubOwnerPurge.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubOwnerPurge.h>
namespace Swift {
- class LuaElementConvertors;
-
- class PubSubOwnerPurgeConvertor : public GenericLuaElementConvertor<PubSubOwnerPurge> {
- public:
- PubSubOwnerPurgeConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubOwnerPurgeConvertor();
+ class LuaElementConvertors;
- 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;
+ class PubSubOwnerPurgeConvertor : public GenericLuaElementConvertor<PubSubOwnerPurge> {
+ public:
+ PubSubOwnerPurgeConvertor();
+ virtual ~PubSubOwnerPurgeConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<PubSubOwnerPurge> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 4ac5573..8fc20d2 100644
--- a/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.cpp
@@ -1,49 +1,44 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-
+#include <memory>
-
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-PubSubOwnerRedirectConvertor::PubSubOwnerRedirectConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubOwnerRedirect>("pubsub_owner_redirect"),
- convertors(convertors) {
+PubSubOwnerRedirectConvertor::PubSubOwnerRedirectConvertor() :
+ 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;
+std::shared_ptr<PubSubOwnerRedirect> PubSubOwnerRedirectConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubOwnerRedirect> result = std::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");
+void PubSubOwnerRedirectConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubOwnerRedirect> payload) {
+ 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 e563f97..3517a49 100644
--- a/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubOwnerRedirect.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubOwnerRedirect.h>
namespace Swift {
- class LuaElementConvertors;
-
- class PubSubOwnerRedirectConvertor : public GenericLuaElementConvertor<PubSubOwnerRedirect> {
- public:
- PubSubOwnerRedirectConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubOwnerRedirectConvertor();
+ class LuaElementConvertors;
- 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;
+ class PubSubOwnerRedirectConvertor : public GenericLuaElementConvertor<PubSubOwnerRedirect> {
+ public:
+ PubSubOwnerRedirectConvertor();
+ virtual ~PubSubOwnerRedirectConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<PubSubOwnerRedirect> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 844d669..e0b3687 100644
--- a/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.cpp
@@ -1,81 +1,76 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-
+#include <memory>
-
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-PubSubOwnerSubscriptionConvertor::PubSubOwnerSubscriptionConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubOwnerSubscription>("pubsub_owner_subscription"),
- convertors(convertors) {
+PubSubOwnerSubscriptionConvertor::PubSubOwnerSubscriptionConvertor() :
+ 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;
+std::shared_ptr<PubSubOwnerSubscription> PubSubOwnerSubscriptionConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubOwnerSubscription> result = std::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");
+void PubSubOwnerSubscriptionConvertor::doConvertToLua(lua_State* L, std::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");
}
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 6742013..2908654 100644
--- a/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubOwnerSubscription.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubOwnerSubscription.h>
namespace Swift {
- class LuaElementConvertors;
-
- class PubSubOwnerSubscriptionConvertor : public GenericLuaElementConvertor<PubSubOwnerSubscription> {
- public:
- PubSubOwnerSubscriptionConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubOwnerSubscriptionConvertor();
+ class LuaElementConvertors;
- 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;
+ class PubSubOwnerSubscriptionConvertor : public GenericLuaElementConvertor<PubSubOwnerSubscription> {
+ public:
+ PubSubOwnerSubscriptionConvertor();
+ virtual ~PubSubOwnerSubscriptionConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<PubSubOwnerSubscription> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 d061b2d..88085b5 100644
--- a/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp
@@ -1,77 +1,76 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Sluift/LuaElementConvertors.h>
-#include <Swiften/Base/foreach.h>
+#include <lua.hpp>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <Sluift/LuaElementConvertors.h>
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);
- }
+std::shared_ptr<PubSubOwnerSubscriptions> PubSubOwnerSubscriptionsConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubOwnerSubscriptions> result = std::make_shared<PubSubOwnerSubscriptions>();
+ lua_getfield(L, -1, "node");
+ if (lua_isstring(L, -1)) {
+ result->setNode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ std::vector< std::shared_ptr<PubSubOwnerSubscription> > items;
+ for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
+ lua_pushnumber(L, i + 1);
+ lua_gettable(L, -2);
+ if (!lua_isnil(L, -1)) {
+ if (std::shared_ptr<PubSubOwnerSubscription> payload = std::dynamic_pointer_cast<PubSubOwnerSubscription>(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_subscription"))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setSubscriptions(items);
- }
- return result;
+ 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;
- }
- }
- }
- }
+void PubSubOwnerSubscriptionsConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubOwnerSubscriptions> payload) {
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ if (!payload->getSubscriptions().empty()) {
+ {
+ int i = 0;
+ for (auto&& item : payload->getSubscriptions()) {
+ if (convertors->convertToLuaUntyped(L, item) > 0) {
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ ++i;
+ }
+ }
+ }
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubOwnerSubscriptionsConvertor::getDocumentation() const {
- return Documentation(
- "PubSubOwnerSubscriptions",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- "- `subscriptions`: array<@{PubSubOwnerSubscription}>\n"
- );
+ 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 dbdff67..c89b814 100644
--- a/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubOwnerSubscriptions.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubOwnerSubscriptions.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 std::shared_ptr<PubSubOwnerSubscriptions> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 961d210..63c97bc 100644
--- a/Sluift/ElementConvertors/PubSubPublishConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubPublishConvertor.cpp
@@ -1,81 +1,80 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubPublishConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Sluift/LuaElementConvertors.h>
-#include <Swiften/Base/foreach.h>
+#include <lua.hpp>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <Sluift/LuaElementConvertors.h>
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);
- }
+std::shared_ptr<PubSubPublish> PubSubPublishConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubPublish> result = std::make_shared<PubSubPublish>();
+ lua_getfield(L, -1, "node");
+ if (lua_isstring(L, -1)) {
+ result->setNode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "items");
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ std::vector< std::shared_ptr<PubSubItem> > items;
+ for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
+ lua_pushnumber(L, i + 1);
+ lua_gettable(L, -2);
+ if (!lua_isnil(L, -1)) {
+ if (std::shared_ptr<PubSubItem> payload = std::dynamic_pointer_cast<PubSubItem>(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setItems(items);
- }
- lua_pop(L, 1);
- return result;
+ 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");
- }
+void PubSubPublishConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubPublish> payload) {
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ if (!payload->getItems().empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(payload->getItems().size()), 0);
+ {
+ int i = 0;
+ for (auto&& item : payload->getItems()) {
+ if (convertors->convertToLuaUntyped(L, item) > 0) {
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ ++i;
+ }
+ }
+ }
+ lua_setfield(L, -2, "items");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubPublishConvertor::getDocumentation() const {
- return Documentation(
- "PubSubPublish",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- "- `items`: array<@{PubSubItem}>\n"
- );
+ 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 6deda0e..1765caf 100644
--- a/Sluift/ElementConvertors/PubSubPublishConvertor.h
+++ b/Sluift/ElementConvertors/PubSubPublishConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubPublish.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubPublish.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 std::shared_ptr<PubSubPublish> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 abf19df..c070ad6 100644
--- a/Sluift/ElementConvertors/PubSubRetractConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubRetractConvertor.cpp
@@ -1,89 +1,90 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubRetractConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Sluift/LuaElementConvertors.h>
-#include <Swiften/Base/foreach.h>
+#include <lua.hpp>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <Sluift/LuaElementConvertors.h>
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);
- }
+std::shared_ptr<PubSubRetract> PubSubRetractConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubRetract> result = std::make_shared<PubSubRetract>();
+ lua_getfield(L, -1, "node");
+ if (lua_isstring(L, -1)) {
+ result->setNode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "items");
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ std::vector< std::shared_ptr<PubSubItem> > items;
+ for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
+ lua_pushnumber(L, i + 1);
+ lua_gettable(L, -2);
+ if (!lua_isnil(L, -1)) {
+ if (std::shared_ptr<PubSubItem> payload = std::dynamic_pointer_cast<PubSubItem>(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setItems(items);
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "notify");
- if (lua_isboolean(L, -1)) {
- result->setNotify(lua_toboolean(L, -1));
- }
- lua_pop(L, 1);
- return result;
+ 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");
+void PubSubRetractConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubRetract> payload) {
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, payload->getNode().c_str());
+ lua_setfield(L, -2, "node");
+ if (!payload->getItems().empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(payload->getItems().size()), 0);
+ {
+ int i = 0;
+ for (auto&& item : payload->getItems()) {
+ if (convertors->convertToLuaUntyped(L, item) > 0) {
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ ++i;
+ }
+ }
+ }
+ lua_setfield(L, -2, "items");
+ }
+ if (payload->isNotify().is_initialized()) {
+ lua_pushboolean(L, payload->isNotify().get_value_or(false));
+ lua_setfield(L, -2, "notify");
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubRetractConvertor::getDocumentation() const {
- return Documentation(
- "PubSubRetract",
- "This table has the following fields:\n\n"
- "- `node`: string\n"
- "- `items`: array<@{PubSubItem}>\n"
- "- `notify`: boolean\n"
- );
+ 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 46aa71b..13f7d0d 100644
--- a/Sluift/ElementConvertors/PubSubRetractConvertor.h
+++ b/Sluift/ElementConvertors/PubSubRetractConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubRetract.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubRetract.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 std::shared_ptr<PubSubRetract> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 64be818..bb5eb61 100644
--- a/Sluift/ElementConvertors/PubSubSubscribeConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubSubscribeConvertor.cpp
@@ -1,70 +1,68 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubSubscribeConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <lua.hpp>
#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
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;
+std::shared_ptr<PubSubSubscribe> PubSubSubscribeConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubSubscribe> result = std::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 (std::shared_ptr<PubSubOptions> payload = std::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");
- }
+void PubSubSubscribeConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 5a7aefe..238f677 100644
--- a/Sluift/ElementConvertors/PubSubSubscribeConvertor.h
+++ b/Sluift/ElementConvertors/PubSubSubscribeConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubSubscribe.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubSubscribe.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 std::shared_ptr<PubSubSubscribe> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 8a068ff..01da15f 100644
--- a/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.cpp
@@ -1,49 +1,44 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-
+#include <memory>
-
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-PubSubSubscribeOptionsConvertor::PubSubSubscribeOptionsConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubSubscribeOptions>("pubsub_subscribe_options"),
- convertors(convertors) {
+PubSubSubscribeOptionsConvertor::PubSubSubscribeOptionsConvertor() :
+ 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;
+std::shared_ptr<PubSubSubscribeOptions> PubSubSubscribeOptionsConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubSubscribeOptions> result = std::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");
+void PubSubSubscribeOptionsConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubSubscribeOptions> payload) {
+ 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 a36e7bb..fed8779 100644
--- a/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubSubscribeOptions.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubSubscribeOptions.h>
namespace Swift {
- class LuaElementConvertors;
-
- class PubSubSubscribeOptionsConvertor : public GenericLuaElementConvertor<PubSubSubscribeOptions> {
- public:
- PubSubSubscribeOptionsConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubSubscribeOptionsConvertor();
+ class LuaElementConvertors;
- 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;
+ class PubSubSubscribeOptionsConvertor : public GenericLuaElementConvertor<PubSubSubscribeOptions> {
+ public:
+ PubSubSubscribeOptionsConvertor();
+ virtual ~PubSubSubscribeOptionsConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<PubSubSubscribeOptions> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 3aad76e..65c6474 100644
--- a/Sluift/ElementConvertors/PubSubSubscriptionConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubSubscriptionConvertor.cpp
@@ -1,112 +1,110 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubSubscriptionConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <lua.hpp>
#include <Sluift/LuaElementConvertors.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
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;
+std::shared_ptr<PubSubSubscription> PubSubSubscriptionConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubSubscription> result = std::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 (std::shared_ptr<PubSubSubscribeOptions> payload = std::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");
+void PubSubSubscriptionConvertor::doConvertToLua(lua_State* L, std::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");
}
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 6d09ddf..5635181 100644
--- a/Sluift/ElementConvertors/PubSubSubscriptionConvertor.h
+++ b/Sluift/ElementConvertors/PubSubSubscriptionConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubSubscription.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubSubscription.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 std::shared_ptr<PubSubSubscription> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 5e66f2f..3712192 100644
--- a/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp
@@ -1,79 +1,78 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Sluift/LuaElementConvertors.h>
-#include <Swiften/Base/foreach.h>
+#include <lua.hpp>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <Sluift/LuaElementConvertors.h>
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);
- }
+std::shared_ptr<PubSubSubscriptions> PubSubSubscriptionsConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubSubscriptions> result = std::make_shared<PubSubSubscriptions>();
+ lua_getfield(L, -1, "node");
+ if (lua_isstring(L, -1)) {
+ result->setNode(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ std::vector< std::shared_ptr<PubSubSubscription> > items;
+ for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
+ lua_pushnumber(L, i + 1);
+ lua_gettable(L, -2);
+ if (!lua_isnil(L, -1)) {
+ if (std::shared_ptr<PubSubSubscription> payload = std::dynamic_pointer_cast<PubSubSubscription>(convertors->convertFromLuaUntyped(L, -1, "pubsub_subscription"))) {
+ items.push_back(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
- result->setSubscriptions(items);
- }
- return result;
+ 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;
- }
- }
- }
- }
+void PubSubSubscriptionsConvertor::doConvertToLua(lua_State* L, std::shared_ptr<PubSubSubscriptions> payload) {
+ lua_createtable(L, 0, 0);
+ if (payload->getNode()) {
+ lua_pushstring(L, (*payload->getNode()).c_str());
+ lua_setfield(L, -2, "node");
+ }
+ if (!payload->getSubscriptions().empty()) {
+ {
+ int i = 0;
+ for (auto&& item : payload->getSubscriptions()) {
+ if (convertors->convertToLuaUntyped(L, item) > 0) {
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ ++i;
+ }
+ }
+ }
+ }
}
boost::optional<LuaElementConvertor::Documentation> PubSubSubscriptionsConvertor::getDocumentation() const {
- return Documentation(
- "PubSubSubscriptions",
- "This table has the following fields:\n\n"
- "- `node`: string (Optional)\n"
- "- `subscriptions`: array<@{PubSubSubscription}>\n"
- );
+ 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 70fc159..2c941e6 100644
--- a/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h
+++ b/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,23 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubSubscriptions.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubSubscriptions.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 std::shared_ptr<PubSubSubscriptions> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 4b515ea..056c84c 100644
--- a/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.cpp
+++ b/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.cpp
@@ -1,69 +1,64 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-
+#include <memory>
-
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-PubSubUnsubscribeConvertor::PubSubUnsubscribeConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<PubSubUnsubscribe>("pubsub_unsubscribe"),
- convertors(convertors) {
+PubSubUnsubscribeConvertor::PubSubUnsubscribeConvertor() :
+ 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;
+std::shared_ptr<PubSubUnsubscribe> PubSubUnsubscribeConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<PubSubUnsubscribe> result = std::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");
- }
+void PubSubUnsubscribeConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 e075298..7270917 100644
--- a/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h
+++ b/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/PubSubUnsubscribe.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/PubSubUnsubscribe.h>
namespace Swift {
- class LuaElementConvertors;
-
- class PubSubUnsubscribeConvertor : public GenericLuaElementConvertor<PubSubUnsubscribe> {
- public:
- PubSubUnsubscribeConvertor(LuaElementConvertors* convertors);
- virtual ~PubSubUnsubscribeConvertor();
+ class LuaElementConvertors;
- 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;
+ class PubSubUnsubscribeConvertor : public GenericLuaElementConvertor<PubSubUnsubscribe> {
+ public:
+ PubSubUnsubscribeConvertor();
+ virtual ~PubSubUnsubscribeConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<PubSubUnsubscribe> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 e859079..9688677 100644
--- a/Sluift/ElementConvertors/RawXMLElementConvertor.cpp
+++ b/Sluift/ElementConvertors/RawXMLElementConvertor.cpp
@@ -1,17 +1,18 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/RawXMLElementConvertor.h>
-#include <iostream>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <lua.hpp>
#include <Swiften/Elements/RawXMLPayload.h>
#include <Swiften/Serializer/PayloadSerializer.h>
+
#include <Sluift/Lua/Check.h>
using namespace Swift;
@@ -22,20 +23,20 @@ RawXMLElementConvertor::RawXMLElementConvertor() {
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>();
+std::shared_ptr<Element> RawXMLElementConvertor::convertFromLua(lua_State* L, int index, const std::string& type) {
+ if (type == "xml") {
+ return std::make_shared<RawXMLPayload>(std::string(Lua::checkString(L, index)));
+ }
+ return std::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::optional<std::string> RawXMLElementConvertor::convertToLua(lua_State* L, std::shared_ptr<Element> element) {
+ std::shared_ptr<Payload> payload = std::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 98be763..79f648f 100644
--- a/Sluift/ElementConvertors/RawXMLElementConvertor.h
+++ b/Sluift/ElementConvertors/RawXMLElementConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,20 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
#include <Sluift/LuaElementConvertor.h>
-#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.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 std::shared_ptr<Element> convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE;
+ virtual boost::optional<std::string> convertToLua(lua_State*, std::shared_ptr<Element>) SWIFTEN_OVERRIDE;
- private:
- FullPayloadSerializerCollection serializers;
- };
+ private:
+ FullPayloadSerializerCollection serializers;
+ };
}
diff --git a/Sluift/ElementConvertors/ResultSetConvertor.cpp b/Sluift/ElementConvertors/ResultSetConvertor.cpp
index 79eb00d..7762a79 100644
--- a/Sluift/ElementConvertors/ResultSetConvertor.cpp
+++ b/Sluift/ElementConvertors/ResultSetConvertor.cpp
@@ -1,116 +1,116 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/numeric/conversion/cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <lua.hpp>
#include <Sluift/ElementConvertors/ResultSetConvertor.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <memory>
+
+#include <boost/numeric/conversion/cast.hpp>
+
+#include <lua.hpp>
using namespace Swift;
-ResultSetConvertor::ResultSetConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<ResultSet>("result_set"),
- convertors(convertors) {
+ResultSetConvertor::ResultSetConvertor() :
+ 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;
+std::shared_ptr<ResultSet> ResultSetConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<ResultSet> result = std::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");
- }
+void ResultSetConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 50a6836..e1b826c 100644
--- a/Sluift/ElementConvertors/ResultSetConvertor.h
+++ b/Sluift/ElementConvertors/ResultSetConvertor.h
@@ -1,29 +1,27 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Sluift/GenericLuaElementConvertor.h>
#include <Swiften/Base/Override.h>
#include <Swiften/Elements/ResultSet.h>
-namespace Swift {
- class LuaElementConvertors;
+#include <Sluift/GenericLuaElementConvertor.h>
- class ResultSetConvertor : public GenericLuaElementConvertor<ResultSet> {
- public:
- ResultSetConvertor(LuaElementConvertors* convertors);
- virtual ~ResultSetConvertor();
+namespace Swift {
+ class LuaElementConvertors;
- 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;
+ class ResultSetConvertor : public GenericLuaElementConvertor<ResultSet> {
+ public:
+ ResultSetConvertor();
+ virtual ~ResultSetConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<ResultSet> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::shared_ptr<ResultSet>) SWIFTEN_OVERRIDE;
+ virtual boost::optional<Documentation> getDocumentation() const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/SConscript b/Sluift/ElementConvertors/SConscript
index 265017b..0bf8022 100644
--- a/Sluift/ElementConvertors/SConscript
+++ b/Sluift/ElementConvertors/SConscript
@@ -2,53 +2,55 @@
Import('env')
convertors = [
- env.File("PubSubRetractConvertor.cpp"),
- env.File("PubSubAffiliationsConvertor.cpp"),
- env.File("PubSubPublishConvertor.cpp"),
- env.File("PubSubItemsConvertor.cpp"),
- env.File("PubSubOwnerRedirectConvertor.cpp"),
- env.File("PubSubEventRedirectConvertor.cpp"),
- env.File("UserTuneConvertor.cpp"),
- env.File("PubSubConfigureConvertor.cpp"),
- env.File("PubSubEventDisassociateConvertor.cpp"),
- env.File("PubSubOwnerAffiliationsConvertor.cpp"),
- env.File("PubSubOwnerConfigureConvertor.cpp"),
- env.File("UserLocationConvertor.cpp"),
- env.File("PubSubSubscribeOptionsConvertor.cpp"),
- env.File("PubSubOwnerSubscriptionsConvertor.cpp"),
- env.File("PubSubDefaultConvertor.cpp"),
- env.File("PubSubEventCollectionConvertor.cpp"),
- env.File("PubSubEventSubscriptionConvertor.cpp"),
- env.File("PubSubEventRetractConvertor.cpp"),
- env.File("PubSubItemConvertor.cpp"),
- env.File("PubSubUnsubscribeConvertor.cpp"),
- env.File("PubSubEventDeleteConvertor.cpp"),
- env.File("PubSubCreateConvertor.cpp"),
- env.File("PubSubOwnerPurgeConvertor.cpp"),
- env.File("PubSubEventItemsConvertor.cpp"),
- env.File("PubSubOptionsConvertor.cpp"),
- env.File("PubSubEventItemConvertor.cpp"),
- env.File("PubSubOwnerSubscriptionConvertor.cpp"),
- env.File("PubSubOwnerAffiliationConvertor.cpp"),
- env.File("PubSubEventPurgeConvertor.cpp"),
- env.File("PubSubAffiliationConvertor.cpp"),
- env.File("PubSubSubscribeConvertor.cpp"),
- env.File("PubSubOwnerDeleteConvertor.cpp"),
- env.File("PubSubOwnerDefaultConvertor.cpp"),
- env.File("PubSubSubscriptionsConvertor.cpp"),
- env.File("PubSubEventAssociateConvertor.cpp"),
- env.File("PubSubSubscriptionConvertor.cpp"),
- env.File("SecurityLabelConvertor.cpp"),
- env.File("PubSubEventConfigurationConvertor.cpp"),
- env.File("IQConvertor.cpp"),
- env.File("PresenceConvertor.cpp"),
- env.File("MessageConvertor.cpp"),
- env.File("ResultSetConvertor.cpp"),
- env.File("ForwardedConvertor.cpp"),
- env.File("MAMResultConvertor.cpp"),
- env.File("MAMQueryConvertor.cpp"),
- env.File("MAMFinConvertor.cpp"),
- env.File("SubjectConvertor.cpp"),
- env.File("IsodeIQDelegationConvertor.cpp")
+ env.File("PubSubRetractConvertor.cpp"),
+ env.File("PubSubAffiliationsConvertor.cpp"),
+ env.File("PubSubPublishConvertor.cpp"),
+ env.File("PubSubItemsConvertor.cpp"),
+ env.File("PubSubOwnerRedirectConvertor.cpp"),
+ env.File("PubSubEventRedirectConvertor.cpp"),
+ env.File("UserTuneConvertor.cpp"),
+ env.File("PubSubConfigureConvertor.cpp"),
+ env.File("PubSubEventDisassociateConvertor.cpp"),
+ env.File("PubSubOwnerAffiliationsConvertor.cpp"),
+ env.File("PubSubOwnerConfigureConvertor.cpp"),
+ env.File("UserLocationConvertor.cpp"),
+ env.File("PubSubSubscribeOptionsConvertor.cpp"),
+ env.File("PubSubOwnerSubscriptionsConvertor.cpp"),
+ env.File("PubSubDefaultConvertor.cpp"),
+ env.File("PubSubEventCollectionConvertor.cpp"),
+ env.File("PubSubEventSubscriptionConvertor.cpp"),
+ env.File("PubSubEventRetractConvertor.cpp"),
+ env.File("PubSubItemConvertor.cpp"),
+ env.File("PubSubUnsubscribeConvertor.cpp"),
+ env.File("PubSubEventDeleteConvertor.cpp"),
+ env.File("PubSubCreateConvertor.cpp"),
+ env.File("PubSubOwnerPurgeConvertor.cpp"),
+ env.File("PubSubEventItemsConvertor.cpp"),
+ env.File("PubSubOptionsConvertor.cpp"),
+ env.File("PubSubEventItemConvertor.cpp"),
+ env.File("PubSubOwnerSubscriptionConvertor.cpp"),
+ env.File("PubSubOwnerAffiliationConvertor.cpp"),
+ env.File("PubSubEventPurgeConvertor.cpp"),
+ env.File("PubSubAffiliationConvertor.cpp"),
+ env.File("PubSubSubscribeConvertor.cpp"),
+ env.File("PubSubOwnerDeleteConvertor.cpp"),
+ env.File("PubSubOwnerDefaultConvertor.cpp"),
+ env.File("PubSubSubscriptionsConvertor.cpp"),
+ env.File("PubSubEventAssociateConvertor.cpp"),
+ env.File("PubSubSubscriptionConvertor.cpp"),
+ env.File("SecurityLabelConvertor.cpp"),
+ env.File("PubSubEventConfigurationConvertor.cpp"),
+ env.File("IQConvertor.cpp"),
+ env.File("PresenceConvertor.cpp"),
+ env.File("MessageConvertor.cpp"),
+ env.File("ResultSetConvertor.cpp"),
+ env.File("ForwardedConvertor.cpp"),
+ env.File("MAMResultConvertor.cpp"),
+ env.File("MAMQueryConvertor.cpp"),
+ env.File("MAMFinConvertor.cpp"),
+ env.File("CarbonsReceivedConvertor.cpp"),
+ env.File("CarbonsSentConvertor.cpp"),
+ env.File("SubjectConvertor.cpp"),
+ env.File("IsodeIQDelegationConvertor.cpp")
]
Return('convertors')
diff --git a/Sluift/ElementConvertors/SecurityLabelConvertor.cpp b/Sluift/ElementConvertors/SecurityLabelConvertor.cpp
index cfaeb7d..21d9a8f 100644
--- a/Sluift/ElementConvertors/SecurityLabelConvertor.cpp
+++ b/Sluift/ElementConvertors/SecurityLabelConvertor.cpp
@@ -1,101 +1,98 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/SecurityLabelConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <boost/numeric/conversion/cast.hpp>
+#include <memory>
-#include <Swiften/Base/foreach.h>
+#include <boost/numeric/conversion/cast.hpp>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-SecurityLabelConvertor::SecurityLabelConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<SecurityLabel>("security_label"),
- convertors(convertors) {
+SecurityLabelConvertor::SecurityLabelConvertor() :
+ 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);
- }
+std::shared_ptr<SecurityLabel> SecurityLabelConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<SecurityLabel> result = std::make_shared<SecurityLabel>();
+ lua_getfield(L, -1, "equivalent_labels");
+ if (lua_type(L, -1) == LUA_TTABLE) {
+ std::vector< std::string > items;
+ for(size_t i = 0; i < lua_objlen(L, -1); ++i) {
+ lua_pushnumber(L, i + 1);
+ lua_gettable(L, -2);
+ if (lua_isstring(L, -1)) {
+ items.push_back(std::string(lua_tostring(L, -1)));
+ }
+ lua_pop(L, 1);
+ }
- result->setEquivalentLabels(items);
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "foreground_color");
- if (lua_isstring(L, -1)) {
- result->setForegroundColor(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "display_marking");
- if (lua_isstring(L, -1)) {
- result->setDisplayMarking(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "background_color");
- if (lua_isstring(L, -1)) {
- result->setBackgroundColor(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- lua_getfield(L, -1, "label");
- if (lua_isstring(L, -1)) {
- result->setLabel(std::string(lua_tostring(L, -1)));
- }
- lua_pop(L, 1);
- return result;
+ 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");
+void SecurityLabelConvertor::doConvertToLua(lua_State* L, std::shared_ptr<SecurityLabel> payload) {
+ lua_createtable(L, 0, 0);
+ if (!payload->getEquivalentLabels().empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(payload->getEquivalentLabels().size()), 0);
+ {
+ int i = 0;
+ for (const auto& item : payload->getEquivalentLabels()) {
+ lua_pushstring(L, item.c_str());
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ ++i;
+ }
+ }
+ lua_setfield(L, -2, "equivalent_labels");
+ }
+ lua_pushstring(L, payload->getForegroundColor().c_str());
+ lua_setfield(L, -2, "foreground_color");
+ lua_pushstring(L, payload->getDisplayMarking().c_str());
+ lua_setfield(L, -2, "display_marking");
+ lua_pushstring(L, payload->getBackgroundColor().c_str());
+ lua_setfield(L, -2, "background_color");
+ lua_pushstring(L, payload->getLabel().c_str());
+ lua_setfield(L, -2, "label");
}
boost::optional<LuaElementConvertor::Documentation> SecurityLabelConvertor::getDocumentation() const {
- return Documentation(
- "SecurityLabel",
- "This table has the following fields:\n\n"
- "- `equivalent_labels`: array<string>\n"
- "- `foreground_color`: string\n"
- "- `display_marking`: string\n"
- "- `background_color`: string\n"
- "- `label`: string\n"
- );
+ 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 8e489c0..a0e7fea 100644
--- a/Sluift/ElementConvertors/SecurityLabelConvertor.h
+++ b/Sluift/ElementConvertors/SecurityLabelConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/SecurityLabel.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/SecurityLabel.h>
namespace Swift {
- class LuaElementConvertors;
-
- class SecurityLabelConvertor : public GenericLuaElementConvertor<SecurityLabel> {
- public:
- SecurityLabelConvertor(LuaElementConvertors* convertors);
- virtual ~SecurityLabelConvertor();
+ class LuaElementConvertors;
- 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;
+ class SecurityLabelConvertor : public GenericLuaElementConvertor<SecurityLabel> {
+ public:
+ SecurityLabelConvertor();
+ virtual ~SecurityLabelConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<SecurityLabel> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 d621593..f997a45 100644
--- a/Sluift/ElementConvertors/SoftwareVersionConvertor.cpp
+++ b/Sluift/ElementConvertors/SoftwareVersionConvertor.cpp
@@ -1,14 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/SoftwareVersionConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
+
+#include <lua.hpp>
+
#include <Sluift/Lua/Check.h>
using namespace Swift;
@@ -19,32 +22,32 @@ SoftwareVersionConvertor::SoftwareVersionConvertor() : GenericLuaElementConverto
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;
+std::shared_ptr<SoftwareVersion> SoftwareVersionConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<SoftwareVersion> result = std::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");
+void SoftwareVersionConvertor::doConvertToLua(lua_State* L, std::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");
}
diff --git a/Sluift/ElementConvertors/SoftwareVersionConvertor.h b/Sluift/ElementConvertors/SoftwareVersionConvertor.h
index aded40a..29b1483 100644
--- a/Sluift/ElementConvertors/SoftwareVersionConvertor.h
+++ b/Sluift/ElementConvertors/SoftwareVersionConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,17 +7,17 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/SoftwareVersion.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/SoftwareVersion.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 std::shared_ptr<SoftwareVersion> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::shared_ptr<SoftwareVersion>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/StanzaConvertor.h b/Sluift/ElementConvertors/StanzaConvertor.h
index b3e75cf..bdaaad3 100644
--- a/Sluift/ElementConvertors/StanzaConvertor.h
+++ b/Sluift/ElementConvertors/StanzaConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,81 +8,81 @@
#include <boost/numeric/conversion/cast.hpp>
-#include <Sluift/GenericLuaElementConvertor.h>
-#include <Sluift/LuaElementConvertors.h>
-#include <Sluift/Lua/Exception.h>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/IQ.h>
-#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/Message.h>
+#include <Swiften/Elements/Payload.h>
+#include <Swiften/Elements/Presence.h>
+
+#include <Sluift/GenericLuaElementConvertor.h>
+#include <Sluift/Lua/Exception.h>
+#include <Sluift/LuaElementConvertors.h>
namespace Swift {
- template <typename T> class StanzaConvertor : public GenericLuaElementConvertor<T> {
- public:
- StanzaConvertor(const std::string& tag)
- : GenericLuaElementConvertor<T>(tag) {
- }
+ 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;
- }
+ std::shared_ptr<T> getStanza(lua_State* L, LuaElementConvertors* convertors) {
+ std::shared_ptr<T> result = std::make_shared<T>();
+ lua_getfield(L, -1, "id");
+ if (lua_isstring(L, -1)) {
+ result->setID(lua_tostring(L, -1));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "from");
+ if (lua_isstring(L, -1)) {
+ result->setFrom(lua_tostring(L, -1));
+ }
+ 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)) {
+ std::shared_ptr<Payload> payload = std::dynamic_pointer_cast<Payload>(convertors->convertFromLua(L, -1));
+ if (!!payload) {
+ result->addPayload(payload);
+ }
+ }
+ lua_pop(L, 1);
+ }
+ }
+ lua_pop(L, 1);
+ return result;
+ }
- void pushStanza(lua_State* L, const 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 std::shared_ptr<T> stanza, LuaElementConvertors* convertors) {
+ lua_createtable(L, 0, 0);
+ lua_pushstring(L, stanza->getID().c_str());
+ lua_setfield(L, -2, "id");
+ lua_pushstring(L, stanza->getFrom().toString().c_str());
+ lua_setfield(L, -2, "from");
+ lua_pushstring(L, stanza->getTo().toString().c_str());
+ lua_setfield(L, -2, "to");
+ if (!stanza->getPayloads().empty()) {
+ lua_createtable(L, boost::numeric_cast<int>(stanza->getPayloads().size()), 0);
+ {
+ int i = 0;
+ for (const auto& item : stanza->getPayloads()) {
+ if (convertors->convertToLua(L, item) > 0) {
+ lua_rawseti(L, -2, boost::numeric_cast<int>(i+1));
+ ++i;
+ }
+ }
+ }
+ lua_setfield(L, -2, "payloads");
+ }
+ }
+ };
}
diff --git a/Sluift/ElementConvertors/StatusConvertor.cpp b/Sluift/ElementConvertors/StatusConvertor.cpp
index 9dc3585..eed4044 100644
--- a/Sluift/ElementConvertors/StatusConvertor.cpp
+++ b/Sluift/ElementConvertors/StatusConvertor.cpp
@@ -1,14 +1,17 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/StatusConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
+
+#include <lua.hpp>
+
#include <Sluift/Lua/Check.h>
using namespace Swift;
@@ -19,18 +22,18 @@ StatusConvertor::StatusConvertor() : GenericLuaElementConvertor<Status>("status"
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;
+std::shared_ptr<Status> StatusConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<Status> result = std::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");
+void StatusConvertor::doConvertToLua(lua_State* L, std::shared_ptr<Status> payload) {
+ 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 2e39f27..53da0ad 100644
--- a/Sluift/ElementConvertors/StatusConvertor.h
+++ b/Sluift/ElementConvertors/StatusConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,17 +7,17 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Status.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/Status.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 std::shared_ptr<Status> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::shared_ptr<Status>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/StatusShowConvertor.cpp b/Sluift/ElementConvertors/StatusShowConvertor.cpp
index 43098ef..6d0a067 100644
--- a/Sluift/ElementConvertors/StatusShowConvertor.cpp
+++ b/Sluift/ElementConvertors/StatusShowConvertor.cpp
@@ -1,14 +1,17 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/StatusShowConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
+
+#include <lua.hpp>
+
#include <Sluift/Lua/Check.h>
#include <Sluift/Lua/Exception.h>
@@ -20,55 +23,55 @@ StatusShowConvertor::StatusShowConvertor() : GenericLuaElementConvertor<StatusSh
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;
+std::shared_ptr<StatusShow> StatusShowConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<StatusShow> result = std::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");
- }
+void StatusShowConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 6447c4e..1521ca3 100644
--- a/Sluift/ElementConvertors/StatusShowConvertor.h
+++ b/Sluift/ElementConvertors/StatusShowConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,20 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/StatusShow.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/StatusShow.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 std::shared_ptr<StatusShow> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 893073f..ae03564 100644
--- a/Sluift/ElementConvertors/SubjectConvertor.cpp
+++ b/Sluift/ElementConvertors/SubjectConvertor.cpp
@@ -1,13 +1,15 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/SubjectConvertor.h>
+#include <memory>
+
#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+
#include <Sluift/Lua/LuaUtils.h>
using namespace Swift;
@@ -18,18 +20,18 @@ SubjectConvertor::SubjectConvertor() : GenericLuaElementConvertor<Subject>("subj
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;
+std::shared_ptr<Subject> SubjectConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<Subject> result = std::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");
- }
+void SubjectConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
diff --git a/Sluift/ElementConvertors/SubjectConvertor.h b/Sluift/ElementConvertors/SubjectConvertor.h
index d517b1e..1520004 100644
--- a/Sluift/ElementConvertors/SubjectConvertor.h
+++ b/Sluift/ElementConvertors/SubjectConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,19 +7,19 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Subject.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/Subject.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 std::shared_ptr<Subject> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::shared_ptr<Subject>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/UserLocationConvertor.cpp b/Sluift/ElementConvertors/UserLocationConvertor.cpp
index 2d546dd..253ca36 100644
--- a/Sluift/ElementConvertors/UserLocationConvertor.cpp
+++ b/Sluift/ElementConvertors/UserLocationConvertor.cpp
@@ -1,261 +1,258 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/UserLocationConvertor.h>
+#include <memory>
+
#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <boost/numeric/conversion/cast.hpp>
#include <Swiften/Base/DateTime.h>
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
using namespace Swift;
-UserLocationConvertor::UserLocationConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<UserLocation>("user_location"),
- convertors(convertors) {
+UserLocationConvertor::UserLocationConvertor() :
+ 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;
+std::shared_ptr<UserLocation> UserLocationConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<UserLocation> result = std::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(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(lua_tonumber(L, -1));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "accuracy");
+ if (lua_isnumber(L, -1)) {
+ result->setAccuracy(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(lua_tonumber(L, -1));
+ }
+ lua_pop(L, 1);
+ lua_getfield(L, -1, "error");
+ if (lua_isnumber(L, -1)) {
+ result->setError(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(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(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");
- }
+void UserLocationConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 7582fed..36e3a0b 100644
--- a/Sluift/ElementConvertors/UserLocationConvertor.h
+++ b/Sluift/ElementConvertors/UserLocationConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/UserLocation.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/UserLocation.h>
namespace Swift {
- class LuaElementConvertors;
-
- class UserLocationConvertor : public GenericLuaElementConvertor<UserLocation> {
- public:
- UserLocationConvertor(LuaElementConvertors* convertors);
- virtual ~UserLocationConvertor();
+ class LuaElementConvertors;
- 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;
+ class UserLocationConvertor : public GenericLuaElementConvertor<UserLocation> {
+ public:
+ UserLocationConvertor();
+ virtual ~UserLocationConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<UserLocation> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 0ce09e9..a9e1bee 100644
--- a/Sluift/ElementConvertors/UserTuneConvertor.cpp
+++ b/Sluift/ElementConvertors/UserTuneConvertor.cpp
@@ -1,111 +1,108 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/UserTuneConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <boost/numeric/conversion/cast.hpp>
-
+#include <memory>
+#include <boost/numeric/conversion/cast.hpp>
-#pragma clang diagnostic ignored "-Wunused-private-field"
+#include <lua.hpp>
using namespace Swift;
-UserTuneConvertor::UserTuneConvertor(LuaElementConvertors* convertors) :
- GenericLuaElementConvertor<UserTune>("user_tune"),
- convertors(convertors) {
+UserTuneConvertor::UserTuneConvertor() :
+ 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;
+std::shared_ptr<UserTune> UserTuneConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<UserTune> result = std::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");
- }
+void UserTuneConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
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 e5d0c36..ba57747 100644
--- a/Sluift/ElementConvertors/UserTuneConvertor.h
+++ b/Sluift/ElementConvertors/UserTuneConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,20 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/UserTune.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/UserTune.h>
namespace Swift {
- class LuaElementConvertors;
-
- class UserTuneConvertor : public GenericLuaElementConvertor<UserTune> {
- public:
- UserTuneConvertor(LuaElementConvertors* convertors);
- virtual ~UserTuneConvertor();
+ class LuaElementConvertors;
- 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;
+ class UserTuneConvertor : public GenericLuaElementConvertor<UserTune> {
+ public:
+ UserTuneConvertor();
+ virtual ~UserTuneConvertor();
- private:
- LuaElementConvertors* convertors;
- };
+ virtual std::shared_ptr<UserTune> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::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 451e0ab..ad521b3 100644
--- a/Sluift/ElementConvertors/VCardConvertor.cpp
+++ b/Sluift/ElementConvertors/VCardConvertor.cpp
@@ -1,18 +1,22 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/VCardConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Sluift/Lua/LuaUtils.h>
+
+#include <lua.hpp>
+
#include <Swiften/Base/ByteArray.h>
#include <Swiften/Base/DateTime.h>
+#include <Sluift/Lua/LuaUtils.h>
+
using namespace Swift;
VCardConvertor::VCardConvertor() : GenericLuaElementConvertor<VCard>("vcard") {
@@ -21,609 +25,609 @@ VCardConvertor::VCardConvertor() : GenericLuaElementConvertor<VCard>("vcard") {
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;
+std::shared_ptr<VCard> VCardConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<VCard> result = std::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");
- }
+void VCardConvertor::doConvertToLua(lua_State* L, std::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");
+ }
}
diff --git a/Sluift/ElementConvertors/VCardConvertor.h b/Sluift/ElementConvertors/VCardConvertor.h
index 135eff0..d63ef10 100644
--- a/Sluift/ElementConvertors/VCardConvertor.h
+++ b/Sluift/ElementConvertors/VCardConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,17 +7,17 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/VCard.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/VCard.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 std::shared_ptr<VCard> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::shared_ptr<VCard>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/ElementConvertors/VCardUpdateConvertor.cpp b/Sluift/ElementConvertors/VCardUpdateConvertor.cpp
index 579f064..21c3d68 100644
--- a/Sluift/ElementConvertors/VCardUpdateConvertor.cpp
+++ b/Sluift/ElementConvertors/VCardUpdateConvertor.cpp
@@ -1,14 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/ElementConvertors/VCardUpdateConvertor.h>
-#include <lua.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
+
+#include <lua.hpp>
+
#include <Sluift/Lua/LuaUtils.h>
using namespace Swift;
@@ -19,18 +22,18 @@ VCardUpdateConvertor::VCardUpdateConvertor() : GenericLuaElementConvertor<VCardU
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;
+std::shared_ptr<VCardUpdate> VCardUpdateConvertor::doConvertFromLua(lua_State* L) {
+ std::shared_ptr<VCardUpdate> result = std::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");
- }
+void VCardUpdateConvertor::doConvertToLua(lua_State* L, std::shared_ptr<VCardUpdate> payload) {
+ 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 b6ffac7..851f3b1 100644
--- a/Sluift/ElementConvertors/VCardUpdateConvertor.h
+++ b/Sluift/ElementConvertors/VCardUpdateConvertor.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,17 +7,17 @@
#pragma once
#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/VCardUpdate.h>
#include <Sluift/GenericLuaElementConvertor.h>
-#include <Swiften/Elements/VCardUpdate.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 std::shared_ptr<VCardUpdate> doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE;
+ virtual void doConvertToLua(lua_State*, std::shared_ptr<VCardUpdate>) SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Sluift/GenericLuaElementConvertor.h b/Sluift/GenericLuaElementConvertor.h
index 430e2b5..d94a324 100644
--- a/Sluift/GenericLuaElementConvertor.h
+++ b/Sluift/GenericLuaElementConvertor.h
@@ -1,54 +1,56 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <lua.hpp>
#include <string>
+#include <lua.hpp>
+
#include <Swiften/Base/Override.h>
-#include <Sluift/LuaElementConvertor.h>
+
#include <Sluift/Lua/Check.h>
#include <Sluift/Lua/LuaUtils.h>
+#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 std::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);
+ std::shared_ptr<Element> result = doConvertFromLua(L);
+ lua_pop(L, 1);
+ return result;
+ }
+ return std::shared_ptr<Element>();
+ }
+
+ virtual boost::optional<std::string> convertToLua(
+ lua_State* L, std::shared_ptr<Element> payload) SWIFTEN_OVERRIDE {
+ if (std::shared_ptr<T> actualPayload = std::dynamic_pointer_cast<T>(payload)) {
+ doConvertToLua(L, actualPayload);
+ assert(lua_type(L, -1) == LUA_TTABLE);
+ return type;
+ }
+ return NO_RESULT;
+ }
+
+ protected:
+ virtual std::shared_ptr<T> doConvertFromLua(lua_State*) = 0;
+ virtual void doConvertToLua(lua_State*, std::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 290508a..6af3906 100644
--- a/Sluift/Helpers.h
+++ b/Sluift/Helpers.h
@@ -1,20 +1,20 @@
/*
- * Copyright (c) 2013-2014 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-
#include <string>
+#include <Swiften/Base/API.h>
+#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 73555d2..d44dcb1 100644
--- a/Sluift/ITunesInterface.h
+++ b/Sluift/ITunesInterface.h
@@ -1,38 +1,40 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/API.h>
+#include <memory>
+#include <string>
-#include <boost/shared_ptr.hpp>
#include <boost/optional/optional.hpp>
+#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;
+ const std::unique_ptr<Private> p;
+ };
}
diff --git a/Sluift/ITunesInterface.mm b/Sluift/ITunesInterface.mm
index 0843aad..33cf1ca 100644
--- a/Sluift/ITunesInterface.mm
+++ b/Sluift/ITunesInterface.mm
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -12,47 +12,47 @@
#pragma clang diagnostic pop
#include <ScriptingBridge/ScriptingBridge.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <boost/optional.hpp>
#include <SwifTools/Cocoa/CocoaUtil.h>
using namespace Swift;
struct ITunesInterface::Private {
- Private() : iTunes(nil) {
- }
+ Private() : iTunes(nil) {
+ }
- iTunesApplication* iTunes;
+ iTunesApplication* iTunes;
};
-ITunesInterface::ITunesInterface() : p(boost::make_shared<Private>()) {
+ITunesInterface::ITunesInterface() : p(new Private()) {
}
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 9a4951e..b956623 100644
--- a/Sluift/Lua/Check.cpp
+++ b/Sluift/Lua/Check.cpp
@@ -1,66 +1,68 @@
/*
- * Copyright (c) 2013-2014 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/Lua/Check.h>
-#include <boost/numeric/conversion/cast.hpp>
-#include <iostream>
#include <sstream>
+
+#include <boost/numeric/conversion/cast.hpp>
+
#include <lua.hpp>
-#include <Sluift/Lua/Exception.h>
#include <Swiften/Base/ByteArray.h>
+#include <Sluift/Lua/Exception.h>
+
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, nullptr);
+ 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 368672d..5f141e1 100644
--- a/Sluift/Lua/Debug.h
+++ b/Sluift/Lua/Debug.h
@@ -1,28 +1,29 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <lua.hpp>
#include <iostream>
+#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 a681b9c..a8ecc5f 100644
--- a/Sluift/Lua/Exception.h
+++ b/Sluift/Lua/Exception.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013-2014 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,16 +7,17 @@
#pragma once
#include <stdexcept>
+
#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 cc43d35..8e1410d 100644
--- a/Sluift/Lua/FunctionRegistration.h
+++ b/Sluift/Lua/FunctionRegistration.h
@@ -1,43 +1,46 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <string>
+
+#include <lua.hpp>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+
#include <Sluift/Lua/FunctionRegistry.h>
-#include <lua.hpp>
-#include <string>
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 99a1722..46c6d18 100644
--- a/Sluift/Lua/FunctionRegistry.cpp
+++ b/Sluift/Lua/FunctionRegistry.cpp
@@ -1,14 +1,13 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/Lua/FunctionRegistry.h>
-#include <Swiften/Base/foreach.h>
-#include <Sluift/Lua/LuaUtils.h>
#include <Sluift/Lua/Exception.h>
+#include <Sluift/Lua/LuaUtils.h>
#include <Sluift/globals.h>
using namespace Swift::Lua;
@@ -20,39 +19,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());
- }
- }
+ for (const auto& registration : registrations) {
+ if (registration.type == type) {
+ lua_pushcclosure(L, registration.function, 0);
+ if (!registration.helpDescription.empty()) {
+ Lua::registerHelp(L, -1, registration.helpDescription, registration.helpParameters, registration.helpOptions);
+ }
+ else {
+ Lua::registerExtraHelp(L, -1, registration.type + "." + registration.name);
+ }
+ lua_setfield(L, -2, registration.name.c_str());
+ }
+ }
}
diff --git a/Sluift/Lua/FunctionRegistry.h b/Sluift/Lua/FunctionRegistry.h
index 800cf05..acab3aa 100644
--- a/Sluift/Lua/FunctionRegistry.h
+++ b/Sluift/Lua/FunctionRegistry.h
@@ -1,47 +1,49 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <lua.hpp>
#include <string>
#include <vector>
+#include <lua.hpp>
+
+#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 78951d8..c677381 100644
--- a/Sluift/Lua/LuaUtils.cpp
+++ b/Sluift/Lua/LuaUtils.cpp
@@ -1,20 +1,21 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/Lua/LuaUtils.h>
-#include <lua.hpp>
-
-#include <boost/scope_exit.hpp>
-#include <Sluift/Lua/Exception.h>
-#include <iostream>
#include <cassert>
#include <sstream>
-#include <boost/numeric/conversion/cast.hpp>
+
#include <boost/algorithm/string/trim.hpp>
+#include <boost/numeric/conversion/cast.hpp>
+#include <boost/scope_exit.hpp>
+
+#include <lua.hpp>
+
+#include <Sluift/Lua/Exception.h>
#include <Sluift/globals.h>
using namespace Swift::Lua;
@@ -22,178 +23,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 4ce3de8..96d954c 100644
--- a/Sluift/Lua/Value.cpp
+++ b/Sluift/Lua/Value.cpp
@@ -1,66 +1,66 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Value.h"
+#include <Sluift/Lua/Value.h>
+
+#include <boost/numeric/conversion/cast.hpp>
+#include <boost/variant/apply_visitor.hpp>
extern "C" {
- #include <lualib.h>
+ #include <lualib.h>
}
-#include <boost/variant/apply_visitor.hpp>
-#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/Base/foreach.h>
using namespace Swift;
using namespace Swift::Lua;
namespace {
- struct PushVisitor : public boost::static_visitor<> {
- PushVisitor(lua_State* state) : state(state) {
- }
+ struct PushVisitor : public boost::static_visitor<> {
+ PushVisitor(lua_State* state) : state(state) {
+ }
- void operator()(const Nil&) const {
- lua_pushnil(state);
- }
+ void operator()(const Nil&) const {
+ lua_pushnil(state);
+ }
- void operator()(const bool& b) const {
- lua_pushboolean(state, b);
- }
+ void operator()(const bool& b) const {
+ lua_pushboolean(state, b);
+ }
- void operator()(const int& i) const {
- lua_pushnumber(state, i);
- }
+ 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::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::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());
- }
- }
+ void operator()(const std::map<std::string, std::shared_ptr<Value> >& table) const {
+ lua_createtable(state, 0, boost::numeric_cast<int>(table.size()));
+ for (const auto& i : table) {
+ boost::apply_visitor(PushVisitor(state), *i.second);
+ lua_setfield(state, -2, i.first.c_str());
+ }
+ }
- lua_State* state;
- };
+ 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 9dd870f..13c4a0c 100644
--- a/Sluift/Lua/Value.h
+++ b/Sluift/Lua/Value.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,54 +7,54 @@
#pragma once
#include <map>
+#include <memory>
#include <string>
#include <vector>
+
#include <boost/variant.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
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, std::shared_ptr<boost::recursive_variant_> >
+ >::type Value;
+
+ typedef std::map<std::string, std::shared_ptr<Value> > Table;
+ typedef std::vector<Value> Array;
+
+ inline std::shared_ptr<Value> nilRef() {
+ return std::make_shared<Value>(Nil());
+ }
+
+ inline std::shared_ptr<Value> valueRef(const std::string& value) {
+ return std::make_shared<Value>(value);
+ }
+
+ inline std::shared_ptr<Value> intRef(int value) {
+ return std::make_shared<Value>(value);
+ }
+
+ inline std::shared_ptr<Value> boolRef(bool value) {
+ return std::make_shared<Value>(value);
+ }
+
+ inline std::shared_ptr<Value> valueRef(const Table& table) {
+ return std::make_shared<Value>(table);
+ }
+
+ inline std::shared_ptr<Value> valueRef(const Array& array) {
+ return std::make_shared<Value>(array);
+ }
+
+ void pushValue(lua_State* state, const Value& value);
+ }
}
diff --git a/Sluift/LuaElementConvertor.h b/Sluift/LuaElementConvertor.h
index b463980..2cf98e7 100644
--- a/Sluift/LuaElementConvertor.h
+++ b/Sluift/LuaElementConvertor.h
@@ -1,40 +1,41 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
+
#include <boost/optional.hpp>
+#include <Swiften/Base/Override.h>
+
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 std::shared_ptr<Element> convertFromLua(lua_State*, int index, const std::string& type) = 0;
+ virtual boost::optional<std::string> convertToLua(lua_State*, std::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 15bb360..aac4d93 100644
--- a/Sluift/LuaElementConvertors.cpp
+++ b/Sluift/LuaElementConvertors.cpp
@@ -1,70 +1,73 @@
/*
- * Copyright (c) 2013-2014 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/LuaElementConvertors.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
-#include <Swiften/Base/foreach.h>
-#include <Sluift/LuaElementConvertor.h>
-#include <Sluift/ElementConvertors/RawXMLElementConvertor.h>
-#include <Sluift/ElementConvertors/PubSubEventConvertor.h>
+#include <Sluift/ElementConvertors/BodyConvertor.h>
+#include <Sluift/ElementConvertors/CarbonsReceivedConvertor.h>
+#include <Sluift/ElementConvertors/CarbonsSentConvertor.h>
+#include <Sluift/ElementConvertors/CommandConvertor.h>
#include <Sluift/ElementConvertors/DOMElementConvertor.h>
#include <Sluift/ElementConvertors/DefaultElementConvertor.h>
-#include <Sluift/ElementConvertors/DiscoItemsConvertor.h>
+#include <Sluift/ElementConvertors/DelayConvertor.h>
#include <Sluift/ElementConvertors/DiscoInfoConvertor.h>
+#include <Sluift/ElementConvertors/DiscoItemsConvertor.h>
#include <Sluift/ElementConvertors/FormConvertor.h>
-#include <Sluift/ElementConvertors/SoftwareVersionConvertor.h>
-#include <Sluift/ElementConvertors/VCardUpdateConvertor.h>
-#include <Sluift/ElementConvertors/VCardConvertor.h>
-#include <Sluift/ElementConvertors/BodyConvertor.h>
-#include <Sluift/ElementConvertors/SubjectConvertor.h>
-#include <Sluift/ElementConvertors/CommandConvertor.h>
-#include <Sluift/ElementConvertors/StatusShowConvertor.h>
-#include <Sluift/ElementConvertors/StatusConvertor.h>
-#include <Sluift/ElementConvertors/DelayConvertor.h>
+#include <Sluift/ElementConvertors/ForwardedConvertor.h>
#include <Sluift/ElementConvertors/IQConvertor.h>
-#include <Sluift/ElementConvertors/PresenceConvertor.h>
+#include <Sluift/ElementConvertors/MAMFinConvertor.h>
+#include <Sluift/ElementConvertors/MAMQueryConvertor.h>
+#include <Sluift/ElementConvertors/MAMResultConvertor.h>
#include <Sluift/ElementConvertors/MessageConvertor.h>
+#include <Sluift/ElementConvertors/PresenceConvertor.h>
+#include <Sluift/ElementConvertors/PubSubEventConvertor.h>
+#include <Sluift/ElementConvertors/RawXMLElementConvertor.h>
#include <Sluift/ElementConvertors/ResultSetConvertor.h>
-#include <Sluift/ElementConvertors/ForwardedConvertor.h>
-#include <Sluift/ElementConvertors/MAMResultConvertor.h>
-#include <Sluift/ElementConvertors/MAMQueryConvertor.h>
-#include <Sluift/ElementConvertors/MAMFinConvertor.h>
-#include <Sluift/Lua/LuaUtils.h>
+#include <Sluift/ElementConvertors/SoftwareVersionConvertor.h>
+#include <Sluift/ElementConvertors/StatusConvertor.h>
+#include <Sluift/ElementConvertors/StatusShowConvertor.h>
+#include <Sluift/ElementConvertors/SubjectConvertor.h>
+#include <Sluift/ElementConvertors/VCardConvertor.h>
+#include <Sluift/ElementConvertors/VCardUpdateConvertor.h>
#include <Sluift/Lua/Exception.h>
+#include <Sluift/Lua/LuaUtils.h>
+#include <Sluift/LuaElementConvertor.h>
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>(this));
- 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(std::make_shared<StatusConvertor>());
+ convertors.push_back(std::make_shared<StatusShowConvertor>());
+ convertors.push_back(std::make_shared<DelayConvertor>());
+ convertors.push_back(std::make_shared<CommandConvertor>(this));
+ convertors.push_back(std::make_shared<PubSubEventConvertor>(this));
+ convertors.push_back(std::make_shared<BodyConvertor>());
+ convertors.push_back(std::make_shared<SubjectConvertor>());
+ convertors.push_back(std::make_shared<VCardConvertor>());
+ convertors.push_back(std::make_shared<VCardUpdateConvertor>());
+ convertors.push_back(std::make_shared<FormConvertor>());
+ convertors.push_back(std::make_shared<SoftwareVersionConvertor>());
+ convertors.push_back(std::make_shared<DiscoInfoConvertor>());
+ convertors.push_back(std::make_shared<DiscoItemsConvertor>());
+ convertors.push_back(std::make_shared<IQConvertor>(this));
+ convertors.push_back(std::make_shared<PresenceConvertor>(this));
+ convertors.push_back(std::make_shared<MessageConvertor>(this));
+ convertors.push_back(std::make_shared<ResultSetConvertor>());
+ convertors.push_back(std::make_shared<ForwardedConvertor>(this));
+ convertors.push_back(std::make_shared<MAMResultConvertor>(this));
+ convertors.push_back(std::make_shared<MAMQueryConvertor>(this));
+ convertors.push_back(std::make_shared<MAMFinConvertor>(this));
+ convertors.push_back(std::make_shared<CarbonsReceivedConvertor>(this));
+ convertors.push_back(std::make_shared<CarbonsSentConvertor>(this));
+ convertors.push_back(std::make_shared<DOMElementConvertor>());
+ convertors.push_back(std::make_shared<RawXMLElementConvertor>());
+ convertors.push_back(std::make_shared<DefaultElementConvertor>());
}
LuaElementConvertors::~LuaElementConvertors() {
@@ -72,65 +75,65 @@ 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");
+std::shared_ptr<Element> LuaElementConvertors::convertFromLua(lua_State* L, int index) {
+ if (lua_isstring(L, index)) {
+ return convertFromLuaUntyped(L, index, "xml");
+ }
+ else if (lua_istable(L, index)) {
+ lua_getfield(L, index, "_type");
+ if (lua_isstring(L, -1)) {
+ std::string type = lua_tostring(L, -1);
+ lua_pop(L, 1);
+ return convertFromLuaUntyped(L, index, type);
+ }
+ lua_pop(L, 1);
+ }
+ throw Lua::Exception("Unable to determine type");
}
-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>();
+std::shared_ptr<Element> LuaElementConvertors::convertFromLuaUntyped(lua_State* L, int index, const std::string& type) {
+ index = Lua::absoluteOffset(L, index);
+ for (auto&& convertor : convertors) {
+ if (std::shared_ptr<Element> result = convertor->convertFromLua(L, index, type)) {
+ return result;
+ }
+ }
+ return std::shared_ptr<Element>();
}
-int LuaElementConvertors::convertToLua(lua_State* L, 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;
+int LuaElementConvertors::convertToLua(lua_State* L, std::shared_ptr<Element> payload) {
+ if (boost::optional<std::string> type = doConvertToLuaUntyped(L, payload)) {
+ if (lua_istable(L, -1)) {
+ lua_pushstring(L, type->c_str());
+ lua_setfield(L, -2, "_type");
+ Lua::registerTableToString(L, -1);
+ }
+ else {
+ assert(*type == "xml");
+ }
+ return 1;
+ }
+ return 0;
}
-int LuaElementConvertors::convertToLuaUntyped(lua_State* L, boost::shared_ptr<Element> payload) {
- if (doConvertToLuaUntyped(L, payload)) {
- return 1;
- }
- return 0;
+int LuaElementConvertors::convertToLuaUntyped(lua_State* L, std::shared_ptr<Element> payload) {
+ if (doConvertToLuaUntyped(L, payload)) {
+ return 1;
+ }
+ return 0;
}
boost::optional<std::string> LuaElementConvertors::doConvertToLuaUntyped(
- lua_State* L, 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, std::shared_ptr<Element> payload) {
+ if (!payload) {
+ return LuaElementConvertor::NO_RESULT;
+ }
+ for (auto&& 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 49acdf7..8e1d10b 100644
--- a/Sluift/LuaElementConvertors.h
+++ b/Sluift/LuaElementConvertors.h
@@ -1,51 +1,52 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-
+#include <memory>
#include <vector>
-#include <boost/shared_ptr.hpp>
+
#include <boost/optional.hpp>
+#include <Swiften/Base/Override.h>
+
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();
+
+ std::shared_ptr<Element> convertFromLua(lua_State*, int index);
+ int convertToLua(lua_State*, std::shared_ptr<Element>);
+
+ /**
+ * Adds a toplevel type+data table with the given type.
+ */
+ std::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*, std::shared_ptr<Element>);
+
+ const std::vector< std::shared_ptr<LuaElementConvertor> >& getConvertors() const {
+ return convertors;
+ }
+
+ private:
+ boost::optional<std::string> doConvertToLuaUntyped(lua_State*, std::shared_ptr<Element>);
+ void registerConvertors();
+
+ private:
+ std::vector< std::shared_ptr<LuaElementConvertor> > convertors;
+ };
}
diff --git a/Sluift/Response.cpp b/Sluift/Response.cpp
index a785f01..dd98a25 100644
--- a/Sluift/Response.cpp
+++ b/Sluift/Response.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,73 +8,74 @@
#include <lua.hpp>
-#include <Sluift/globals.h>
#include <Swiften/Elements/ErrorPayload.h>
+
#include <Sluift/Lua/LuaUtils.h>
+#include <Sluift/globals.h>
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;
+static std::string getErrorString(std::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;
}
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 591e54d..dc35289 100644
--- a/Sluift/Response.h
+++ b/Sluift/Response.h
@@ -1,36 +1,36 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Elements/Payload.h>
-#include <Swiften/Elements/ErrorPayload.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Elements/ErrorPayload.h>
+#include <Swiften/Elements/Payload.h>
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(std::shared_ptr<Payload> result, std::shared_ptr<ErrorPayload> error) : result(result), error(error) {}
+ SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Response)
+ ~Response();
+
+ static Response withResult(std::shared_ptr<Payload> response) {
+ return Response(response, std::shared_ptr<ErrorPayload>());
+ }
+
+ static Response withError(std::shared_ptr<ErrorPayload> error) {
+ return Response(std::shared_ptr<Payload>(), error);
+ }
+
+ int convertToLuaResult(lua_State* L);
+
+ std::shared_ptr<Payload> result;
+ std::shared_ptr<ErrorPayload> error;
+ };
+ }
}
diff --git a/Sluift/SConscript b/Sluift/SConscript
index 09da0a9..de9cab6 100644
--- a/Sluift/SConscript
+++ b/Sluift/SConscript
@@ -3,86 +3,86 @@ import Version, os.path
Import(["env"])
if env["SCONS_STAGE"] == "build" and not GetOption("help") and not env.get("HAVE_LUA", 0) :
- print "Warning: Lua was not found. Sluift will not be built."
- if "Sluift" in env["PROJECTS"] :
- env["PROJECTS"].remove("Sluift")
-
+ print "Warning: Lua was not found. Sluift will not be built."
+ if "Sluift" in env["PROJECTS"] :
+ env["PROJECTS"].remove("Sluift")
+
elif env["SCONS_STAGE"] == "build" :
- sluift_sources = [
- "Lua/Value.cpp",
- "Lua/Exception.cpp",
- "Lua/Check.cpp",
- "Lua/FunctionRegistration.cpp",
- "Lua/FunctionRegistry.cpp",
- "Lua/LuaUtils.cpp",
- "LuaElementConvertors.cpp",
- "LuaElementConvertor.cpp",
- "Response.cpp",
- "ElementConvertors/BodyConvertor.cpp",
- "ElementConvertors/VCardUpdateConvertor.cpp",
- "ElementConvertors/PubSubEventConvertor.cpp",
- "ElementConvertors/RawXMLElementConvertor.cpp",
- "ElementConvertors/DOMElementConvertor.cpp",
- "ElementConvertors/DefaultElementConvertor.cpp",
- "ElementConvertors/DiscoInfoConvertor.cpp",
- "ElementConvertors/DiscoItemsConvertor.cpp",
- "ElementConvertors/FormConvertor.cpp",
- "ElementConvertors/SoftwareVersionConvertor.cpp",
- "ElementConvertors/VCardConvertor.cpp",
- "ElementConvertors/CommandConvertor.cpp",
- "ElementConvertors/StatusConvertor.cpp",
- "ElementConvertors/StatusShowConvertor.cpp",
- "ElementConvertors/DelayConvertor.cpp",
- "Helpers.cpp",
- "SluiftClient.cpp",
- "SluiftComponent.cpp",
- "Watchdog.cpp",
- "core.c",
- "client.cpp",
- "component.cpp",
- "sluift.cpp"
- ]
- sluift_sources += env.SConscript("ElementConvertors/SConscript")
+ sluift_sources = [
+ "Lua/Value.cpp",
+ "Lua/Exception.cpp",
+ "Lua/Check.cpp",
+ "Lua/FunctionRegistration.cpp",
+ "Lua/FunctionRegistry.cpp",
+ "Lua/LuaUtils.cpp",
+ "LuaElementConvertors.cpp",
+ "LuaElementConvertor.cpp",
+ "Response.cpp",
+ "ElementConvertors/BodyConvertor.cpp",
+ "ElementConvertors/VCardUpdateConvertor.cpp",
+ "ElementConvertors/PubSubEventConvertor.cpp",
+ "ElementConvertors/RawXMLElementConvertor.cpp",
+ "ElementConvertors/DOMElementConvertor.cpp",
+ "ElementConvertors/DefaultElementConvertor.cpp",
+ "ElementConvertors/DiscoInfoConvertor.cpp",
+ "ElementConvertors/DiscoItemsConvertor.cpp",
+ "ElementConvertors/FormConvertor.cpp",
+ "ElementConvertors/SoftwareVersionConvertor.cpp",
+ "ElementConvertors/VCardConvertor.cpp",
+ "ElementConvertors/CommandConvertor.cpp",
+ "ElementConvertors/StatusConvertor.cpp",
+ "ElementConvertors/StatusShowConvertor.cpp",
+ "ElementConvertors/DelayConvertor.cpp",
+ "Helpers.cpp",
+ "SluiftClient.cpp",
+ "SluiftComponent.cpp",
+ "Watchdog.cpp",
+ "core.c",
+ "client.cpp",
+ "component.cpp",
+ "sluift.cpp"
+ ]
+ sluift_sources += env.SConscript("ElementConvertors/SConscript")
- sluift_env = env.Clone()
- sluift_env.UseFlags(env.get("LUA_FLAGS", {}))
- sluift_env.UseFlags(env["SWIFTEN_FLAGS"])
- sluift_env.UseFlags(env["SWIFTEN_DEP_FLAGS"])
- # Support compilation on both Lua 5.1 and Lua 5.2
- sluift_env.Append(CPPDEFINES = ["LUA_COMPAT_ALL"])
- if sluift_env["PLATFORM"] == "win32" :
- sluift_env.Append(CPPDEFINES = ["SLUIFT_BUILD_DLL"])
+ sluift_env = env.Clone()
+ sluift_env.UseFlags(env.get("LUA_FLAGS", {}))
+ sluift_env.UseFlags(env["SWIFTEN_FLAGS"])
+ sluift_env.UseFlags(env["SWIFTEN_DEP_FLAGS"])
+ # Support compilation on both Lua 5.1 and Lua 5.2
+ sluift_env.Append(CPPDEFINES = ["LUA_COMPAT_ALL"])
+ if sluift_env["PLATFORM"] == "win32" :
+ sluift_env.Append(CPPDEFINES = ["SLUIFT_BUILD_DLL"])
- if sluift_env["PLATFORM"] == "darwin" and os.path.isdir("/Applications/iTunes.app") :
- sluift_env.Append(FRAMEWORKS = ["ScriptingBridge"])
- sluift_env.Command("iTunes.h", "/Applications/iTunes.app",
- "sdef ${SOURCE} | sdp -fh --basename iTunes -V 10.10 -o ${TARGET.dir}")
- sluift_env.Append(CPPDEFINES = ["HAVE_ITUNES"])
- sluift_sources += ["ITunesInterface.mm"]
+ if sluift_env["PLATFORM"] == "darwin" and os.path.isdir("/Applications/iTunes.app") :
+ sluift_env.Append(FRAMEWORKS = ["ScriptingBridge"])
+ sluift_env.Command("iTunes.h", "/Applications/iTunes.app",
+ "sdef ${SOURCE} | sdp -fh --basename iTunes -V 10.10 -o ${TARGET.dir}")
+ sluift_env.Append(CPPDEFINES = ["HAVE_ITUNES"])
+ sluift_sources += ["ITunesInterface.mm"]
- # Generate Version.h
- version_header = "#pragma once\n\n"
- version_header += "#define SLUIFT_VERSION_STRING \"" + Version.getBuildVersion(env.Dir("#").abspath, "sluift") + "\"\n"
- sluift_env.WriteVal("Version.h", sluift_env.Value(version_header))
+ # Generate Version.h
+ version_header = "#pragma once\n\n"
+ version_header += "#define SLUIFT_VERSION_STRING \"" + Version.getBuildVersion(env.Dir("#").abspath, "sluift") + "\"\n"
+ sluift_env.WriteVal("Version.h", sluift_env.Value(version_header))
- # Generate core.c
- def generate_embedded_lua(env, target, source) :
- f = open(source[0].abspath, "r")
- data = f.read()
- f.close()
- f = open(target[0].abspath, "w")
- f.write('#include <stddef.h>\n')
- f.write('const size_t ' + source[0].name.replace(".", "_") + "_size = " + str(len(data)) + ";\n")
- f.write('const char ' + source[0].name.replace(".", "_") + "[] = {" + ", ".join([str(ord(c)) for c in data]) + "};\n")
- f.close()
- sluift_env.Command("core.c", ["core.lua"], env.Action(generate_embedded_lua, cmdstr="$GENCOMSTR"))
+ # Generate core.c
+ def generate_embedded_lua(env, target, source) :
+ f = open(source[0].abspath, "r")
+ data = f.read()
+ f.close()
+ f = open(target[0].abspath, "w")
+ f.write('#include <stddef.h>\n')
+ f.write('const size_t ' + source[0].name.replace(".", "_") + "_size = " + str(len(data)) + ";\n")
+ f.write('const char ' + source[0].name.replace(".", "_") + "[] = {" + ", ".join([str(ord(c)) for c in data]) + "};\n")
+ f.close()
+ sluift_env.Command("core.c", ["core.lua"], env.Action(generate_embedded_lua, cmdstr="$GENCOMSTR"))
- sluift_env.WriteVal("dll.c", sluift_env.Value(""))
+ sluift_env.WriteVal("dll.c", sluift_env.Value(""))
- sluift_sources = [env.File(x) for x in sluift_sources]
- for sluift_variant in ['dll', 'exe'] :
- SConscript(["SConscript.variant"], variant_dir = sluift_variant,
- duplicate = 0,
- exports = ['sluift_sources', 'sluift_variant', 'sluift_env'])
+ sluift_sources = [env.File(x) for x in sluift_sources]
+ for sluift_variant in ['dll', 'exe'] :
+ SConscript(["SConscript.variant"], variant_dir = sluift_variant,
+ duplicate = 0,
+ exports = ['sluift_sources', 'sluift_variant', 'sluift_env'])
diff --git a/Sluift/SConscript.variant b/Sluift/SConscript.variant
index d0e2b18..9f56c91 100644
--- a/Sluift/SConscript.variant
+++ b/Sluift/SConscript.variant
@@ -6,37 +6,37 @@ Import('sluift_variant')
Import('sluift_sources')
if sluift_variant == 'exe' :
- common_objects = sluift_env.StaticObject(sluift_sources)
+ common_objects = sluift_env.StaticObject(sluift_sources)
- sluift_exe_env = sluift_env.Clone()
- tokenize = sluift_exe_env.StaticObject("#/Sluift/tokenize.cpp")
- exe_sources = tokenize + [
- "#/Sluift/Console.cpp",
- "#/Sluift/Terminal.cpp",
- "#/Sluift/StandardTerminal.cpp",
- "#/Sluift/Completer.cpp",
- "#/Sluift/main.cpp",
- ]
+ sluift_exe_env = sluift_env.Clone()
+ tokenize = sluift_exe_env.StaticObject("#/Sluift/tokenize.cpp")
+ exe_sources = tokenize + [
+ "#/Sluift/Console.cpp",
+ "#/Sluift/Terminal.cpp",
+ "#/Sluift/StandardTerminal.cpp",
+ "#/Sluift/Completer.cpp",
+ "#/Sluift/main.cpp",
+ ]
- if sluift_exe_env.get("HAVE_EDITLINE", False) :
- sluift_exe_env.Append(CPPDEFINES = ["HAVE_EDITLINE"])
- sluift_exe_env.MergeFlags(sluift_exe_env["EDITLINE_FLAGS"])
- exe_sources += ["#/Sluift/EditlineTerminal.cpp"]
+ if sluift_exe_env.get("HAVE_EDITLINE", False) :
+ sluift_exe_env.Append(CPPDEFINES = ["HAVE_EDITLINE"])
+ sluift_exe_env.MergeFlags(sluift_exe_env["EDITLINE_FLAGS"])
+ exe_sources += ["#/Sluift/EditlineTerminal.cpp"]
- env["SLUIFT"] = sluift_exe_env.Program("sluift", common_objects + exe_sources)
- if sluift_exe_env.get("SLUIFT_INSTALLDIR", "") :
- sluift_exe_env.Install(os.path.join(sluift_exe_env["SLUIFT_INSTALLDIR"], "bin"), env["SLUIFT"])
+ env["SLUIFT"] = sluift_exe_env.Program("sluift", common_objects + exe_sources)
+ if sluift_exe_env.get("SLUIFT_INSTALLDIR", "") :
+ sluift_exe_env.Install(os.path.join(sluift_exe_env["SLUIFT_INSTALLDIR"], "bin"), env["SLUIFT"])
- # Unit tests
- env.Append(UNITTEST_OBJECTS = tokenize + ["#/Sluift/UnitTest/TokenizeTest.cpp"])
+ # Unit tests
+ env.Append(UNITTEST_OBJECTS = tokenize + ["#/Sluift/UnitTest/TokenizeTest.cpp"])
else :
- sluift_env["SLUIFT_DLL_SUFFIX"] = "${SHLIBSUFFIX}"
- if sluift_env["PLATFORM"] == "darwin" :
- sluift_env["SLUIFT_DLL_SUFFIX"] = ".so"
- sluift_dll = sluift_env.SharedLibrary(sluift_env.File("sluift${SLUIFT_DLL_SUFFIX}"),
- sluift_sources + ["#/Sluift/dll.c"])
- if sluift_env.get("SLUIFT_INSTALLDIR", False) and sluift_env.get("LUA_VERSION", False) :
- sluift_env.Install(
- os.path.join(sluift_env["SLUIFT_INSTALLDIR"], "lib", "lua", sluift_env["LUA_VERSION"]),
- sluift_dll)
+ sluift_env["SLUIFT_DLL_SUFFIX"] = "${SHLIBSUFFIX}"
+ if sluift_env["PLATFORM"] == "darwin" :
+ sluift_env["SLUIFT_DLL_SUFFIX"] = ".so"
+ sluift_dll = sluift_env.SharedLibrary(sluift_env.File("sluift${SLUIFT_DLL_SUFFIX}"),
+ sluift_sources + ["#/Sluift/dll.c"])
+ if sluift_env.get("SLUIFT_INSTALLDIR", False) and sluift_env.get("LUA_VERSION", False) :
+ sluift_env.Install(
+ os.path.join(sluift_env["SLUIFT_INSTALLDIR"], "lib", "lua", sluift_env["LUA_VERSION"]),
+ sluift_dll)
diff --git a/Sluift/SluiftClient.cpp b/Sluift/SluiftClient.cpp
index d2b1beb..f1c0191 100644
--- a/Sluift/SluiftClient.cpp
+++ b/Sluift/SluiftClient.cpp
@@ -8,182 +8,183 @@
#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/Client/Client.h>
-#include <Swiften/Roster/XMPPRoster.h>
-#include <Sluift/SluiftGlobals.h>
-#include <Sluift/Lua/Exception.h>
+#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/Elements/Message.h>
+#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/PubSubEvent.h>
#include <Swiften/Queries/RawRequest.h>
+#include <Swiften/Roster/XMPPRoster.h>
+
#include <Sluift/Helpers.h>
-#include <Swiften/Elements/Presence.h>
+#include <Sluift/Lua/Exception.h>
+#include <Sluift/SluiftGlobals.h>
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(nullptr) {
+ 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 = nullptr;
+ }
}
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));
+void SluiftClient::handleIncomingMessage(std::shared_ptr<Message> 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));
+void SluiftClient::handleIncomingPresence(std::shared_ptr<Presence> stanza) {
+ pendingEvents.push_back(Event(stanza));
}
-void SluiftClient::handleIncomingPubSubEvent(const JID& from, boost::shared_ptr<PubSubEventPayload> event) {
- pendingEvents.push_back(Event(from, event));
+void SluiftClient::handleIncomingPubSubEvent(const JID& from, std::shared_ptr<PubSubEventPayload> 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;
+void SluiftClient::handleRequestResponse(std::shared_ptr<Payload> response, std::shared_ptr<ErrorPayload> error) {
+ 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();
+Sluift::Response SluiftClient::doSendRequest(std::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);
+ Watchdog watchdog(timeout, networkFactories->getTimerFactory());
+ while (!watchdog.getTimedOut() && !requestResponseReceived) {
+ eventLoop->runUntilEvents();
+ }
+ return Sluift::Response(requestResponse, watchdog.getTimedOut() ?
+ std::make_shared<ErrorPayload>(ErrorPayload::RemoteServerTimeout) : requestError);
}
diff --git a/Sluift/SluiftClient.h b/Sluift/SluiftClient.h
index 68c4b61..2c221e6 100644
--- a/Sluift/SluiftClient.h
+++ b/Sluift/SluiftClient.h
@@ -7,125 +7,127 @@
#pragma once
#include <deque>
-#include <boost/optional.hpp>
+
#include <boost/bind.hpp>
#include <boost/function.hpp>
+#include <boost/optional.hpp>
+#include <Swiften/Client/Client.h>
+#include <Swiften/Client/ClientError.h>
#include <Swiften/Client/ClientOptions.h>
#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Presence.h>
-#include <Swiften/Queries/GenericRequest.h>
-#include <Swiften/Roster/XMPPRosterItem.h>
-#include <Swiften/Client/ClientError.h>
-#include <Swiften/Network/NetworkFactories.h>
-#include <Swiften/Client/Client.h>
#include <Swiften/EventLoop/SimpleEventLoop.h>
-#include <Sluift/Watchdog.h>
+#include <Swiften/Network/NetworkFactories.h>
#include <Swiften/PubSub/PubSubManager.h>
+#include <Swiften/Queries/GenericRequest.h>
+#include <Swiften/Roster/XMPPRosterItem.h>
+
#include <Sluift/Response.h>
+#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(std::shared_ptr<Message> stanza) : type(MessageType), stanza(stanza) {}
+ Event(std::shared_ptr<Presence> stanza) : type(PresenceType), stanza(stanza) {}
+ Event(const JID& from, std::shared_ptr<PubSubEventPayload> payload) : type(PubSubEventType), from(from), pubsubEvent(payload) {}
+
+ Type type;
+
+ // Message & Presence
+ std::shared_ptr<Stanza> stanza;
+
+ // PubSubEvent
+ JID from;
+ std::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, std::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::signals2::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::signals2::scoped_connection c(request->onResponse.connect(
+ boost::bind(&SluiftClient::handleRequestResponse, this, std::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(std::shared_ptr<Request> request, int timeout);
+
+ void handleIncomingMessage(std::shared_ptr<Message> stanza);
+ void handleIncomingPresence(std::shared_ptr<Presence> stanza);
+ void handleIncomingPubSubEvent(const JID& from, std::shared_ptr<PubSubEventPayload> event);
+ void handleInitialRosterPopulated();
+ void handleRequestResponse(std::shared_ptr<Payload> response, std::shared_ptr<ErrorPayload> error);
+ void handleDisconnected(const boost::optional<ClientError>& error);
+
+ private:
+ NetworkFactories* networkFactories;
+ SimpleEventLoop* eventLoop;
+ Client* client;
+ ClientOptions options;
+ ClientXMLTracer* tracer;
+ bool rosterReceived = false;
+ std::deque<Event> pendingEvents;
+ boost::optional<ClientError> disconnectedError;
+ bool requestResponseReceived = false;
+ std::shared_ptr<Payload> requestResponse;
+ std::shared_ptr<ErrorPayload> requestError;
+ };
}
diff --git a/Sluift/SluiftComponent.cpp b/Sluift/SluiftComponent.cpp
index af3c33b..e1d1738 100644
--- a/Sluift/SluiftComponent.cpp
+++ b/Sluift/SluiftComponent.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,138 +8,139 @@
#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/Component/ComponentXMLTracer.h>
#include <Swiften/Component/Component.h>
-#include <Swiften/Roster/XMPPRoster.h>
-#include <Sluift/SluiftGlobals.h>
-#include <Sluift/Lua/Exception.h>
+#include <Swiften/Component/ComponentXMLTracer.h>
#include <Swiften/Elements/Message.h>
+#include <Swiften/Elements/Presence.h>
#include <Swiften/Queries/RawRequest.h>
+#include <Swiften/Roster/XMPPRoster.h>
+
#include <Sluift/Helpers.h>
-#include <Swiften/Elements/Presence.h>
+#include <Sluift/Lua/Exception.h>
+#include <Sluift/SluiftGlobals.h>
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(nullptr) {
+ 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 = nullptr;
+ }
}
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));
+void SluiftComponent::handleIncomingMessage(std::shared_ptr<Message> stanza) {
+ pendingEvents.push_back(Event(stanza));
}
-void SluiftComponent::handleIncomingPresence(boost::shared_ptr<Presence> stanza) {
- pendingEvents.push_back(Event(stanza));
+void SluiftComponent::handleIncomingPresence(std::shared_ptr<Presence> 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;
+void SluiftComponent::handleRequestResponse(std::shared_ptr<Payload> response, std::shared_ptr<ErrorPayload> error) {
+ 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);
+Sluift::Response SluiftComponent::doSendRequest(std::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() ?
+ std::make_shared<ErrorPayload>(ErrorPayload::RemoteServerTimeout) : requestError);
}
diff --git a/Sluift/SluiftComponent.h b/Sluift/SluiftComponent.h
index 4e5e763..d45c3b2 100644
--- a/Sluift/SluiftComponent.h
+++ b/Sluift/SluiftComponent.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,101 +7,103 @@
#pragma once
#include <deque>
-#include <boost/optional.hpp>
+
#include <boost/bind.hpp>
#include <boost/function.hpp>
+#include <boost/optional.hpp>
#include <Swiften/Client/ClientOptions.h>
+#include <Swiften/Component/Component.h>
+#include <Swiften/Component/ComponentError.h>
#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Presence.h>
+#include <Swiften/EventLoop/SimpleEventLoop.h>
+#include <Swiften/Network/NetworkFactories.h>
#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Roster/XMPPRosterItem.h>
-#include <Swiften/Component/ComponentError.h>
-#include <Swiften/Network/NetworkFactories.h>
-#include <Swiften/Component/Component.h>
-#include <Swiften/EventLoop/SimpleEventLoop.h>
-#include <Sluift/Watchdog.h>
+
#include <Sluift/Response.h>
+#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(std::shared_ptr<Message> stanza) : type(MessageType), stanza(stanza) {}
+ Event(std::shared_ptr<Presence> stanza) : type(PresenceType), stanza(stanza) {}
+
+ Type type;
+
+ // Message & Presence
+ std::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::signals2::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::signals2::scoped_connection c(request->onResponse.connect(
+ boost::bind(&SluiftComponent::handleRequestResponse, this, std::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(std::shared_ptr<Request> request, int timeout);
+
+ void handleIncomingMessage(std::shared_ptr<Message> stanza);
+ void handleIncomingPresence(std::shared_ptr<Presence> stanza);
+ void handleRequestResponse(std::shared_ptr<Payload> response, std::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 = false;
+ std::shared_ptr<Payload> requestResponse;
+ std::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 6e4767d..1378346 100644
--- a/Sluift/StandardTerminal.cpp
+++ b/Sluift/StandardTerminal.cpp
@@ -1,15 +1,16 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/StandardTerminal.h>
-#include <boost/optional.hpp>
#include <iostream>
#include <stdexcept>
+#include <boost/optional.hpp>
+
using namespace Swift;
StandardTerminal::StandardTerminal() {
@@ -19,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 6c0eed8..2109878 100644
--- a/Sluift/StandardTerminal.h
+++ b/Sluift/StandardTerminal.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,16 +7,17 @@
#pragma once
#include <Swiften/Base/Override.h>
+
#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.cpp b/Sluift/Terminal.cpp
index db1332a..4b54a87 100644
--- a/Sluift/Terminal.cpp
+++ b/Sluift/Terminal.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,7 +8,7 @@
using namespace Swift;
-Terminal::Terminal() : completer(NULL) {
+Terminal::Terminal() : completer(nullptr) {
}
Terminal::~Terminal() {
diff --git a/Sluift/Terminal.h b/Sluift/Terminal.h
index 3bc63e3..3443d16 100644
--- a/Sluift/Terminal.h
+++ b/Sluift/Terminal.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,29 +7,30 @@
#pragma once
#include <string>
+
#include <boost/optional/optional.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/Tests/FormTest.lua b/Sluift/Tests/FormTest.lua
index 8065360..d584646 100644
--- a/Sluift/Tests/FormTest.lua
+++ b/Sluift/Tests/FormTest.lua
@@ -1,5 +1,5 @@
--[[
- Copyright (c) 2013 Isode Limited.
+ Copyright (c) 2013-2016 Isode Limited.
All rights reserved.
See the COPYING file for more information.
--]]
@@ -90,3 +90,15 @@ assert(type(text_multi_field['value']) == 'table')
--print(sluift.to_xml({type = 'form', data = form}))
+
+-- test parsing an empty form -- this had issues as reported in SWIFT-174
+empty_form = [[<x xmlns='jabber:x:data' type='form'/>]]
+form = sluift.from_xml(empty_form)
+-- and check if we can access all fields without problems
+assert(type(form._type))
+assert(type(form.title))
+assert(type(form.instructions))
+assert(type(form.type))
+assert(type(form.fields))
+assert(type(form.items))
+assert(type(form.reported_items))
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 6373a20..186effc 100644
--- a/Sluift/client.cpp
+++ b/Sluift/client.cpp
@@ -4,774 +4,774 @@
* See the COPYING file for more information.
*/
-#include <boost/lambda/lambda.hpp>
-#include <boost/lambda/bind.hpp>
#include <boost/assign/list_of.hpp>
-#include <iostream>
+#include <boost/lambda/bind.hpp>
+#include <boost/lambda/lambda.hpp>
-#include <Sluift/SluiftClient.h>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Elements/SoftwareVersion.h>
+#include <Swiften/Base/IDGenerator.h>
+#include <Swiften/Disco/ClientDiscoManager.h>
+#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/RawXMLPayload.h>
#include <Swiften/Elements/RosterItemPayload.h>
#include <Swiften/Elements/RosterPayload.h>
-#include <Swiften/Elements/DiscoInfo.h>
-#include <Swiften/Elements/MAMQuery.h>
-#include <Swiften/Disco/ClientDiscoManager.h>
-#include <Swiften/Queries/GenericRequest.h>
+#include <Swiften/Elements/SoftwareVersion.h>
+#include <Swiften/JID/JID.h>
#include <Swiften/Presence/PresenceSender.h>
-#include <Swiften/Roster/XMPPRoster.h>
-#include <Swiften/Roster/SetRosterRequest.h>
#include <Swiften/Presence/SubscriptionManager.h>
-#include <Swiften/Roster/XMPPRosterItem.h>
+#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Queries/Requests/GetSoftwareVersionRequest.h>
+#include <Swiften/Roster/SetRosterRequest.h>
+#include <Swiften/Roster/XMPPRoster.h>
+#include <Swiften/Roster/XMPPRosterItem.h>
#include <Swiften/TLS/PKCS12Certificate.h>
-#include <Sluift/Lua/FunctionRegistration.h>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Base/IDGenerator.h>
+
+#include <Sluift/ElementConvertors/IQConvertor.h>
+#include <Sluift/ElementConvertors/MessageConvertor.h>
+#include <Sluift/ElementConvertors/PresenceConvertor.h>
+#include <Sluift/ElementConvertors/StanzaConvertor.h>
+#include <Sluift/ElementConvertors/StatusShowConvertor.h>
#include <Sluift/Lua/Check.h>
-#include <Sluift/Lua/Value.h>
#include <Sluift/Lua/Exception.h>
+#include <Sluift/Lua/FunctionRegistration.h>
#include <Sluift/Lua/LuaUtils.h>
+#include <Sluift/Lua/Value.h>
+#include <Sluift/SluiftClient.h>
#include <Sluift/globals.h>
-#include <Sluift/ElementConvertors/StanzaConvertor.h>
-#include <Sluift/ElementConvertors/IQConvertor.h>
-#include <Sluift/ElementConvertors/PresenceConvertor.h>
-#include <Sluift/ElementConvertors/MessageConvertor.h>
-#include <Sluift/ElementConvertors/StatusShowConvertor.h>
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;
-}
-
-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");
- }
-}
-
-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>();
- }
-}
-
-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;
+ 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<std::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");
+ }
+}
+
+static std::shared_ptr<Payload> getPayload(lua_State* L, int index) {
+ if (lua_type(L, index) == LUA_TTABLE) {
+ return std::dynamic_pointer_cast<Payload>(Sluift::globals.elementConvertor.convertFromLua(L, index));
+ }
+ else if (lua_type(L, index) == LUA_TSTRING) {
+ return std::make_shared<RawXMLPayload>(Lua::checkString(L, index));
+ }
+ else {
+ return std::shared_ptr<Payload>();
+ }
+}
+
+static std::vector< std::shared_ptr<Payload> > getPayloadsFromTable(lua_State* L, int index) {
+ index = Lua::absoluteOffset(L, index);
+ std::vector< std::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)) {
+ std::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 (std::shared_ptr<SoftwareVersion> version = std::dynamic_pointer_cast<SoftwareVersion>(Sluift::globals.elementConvertor.convertFromLuaUntyped(L, 2, "software_version"))) {
+ client->setSoftwareVersion(version->getName(), version->getVersion(), version->getOS());
+ }
+ return 0;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, get_contacts,
- "Returns a table of all the contacts in the contact list.",
- "self\n",
- ""
+ 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;
+ for (const auto& item : client->getRoster(getGlobalTimeout(L))) {
+ std::string subscription;
+ switch(item.getSubscription()) {
+ case RosterItemPayload::None: subscription = "none"; break;
+ case RosterItemPayload::To: subscription = "to"; break;
+ case RosterItemPayload::From: subscription = "from"; break;
+ case RosterItemPayload::Both: subscription = "both"; break;
+ case RosterItemPayload::Remove: subscription = "remove"; break;
+ }
+ Lua::Table itemTable = boost::assign::map_list_of
+ ("jid", std::make_shared<Lua::Value>(item.getJID().toString()))
+ ("name", std::make_shared<Lua::Value>(item.getName()))
+ ("subscription", std::make_shared<Lua::Value>(subscription))
+ ("groups", std::make_shared<Lua::Value>(std::vector<Lua::Value>(item.getGroups().begin(), item.getGroups().end())));
+ contactsTable[item.getJID().toString()] = std::make_shared<Lua::Value>(itemTable);
+ }
+ pushValue(L, contactsTable);
+ Lua::registerTableToString(L, -1);
+ return 1;
}
SLUIFT_LUA_FUNCTION_WITH_HELP(
- Client, send_message,
- "Send a message.",
- "self\n"
- "to the JID to send the message to\n"
- "body the body of the message. Can alternatively be specified using the `body` option\n",
-
- "to the JID to send the message to\n"
- "body the body of the message\n"
- "subject the subject of the MUC room to set\n"
- "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<std::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 = std::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();
+ std::shared_ptr<Presence> presence = std::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< std::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);
+ std::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(
+ std::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 (std::shared_ptr<payloadType> p = std::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");
+ }
+ std::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", std::make_shared<Lua::Value>(client->getOptions().manualHostname))
+ ("port", std::make_shared<Lua::Value>(client->getOptions().manualPort))
+ ("ack", std::make_shared<Lua::Value>(client->getOptions().useAcks))
+ ("compress", std::make_shared<Lua::Value>(client->getOptions().useStreamCompression))
+ ("tls", std::make_shared<Lua::Value>(client->getOptions().useTLS == ClientOptions::NeverUseTLS ? false : true))
+ ("bosh_url", std::make_shared<Lua::Value>(client->getOptions().boshURL.toString()))
+ ("allow_plain_without_tls", std::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 = std::dynamic_pointer_cast<Message>(event.stanza);
+ Lua::Table result = boost::assign::map_list_of
+ ("type", std::make_shared<Lua::Value>(std::string("message")))
+ ("from", std::make_shared<Lua::Value>(message->getFrom().toString()))
+ ("to", std::make_shared<Lua::Value>(message->getTo().toString()))
+ ("body", std::make_shared<Lua::Value>(message->getBody().get_value_or("")))
+ ("message_type", std::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 = std::dynamic_pointer_cast<Presence>(event.stanza);
+ Lua::Table result = boost::assign::map_list_of
+ ("type", std::make_shared<Lua::Value>(std::string("presence")))
+ ("from", std::make_shared<Lua::Value>(presence->getFrom().toString()))
+ ("to", std::make_shared<Lua::Value>(presence->getTo().toString()))
+ ("status", std::make_shared<Lua::Value>(presence->getStatus()))
+ ("presence_type", std::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 = std::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 = std::make_shared<RosterPayload>();
+ roster->addItem(RosterItemPayload(JID(Lua::checkString(L, 2)), "", RosterItemPayload::Remove));
- 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);
+ 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 (std::shared_ptr<DiscoInfo> discoInfo = std::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(std::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 a9ac2d9..df96d43 100644
--- a/Sluift/component.cpp
+++ b/Sluift/component.cpp
@@ -1,30 +1,14 @@
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <iostream>
-
#include <boost/assign/list_of.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
-#include <Sluift/ElementConvertors/IQConvertor.h>
-#include <Sluift/ElementConvertors/MessageConvertor.h>
-#include <Sluift/ElementConvertors/PresenceConvertor.h>
-#include <Sluift/ElementConvertors/StanzaConvertor.h>
-#include <Sluift/ElementConvertors/StatusShowConvertor.h>
-#include <Sluift/Lua/Check.h>
-#include <Sluift/Lua/Exception.h>
-#include <Sluift/Lua/FunctionRegistration.h>
-#include <Sluift/Lua/LuaUtils.h>
-#include <Sluift/Lua/Value.h>
-#include <Sluift/SluiftComponent.h>
-#include <Sluift/globals.h>
-
#include <Swiften/Base/IDGenerator.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/MAMQuery.h>
#include <Swiften/Elements/Message.h>
@@ -43,427 +27,440 @@
#include <Swiften/Roster/XMPPRoster.h>
#include <Swiften/Roster/XMPPRosterItem.h>
+#include <Sluift/ElementConvertors/IQConvertor.h>
+#include <Sluift/ElementConvertors/MessageConvertor.h>
+#include <Sluift/ElementConvertors/PresenceConvertor.h>
+#include <Sluift/ElementConvertors/StanzaConvertor.h>
+#include <Sluift/ElementConvertors/StatusShowConvertor.h>
+#include <Sluift/Lua/Check.h>
+#include <Sluift/Lua/Exception.h>
+#include <Sluift/Lua/FunctionRegistration.h>
+#include <Sluift/Lua/LuaUtils.h>
+#include <Sluift/Lua/Value.h>
+#include <Sluift/SluiftComponent.h>
+#include <Sluift/globals.h>
+
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");
- }
+static void addPayloadsToTable(lua_State* L, const std::vector<std::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");
+ }
}
-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>();
- }
+static std::shared_ptr<Payload> getPayload(lua_State* L, int index) {
+ if (lua_type(L, index) == LUA_TTABLE) {
+ return std::dynamic_pointer_cast<Payload>(Sluift::globals.elementConvertor.convertFromLua(L, index));
+ }
+ else if (lua_type(L, index) == LUA_TSTRING) {
+ return std::make_shared<RawXMLPayload>(Lua::checkString(L, index));
+ }
+ else {
+ return std::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;
+static std::vector< std::shared_ptr<Payload> > getPayloadsFromTable(lua_State* L, int index) {
+ index = Lua::absoluteOffset(L, index);
+ std::vector< std::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)) {
+ std::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 (std::shared_ptr<SoftwareVersion> version = std::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<std::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 = std::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();
+ std::shared_ptr<Presence> presence = std::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< std::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;
+ }
+
+ std::shared_ptr<Payload> payload;
+ lua_getfield(L, 2, "query");
+ payload = getPayload(L, -1);
+ lua_pop(L, 1);
+
+ return component->sendRequest(
+ std::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 = std::dynamic_pointer_cast<Message>(event.stanza);
+ Lua::Table result = boost::assign::map_list_of
+ ("type", std::make_shared<Lua::Value>(std::string("message")))
+ ("from", std::make_shared<Lua::Value>(message->getFrom().toString()))
+ ("to", std::make_shared<Lua::Value>(message->getTo().toString()))
+ ("body", std::make_shared<Lua::Value>(message->getBody().get_value_or("")))
+ ("message_type", std::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 = std::dynamic_pointer_cast<Presence>(event.stanza);
+ Lua::Table result = boost::assign::map_list_of
+ ("type", std::make_shared<Lua::Value>(std::string("presence")))
+ ("from", std::make_shared<Lua::Value>(presence->getFrom().toString()))
+ ("to", std::make_shared<Lua::Value>(presence->getTo().toString()))
+ ("status", std::make_shared<Lua::Value>(presence->getStatus()))
+ ("presence_type", std::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..65d6d60 100644
--- a/Sluift/main.cpp
+++ b/Sluift/main.cpp
@@ -1,20 +1,24 @@
/*
- * Copyright (c) 2013-2014 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <iostream>
#include <string>
#include <vector>
-#include <lua.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Base/Platform.h>
+
+#include <boost/assign/list_of.hpp>
+#include <boost/numeric/conversion/cast.hpp>
+#include <boost/program_options.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
-#include <boost/program_options.hpp>
#include <boost/version.hpp>
-#include <boost/numeric/conversion/cast.hpp>
-#include <boost/assign/list_of.hpp>
+
+#include <lua.hpp>
+
+#include <Swiften/Base/Platform.h>
+
#include <Sluift/globals.h>
#include <Sluift/Console.h>
#include <Sluift/StandardTerminal.h>
@@ -34,155 +38,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},
+ {nullptr, nullptr}
};
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()));
+ for (const auto& scriptArgument : scriptArguments) {
+ lua_pushstring(L, scriptArgument.c_str());
+ }
+ checkResult(L, Console::call(L, boost::numeric_cast<int>(scriptArguments.size()), false));
}
int main(int argc, char* argv[]) {
- // Parse program options
- boost::program_options::options_description visibleOptions("Options");
- visibleOptions.add_options()
- ("help,h", "Display this help message")
- ("version,v", "Display version information")
- ("interactive,i", "Enter interactive mode after executing script")
- ;
- boost::program_options::options_description hiddenOptions("Hidden Options");
- hiddenOptions.add_options()
- ("script", boost::program_options::value< std::string >(), "Script to be executed")
- ("script-arguments", boost::program_options::value< std::vector<std::string> >(), "Script arguments")
- ;
- boost::program_options::options_description options("All Options");
- options.add(visibleOptions).add(hiddenOptions);
-
- boost::program_options::positional_options_description positional_options;
- positional_options.add("script", 1).add("script-arguments", -1);
-
- boost::program_options::variables_map arguments;
- try {
- boost::program_options::store(
- boost::program_options::command_line_parser(argc, argv)
- .options(options)
- .positional(positional_options).run(), arguments);
- }
- 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");
+ for (const auto& globalImport : globalImports) {
+ lua_getfield(L, -1, globalImport.c_str());
+ lua_setglobal(L, globalImport.c_str());
+ }
+ lua_pop(L, 1);
+
+ std::cout << SLUIFT_WELCOME_STRING << std::endl;
#ifdef HAVE_EDITLINE
- EditlineTerminal& terminal = EditlineTerminal::getInstance();
+ 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 7a40270..561f404 100644
--- a/Sluift/sluift.cpp
+++ b/Sluift/sluift.cpp
@@ -1,61 +1,62 @@
/*
- * Copyright (c) 2011-2014 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/sluift.h>
-#include <lua.hpp>
-
#include <string>
-#include <boost/bind.hpp>
-#include <boost/numeric/conversion/cast.hpp>
+
#include <boost/assign/list_of.hpp>
+#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
+#include <boost/numeric/conversion/cast.hpp>
+
+#include <lua.hpp>
-#include "Watchdog.h"
-#include <Sluift/Lua/Check.h>
-#include <Sluift/SluiftClient.h>
-#include <Sluift/SluiftComponent.h>
-#include <Sluift/globals.h>
-#include <Sluift/Lua/Exception.h>
-#include <Sluift/Lua/LuaUtils.h>
-#include <Sluift/Lua/FunctionRegistration.h>
-#include <Swiften/Base/sleep.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/IDGenerator.h>
+#include <Swiften/Base/sleep.h>
+#include <Swiften/Crypto/CryptoProvider.h>
+#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/IDN/IDNConverter.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
-#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializer.h>
-#include <Swiften/TLS/Certificate.h>
-#include <Swiften/TLS/CertificateFactory.h>
-#include <Sluift/LuaElementConvertor.h>
-#include <Sluift/Lua/Debug.h>
+#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
#include <Swiften/StringCodecs/Base64.h>
#include <Swiften/StringCodecs/Hexify.h>
-#include <Swiften/IDN/IDNConverter.h>
-#include <Swiften/Crypto/CryptoProvider.h>
-#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/TLS/Certificate.h>
+#include <Swiften/TLS/CertificateFactory.h>
+
#include <Sluift/ITunesInterface.h>
+#include <Sluift/Lua/Check.h>
+#include <Sluift/Lua/Debug.h>
+#include <Sluift/Lua/Exception.h>
+#include <Sluift/Lua/FunctionRegistration.h>
+#include <Sluift/Lua/LuaUtils.h>
+#include <Sluift/LuaElementConvertor.h>
+#include <Sluift/SluiftClient.h>
+#include <Sluift/SluiftComponent.h>
+#include <Sluift/Watchdog.h>
+#include <Sluift/globals.h>
using namespace Swift;
namespace Swift {
- namespace Sluift {
- SluiftGlobals globals;
- }
+ 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;
}
@@ -64,157 +65,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 std::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;
+ std::shared_ptr<Payload> payload = std::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;
}
/*******************************************************************************
@@ -222,34 +223,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;
}
/*******************************************************************************
@@ -257,30 +258,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;
}
@@ -289,32 +290,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;
}
/*******************************************************************************
@@ -322,22 +323,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;
}
/*******************************************************************************
@@ -345,43 +346,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;
}
/*******************************************************************************
@@ -390,26 +391,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
@@ -417,84 +418,84 @@ SLUIFT_LUA_FUNCTION(iTunes, get_current_track) {
* Module registration
******************************************************************************/
-static const luaL_Reg sluift_functions[] = { {NULL, NULL} };
+static const luaL_Reg sluift_functions[] = { {nullptr, nullptr} };
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");
+ for (const auto& coreLibExport : coreLibExports) {
+ lua_getfield(L, -1, coreLibExport.c_str());
+ lua_setfield(L, -3, coreLibExport.c_str());
+ }
+ lua_pop(L, 1);
+
+ // Load client metatable
+ lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
+ std::vector<std::string> tables = boost::assign::list_of("Client");
+ for (const auto& table : tables) {
+ lua_getfield(L, -1, table.c_str());
+ Lua::FunctionRegistry::getInstance().addFunctionsToTable(L, table);
+ lua_pop(L, 1);
+ }
+ lua_pop(L, 1);
+
+ // Load component metatable
+ lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex);
+ std::vector<std::string> comp_tables = boost::assign::list_of("Component");
+ for (const auto& table : comp_tables) {
+ lua_getfield(L, -1, table.c_str());
+ Lua::FunctionRegistry::getInstance().addFunctionsToTable(L, table);
+ lua_pop(L, 1);
+ }
+ lua_pop(L, 1);
+
+ // Register documentation for all elements
+ for (auto&& convertor : Sluift::globals.elementConvertor.getConvertors()) {
+ boost::optional<LuaElementConvertor::Documentation> documentation = convertor->getDocumentation();
+ if (documentation) {
+ Lua::registerClassHelp(L, documentation->className, documentation->description);
+ }
+ }
+
+ // Register global documentation
+ Lua::registerExtraHelp(L, -1, "sluift");
+
+ return 1;
}
diff --git a/Sluift/tokenize.cpp b/Sluift/tokenize.cpp
index 55ab744..ff162d6 100644
--- a/Sluift/tokenize.cpp
+++ b/Sluift/tokenize.cpp
@@ -1,86 +1,87 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Sluift/tokenize.h>
-#include <boost/tokenizer.hpp>
#include <cctype>
+#include <boost/tokenizer.hpp>
+
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;
+ }
+ }
- // 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;
- }
- };
+ 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 9a65b07..33ea435 100644
--- a/Sluift/tokenize.h
+++ b/Sluift/tokenize.h
@@ -1,16 +1,16 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <string>
+#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 358a5fc..8b952bb 100644
--- a/SwifTools/Application/ApplicationPathProvider.cpp
+++ b/SwifTools/Application/ApplicationPathProvider.cpp
@@ -1,14 +1,14 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <SwifTools/Application/ApplicationPathProvider.h>
+
#include <boost/filesystem.hpp>
-#include <iostream>
-#include <SwifTools/Application/ApplicationPathProvider.h>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Base/Log.h>
#include <Swiften/Base/Paths.h>
namespace Swift {
@@ -20,29 +20,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) {
+ SWIFT_LOG(error) << e.what() << std::endl;
+ }
+ return result;
}
boost::filesystem::path ApplicationPathProvider::getResourcePath(const std::string& resource) const {
- std::vector<boost::filesystem::path> resourcePaths = getResourceDirs();
- foreach(const boost::filesystem::path& resourcePath, resourcePaths) {
- boost::filesystem::path r(resourcePath / resource);
- if (boost::filesystem::exists(r)) {
- return r;
- }
- }
- return boost::filesystem::path();
+ std::vector<boost::filesystem::path> resourcePaths = getResourceDirs();
+ for (const auto& resourcePath : resourcePaths) {
+ boost::filesystem::path r(resourcePath / resource);
+ if (boost::filesystem::exists(r)) {
+ return r;
+ }
+ }
+ return boost::filesystem::path();
}
boost::filesystem::path ApplicationPathProvider::getExecutableDir() const {
- return Paths::getExecutablePath();
+ 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..4b366c6 100644
--- a/SwifTools/Application/CocoaApplication.h
+++ b/SwifTools/Application/CocoaApplication.h
@@ -1,19 +1,21 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
namespace Swift {
- class CocoaApplication {
- public:
- CocoaApplication();
- ~CocoaApplication();
+ class CocoaApplication {
+ public:
+ CocoaApplication();
+ ~CocoaApplication();
- private:
- class Private;
- Private* d;
- };
+ private:
+ class Private;
+ const std::unique_ptr<Private> d;
+ };
}
diff --git a/SwifTools/Application/CocoaApplication.mm b/SwifTools/Application/CocoaApplication.mm
index cbb5f2e..f058ed4 100644
--- a/SwifTools/Application/CocoaApplication.mm
+++ b/SwifTools/Application/CocoaApplication.mm
@@ -1,3 +1,9 @@
+/*
+ * Copyright (c) 2010-2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <SwifTools/Application/CocoaApplication.h>
#include <AppKit/AppKit.h>
@@ -6,19 +12,17 @@
namespace Swift {
class CocoaApplication::Private {
- public:
- NSAutoreleasePool* autoReleasePool_;
+ public:
+ NSAutoreleasePool* autoReleasePool_;
};
-CocoaApplication::CocoaApplication() {
- d = new CocoaApplication::Private();
- NSApplicationLoad();
- d->autoReleasePool_ = [[NSAutoreleasePool alloc] init];
+CocoaApplication::CocoaApplication() : d(new Private()) {
+ NSApplicationLoad();
+ d->autoReleasePool_ = [[NSAutoreleasePool alloc] init];
}
CocoaApplication::~CocoaApplication() {
- [d->autoReleasePool_ release];
- delete d;
+ [d->autoReleasePool_ release];
}
}
diff --git a/SwifTools/Application/MacOSXApplicationPathProvider.cpp b/SwifTools/Application/MacOSXApplicationPathProvider.cpp
index 4d6c0c0..684d8b2 100644
--- a/SwifTools/Application/MacOSXApplicationPathProvider.cpp
+++ b/SwifTools/Application/MacOSXApplicationPathProvider.cpp
@@ -1,34 +1,35 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <SwifTools/Application/MacOSXApplicationPathProvider.h>
-#include <iostream>
#include <mach-o/dyld.h>
+#include <Swiften/Base/Log.h>
+
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) {
+ SWIFT_LOG(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/SConscript b/SwifTools/Application/SConscript
index 32924fc..29bcceb 100644
--- a/SwifTools/Application/SConscript
+++ b/SwifTools/Application/SConscript
@@ -1,27 +1,27 @@
Import("swiftools_env", "env")
sources = [
- "ApplicationPathProvider.cpp",
- ]
+ "ApplicationPathProvider.cpp",
+ ]
if swiftools_env["PLATFORM"] == "darwin" and swiftools_env["target"] == "native" :
- sources += [
- "CocoaApplication.mm",
- "MacOSXApplicationPathProvider.cpp",
- ]
+ sources += [
+ "CocoaApplication.mm",
+ "MacOSXApplicationPathProvider.cpp",
+ ]
elif swiftools_env["PLATFORM"] == "win32" :
- sources += [
- "WindowsApplicationPathProvider.cpp"
- ]
+ sources += [
+ "WindowsApplicationPathProvider.cpp"
+ ]
else :
- sources += [
- "UnixApplicationPathProvider.cpp"
- ]
+ sources += [
+ "UnixApplicationPathProvider.cpp"
+ ]
objects = swiftools_env.StaticObject(sources)
swiftools_env.Append(SWIFTOOLS_OBJECTS = [objects])
if swiftools_env["PLATFORM"] != "darwin" or swiftools_env["target"] == "native" :
- env.Append(UNITTEST_SOURCES = [
- File("UnitTest/ApplicationPathProviderTest.cpp")
- ])
+ env.Append(UNITTEST_SOURCES = [
+ File("UnitTest/ApplicationPathProviderTest.cpp")
+ ])
diff --git a/SwifTools/Application/UnitTest/ApplicationPathProviderTest.cpp b/SwifTools/Application/UnitTest/ApplicationPathProviderTest.cpp
index 46b259d..433b379 100644
--- a/SwifTools/Application/UnitTest/ApplicationPathProviderTest.cpp
+++ b/SwifTools/Application/UnitTest/ApplicationPathProviderTest.cpp
@@ -1,51 +1,54 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
#include <string>
+
#include <boost/algorithm/string.hpp>
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
#include <Swiften/Base/Path.h>
+
#include <SwifTools/Application/PlatformApplicationPathProvider.h>
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 f159821..e455d23 100644
--- a/SwifTools/Application/UnixApplicationPathProvider.cpp
+++ b/SwifTools/Application/UnixApplicationPathProvider.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,55 +7,56 @@
#include <SwifTools/Application/UnixApplicationPathProvider.h>
#include <stdlib.h>
-#include <unistd.h>
+
#include <boost/algorithm/string.hpp>
-#include <iostream>
+#include <unistd.h>
+
+#include <Swiften/Base/Log.h>
#include <Swiften/Base/String.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
UnixApplicationPathProvider::UnixApplicationPathProvider(const std::string& name) : ApplicationPathProvider(name) {
- resourceDirs.push_back(getExecutableDir() / "../resources"); // Development
- resourceDirs.push_back(getExecutableDir() / ".." / "share" / boost::to_lower_copy(getApplicationName())); // Local install
- char* xdgDataDirs = getenv("XDG_DATA_DIRS");
- if (xdgDataDirs) {
- std::vector<std::string> dataDirs = String::split(xdgDataDirs, ':');
- if (!dataDirs.empty()) {
- foreach(const std::string& dir, dataDirs) {
- 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()) {
+ for (const auto& dir : dataDirs) {
+ resourceDirs.push_back(boost::filesystem::path(dir) / "swift");
+ }
+ return;
+ }
+ }
+ resourceDirs.push_back("/usr/local/share/" + boost::to_lower_copy(getApplicationName()));
+ resourceDirs.push_back("/usr/share/" + boost::to_lower_copy(getApplicationName()));
}
boost::filesystem::path UnixApplicationPathProvider::getHomeDir() const {
- char* home = getenv("HOME");
- return home ? boost::filesystem::path(home) : boost::filesystem::path();
+ char* home = getenv("HOME");
+ return home ? boost::filesystem::path(home) : boost::filesystem::path();
}
boost::filesystem::path UnixApplicationPathProvider::getDataDir() const {
- char* xdgDataHome = getenv("XDG_DATA_HOME");
- std::string dataDir;
- if (xdgDataHome) {
- dataDir = std::string(xdgDataHome);
- }
-
- boost::filesystem::path dataPath = (dataDir.empty() ?
- getHomeDir() / ".local" / "share"
- : boost::filesystem::path(dataDir)) / boost::to_lower_copy(getApplicationName());
-
- try {
- boost::filesystem::create_directories(dataPath);
- }
- catch (const boost::filesystem::filesystem_error& e) {
- std::cerr << "ERROR: " << e.what() << std::endl;
- }
- return dataPath;
+ char* xdgDataHome = getenv("XDG_DATA_HOME");
+ std::string dataDir;
+ if (xdgDataHome) {
+ dataDir = std::string(xdgDataHome);
+ }
+
+ boost::filesystem::path dataPath = (dataDir.empty() ?
+ getHomeDir() / ".local" / "share"
+ : boost::filesystem::path(dataDir)) / boost::to_lower_copy(getApplicationName());
+
+ try {
+ boost::filesystem::create_directories(dataPath);
+ }
+ catch (const boost::filesystem::filesystem_error& e) {
+ SWIFT_LOG(error) << "file system 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 ee4b16e..e90214c 100644
--- a/SwifTools/Application/WindowsApplicationPathProvider.cpp
+++ b/SwifTools/Application/WindowsApplicationPathProvider.cpp
@@ -1,36 +1,38 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <SwifTools/Application/WindowsApplicationPathProvider.h>
-#include <windows.h>
#include <cassert>
+
+#include <windows.h>
+
#include <Swiften/Base/String.h>
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..274bf50 100644
--- a/SwifTools/AutoUpdater/AutoUpdater.h
+++ b/SwifTools/AutoUpdater/AutoUpdater.h
@@ -1,16 +1,30 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
+#include <boost/signals2.hpp>
+
namespace Swift {
- class AutoUpdater {
- public:
- virtual ~AutoUpdater();
+ class AutoUpdater {
+ public:
+ virtual ~AutoUpdater();
+
+ virtual void setAppcastFeed(const std::string& appcastFeed) = 0;
+ virtual void checkForUpdates() = 0;
+ virtual bool recommendRestartToUpdate() = 0;
- virtual void checkForUpdates() = 0;
- };
+ public:
+ /**
+ * Emit this signal if a new version of the software has been downloaded
+ * and the user needs to be notified so they can quit the app and start
+ * the newer version.
+ */
+ boost::signals2::signal<void()> onSuggestRestartToUserToUpdate;
+ };
}
diff --git a/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.cpp b/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.cpp
index 424c6e0..9ae8c09 100644
--- a/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.cpp
+++ b/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 nullptr;
#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 4951342..dd22e73 100644
--- a/SwifTools/AutoUpdater/SparkleAutoUpdater.h
+++ b/SwifTools/AutoUpdater/SparkleAutoUpdater.h
@@ -1,24 +1,34 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
+
#include <SwifTools/AutoUpdater/AutoUpdater.h>
namespace Swift {
- class SparkleAutoUpdater : public AutoUpdater {
- public:
- SparkleAutoUpdater(const std::string& url);
- ~SparkleAutoUpdater();
+ /**
+ * @brief The SparkleAutoUpdater class provides integration with Sparkle.
+ * This enables automatic silent background updates. If using this in Qt you
+ * need to emit a NSApplicationWillTerminateNotification before you quit
+ * the application.
+ */
+ class SparkleAutoUpdater : public AutoUpdater {
+ public:
+ SparkleAutoUpdater(const std::string& appcastFeed);
+ ~SparkleAutoUpdater();
+
+ void setAppcastFeed(const std::string& appcastFeed);
+ void checkForUpdates();
+ bool recommendRestartToUpdate();
- void checkForUpdates();
-
- private:
- class Private;
- Private* d;
- };
+ private:
+ class Private;
+ const std::unique_ptr<Private> d;
+ };
}
diff --git a/SwifTools/AutoUpdater/SparkleAutoUpdater.mm b/SwifTools/AutoUpdater/SparkleAutoUpdater.mm
index c35abc8..0c296ee 100644
--- a/SwifTools/AutoUpdater/SparkleAutoUpdater.mm
+++ b/SwifTools/AutoUpdater/SparkleAutoUpdater.mm
@@ -1,34 +1,62 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <SwifTools/AutoUpdater/SparkleAutoUpdater.h>
#include <Cocoa/Cocoa.h>
#include <Sparkle/Sparkle.h>
+#include <SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.h>
+#include <SwifTools/Cocoa/CocoaUtil.h>
+
namespace Swift {
class SparkleAutoUpdater::Private {
- public:
- SUUpdater* updater;
+ public:
+ SUUpdater* updater;
+ boost::intrusive_ptr<SparkleAutoUpdaterDelegate> delegate;
+ bool restartToUpdate = false;
};
-SparkleAutoUpdater::SparkleAutoUpdater(const std::string& url) {
- d = new Private;
+SparkleAutoUpdater::SparkleAutoUpdater(const std::string& appcastFeed) : d(new Private()) {
+ d->updater = [SUUpdater sharedUpdater];
+ [d->updater retain];
- d->updater = [SUUpdater sharedUpdater];
- [d->updater retain];
- [d->updater setAutomaticallyChecksForUpdates: true];
+ d->delegate = boost::intrusive_ptr<SparkleAutoUpdaterDelegate>([[SparkleAutoUpdaterDelegate alloc] init], false);
+ [d->delegate.get() setUpdateDownloadFinished: [&](){
+ d->restartToUpdate = true;
+ onSuggestRestartToUserToUpdate();
+ }];
+ [d->updater setDelegate: d->delegate.get()];
- NSURL* nsurl = [NSURL URLWithString:
- [NSString stringWithUTF8String: url.c_str()]];
- [d->updater setFeedURL: nsurl];
+ [d->updater setAutomaticallyChecksForUpdates: true];
+ // Automatically check for an update after a day.
+ [d->updater setUpdateCheckInterval: 86400];
+ [d->updater setAutomaticallyDownloadsUpdates: true];
+
+ NSURL* nsurl = [NSURL URLWithString: std2NSString(appcastFeed)];
+ [d->updater setFeedURL: nsurl];
}
SparkleAutoUpdater::~SparkleAutoUpdater() {
- [d->updater release];
- delete d;
+ [d->updater release];
+}
+
+void SparkleAutoUpdater::setAppcastFeed(const std::string& appcastFeed) {
+ NSURL* nsurl = [NSURL URLWithString: std2NSString(appcastFeed)];
+ [d->updater setFeedURL: nsurl];
}
void SparkleAutoUpdater::checkForUpdates() {
- [d->updater checkForUpdatesInBackground];
+ [d->updater resetUpdateCycle];
+ [d->updater checkForUpdatesInBackground];
+}
+
+bool SparkleAutoUpdater::recommendRestartToUpdate() {
+ return d->restartToUpdate;
}
}
diff --git a/SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.h b/SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.h
new file mode 100644
index 0000000..8f408de
--- /dev/null
+++ b/SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#pragma once
+
+#include <functional>
+
+#import <Cocoa/Cocoa.h>
+
+#import <Sparkle/Sparkle.h>
+
+namespace Swift {
+ class SparkleAutoUpdater;
+}
+
+@interface SparkleAutoUpdaterDelegate : NSObject<SUUpdaterDelegate>
+@property (atomic) std::function< void ()> updateDownloadFinished;
+
+- (void)updater:(SUUpdater *)updater didFinishLoadingAppcast:(SUAppcast *)appcast;
+
+- (void)updater:(SUUpdater *)updater didFindValidUpdate:(SUAppcastItem *)update;
+
+- (id <SUVersionComparison>)versionComparatorForUpdater:(SUUpdater *)updater;
+
+- (void)updaterDidNotFindUpdate:(SUUpdater *)update;
+
+- (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update;
+
+- (void)updater:(SUUpdater *)updater willInstallUpdateOnQuit:(SUAppcastItem *)item immediateInstallationInvocation:(NSInvocation *)invocation;
+
+- (void)updater:(SUUpdater *)updater didAbortWithError:(NSError *)error;
+@end
diff --git a/SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.mm b/SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.mm
new file mode 100644
index 0000000..6e832ba
--- /dev/null
+++ b/SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.mm
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#import "SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.h"
+
+#include <string>
+
+#include <Swiften/Base/Log.h>
+
+#include <SwifTools/Cocoa/CocoaUtil.h>
+
+using namespace Swift;
+
+@implementation SparkleAutoUpdaterDelegate
+
+@synthesize updateDownloadFinished;
+
+- (void)updater:(SUUpdater *)updater didFinishLoadingAppcast:(SUAppcast *)appcast {
+ (void)updater;
+ (void)appcast;
+}
+
+- (void)updater:(SUUpdater *)updater didFindValidUpdate:(SUAppcastItem *)update {
+ (void)updater;
+ (void)update;
+}
+
+- (id <SUVersionComparison>)versionComparatorForUpdater:(SUUpdater *)updater {
+ (void)updater;
+ return nil;
+}
+
+- (void)updaterDidNotFindUpdate:(SUUpdater *)updater {
+ (void)updater;
+}
+
+- (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update {
+ (void)updater;
+ (void)update;
+}
+
+- (void)updater:(SUUpdater *)updater willInstallUpdateOnQuit:(SUAppcastItem *)item immediateInstallationInvocation:(NSInvocation *)invocation {
+ (void)updater;
+ (void)item;
+ (void)invocation;
+ updateDownloadFinished();
+}
+
+- (void)updater:(SUUpdater *)updater didAbortWithError:(NSError *)error {
+ (void)updater;
+ SWIFT_LOG(error) << ns2StdString([error localizedDescription]) << std::endl;
+}
+
+@end
diff --git a/SwifTools/Cocoa/CocoaAction.h b/SwifTools/Cocoa/CocoaAction.h
index 73ac209..8807f08 100644
--- a/SwifTools/Cocoa/CocoaAction.h
+++ b/SwifTools/Cocoa/CocoaAction.h
@@ -1,14 +1,15 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Cocoa/Cocoa.h>
#include <boost/function.hpp>
+#include <Cocoa/Cocoa.h>
+
@interface CocoaAction : NSObject
/**
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 49ed682..8c4dd64 100644
--- a/SwifTools/Cocoa/CocoaUtil.h
+++ b/SwifTools/Cocoa/CocoaUtil.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,21 +7,41 @@
#pragma once
// Conversion utilities
-#define NS2STDSTRING(a) (a == nil ? std::string() : std::string([a cStringUsingEncoding:NSUTF8StringEncoding]))
-#define STD2NSSTRING(a) [NSString stringWithCString:a.c_str() encoding:NSUTF8StringEncoding]
+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;
+}
+
+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);
+}
+
+}
// Intrusive pointer for NSObjects
-namespace boost {
- inline void intrusive_ptr_add_ref(NSObject* object) {
- [object retain];
- }
-
- inline void intrusive_ptr_release(NSObject* 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/Cocoa/SConscript b/SwifTools/Cocoa/SConscript
index 4ae4a07..f4bd286 100644
--- a/SwifTools/Cocoa/SConscript
+++ b/SwifTools/Cocoa/SConscript
@@ -2,7 +2,7 @@ Import("swiftools_env", "env")
sources = []
if swiftools_env["PLATFORM"] == "darwin" and swiftools_env["target"] == "native" :
- sources += ["CocoaAction.mm"]
+ sources += ["CocoaAction.mm"]
objects = swiftools_env.StaticObject(sources)
swiftools_env.Append(SWIFTOOLS_OBJECTS = [objects])
diff --git a/SwifTools/CrashReporter.cpp b/SwifTools/CrashReporter.cpp
index 35db605..bf637c8 100644
--- a/SwifTools/CrashReporter.cpp
+++ b/SwifTools/CrashReporter.cpp
@@ -1,19 +1,20 @@
/*
- * Copyright (c) 2012-2014 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Base/Log.h>
-#include <SwifTools/CrashReporter.h>
#include <Swiften/Base/Platform.h>
#include <Swiften/Base/Path.h>
+#include <SwifTools/CrashReporter.h>
+
#if defined(HAVE_BREAKPAD)
#pragma GCC diagnostic ignored "-Wold-style-cast"
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#ifdef SWIFTEN_PLATFORM_MACOSX
#include "client/mac/handler/exception_handler.h"
@@ -24,46 +25,47 @@
#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;
+ std::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;
- }
- }
+CrashReporter::CrashReporter(const boost::filesystem::path& path, const std::string& dumpPrefix) {
+ // 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 = std::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 = std::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));
+ p->handler->set_dump_filename_prefix(std::wstring(dumpPrefix.begin(), dumpPrefix.end()));
// 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 = std::make_shared<google_breakpad::ExceptionHandler>(pathToString(path), (google_breakpad::ExceptionHandler::FilterCallback) 0, handleDump, (void*) 0, true, (const char*) 0);
#endif
}
@@ -73,7 +75,7 @@ CrashReporter::CrashReporter(const boost::filesystem::path& path) {
// Dummy implementation
namespace Swift {
- CrashReporter::CrashReporter(const boost::filesystem::path&) {}
+ CrashReporter::CrashReporter(const boost::filesystem::path&, const std::string&) {}
}
#endif
diff --git a/SwifTools/CrashReporter.h b/SwifTools/CrashReporter.h
index 73eadb3..1efa801 100644
--- a/SwifTools/CrashReporter.h
+++ b/SwifTools/CrashReporter.h
@@ -1,22 +1,23 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/filesystem.hpp>
+#include <memory>
#include <string>
+#include <boost/filesystem.hpp>
+
namespace Swift {
- class CrashReporter {
- public:
- CrashReporter(const boost::filesystem::path& path);
+ class CrashReporter {
+ public:
+ CrashReporter(const boost::filesystem::path& path, const std::string& dumpPrefix);
- private:
- struct Private;
- boost::shared_ptr<Private> p;
- };
+ private:
+ struct Private;
+ std::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 8c196d8..5c7207c 100644
--- a/SwifTools/Dock/MacOSXDock.mm
+++ b/SwifTools/Dock/MacOSXDock.mm
@@ -1,14 +1,15 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <SwifTools/Dock/MacOSXDock.h>
+#include <boost/lexical_cast.hpp>
+
#include <AppKit/AppKit.h>
#include <Cocoa/Cocoa.h>
-#include <boost/lexical_cast.hpp>
#include <Swiften/Base/String.h>
@@ -18,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/SConscript b/SwifTools/Dock/SConscript
index 94797cb..3dbcf60 100644
--- a/SwifTools/Dock/SConscript
+++ b/SwifTools/Dock/SConscript
@@ -1,13 +1,13 @@
Import("swiftools_env")
sources = [
- "Dock.cpp",
- ]
+ "Dock.cpp",
+ ]
if swiftools_env["PLATFORM"] == "darwin" and swiftools_env["target"] == "native" :
- sources += [
- "MacOSXDock.mm",
- ]
+ sources += [
+ "MacOSXDock.mm",
+ ]
objects = swiftools_env.StaticObject(sources)
swiftools_env.Append(SWIFTOOLS_OBJECTS = objects)
diff --git a/SwifTools/Dock/WindowsDock.h b/SwifTools/Dock/WindowsDock.h
index 3fceb3f..fc10a48 100644
--- a/SwifTools/Dock/WindowsDock.h
+++ b/SwifTools/Dock/WindowsDock.h
@@ -1,42 +1,43 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QSystemTrayIcon>
#include <boost/lexical_cast.hpp>
+#include <QSystemTrayIcon>
+
#include <SwifTools/Dock/Dock.h>
#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 4c3f634..1de369b 100644
--- a/SwifTools/HunspellChecker.cpp
+++ b/SwifTools/HunspellChecker.cpp
@@ -4,54 +4,165 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <SwifTools/HunspellChecker.h>
#include <algorithm>
-#include <hunspell/hunspell.hxx>
+
#include <boost/algorithm/string.hpp>
+#include <boost/filesystem.hpp>
+#include <boost/regex.hpp>
+
+#include <hunspell/hunspell.hxx>
+#include <Swiften/Base/Log.h>
namespace Swift {
-HunspellChecker::HunspellChecker(const char* affix_path, const char* dictionary_path) {
- speller_ = new Hunspell(affix_path, dictionary_path);
+static std::vector<std::string> recursiveFileSearch(const std::vector<std::string>& paths, const boost::regex& regex) {
+ std::vector<std::string> matches;
+
+ for (auto& path : paths) {
+ if (boost::filesystem::exists(path)) {
+ boost::cmatch what;
+ for (auto filename : boost::make_iterator_range(boost::filesystem::directory_iterator(path), boost::filesystem::directory_iterator())) {
+ if (boost::filesystem::is_regular_file(filename) && boost::regex_match(filename.path().c_str(), what, regex)) {
+ matches.push_back(filename.path().string());
+ }
+ }
+ }
+ }
+ return matches;
+}
+
+HunspellChecker::HunspellChecker() {
}
HunspellChecker::~HunspellChecker() {
- delete speller_;
+}
+
+std::vector<std::string> HunspellChecker::hunspellDictionaryPaths() const {
+ // The following list of paths comes from the source of the Hunspell command line tool.
+ std::vector<std::string> paths = {
+ "/usr/share/hunspell",
+ "/usr/share/myspell",
+ "/usr/share/myspell/dicts",
+ "/Library/Spelling",
+ "/opt/openoffice.org/basis3.0/share/dict/ooo",
+ "/usr/lib/openoffice.org/basis3.0/share/dict/ooo",
+ "/opt/openoffice.org2.4/share/dict/ooo",
+ "/usr/lib/openoffice.org2.4/share/dict/ooo",
+ "/opt/openoffice.org2.3/share/dict/ooo",
+ "/usr/lib/openoffice.org2.3/share/dict/ooo",
+ "/opt/openoffice.org2.2/share/dict/ooo",
+ "/usr/lib/openoffice.org2.2/share/dict/ooo",
+ "/opt/openoffice.org2.1/share/dict/ooo",
+ "/usr/lib/openoffice.org2.1/share/dict/ooo",
+ "/opt/openoffice.org2.0/share/dict/ooo",
+ "/usr/lib/openoffice.org2.0/share/dict/ooo"
+ };
+
+ if (std::getenv("DICPATH")) {
+ std::string dicpathEnvironment(std::getenv("DICPATH"));
+ std::vector<std::string> dicpaths;
+ boost::split(dicpaths,dicpathEnvironment,boost::is_any_of(":"));
+ paths.insert(paths.begin(), dicpaths.begin(), dicpaths.end());
+ }
+
+ return paths;
+}
+
+bool HunspellChecker::isAutomaticallyDetectingLanguage() {
+ return false;
+}
+
+void HunspellChecker::setActiveLanguage(const std::string& language) {
+ auto dictionaries = detectedDictionaries();
+ if (dictionaries.find(language) != dictionaries.end()) {
+ SWIFT_LOG(debug) << "Initialized Hunspell with dic,aff files " << dictionaries[language].dicPath << " , " << dictionaries[language].affPath << std::endl;
+ speller_ = std::unique_ptr<Hunspell>(new Hunspell(dictionaries[language].affPath.c_str(), dictionaries[language].dicPath.c_str()));
+ activeLangauge_ = language;
+ }
+ else {
+ SWIFT_LOG(warning) << "Unsupported language '" << language << "'" << std::endl;
+ }
+}
+
+std::string HunspellChecker::activeLanguage() const {
+ return activeLangauge_.get_value_or("");
+}
+
+std::vector<std::string> HunspellChecker::supportedLanguages() const {
+ std::vector<std::string> languages;
+
+ for (const auto& n : detectedDictionaries()) {
+ languages.push_back(n.first);
+ }
+
+ return languages;
+}
+
+std::unordered_map<std::string, HunspellChecker::Dictionary> HunspellChecker::detectedDictionaries() const {
+ std::unordered_map<std::string, HunspellChecker::Dictionary> dictionaries;
+
+ auto dictionaryFiles = recursiveFileSearch(hunspellDictionaryPaths(), boost::regex(".*\\.dic$"));
+ for (const auto& dictionary : dictionaryFiles) {
+ std::string correspondingAffixPath = dictionary;
+ boost::replace_last(correspondingAffixPath, ".dic", ".aff");
+ if (boost::filesystem::is_regular_file(correspondingAffixPath)) {
+ auto filenameWithoutExtension = boost::filesystem::basename(dictionary);
+ dictionaries[filenameWithoutExtension] = {dictionary, correspondingAffixPath};
+ }
+ }
+
+ return dictionaries;
}
bool HunspellChecker::isCorrect(const std::string& word) {
- return speller_->spell(word.c_str());
+ if (speller_) {
+ return speller_->spell(word.c_str());
+ }
+ else {
+ return true;
+ }
}
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);
- }
- }
+ if (speller_) {
+ 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 (speller_) {
+ 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 12c0485..2d4831e 100644
--- a/SwifTools/HunspellChecker.h
+++ b/SwifTools/HunspellChecker.h
@@ -4,24 +4,54 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#pragma once
+
+#include <memory>
+#include <string>
+#include <unordered_map>
#include <vector>
+
#include <boost/algorithm/string.hpp>
-#include <boost/tuple/tuple.hpp>
-#include <SwifTools/SpellChecker.h>
+#include <boost/optional.hpp>
-#pragma once
+#include <SwifTools/SpellChecker.h>
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();
+ virtual ~HunspellChecker();
+
+ virtual bool isAutomaticallyDetectingLanguage();
+
+ virtual void setActiveLanguage(const std::string& language);
+ virtual std::string activeLanguage() const;
+ virtual std::vector<std::string> supportedLanguages() const;
+
+ 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:
+ struct Dictionary {
+ std::string dicPath;
+ std::string affPath;
+ };
+
+ std::unordered_map<std::string, Dictionary> detectedDictionaries() const;
+ std::vector<std::string> hunspellDictionaryPaths() const;
+
+ private:
+ std::unique_ptr<Hunspell> speller_;
+ boost::optional<std::string> activeLangauge_;
+
+ };
}
diff --git a/SwifTools/Idle/ActualIdleDetector.cpp b/SwifTools/Idle/ActualIdleDetector.cpp
index 2e2f1f1..2a16fca 100644
--- a/SwifTools/Idle/ActualIdleDetector.cpp
+++ b/SwifTools/Idle/ActualIdleDetector.cpp
@@ -6,7 +6,6 @@
#include <SwifTools/Idle/ActualIdleDetector.h>
-
#include <boost/bind.hpp>
#include <Swiften/Network/Timer.h>
@@ -17,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..176eb11 100644
--- a/SwifTools/Idle/ActualIdleDetector.h
+++ b/SwifTools/Idle/ActualIdleDetector.h
@@ -1,30 +1,30 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#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::signals2::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;
+ std::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 1f98c3e..3e9df66 100644
--- a/SwifTools/Idle/IdleDetector.h
+++ b/SwifTools/Idle/IdleDetector.h
@@ -1,43 +1,44 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
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::signals2::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 24d15b3..a0b78e6 100644
--- a/SwifTools/Idle/IdleQuerierTest/IdleQuerierTest.cpp
+++ b/SwifTools/Idle/IdleQuerierTest/IdleQuerierTest.cpp
@@ -1,23 +1,24 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <iostream>
#include <cassert>
+#include <iostream>
-#include <SwifTools/Idle/PlatformIdleQuerier.h>
#include <Swiften/Base/sleep.h>
+#include <SwifTools/Idle/PlatformIdleQuerier.h>
+
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/IdleQuerierTest/SConscript b/SwifTools/Idle/IdleQuerierTest/SConscript
index 5878a46..89bb3f9 100644
--- a/SwifTools/Idle/IdleQuerierTest/SConscript
+++ b/SwifTools/Idle/IdleQuerierTest/SConscript
@@ -1,12 +1,12 @@
Import("env")
if env["TEST"] :
- myenv = env.Clone()
- myenv.MergeFlags(myenv["SWIFTOOLS_FLAGS"])
- myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
- myenv.MergeFlags(myenv["BOOST_FLAGS"])
- if myenv["HAVE_XSS"] :
- myenv.MergeFlags(myenv.get("XSS_FLAGS", {}))
- myenv.Append(LIBS = ["X11"])
- myenv.MergeFlags(myenv["PLATFORM_FLAGS"])
- tester = myenv.Program("IdleQuerierTest", ["IdleQuerierTest.cpp"])
+ myenv = env.Clone()
+ myenv.MergeFlags(myenv["SWIFTOOLS_FLAGS"])
+ myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
+ myenv.MergeFlags(myenv["BOOST_FLAGS"])
+ if myenv["HAVE_XSS"] :
+ myenv.MergeFlags(myenv.get("XSS_FLAGS", {}))
+ myenv.Append(LIBS = ["X11"])
+ myenv.MergeFlags(myenv["PLATFORM_FLAGS"])
+ tester = myenv.Program("IdleQuerierTest", ["IdleQuerierTest.cpp"])
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..8b62df8 100644
--- a/SwifTools/Idle/PlatformIdleQuerier.cpp
+++ b/SwifTools/Idle/PlatformIdleQuerier.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -21,24 +21,24 @@
namespace Swift {
-PlatformIdleQuerier::PlatformIdleQuerier() : querier(NULL) {
+PlatformIdleQuerier::PlatformIdleQuerier() : querier(nullptr) {
#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 5ed5762..ecd72b1 100644
--- a/SwifTools/Idle/UnitTest/ActualIdleDetectorTest.cpp
+++ b/SwifTools/Idle/UnitTest/ActualIdleDetectorTest.cpp
@@ -1,170 +1,168 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/bind.hpp>
+
+#include <Swiften/Network/Timer.h>
+#include <Swiften/Network/TimerFactory.h>
#include <SwifTools/Idle/ActualIdleDetector.h>
#include <SwifTools/Idle/IdleQuerier.h>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Network/TimerFactory.h>
-#include <Swiften/Network/Timer.h>
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 = std::unique_ptr<MockIdleQuerier>(new MockIdleQuerier());
+ timerFactory = std::unique_ptr<MockTimerFactory>(new MockTimerFactory());
+ idleEvents.clear();
+ }
+
+ 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::unique_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::unique_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::unique_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::unique_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.get(), timerFactory.get(), 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) {
+ for (std::shared_ptr<MockTimer> timer : timers) {
+ timer->updateTime(milliseconds);
+ }
+ }
+
+ std::shared_ptr<Timer> createTimer(int milliseconds) {
+ std::shared_ptr<MockTimer> timer(new MockTimer(milliseconds));
+ timers.push_back(timer);
+ return timer;
+ }
+
+ std::vector<std::shared_ptr<MockTimer> > timers;
+ };
+
+ std::unique_ptr<MockIdleQuerier> querier;
+ std::unique_ptr<MockTimerFactory> timerFactory;
+ std::vector<bool> idleEvents;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ActualIdleDetectorTest);
diff --git a/SwifTools/Idle/UnitTest/SConscript b/SwifTools/Idle/UnitTest/SConscript
index f193349..26a9190 100644
--- a/SwifTools/Idle/UnitTest/SConscript
+++ b/SwifTools/Idle/UnitTest/SConscript
@@ -1,5 +1,5 @@
Import("env")
env.Append(UNITTEST_SOURCES = [
- File("ActualIdleDetectorTest.cpp")
- ])
+ File("ActualIdleDetectorTest.cpp")
+ ])
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 a7360a8..b9f1aa3 100644
--- a/SwifTools/LastLineTracker.cpp
+++ b/SwifTools/LastLineTracker.cpp
@@ -4,27 +4,33 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "LastLineTracker.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <SwifTools/LastLineTracker.h>
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 71deddd..b1557e5 100644
--- a/SwifTools/Linkify.cpp
+++ b/SwifTools/Linkify.cpp
@@ -1,103 +1,104 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <SwifTools/Linkify.h>
-#include <boost/regex.hpp>
-#include <sstream>
#include <iostream>
+#include <sstream>
+
+#include <boost/regex.hpp>
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 7fd110d..64c92dc 100644
--- a/SwifTools/Linkify.h
+++ b/SwifTools/Linkify.h
@@ -1,27 +1,27 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <string>
+#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 f2f8ebc..7587c99 100644
--- a/SwifTools/MacOSXChecker.h
+++ b/SwifTools/MacOSXChecker.h
@@ -4,19 +4,34 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <vector>
+
#include <boost/tuple/tuple.hpp>
+
#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 isAutomaticallyDetectingLanguage();
+
+ virtual void setActiveLanguage(const std::string& language);
+ virtual std::string activeLanguage() const;
+ virtual std::vector<std::string> supportedLanguages() const;
+
+ 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 0c73427..519f06c 100644
--- a/SwifTools/MacOSXChecker.mm
+++ b/SwifTools/MacOSXChecker.mm
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,6 +13,8 @@
#include <SwifTools/MacOSXChecker.h>
#include <algorithm>
+#include <cassert>
+
#include <boost/algorithm/string.hpp>
#include <AppKit/AppKit.h>
@@ -20,43 +22,58 @@
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;
+}
+
+bool MacOSXChecker::isAutomaticallyDetectingLanguage() {
+ return true;
+}
+
+void MacOSXChecker::setActiveLanguage(const std::string& /*language*/) {
+ assert(false);
+}
+
+std::string MacOSXChecker::activeLanguage() const {
+ assert(false);
+}
+std::vector<std::string> MacOSXChecker::supportedLanguages() const {
+ assert(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 e7cf838..89025af 100644
--- a/SwifTools/Notifier/GNTPNotifier.cpp
+++ b/SwifTools/Notifier/GNTPNotifier.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -10,77 +10,77 @@
#include <cassert>
#include <iostream>
-#include <boost/bind.hpp>
#include <sstream>
-#include <Swiften/Base/foreach.h>
+#include <boost/bind.hpp>
+
#include <Swiften/Base/Path.h>
#include <Swiften/Network/ConnectionFactory.h>
namespace Swift {
GNTPNotifier::GNTPNotifier(const std::string& name, const boost::filesystem::path& icon, ConnectionFactory* connectionFactory) : name(name), icon(icon), connectionFactory(connectionFactory), initialized(false), registered(false) {
- // Registration message
- std::ostringstream message;
- message << "GNTP/1.0 REGISTER NONE\r\n";
- message << "Application-Name: " << name << "\r\n";
- message << "Application-Icon: file://" << pathToString(icon) << "\r\n";
- message << "Notifications-Count: " << getAllTypes().size() << "\r\n";
- std::vector<Notifier::Type> defaultTypes = getDefaultTypes();
- std::vector<Notifier::Type> allTypes = getAllTypes();
- foreach(Notifier::Type type, allTypes) {
- 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();
+ for (const auto& type : allTypes) {
+ message << "\r\n";
+ message << "Notification-Name: " << typeToString(type) << "\r\n";
+ message << "Notification-Enabled: " << (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end() ? "false" : "true") << "\r\n";
+ }
+ message << "\r\n";
- send(message.str());
+ 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 574ab67..44811e7 100644
--- a/SwifTools/Notifier/GNTPNotifier.h
+++ b/SwifTools/Notifier/GNTPNotifier.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,31 +8,32 @@
#include <boost/filesystem.hpp>
-#include <SwifTools/Notifier/Notifier.h>
#include <Swiften/Network/Connection.h>
+#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..1b5f191 100644
--- a/SwifTools/Notifier/GrowlNotifier.h
+++ b/SwifTools/Notifier/GrowlNotifier.h
@@ -1,41 +1,43 @@
/*
- * Copyright (c) 2010-2011 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#include <boost/filesystem/fstream.hpp>
#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;
+ const std::unique_ptr<Private> p;
+ };
}
diff --git a/SwifTools/Notifier/GrowlNotifier.mm b/SwifTools/Notifier/GrowlNotifier.mm
index acaf45c..4ca53f7 100644
--- a/SwifTools/Notifier/GrowlNotifier.mm
+++ b/SwifTools/Notifier/GrowlNotifier.mm
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2011 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <SwifTools/Notifier/GrowlNotifier.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <set>
#include <SwifTools/Notifier/GrowlNotifierDelegate.h>
@@ -17,101 +17,100 @@
#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()];
+GrowlNotifier::GrowlNotifier(const std::string& name) : p(new 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 e06b784..e12500b 100644
--- a/SwifTools/Notifier/LoggingNotifier.h
+++ b/SwifTools/Notifier/LoggingNotifier.h
@@ -1,32 +1,33 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <SwifTools/Notifier/Notifier.h>
#include <Swiften/Base/ByteArray.h>
+#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..838971c 100644
--- a/SwifTools/Notifier/NotificationCenterNotifier.h
+++ b/SwifTools/Notifier/NotificationCenterNotifier.h
@@ -1,11 +1,12 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
#include <SwifTools/Notifier/Notifier.h>
@@ -18,21 +19,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;
+ const std::unique_ptr<Private> p;
};
}
diff --git a/SwifTools/Notifier/NotificationCenterNotifier.mm b/SwifTools/Notifier/NotificationCenterNotifier.mm
index 10319c8..1538186 100644
--- a/SwifTools/Notifier/NotificationCenterNotifier.mm
+++ b/SwifTools/Notifier/NotificationCenterNotifier.mm
@@ -9,7 +9,7 @@
#include <map>
#include <string>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Base/Log.h>
@@ -19,78 +19,77 @@
#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, std::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];
+NotificationCenterNotifier::NotificationCenterNotifier() : p(new 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)] = std::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 617619c..84ec943 100644
--- a/SwifTools/Notifier/NotificationCenterNotifierDelegate.mm
+++ b/SwifTools/Notifier/NotificationCenterNotifierDelegate.mm
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 ddb9a09..afd596b 100644
--- a/SwifTools/Notifier/Notifier.h
+++ b/SwifTools/Notifier/Notifier.h
@@ -1,50 +1,51 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/function.hpp>
-#include <boost/filesystem/path.hpp>
#include <string>
#include <vector>
+#include <boost/filesystem/path.hpp>
+#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/SConscript b/SwifTools/Notifier/SConscript
index e60937b..b3c8115 100644
--- a/SwifTools/Notifier/SConscript
+++ b/SwifTools/Notifier/SConscript
@@ -3,25 +3,19 @@ Import("swiftools_env")
myenv = swiftools_env.Clone()
sources = [
- "Notifier.cpp",
- ]
+ "Notifier.cpp",
+ ]
if swiftools_env.get("HAVE_GROWL", False) :
- sources += [
- "GrowlNotifier.mm",
- "GrowlNotifierDelegate.mm",
- ]
-elif myenv["PLATFORM"] == "darwin" :
- sources += [
- "NotificationCenterNotifier.mm",
- "NotificationCenterNotifierDelegate.mm",
- ]
+ sources += [
+ "GrowlNotifier.mm",
+ "GrowlNotifierDelegate.mm",
+ ]
+elif myenv["PLATFORM"] == "darwin" and myenv["target"] == "native" :
+ sources += [
+ "NotificationCenterNotifier.mm",
+ "NotificationCenterNotifierDelegate.mm",
+ ]
-if swiftools_env.get("HAVE_SNARL", False) :
- myenv.MergeFlags(myenv["SNARL_FLAGS"])
- sources += [
- "SnarlNotifier.cpp",
- ]
-
objects = myenv.StaticObject(sources)
swiftools_env.Append(SWIFTOOLS_OBJECTS = objects)
diff --git a/SwifTools/Notifier/SnarlNotifier.cpp b/SwifTools/Notifier/SnarlNotifier.cpp
deleted file mode 100644
index b4e5ef3..0000000
--- a/SwifTools/Notifier/SnarlNotifier.cpp
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (c) 2010 Isode Limited.
- * All rights reserved.
- * See the COPYING file for more information.
- */
-
-#include <SwifTools/Notifier/SnarlNotifier.h>
-
-#include <cassert>
-#include <iostream>
-#include <boost/bind.hpp>
-
-#include <Swiften/Base/foreach.h>
-#include <SwifTools/Notifier/Win32NotifierWindow.h>
-
-#define SWIFT_SNARLNOTIFIER_MESSAGE_ID 0x4567 // Sounds sick to pick a number, but this is windows
-
-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());
- }
-}
-
-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;
- }
-}
-
-bool SnarlNotifier::isAvailable() const {
- 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));
- }
-}
-
-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";
- }
- }
- }
-}
-
-}
diff --git a/SwifTools/Notifier/SnarlNotifier.h b/SwifTools/Notifier/SnarlNotifier.h
deleted file mode 100644
index 6d4c16e..0000000
--- a/SwifTools/Notifier/SnarlNotifier.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2010 Isode Limited.
- * All rights reserved.
- * See the COPYING file for more information.
- */
-
-#pragma once
-
-#include <map>
-
-#include <SwifTools/Notifier/Notifier.h>
-#include <SnarlInterface.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;
- };
-}
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..cff80ec 100644
--- a/SwifTools/Notifier/Win32NotifierWindow.h
+++ b/SwifTools/Notifier/Win32NotifierWindow.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,15 +8,15 @@
//#include <windows.h>
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
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::signals2::signal<void (MSG*)> onMessageReceived;
+ };
}
diff --git a/SwifTools/SConscript b/SwifTools/SConscript
index b9822e0..dec343e 100644
--- a/SwifTools/SConscript
+++ b/SwifTools/SConscript
@@ -5,79 +5,79 @@ Import("env")
################################################################################
if env["SCONS_STAGE"] == "flags" :
- env["SWIFTOOLS_FLAGS"] = {
- "LIBPATH": [Dir(".")],
- "LIBS": ["SwifTools"]
- }
+ env["SWIFTOOLS_FLAGS"] = {
+ "LIBPATH": [Dir(".")],
+ "LIBS": ["SwifTools"]
+ }
################################################################################
# Build
################################################################################
if env["SCONS_STAGE"] == "build" :
- swiftools_env = env.Clone()
- swiftools_env.UseFlags(swiftools_env["SWIFTEN_FLAGS"])
- swiftools_env.UseFlags(swiftools_env["BOOST_FLAGS"])
+ swiftools_env = env.Clone()
+ swiftools_env.UseFlags(swiftools_env["SWIFTEN_FLAGS"])
+ swiftools_env.UseFlags(swiftools_env["BOOST_FLAGS"])
- sources = [
- "Idle/IdleDetector.cpp",
- "Idle/ActualIdleDetector.cpp",
- "Idle/IdleQuerier.cpp",
- "Idle/PlatformIdleQuerier.cpp",
- "AutoUpdater/AutoUpdater.cpp",
- "AutoUpdater/PlatformAutoUpdaterFactory.cpp",
- "Linkify.cpp",
- "TabComplete.cpp",
- "LastLineTracker.cpp",
- ]
-
- if swiftools_env["HAVE_HUNSPELL"] :
- swiftools_env.UseFlags(swiftools_env["HUNSPELL_FLAGS"])
- swiftools_env.Append(CPPDEFINES = ["HAVE_HUNSPELL"])
- sources += [
- "SpellCheckerFactory.cpp",
- "HunspellChecker.cpp",
- "SpellParser.cpp",
- ]
- elif swiftools_env["PLATFORM"] == "darwin" and env["target"] == "native" :
- sources += [
- "SpellCheckerFactory.cpp",
- "MacOSXChecker.mm",
- "SpellParser.cpp",
- ]
+ sources = [
+ "Idle/IdleDetector.cpp",
+ "Idle/ActualIdleDetector.cpp",
+ "Idle/IdleQuerier.cpp",
+ "Idle/PlatformIdleQuerier.cpp",
+ "AutoUpdater/AutoUpdater.cpp",
+ "AutoUpdater/PlatformAutoUpdaterFactory.cpp",
+ "Linkify.cpp",
+ "TabComplete.cpp",
+ "LastLineTracker.cpp",
+ ]
+ if swiftools_env["HAVE_HUNSPELL"] :
+ swiftools_env.UseFlags(swiftools_env["HUNSPELL_FLAGS"])
+ swiftools_env.Append(CPPDEFINES = ["HAVE_HUNSPELL"])
+ sources += [
+ "SpellCheckerFactory.cpp",
+ "HunspellChecker.cpp",
+ "SpellParser.cpp",
+ ]
+ elif swiftools_env["PLATFORM"] == "darwin" and env["target"] == "native" :
+ sources += [
+ "SpellCheckerFactory.cpp",
+ "MacOSXChecker.mm",
+ "SpellParser.cpp",
+ ]
- if swiftools_env.get("HAVE_SPARKLE", 0) :
- swiftools_env.UseFlags(swiftools_env["SPARKLE_FLAGS"])
- swiftools_env.Append(CPPDEFINES = ["HAVE_SPARKLE"])
- sources += ["AutoUpdater/SparkleAutoUpdater.mm"]
- if swiftools_env["PLATFORM"] == "win32" :
- sources += ["Idle/WindowsIdleQuerier.cpp"]
- elif swiftools_env["PLATFORM"] == "darwin" and swiftools_env.get("HAVE_IOKIT", False) :
- swiftools_env.Append(CPPDEFINES = ["HAVE_IOKIT"])
- sources += ["Idle/MacOSXIdleQuerier.cpp"]
- elif swiftools_env["HAVE_XSS"] :
- swiftools_env.Append(CPPDEFINES = ["HAVE_XSS"])
- sources += ["Idle/XSSIdleQuerier.cpp"]
+ if swiftools_env.get("HAVE_SPARKLE", 0) :
+ swiftools_env.UseFlags(swiftools_env["SPARKLE_FLAGS"])
+ swiftools_env.Append(CPPDEFINES = ["HAVE_SPARKLE"])
+ sources += ["AutoUpdater/SparkleAutoUpdater.mm", "AutoUpdater/SparkleAutoUpdaterDelegate.mm"]
- if env.get("HAVE_BREAKPAD", False) :
- swiftools_env.UseFlags(swiftools_env["BREAKPAD_FLAGS"])
- swiftools_env.Append(CPPDEFINES = ["HAVE_BREAKPAD"])
- sources += ["CrashReporter.cpp"]
-
- swiftools_env["SWIFTOOLS_OBJECTS"] = []
- Export("swiftools_env")
-
- SConscript(dirs = [
- "Application",
- "Dock",
- "Notifier",
- "URIHandler",
- "Idle/IdleQuerierTest",
- "Idle/UnitTest",
- "Cocoa",
- "UnitTest"
- ])
+ if swiftools_env["PLATFORM"] == "win32" :
+ sources += ["Idle/WindowsIdleQuerier.cpp"]
+ elif swiftools_env["PLATFORM"] == "darwin" and swiftools_env.get("HAVE_IOKIT", False) :
+ swiftools_env.Append(CPPDEFINES = ["HAVE_IOKIT"])
+ sources += ["Idle/MacOSXIdleQuerier.cpp"]
+ elif swiftools_env["HAVE_XSS"] :
+ swiftools_env.Append(CPPDEFINES = ["HAVE_XSS"])
+ sources += ["Idle/XSSIdleQuerier.cpp"]
- swiftools_env.StaticLibrary("SwifTools", sources + swiftools_env["SWIFTOOLS_OBJECTS"])
+ if env.get("HAVE_BREAKPAD", False) :
+ swiftools_env.UseFlags(swiftools_env["BREAKPAD_FLAGS"])
+ swiftools_env.Append(CPPDEFINES = ["HAVE_BREAKPAD"])
+ sources += ["CrashReporter.cpp"]
+
+ swiftools_env["SWIFTOOLS_OBJECTS"] = []
+ Export("swiftools_env")
+
+ SConscript(dirs = [
+ "Application",
+ "Dock",
+ "Notifier",
+ "URIHandler",
+ "Idle/IdleQuerierTest",
+ "Idle/UnitTest",
+ "Cocoa",
+ "UnitTest"
+ ])
+
+ swiftools_env.StaticLibrary("SwifTools", sources + swiftools_env["SWIFTOOLS_OBJECTS"])
diff --git a/SwifTools/SpellChecker.h b/SwifTools/SpellChecker.h
index fd38418..664fc63 100644
--- a/SwifTools/SpellChecker.h
+++ b/SwifTools/SpellChecker.h
@@ -4,27 +4,38 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include <SwifTools/SpellParser.h>
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#pragma once
-#include <boost/algorithm/string.hpp>
-#include <boost/tuple/tuple.hpp>
#include <vector>
-#pragma once
+#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() {
+ }
+
+ virtual ~SpellChecker() {
+ }
+
+ virtual bool isAutomaticallyDetectingLanguage() = 0;
+
+ virtual void setActiveLanguage(const std::string& language) = 0;
+ virtual std::string activeLanguage() const = 0;
+ virtual std::vector<std::string> supportedLanguages() const = 0;
+
+ 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..bfd3d4a 100644
--- a/SwifTools/SpellCheckerFactory.cpp
+++ b/SwifTools/SpellCheckerFactory.cpp
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <boost/filesystem/operations.hpp>
#include <SwifTools/SpellChecker.h>
@@ -23,18 +29,12 @@ 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;
+SpellChecker* SpellCheckerFactory::createSpellChecker() {
+ return new HunspellChecker();
}
#elif defined(SWIFTEN_PLATFORM_MACOSX)
-SpellChecker* SpellCheckerFactory::createSpellChecker(const std::string& /*dictFile*/) {
- return new MacOSXChecker();
+SpellChecker* SpellCheckerFactory::createSpellChecker() {
+ return new MacOSXChecker();
}
#endif
diff --git a/SwifTools/SpellCheckerFactory.h b/SwifTools/SpellCheckerFactory.h
index 91118f9..eb2ade6 100644
--- a/SwifTools/SpellCheckerFactory.h
+++ b/SwifTools/SpellCheckerFactory.h
@@ -4,8 +4,16 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
+#include <string>
+
#include <Swiften/Base/Platform.h>
#ifdef HAVE_HUNSPELL
@@ -15,10 +23,11 @@
#endif
namespace Swift {
- class SpellChecker;
- class SpellCheckerFactory {
- public:
- SpellCheckerFactory();
- SpellChecker* createSpellChecker(const std::string& dictFile);
- };
+ class SpellChecker;
+
+ class SpellCheckerFactory {
+ public:
+ SpellCheckerFactory();
+ SpellChecker* createSpellChecker();
+ };
}
diff --git a/SwifTools/SpellParser.cpp b/SwifTools/SpellParser.cpp
index 8cb42e4..5bafa6e 100644
--- a/SwifTools/SpellParser.cpp
+++ b/SwifTools/SpellParser.cpp
@@ -4,14 +4,20 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <SwifTools/SpellParser.h>
-#include <boost/spirit/include/lex_lexertl.hpp>
+#include <string>
+
#include <boost/bind.hpp>
-#include <boost/ref.hpp>
#include <boost/numeric/conversion/cast.hpp>
-
-#include <string>
+#include <boost/ref.hpp>
+#include <boost/spirit/include/lex_lexertl.hpp>
namespace lex = boost::spirit::lex;
@@ -20,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 b64565c..5b057c9 100644
--- a/SwifTools/SpellParser.h
+++ b/SwifTools/SpellParser.h
@@ -4,28 +4,33 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
+#include <vector>
+
#include <boost/algorithm/string.hpp>
#include <boost/tuple/tuple.hpp>
-#include <boost/algorithm/string.hpp>
-
-#include <vector>
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 bfab2aa..39a70cc 100644
--- a/SwifTools/TabComplete.cpp
+++ b/SwifTools/TabComplete.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,49 +7,48 @@
#include <SwifTools/TabComplete.h>
#include <algorithm>
-#include <boost/algorithm/string.hpp>
-#include <Swiften/Base/foreach.h>
+#include <boost/algorithm/string.hpp>
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();
+ for (auto&& candidate : words_) {
+ if (boost::starts_with(boost::to_lower_copy(candidate), boost::to_lower_copy(word))) {
+ lastCompletionCandidates_.push_back(candidate);
+ }
+ }
+ lastCompletion_ = !lastCompletionCandidates_.empty() ? lastCompletionCandidates_[0] : word;
+ }
+ return lastCompletion_;
}
}
diff --git a/SwifTools/TabComplete.h b/SwifTools/TabComplete.h
index feb1ffc..ac1e07e 100644
--- a/SwifTools/TabComplete.h
+++ b/SwifTools/TabComplete.h
@@ -1,25 +1,24 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
-
#include <string>
+#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..8136fa7 100644
--- a/SwifTools/URIHandler/MacOSXURIHandler.h
+++ b/SwifTools/URIHandler/MacOSXURIHandler.h
@@ -1,24 +1,26 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#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;
+ const std::unique_ptr<Private> p;
+ };
}
diff --git a/SwifTools/URIHandler/MacOSXURIHandler.mm b/SwifTools/URIHandler/MacOSXURIHandler.mm
index d542408..ae7dc44 100644
--- a/SwifTools/URIHandler/MacOSXURIHandler.mm
+++ b/SwifTools/URIHandler/MacOSXURIHandler.mm
@@ -1,14 +1,15 @@
/*
- * Copyright (c) 2011-2013 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <SwifTools/URIHandler/MacOSXURIHandler.h>
-#include <Cocoa/Cocoa.h>
#include <iostream>
+#include <Cocoa/Cocoa.h>
+
using namespace Swift;
@interface MacOSXURIEventHandler : NSObject {
@@ -20,47 +21,45 @@ 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];
+MacOSXURIHandler::MacOSXURIHandler() : p(new Private()) {
+ p->eventHandler = [[MacOSXURIEventHandler alloc] initWithHandler: this];
}
MacOSXURIHandler::~MacOSXURIHandler() {
- [p->eventHandler release];
- delete p;
+ [p->eventHandler release];
}
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/SConscript b/SwifTools/URIHandler/SConscript
index 90ec00a..8ebbdaf 100644
--- a/SwifTools/URIHandler/SConscript
+++ b/SwifTools/URIHandler/SConscript
@@ -1,22 +1,22 @@
Import("swiftools_env", "env")
sources = [
- "XMPPURI.cpp",
- "URIHandler.cpp",
- ]
+ "XMPPURI.cpp",
+ "URIHandler.cpp",
+ ]
if swiftools_env["PLATFORM"] == "darwin" and swiftools_env["target"] == "native" :
- sources += [
- "MacOSXURIHandler.mm"
- ]
+ sources += [
+ "MacOSXURIHandler.mm"
+ ]
elif swiftools_env["PLATFORM"] == "win32" :
- sources += []
+ sources += []
else :
- sources += []
+ sources += []
objects = swiftools_env.StaticObject(sources)
swiftools_env.Append(SWIFTOOLS_OBJECTS = [objects])
env.Append(UNITTEST_SOURCES = [
- File("UnitTest/XMPPURITest.cpp"),
- ])
+ File("UnitTest/XMPPURITest.cpp"),
+ ])
diff --git a/SwifTools/URIHandler/URIHandler.h b/SwifTools/URIHandler/URIHandler.h
index 14bab5b..8aeb11a 100644
--- a/SwifTools/URIHandler/URIHandler.h
+++ b/SwifTools/URIHandler/URIHandler.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,15 @@
#pragma once
#include <string>
-#include <Swiften/Base/boost_bsignals.h>
+
+#include <boost/signals2.hpp>
namespace Swift {
- class URIHandler {
- public:
- URIHandler();
- virtual ~URIHandler();
+ class URIHandler {
+ public:
+ URIHandler();
+ virtual ~URIHandler();
- boost::signal<void (const std::string&)> onURI;
- };
+ boost::signals2::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 2fe45c0..8b8b81c 100644
--- a/SwifTools/URIHandler/XMPPURI.cpp
+++ b/SwifTools/URIHandler/XMPPURI.cpp
@@ -1,22 +1,24 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <SwifTools/URIHandler/XMPPURI.h>
-#include <Swiften/Base/URL.h>
-#include <boost/algorithm/string/predicate.hpp>
-#include <boost/algorithm/string/find_format.hpp>
-#include <boost/algorithm/string/formatter.hpp>
-#include <boost/algorithm/string/find_iterator.hpp>
-#include <boost/algorithm/string/split.hpp>
-#include <boost/algorithm/string/classification.hpp>
#include <sstream>
#include <stdexcept>
#include <vector>
+#include <boost/algorithm/string/classification.hpp>
+#include <boost/algorithm/string/find_format.hpp>
+#include <boost/algorithm/string/find_iterator.hpp>
+#include <boost/algorithm/string/formatter.hpp>
+#include <boost/algorithm/string/predicate.hpp>
+#include <boost/algorithm/string/split.hpp>
+
+#include <Swiften/Base/URL.h>
+
using namespace Swift;
@@ -24,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 91375ff..a8c9f95 100644
--- a/SwifTools/URIHandler/XMPPURI.h
+++ b/SwifTools/URIHandler/XMPPURI.h
@@ -1,73 +1,73 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <string>
#include <map>
+#include <string>
#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/SConscript b/SwifTools/UnitTest/SConscript
index dbd1ce5..bf44899 100644
--- a/SwifTools/UnitTest/SConscript
+++ b/SwifTools/UnitTest/SConscript
@@ -1,12 +1,12 @@
Import("env")
env.Append(UNITTEST_SOURCES = [
- File("LinkifyTest.cpp"),
- File("TabCompleteTest.cpp"),
- File("LastLineTrackerTest.cpp"),
- ])
+ File("LinkifyTest.cpp"),
+ File("TabCompleteTest.cpp"),
+ File("LastLineTrackerTest.cpp"),
+ ])
if env["HAVE_HUNSPELL"] :
- env.Append(UNITTEST_SOURCES = [
- File("SpellParserTest.cpp"),
- ])
+ env.Append(UNITTEST_SOURCES = [
+ File("SpellParserTest.cpp"),
+ ])
diff --git a/SwifTools/UnitTest/SpellParserTest.cpp b/SwifTools/UnitTest/SpellParserTest.cpp
index 09e686c..ccfd7e5 100644
--- a/SwifTools/UnitTest/SpellParserTest.cpp
+++ b/SwifTools/UnitTest/SpellParserTest.cpp
@@ -4,48 +4,55 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <memory>
#include <boost/algorithm/string.hpp>
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
#include <SwifTools/SpellParser.h>
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() {
+ }
+ 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:
+ const std::unique_ptr<SpellParser> parser_ = std::unique_ptr<SpellParser>(new SpellParser());
+ 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/ChangeLog.md b/Swift/ChangeLog.md
index 097de4d..4c88d88 100644
--- a/Swift/ChangeLog.md
+++ b/Swift/ChangeLog.md
@@ -1,5 +1,52 @@
-3.0-beta1
----------
+4.0-in-progress
+---------------
+- Fix UI layout issue for translations that require right-to-left (RTL) layout
+- macOS releases are now code-signed with a key from Apple, so they can be run without Gatekeeper trust warnings
+- Handle sessions being closed by the server
+
+4.0-beta2 ( 2016-07-20 )
+------------------------
+- Fix Swift bug introduced in 4.0-beta1 that results in the UI sometimes getting stuck during login
+
+4.0-beta1 ( 2016-07-15 )
+------------------------
+- Support for message carbons (XEP-0280)
+- Improved spell checker support on Linux
+- Enabled trellis mode as a default feature, allowing several tiled chats windows to be shown at once
+- New chat theme including a new font
+- And assorted smaller features and usability enhancements
+
+3.0 ( 2016-02-24 )
+------------------
+- File transfer and Mac Notification Center issues fixed
+- Fix connection to servers with invalid or untrusted certificates on OS/X
+- Support for the Notification Center on OS X
+- Users can now authenticate using certificates (and smart cards on Windows) when using the 'BOSH' connection type.
+- Encryption on OS X now uses the platform's native 'Secure Transport' mechanisms.
+- Emoticons menu in chat dialogs
+- Bookmark for rooms can now be edited directly from the ‘Recent Chats’ list
+- Adds option to workaround servers that don’t interoperate well with Windows (schannel) encryption
+- Rooms entered while offline will now get entered on reconnect
+- Chats can now be seamlessly upgraded to multi-person chats by either inviting someone via the ‘cog’ menu, or dragging them from the roster. This relies on server-side support with an appropriate chatroom (MUC) service.
+- Highlighting of keywords and messages from particular users can now be configured (Keyword Highlighting Blog post).
+- Full profile vcards (contact information etc.) are now supported and can be configured for the user and queried for contacts.
+- Simple Communication Blocking is now supported (subject to server support) to allow the blocking of nuisance users.
+- Swift can now transfer files via the ‘Jingle File Transfer’ protocol.
+- The status setter will now remember previously set statuses and will allow quick access to these when the user types part of a recently used status.
+- Tooltips for contacts in the roster now show their vcard profile information
+- The top of the roster window now shows a tooltip with your vcard profile information in
+- Chatrooms (MUCs) can now be bookmarked by right-clicking on their entry in the Recent Chats list, or from the ‘cog’ menu for any room you’re currently in.
+- The tooltips for MUC occupants now show their affiliation and role in the room (e.g. Administrator)
+- Support for ‘right-to-left’ languages has been improved.
+- A small number of emoticons will be automatically rendered when receiving text, e.g. :), this can be disabled from the View menu.
+- Swift now distinguishes between contacts who have chosen to show as ‘away’ and those whose clients have noticed they’re idle (requires support in contacts' clients).
+- Typing search terms with the roster selected will start to search for contacts matching the terms (useful for users with large rosters).
+- An experimental ‘Trellis’ view for viewing several chats and rooms at once has been added. This is currently hidden; contact us if you’re interested in testing this feature.
+- And assorted smaller features and usability enhancements.
+
+
+3.0-beta1 ( 2015-02-23 )
+------------------------
- Allow toggling of a more compact roster display.
- Remember status settings and provide quick access to them with searching of recent selections in the status setter.
@@ -7,8 +54,8 @@
---
- Fixed potential crash when using proxies on Mac OS X.
-2.0-beta2
----------
+2.0-beta2 ( 2012-10-07 )
+------------------------
- Enable auto-completion of nicknames that don't start with a letter.
- Generate crash dumps on Windows.
- Connection timeouts are now on each connection separately, instead of on the complete connection process.
@@ -28,8 +75,8 @@
Thanks to Tobias Markmann.
-2.0-beta1
----------
+2.0-beta1 ( 2012-04-29 )
+------------------------
- Windows packages are now built in Microsoft Installer's ".msi" format. Please
uninstall any older NSIS-based Swift packages before upgrading to this release.
- Suitable names will now be suggested from the contact's vcard when adding/editing their roster entry.
@@ -55,6 +102,6 @@ Thanks to Tobias Markmann, Jan Kaluza, Thilo Cestonaro, Arnt Gulbrandsen, Vlad V
Yoann Blein, Catalin Badea, Pavol Babincak, Mateusz Piekos, Alexey Melnikov and Soren Dreijer.
-1.0
----
-- Initial release.
+1.0 ( 2011-04-18 )
+------------------
+- Initial release. \ No newline at end of file
diff --git a/Swift/Controllers/AdHocController.cpp b/Swift/Controllers/AdHocController.cpp
index b48b832..5e10beb 100644
--- a/Swift/Controllers/AdHocController.cpp
+++ b/Swift/Controllers/AdHocController.cpp
@@ -1,31 +1,33 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/bind.hpp>
#include <Swift/Controllers/AdHocController.h>
+
+#include <boost/bind.hpp>
+
#include <Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h>
namespace Swift {
-AdHocController::AdHocController(AdHocCommandWindowFactory* factory, boost::shared_ptr<OutgoingAdHocCommandSession> command) {
- window_ = factory->createAdHocCommandWindow(command);
- window_->onClosing.connect(boost::bind(&AdHocController::handleWindowClosed, this));
+AdHocController::AdHocController(AdHocCommandWindowFactory* factory, std::shared_ptr<OutgoingAdHocCommandSession> command) {
+ 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 1ac148c..a6a5c70 100644
--- a/Swift/Controllers/AdHocController.h
+++ b/Swift/Controllers/AdHocController.h
@@ -1,12 +1,13 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <Swiften/AdHoc/OutgoingAdHocCommandSession.h>
namespace Swift {
@@ -16,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, std::shared_ptr<OutgoingAdHocCommandSession> command);
+ ~AdHocController();
+ boost::signals2::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 a572846..717f083 100644
--- a/Swift/Controllers/AdHocManager.cpp
+++ b/Swift/Controllers/AdHocManager.cpp
@@ -1,94 +1,94 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/AdHocManager.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Queries/IQRouter.h>
#include <Swiften/AdHoc/OutgoingAdHocCommandSession.h>
-#include <Swift/Controllers/UIInterfaces/MainWindow.h>
-#include <Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h>
+#include <Swiften/Queries/IQRouter.h>
+
+#include <Swift/Controllers/UIEvents/RequestAdHocUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestAdHocWithJIDUIEvent.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
-#include <Swift/Controllers/UIEvents/RequestAdHocUIEvent.h>
+#include <Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h>
+#include <Swift/Controllers/UIInterfaces/MainWindow.h>
namespace Swift {
AdHocManager::AdHocManager(const JID& jid, AdHocCommandWindowFactory* factory, IQRouter* iqRouter, UIEventStream* uiEventStream, MainWindow* mainWindow) : jid_(jid) {
- iqRouter_ = iqRouter;
- uiEventStream_ = uiEventStream;
- mainWindow_ = mainWindow;
- factory_ = factory;
+ 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 (auto& controller : controllers_) {
+ controller->onDeleting.disconnect(boost::bind(&AdHocManager::removeController, this, controller));
+ }
}
-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));
+void AdHocManager::removeController(std::shared_ptr<AdHocController> controller) {
+ controller->onDeleting.disconnect(boost::bind(&AdHocManager::removeController, this, controller));
+ controllers_.erase(std::find(controllers_.begin(), controllers_.end(), controller));
}
-void AdHocManager::setServerDiscoInfo(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>());
- }
+void AdHocManager::setServerDiscoInfo(std::shared_ptr<DiscoInfo> info) {
+ if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::CommandsFeature)) {
+ if (discoItemsRequest_) {
+ discoItemsRequest_->onResponse.disconnect(boost::bind(&AdHocManager::handleServerDiscoItemsResponse, this, _1, _2));
+ discoItemsRequest_.reset();
+ }
+ discoItemsRequest_ = GetDiscoItemsRequest::create(JID(jid_.getDomain()), DiscoInfo::CommandsFeature, iqRouter_);
+ discoItemsRequest_->onResponse.connect(boost::bind(&AdHocManager::handleServerDiscoItemsResponse, this, _1, _2));
+ discoItemsRequest_->send();
+ } else {
+ mainWindow_->setAvailableAdHocCommands(std::vector<DiscoItems::Item>());
+ }
}
void AdHocManager::setOnline(bool online) {
- foreach (boost::shared_ptr<AdHocController> controller, controllers_) {
- controller->setOnline(online);
- }
+ for (auto&& 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);
+void AdHocManager::handleServerDiscoItemsResponse(std::shared_ptr<DiscoItems> items, ErrorPayload::ref error) {
+ std::vector<DiscoItems::Item> commands;
+ if (!error) {
+ for (const auto& item : items->getItems()) {
+ if (item.getNode() != "http://isode.com/xmpp/commands#test") {
+ commands.push_back(item);
+ }
+ }
+ }
+ mainWindow_->setAvailableAdHocCommands(commands);
}
-void AdHocManager::handleUIEvent(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);
- }
+void AdHocManager::handleUIEvent(std::shared_ptr<UIEvent> event) {
+ std::shared_ptr<RequestAdHocUIEvent> adHocEvent = std::dynamic_pointer_cast<RequestAdHocUIEvent>(event);
+ if (adHocEvent) {
+ std::shared_ptr<OutgoingAdHocCommandSession> command = std::make_shared<OutgoingAdHocCommandSession>(adHocEvent->getCommand().getJID(), adHocEvent->getCommand().getNode(), iqRouter_);
+ std::shared_ptr<AdHocController> controller = std::make_shared<AdHocController>(factory_, command);
+ controller->onDeleting.connect(boost::bind(&AdHocManager::removeController, this, controller));
+ controllers_.push_back(controller);
+ }
+ std::shared_ptr<RequestAdHocWithJIDUIEvent> adHocJIDEvent = std::dynamic_pointer_cast<RequestAdHocWithJIDUIEvent>(event);
+ if (!!adHocJIDEvent) {
+ std::shared_ptr<OutgoingAdHocCommandSession> command = std::make_shared<OutgoingAdHocCommandSession>(adHocJIDEvent->getJID(), adHocJIDEvent->getNode(), iqRouter_);
+ std::shared_ptr<AdHocController> controller = std::make_shared<AdHocController>(factory_, command);
+ controller->onDeleting.connect(boost::bind(&AdHocManager::removeController, this, controller));
+ controllers_.push_back(controller);
+ }
}
}
diff --git a/Swift/Controllers/AdHocManager.h b/Swift/Controllers/AdHocManager.h
index 00289b0..0786370 100644
--- a/Swift/Controllers/AdHocManager.h
+++ b/Swift/Controllers/AdHocManager.h
@@ -1,44 +1,51 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#pragma once
+
#include <vector>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/JID/JID.h>
+#include <boost/signals2.hpp>
+
+#include <Swiften/Disco/GetDiscoItemsRequest.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/DiscoItems.h>
#include <Swiften/Elements/ErrorPayload.h>
-#include <Swiften/Disco/GetDiscoItemsRequest.h>
-#include <Swiften/Client/Client.h>
-#include <Swift/Controllers/UIEvents/UIEvent.h>
+#include <Swiften/JID/JID.h>
+
#include <Swift/Controllers/AdHocController.h>
+#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
class IQRouter;
class MainWindow;
class UIEventStream;
class AdHocCommandWindowFactory;
+
class AdHocManager {
public:
- AdHocManager(const JID& jid, AdHocCommandWindowFactory* factory, IQRouter* iqRouter, UIEventStream* uiEventStream, MainWindow* mainWindow);
- ~AdHocManager();
- void removeController(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(std::shared_ptr<AdHocController> contoller);
+ void setServerDiscoInfo(std::shared_ptr<DiscoInfo> info);
+ void setOnline(bool online);
+
+private:
+ void handleServerDiscoItemsResponse(std::shared_ptr<DiscoItems>, ErrorPayload::ref error);
+ void handleUIEvent(std::shared_ptr<UIEvent> event);
+ boost::signals2::signal<void (const AdHocController&)> onControllerComplete;
+
private:
- 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_;
+ JID jid_;
+ IQRouter* iqRouter_;
+ UIEventStream* uiEventStream_;
+ MainWindow* mainWindow_;
+ AdHocCommandWindowFactory* factory_;
+ GetDiscoItemsRequest::ref discoItemsRequest_;
+ std::vector<std::shared_ptr<AdHocController> > controllers_;
};
}
diff --git a/Swift/Controllers/BlockListController.cpp b/Swift/Controllers/BlockListController.cpp
index be70946..37c536b 100644
--- a/Swift/Controllers/BlockListController.cpp
+++ b/Swift/Controllers/BlockListController.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,173 +14,172 @@
#include <boost/bind.hpp>
+#include <Swiften/Base/format.h>
#include <Swiften/Client/ClientBlockListManager.h>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Base/format.h>
#include <Swift/Controllers/Intl.h>
-#include <Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestBlockListDialogUIEvent.h>
-#include <Swift/Controllers/XMPPEvents/ErrorEvent.h>
+#include <Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h>
#include <Swift/Controllers/UIInterfaces/BlockListEditorWidget.h>
+#include <Swift/Controllers/XMPPEvents/ErrorEvent.h>
#include <Swift/Controllers/XMPPEvents/EventController.h>
namespace Swift {
-BlockListController::BlockListController(ClientBlockListManager* blockListManager, UIEventStream* uiEventStream, BlockListEditorWidgetFactory* blockListEditorWidgetFactory, EventController* eventController) : blockListManager_(blockListManager), blockListEditorWidgetFactory_(blockListEditorWidgetFactory), blockListEditorWidget_(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));
+BlockListController::BlockListController(ClientBlockListManager* blockListManager, UIEventStream* uiEventStream, BlockListEditorWidgetFactory* blockListEditorWidgetFactory, EventController* eventController) : blockListManager_(blockListManager), blockListEditorWidgetFactory_(blockListEditorWidgetFactory), blockListEditorWidget_(nullptr), eventController_(eventController), remainingRequests_(0), uiEventStream_(uiEventStream) {
+ uiEventStream->onUIEvent.connect(boost::bind(&BlockListController::handleUIEvent, this, _1));
+ blockListManager_->getBlockList()->onItemAdded.connect(boost::bind(&BlockListController::handleBlockListChanged, this));
+ blockListManager_->getBlockList()->onItemRemoved.connect(boost::bind(&BlockListController::handleBlockListChanged, this));
}
BlockListController::~BlockListController() {
- uiEventStream_->onUIEvent.disconnect(boost::bind(&BlockListController::handleUIEvent, this, _1));
- blockListManager_->getBlockList()->onItemAdded.disconnect(boost::bind(&BlockListController::handleBlockListChanged, this));
- blockListManager_->getBlockList()->onItemRemoved.disconnect(boost::bind(&BlockListController::handleBlockListChanged, this));
+ 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);
- }
- }
+ for (const auto& jid : blockListBeforeEdit) {
+ if (std::find(newBlockList.begin(), newBlockList.end(), jid) == newBlockList.end()) {
+ jidsToUnblock.push_back(jid);
+ }
+ }
+
+ for (const auto& 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;
- }
+void BlockListController::handleUIEvent(std::shared_ptr<UIEvent> rawEvent) {
+ // handle UI dialog
+ std::shared_ptr<RequestBlockListDialogUIEvent> requestDialogEvent = std::dynamic_pointer_cast<RequestBlockListDialogUIEvent>(rawEvent);
+ if (requestDialogEvent != nullptr) {
+ if (blockListEditorWidget_ == nullptr) {
+ blockListEditorWidget_ = blockListEditorWidgetFactory_->createBlockListEditorWidget();
+ blockListEditorWidget_->onSetNewBlockList.connect(boost::bind(&BlockListController::handleSetNewBlockList, this, _1));
+ }
+ blockListBeforeEdit = blockListManager_->getBlockList()->getItems();
+ blockListEditorWidget_->setCurrentBlockList(blockListBeforeEdit);
+ blockListEditorWidget_->setError("");
+ blockListEditorWidget_->show();
+ return;
+ }
+
+ // handle block state change
+ std::shared_ptr<RequestChangeBlockStateUIEvent> changeStateEvent = std::dynamic_pointer_cast<RequestChangeBlockStateUIEvent>(rawEvent);
+ if (changeStateEvent != nullptr) {
+ if (changeStateEvent->getBlockState() == RequestChangeBlockStateUIEvent::Blocked) {
+ GenericRequest<BlockPayload>::ref blockRequest = blockListManager_->createBlockJIDRequest(changeStateEvent->getContact());
+ blockRequest->onResponse.connect(boost::bind(&BlockListController::handleBlockResponse, this, blockRequest, _1, _2, std::vector<JID>(1, changeStateEvent->getContact()), false));
+ blockRequest->send();
+ } else if (changeStateEvent->getBlockState() == RequestChangeBlockStateUIEvent::Unblocked) {
+ GenericRequest<UnblockPayload>::ref unblockRequest = blockListManager_->createUnblockJIDRequest(changeStateEvent->getContact());
+ 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();
- }
- }
+void BlockListController::handleBlockResponse(GenericRequest<BlockPayload>::ref request, std::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(std::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();
- }
- }
+void BlockListController::handleUnblockResponse(GenericRequest<UnblockPayload>::ref request, std::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(std::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);
- }
- }
+ for (const auto& 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());
- }
+ for (const auto& 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 99c143c..c1f6fee 100644
--- a/Swift/Controllers/BlockListController.h
+++ b/Swift/Controllers/BlockListController.h
@@ -4,11 +4,18 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Queries/GenericRequest.h>
+
#include <Swift/Controllers/UIEvents/UIEventStream.h>
#include <Swift/Controllers/UIInterfaces/BlockListEditorWidgetFactory.h>
@@ -21,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(std::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, std::shared_ptr<BlockPayload>, ErrorPayload::ref error, const std::vector<JID>& jids, bool originEditor);
+ void handleUnblockResponse(GenericRequest<UnblockPayload>::ref, std::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 656c8ed..080b157 100644
--- a/Swift/Controllers/CertificateMemoryStorageFactory.h
+++ b/Swift/Controllers/CertificateMemoryStorageFactory.h
@@ -1,28 +1,28 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swift/Controllers/Storages/CertificateStorageFactory.h>
#include <Swift/Controllers/Storages/CertificateMemoryStorage.h>
+#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 e49e378..646612b 100644
--- a/Swift/Controllers/Chat/AutoAcceptMUCInviteDecider.h
+++ b/Swift/Controllers/Chat/AutoAcceptMUCInviteDecider.h
@@ -5,49 +5,50 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Roster/XMPPRoster.h>
#include <Swiften/Elements/MUCInvitationPayload.h>
-#include <Swift/Controllers/Settings/SettingsProvider.h>
+#include <Swiften/Roster/XMPPRoster.h>
+
#include <Swift/Controllers/SettingConstants.h>
+#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 a80eee5..cd8fa0c 100644
--- a/Swift/Controllers/Chat/ChatController.cpp
+++ b/Swift/Controllers/Chat/ChatController.cpp
@@ -6,14 +6,13 @@
#include <Swift/Controllers/Chat/ChatController.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Avatars/AvatarManager.h>
#include <Swiften/Base/Algorithm.h>
-#include <Swiften/Base/DateTime.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/format.h>
#include <Swiften/Chat/ChatStateNotifier.h>
#include <Swiften/Chat/ChatStateTracker.h>
@@ -33,6 +32,7 @@
#include <Swift/Controllers/Intl.h>
#include <Swift/Controllers/SettingConstants.h>
#include <Swift/Controllers/StatusUtil.h>
+#include <Swift/Controllers/Translator.h>
#include <Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h>
#include <Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h>
#include <Swift/Controllers/UIEvents/InviteToMUCUIEvent.h>
@@ -43,491 +43,509 @@
#include <Swift/Controllers/UIEvents/UIEventStream.h>
#include <Swift/Controllers/UIInterfaces/ChatWindowFactory.h>
#include <Swift/Controllers/XMPPEvents/EventController.h>
+#include <Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.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));
+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, std::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%")) % Swift::Translator::getInstance()->ptimeToHumanReadableString(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_);
-}
-
-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();
-
- 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();
- }
-}
-
-bool ChatController::isIncomingMessageFromMe(boost::shared_ptr<Message>) {
- 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);
- }
- }
-}
-
-void ChatController::postHandleIncomingMessage(boost::shared_ptr<MessageEvent> messageEvent, const HighlightAction& highlight) {
- eventController_->handleIncomingEvent(messageEvent);
- if (!messageEvent->getConcluded()) {
- highlighter_->handleHighlightAction(highlight);
- }
-}
-
-
-void ChatController::preSendMessageRequest(boost::shared_ptr<Message> message) {
- chatStateNotifier_->addChatStateRequest(message);
- if (userWantsReceipts_ && (contactSupportsReceipts_ != No) && message) {
- message->addPayload(boost::make_shared<DeliveryReceiptRequest>());
- }
+ 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(std::shared_ptr<DiscoInfo> info) {
+ ChatControllerBase::setAvailableServerFeatures(info);
+ if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::BlockingCommandFeature)) {
+ std::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
+
+ blockingOnStateChangedConnection_ = blockList->onStateChanged.connect(boost::bind(&ChatController::handleBlockingStateChanged, this));
+ blockingOnItemAddedConnection_ = blockList->onItemAdded.connect(boost::bind(&ChatController::handleBlockingStateChanged, this));
+ blockingOnItemRemovedConnection_ = blockList->onItemRemoved.connect(boost::bind(&ChatController::handleBlockingStateChanged, this));
+
+ handleBlockingStateChanged();
+ }
+}
+
+bool ChatController::isIncomingMessageFromMe(std::shared_ptr<Message>) {
+ return false;
+}
+
+void ChatController::preHandleIncomingMessage(std::shared_ptr<MessageEvent> messageEvent) {
+ if (messageEvent->isReadable()) {
+ chatWindow_->flash();
+ lastWasPresence_ = false;
+ }
+ std::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 (std::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_) {
+ std::shared_ptr<Message> receiptMessage = std::make_shared<Message>();
+ receiptMessage->setTo(toJID_);
+ receiptMessage->addPayload(std::make_shared<DeliveryReceipt>(message->getID()));
+ stanzaChannel_->sendMessage(receiptMessage);
+ }
+ }
+}
+
+void ChatController::postHandleIncomingMessage(std::shared_ptr<MessageEvent> messageEvent, const ChatWindow::ChatMessage& chatMessage) {
+ eventController_->handleIncomingEvent(messageEvent);
+ if (!messageEvent->getConcluded()) {
+ handleHighlightActions(chatMessage);
+ }
+}
+
+
+void ChatController::preSendMessageRequest(std::shared_ptr<Message> message) {
+ chatStateNotifier_->addChatStateRequest(message);
+ if (userWantsReceipts_ && (contactSupportsReceipts_ != No) && message) {
+ message->addPayload(std::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_));
- }
- }
+ std::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(std::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Blocked, toJID_));
+ } else {
+ eventStream_->send(std::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(std::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, toJID_));
+ } else {
+ eventStream_->send(std::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);
+ std::shared_ptr<UIEvent> event(new RequestInviteToMUCUIEvent(getToJID(), 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());
- }
+void ChatController::handleUIEvent(std::shared_ptr<UIEvent> event) {
+ std::shared_ptr<InviteToMUCUIEvent> inviteEvent = std::dynamic_pointer_cast<InviteToMUCUIEvent>(event);
+ if (inviteEvent && inviteEvent->getOriginator() == getToJID()) {
+ onConvertToMUC(detachChatWindow(), inviteEvent->getInvites(), inviteEvent->getReason());
+ }
}
+void ChatController::handleIncomingOwnMessage(std::shared_ptr<Message> message) {
+ if (!message->getBody().get_value_or("").empty()) {
+ postSendMessage(message->getBody().get_value_or(""), message);
+ handleStanzaAcked(message);
+ }
+}
-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(body, myLastMessageUIID_, true, boost::posix_time::microsec_clock::universal_time(), HighlightAction());
- } else {
- myLastMessageUIID_ = addMessage(body, QT_TRANSLATE_NOOP("", "me"), true, labelsEnabled_ ? chatWindow_->getSelectedSecurityLabel().getLabel() : boost::shared_ptr<SecurityLabel>(), avatarManager_->getAvatarPath(selfJID_), boost::posix_time::microsec_clock::universal_time(), HighlightAction());
- }
+void ChatController::postSendMessage(const std::string& body, std::shared_ptr<Stanza> sentStanza) {
+ std::shared_ptr<Replace> replace = sentStanza->getPayload<Replace>();
+ if (replace) {
+ eraseIf(unackedStanzas_, PairSecondEquals<std::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() : std::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);
- }
+void ChatController::handleStanzaAcked(std::shared_ptr<Stanza> stanza) {
+ std::map<std::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) {
+ for (auto& stanzaIdPair : unackedStanzas_) {
+ chatWindow_->setAckState(stanzaIdPair.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;
+
+ if (ftc->isIncoming()) {
+ auto incomingFileTransferEvent = std::make_shared<IncomingFileTransferEvent>(ftc->getOtherParty());
+ if (hasOpenWindow()) {
+ incomingFileTransferEvent->conclude();
+ }
+ else {
+ unreadMessages_.push_back(incomingFileTransferEvent);
+ updateMessageCount();
+ }
+ eventController_->handleIncomingEvent(incomingFileTransferEvent);
+ }
}
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(std::make_shared<SendFileUIEvent>(getToJID(), filename));
}
void ChatController::handleWhiteboardSessionAccept() {
- eventStream_->send(boost::make_shared<AcceptWhiteboardSessionUIEvent>(toJID_));
+ eventStream_->send(std::make_shared<AcceptWhiteboardSessionUIEvent>(toJID_));
}
void ChatController::handleWhiteboardSessionCancel() {
- eventStream_->send(boost::make_shared<CancelWhiteboardSessionUIEvent>(toJID_));
+ eventStream_->send(std::make_shared<CancelWhiteboardSessionUIEvent>(toJID_));
}
void ChatController::handleWhiteboardWindowShow() {
- eventStream_->send(boost::make_shared<ShowWhiteboardUIEvent>(toJID_));
+ eventStream_->send(std::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);
-}
-
-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 + ".";
-}
-
-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;
- }
-}
-
-boost::optional<boost::posix_time::ptime> ChatController::getMessageTimestamp(boost::shared_ptr<Message> message) const {
- return message->getTimestamp();
+ return nickResolver_->jidToNick(from);
+}
+
+std::string ChatController::getStatusChangeString(std::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%")) % Swift::Translator::getInstance()->ptimeToHumanReadableString(idle->getSince()));
+ }
+
+ if (!response.empty()) {
+ response = str(format(response) % nick);
+ }
+
+ if (!presence->getStatus().empty()) {
+ response += " (" + presence->getStatus() + ")";
+ }
+ return response + ".";
+}
+
+void ChatController::handlePresenceChange(std::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 = std::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(std::shared_ptr<Message> message) const {
+ 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 9ee82eb..7bd6107 100644
--- a/Swift/Controllers/Chat/ChatController.h
+++ b/Swift/Controllers/Chat/ChatController.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 HighlightAction&) 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, std::shared_ptr<ChatMessageParser> chatMessageParser, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider);
+ virtual ~ChatController();
+ virtual void setToJID(const JID& jid) SWIFTEN_OVERRIDE;
+ virtual void setAvailableServerFeatures(std::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;
+ virtual void handleIncomingOwnMessage(std::shared_ptr<Message> message) 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(std::shared_ptr<Presence> newPresence);
+ std::string getStatusChangeString(std::shared_ptr<Presence> presence);
+ virtual bool isIncomingMessageFromMe(std::shared_ptr<Message> message) SWIFTEN_OVERRIDE;
+ virtual void postSendMessage(const std::string &body, std::shared_ptr<Stanza> sentStanza) SWIFTEN_OVERRIDE;
+ virtual void preHandleIncomingMessage(std::shared_ptr<MessageEvent> messageEvent) SWIFTEN_OVERRIDE;
+ virtual void postHandleIncomingMessage(std::shared_ptr<MessageEvent> messageEvent, const ChatWindow::ChatMessage& chatMessage) SWIFTEN_OVERRIDE;
+ virtual void preSendMessageRequest(std::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(std::shared_ptr<Message>) const SWIFTEN_OVERRIDE;
+ void handleStanzaAcked(std::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(std::shared_ptr<UIEvent> event);
+
+ private:
+ NickResolver* nickResolver_;
+ ChatStateNotifier* chatStateNotifier_;
+ ChatStateTracker* chatStateTracker_;
+ std::string myLastMessageUIID_;
+ bool isInMUC_;
+ std::string lastStatusChangeString_;
+ std::map<std::shared_ptr<Stanza>, std::string> unackedStanzas_;
+ std::map<std::string, std::string> requestedReceipts_;
+ StatusShow::Type lastShownStatus_;
+ UIEventStream* eventStream_;
+
+ Tristate contactSupportsReceipts_;
+ bool receivingPresenceFromUs_ = false;
+ bool userWantsReceipts_;
+ std::map<std::string, FileTransferController*> ftControllers;
+ SettingsProvider* settings_;
+ std::string lastWbID_;
+
+ ClientBlockListManager* clientBlockListManager_;
+ boost::signals2::scoped_connection blockingOnStateChangedConnection_;
+ boost::signals2::scoped_connection blockingOnItemAddedConnection_;
+ boost::signals2::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 fef3e7a..da9064e 100644
--- a/Swift/Controllers/Chat/ChatControllerBase.cpp
+++ b/Swift/Controllers/Chat/ChatControllerBase.cpp
@@ -7,19 +7,15 @@
#include <Swift/Controllers/Chat/ChatControllerBase.h>
#include <map>
+#include <memory>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
-#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/numeric/conversion/cast.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Avatars/AvatarManager.h>
#include <Swiften/Base/Path.h>
-#include <Swiften/Base/String.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/format.h>
#include <Swiften/Client/StanzaChannel.h>
#include <Swiften/Disco/EntityCapsProvider.h>
@@ -42,343 +38,384 @@
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();
+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, std::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();
}
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_ = nullptr;
+ 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);
+ lastWasPresence_ = false;
+ 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;
- }
+void ChatControllerBase::setAvailableServerFeatures(std::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;
+ }
}
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();
+ for (std::shared_ptr<StanzaEvent> stanzaEvent : unreadMessages_) {
+ stanzaEvent->conclude();
+ }
+ unreadMessages_.clear();
+ updateMessageCount();
+ }
}
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;
+ }
+ std::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(std::make_shared<Delay>(now, selfJID_));
+ }
+ if (isCorrectionMessage) {
+ message->addPayload(std::shared_ptr<Replace> (new Replace(lastSentMessageStanzaID_)));
+ }
+ message->setID(lastSentMessageStanzaID_ = idGenerator_.generateID());
+ stanzaChannel_->sendMessage(message);
+ postSendMessage(message->getBody().get(), std::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();
- }
+void ChatControllerBase::handleSecurityLabelsCatalogResponse(std::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();
+ }
}
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();
}
-std::string ChatControllerBase::addMessage(const std::string& message, const std::string& senderName, bool senderIsSelf, const boost::shared_ptr<SecurityLabel> label, const boost::filesystem::path& avatarPath, const boost::posix_time::ptime& time, const HighlightAction& highlight) {
- if (boost::starts_with(message, "/me ")) {
- return chatWindow_->addAction(chatMessageParser_->parseMessageBody(String::getSplittedAtFirst(message, ' ').second), senderName, senderIsSelf, label, pathToString(avatarPath), time, highlight);
- } else {
- return chatWindow_->addMessage(chatMessageParser_->parseMessageBody(message,highlighter_->getNick(),senderIsSelf), senderName, senderIsSelf, label, pathToString(avatarPath), time, highlight);
- }
+ChatWindow::ChatMessage ChatControllerBase::buildChatWindowChatMessage(const std::string& message, bool senderIsSelf, const HighlightAction& fullMessageHighlightAction) {
+ ChatWindow::ChatMessage chatMessage;
+ chatMessage = chatMessageParser_->parseMessageBody(message, highlighter_->getNick(), senderIsSelf);
+ chatMessage.setFullMessageHighlightAction(fullMessageHighlightAction);
+ return chatMessage;
}
-void ChatControllerBase::replaceMessage(const std::string& message, const std::string& id, bool senderIsSelf, const boost::posix_time::ptime& time, const HighlightAction& highlight) {
- if (boost::starts_with(message, "/me ")) {
- chatWindow_->replaceWithAction(chatMessageParser_->parseMessageBody(String::getSplittedAtFirst(message, ' ').second), id, time, highlight);
- } else {
- chatWindow_->replaceMessage(chatMessageParser_->parseMessageBody(message,highlighter_->getNick(),senderIsSelf), id, time, highlight);
- }
+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());
+ }
+ for (std::shared_ptr<ChatWindow::ChatMessagePart> part : chatMessage.getParts()) {
+ std::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightMessage = std::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());
+ }
+ }
+ }
+}
+
+void ChatControllerBase::updateMessageCount() {
+ chatWindow_->setUnreadMessageCount(boost::numeric_cast<int>(unreadMessages_.size()));
+ onUnreadCountChanged();
+}
+
+std::string ChatControllerBase::addMessage(const ChatWindow::ChatMessage& chatMessage, const std::string& senderName, bool senderIsSelf, const std::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);
+ }
+}
+
+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);
+ }
}
bool ChatControllerBase::isFromContact(const JID& from) {
- 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();
- std::string body = message->getBody().get_value_or("");
- HighlightAction highlight;
- 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
- if (!isIncomingMessageFromMe(message)) {
- highlight = highlighter_->findAction(body, senderHighlightNameFromMessage(from));
- }
-
- boost::shared_ptr<Replace> replace = message->getPayload<Replace>();
- if (replace) {
- std::string body = message->getBody().get_value_or("");
- // Should check if the user has a previous message
- std::map<JID, std::string>::iterator lastMessage;
- lastMessage = lastMessagesUIID_.find(from);
- if (lastMessage != lastMessagesUIID_.end()) {
- replaceMessage(body, lastMessagesUIID_[from], isIncomingMessageFromMe(message), timeStamp, highlight);
- }
- }
- else {
- addMessageHandleIncomingMessage(from, body, isIncomingMessageFromMe(message), label, timeStamp, highlight);
- }
-
- logMessage(body, from, selfJID_, timeStamp, true);
- }
- chatWindow_->show();
- chatWindow_->setUnreadMessageCount(boost::numeric_cast<int>(unreadMessages_.size()));
- onUnreadCountChanged();
- postHandleIncomingMessage(messageEvent, highlight);
-}
-
-void ChatControllerBase::addMessageHandleIncomingMessage(const JID& from, const std::string& message, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const boost::posix_time::ptime& timeStamp, const HighlightAction& highlight) {
- lastMessagesUIID_[from] = addMessage(message, senderDisplayNameFromMessage(from), senderIsSelf, label, avatarManager_->getAvatarPath(from), timeStamp, highlight);
-}
-
-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;
+ return from.toBare() == toJID_.toBare();
+}
+
+void ChatControllerBase::handleIncomingMessage(std::shared_ptr<MessageEvent> messageEvent) {
+ preHandleIncomingMessage(messageEvent);
+ if (messageEvent->isReadable() && !messageEvent->getConcluded()) {
+ unreadMessages_.push_back(messageEvent);
+ if (messageEvent->targetsMe()) {
+ targetedUnreadMessages_.push_back(messageEvent);
+ }
+ }
+
+ std::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;
+ if (message->getPayload<Swift::ErrorPayload>()->getCondition() == ErrorPayload::ItemNotFound) {
+ errorMessage = QT_TRANSLATE_NOOP("", "This user could not be found in the room.");
+ }
+ else {
+ 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<std::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);
+ }
+ std::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));
+ }
+
+ std::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();
+ updateMessageCount();
+ postHandleIncomingMessage(messageEvent, chatMessage);
+}
+
+void ChatControllerBase::addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, std::shared_ptr<SecurityLabel> label, const boost::posix_time::ptime& timeStamp) {
+ lastMessagesUIID_[from] = addMessage(message, senderDisplayNameFromMessage(from), senderIsSelf, label, avatarManager_->getAvatarPath(from), timeStamp);
+}
+
+std::string ChatControllerBase::getErrorMessage(std::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;
}
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();
+ updateMessageCount();
+ chatWindow_->addMUCInvitation(senderDisplayNameFromMessage(event->getInviter()), event->getRoomJID(), event->getReason(), event->getPassword(), event->getDirect(), event->getImpromptu());
+ eventController_->handleIncomingEvent(event);
+ lastWasPresence_ = false;
}
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(std::make_shared<JoinMUCUIEvent>(invite->getJID(), boost::optional<std::string>(), boost::optional<std::string>(), false, false, true));
+ } else {
+ MUCInviteEvent::ref inviteEvent = std::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 = std::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 4e68a2b..4255c19 100644
--- a/Swift/Controllers/Chat/ChatControllerBase.h
+++ b/Swift/Controllers/Chat/ChatControllerBase.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,16 +7,16 @@
#pragma once
#include <map>
+#include <memory>
#include <string>
#include <vector>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/IDGenerator.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/ErrorPayload.h>
#include <Swiften/Elements/SecurityLabelsCatalog.h>
@@ -35,104 +35,110 @@
#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 std::string& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const boost::filesystem::path& avatarPath, const boost::posix_time::ptime& time, const HighlightAction& highlight);
- void replaceMessage(const std::string& message, const std::string& id, bool senderIsSelf, const boost::posix_time::ptime& time, const HighlightAction& highlight);
- 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::signals2::trackable {
+ public:
+ virtual ~ChatControllerBase();
+ void showChatWindow();
+ void activateChatWindow();
+ bool hasOpenWindow() const;
+ virtual void setAvailableServerFeatures(std::shared_ptr<DiscoInfo> info);
+ virtual void handleIncomingOwnMessage(std::shared_ptr<Message> /*message*/) {}
+ void handleIncomingMessage(std::shared_ptr<MessageEvent> message);
+ std::string addMessage(const ChatWindow::ChatMessage& chatMessage, const std::string& senderName, bool senderIsSelf, std::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::signals2::signal<void (const std::string& /*activity*/)> onActivity;
+ boost::signals2::signal<void ()> onUnreadCountChanged;
+ boost::signals2::signal<void ()> onWindowClosed;
+ int getUnreadCount();
+ const JID& getToJID() {return toJID_;}
+ void handleCapsChanged(const JID& jid);
+ void setCanStartImpromptuChats(bool supportsImpromptu);
+ virtual ChatWindow* detachChatWindow();
+ boost::signals2::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, std::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 std::string& message, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const boost::posix_time::ptime& time, const HighlightAction& highlight);
- virtual void postHandleIncomingMessage(boost::shared_ptr<MessageEvent>, const HighlightAction&) {}
- 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;
+ /**
+ * Pass the Message appended, and the stanza used to send it.
+ */
+ virtual void postSendMessage(const std::string&, std::shared_ptr<Stanza>) {}
+ virtual std::string senderDisplayNameFromMessage(const JID& from) = 0;
+ virtual std::string senderHighlightNameFromMessage(const JID& from) = 0;
+ virtual bool isIncomingMessageFromMe(std::shared_ptr<Message>) = 0;
+ virtual void preHandleIncomingMessage(std::shared_ptr<MessageEvent>) {}
+ virtual void addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, std::shared_ptr<SecurityLabel> label, const boost::posix_time::ptime& time);
+ virtual void postHandleIncomingMessage(std::shared_ptr<MessageEvent>, const ChatWindow::ChatMessage&) {}
+ virtual void preSendMessageRequest(std::shared_ptr<Message>) {}
+ virtual bool isFromContact(const JID& from);
+ virtual boost::optional<boost::posix_time::ptime> getMessageTimestamp(std::shared_ptr<Message>) const = 0;
+ virtual void dayTicked() {}
+ virtual void handleBareJIDCapsChanged(const JID& jid) = 0;
+ std::string getErrorMessage(std::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);
+ void updateMessageCount();
- 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();
+ private:
+ IDGenerator idGenerator_;
+ std::string lastSentMessageStanzaID_;
+ void createDayChangeTimer();
- 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_;
- };
+ void handleSendMessageRequest(const std::string &body, bool isCorrectionMessage);
+ void handleAllMessagesRead();
+ void handleSecurityLabelsCatalogResponse(std::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<std::shared_ptr<StanzaEvent> > unreadMessages_;
+ std::vector<std::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_;
+ std::shared_ptr<Timer> dateChangeTimer_;
+ TimerFactory* timerFactory_;
+ EntityCapsProvider* entityCapsProvider_;
+ SecurityLabelsCatalog::Item lastLabel_;
+ HistoryController* historyController_;
+ MUCRegistry* mucRegistry_;
+ Highlighter* highlighter_;
+ std::shared_ptr<ChatMessageParser> chatMessageParser_;
+ AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider_;
+ UIEventStream* eventStream_;
+ bool lastWasPresence_ = false;
+ };
}
diff --git a/Swift/Controllers/Chat/ChatMessageParser.cpp b/Swift/Controllers/Chat/ChatMessageParser.cpp
index 666ec2f..ec7df6c 100644
--- a/Swift/Controllers/Chat/ChatMessageParser.cpp
+++ b/Swift/Controllers/Chat/ChatMessageParser.cpp
@@ -1,197 +1,197 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Chat/ChatMessageParser.h>
-#include <vector>
+#include <memory>
#include <utility>
+#include <vector>
-#include <boost/smart_ptr/make_shared.hpp>
#include <boost/algorithm/string.hpp>
#include <Swiften/Base/Regex.h>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Base/String.h>
#include <SwifTools/Linkify.h>
-
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->foregroundColor = rule.getAction().getTextColor();
- highlightPart->backgroundColor = rule.getAction().getTextBackground();
- 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;
+ if (boost::starts_with(body, "/me ")) {
+ remaining = String::getSplittedAtFirst(body, ' ').second;
+ parsedMessage.setIsMeCommand(true);
+ }
+
+ /* 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(std::make_shared<ChatWindow::ChatURIMessagePart>(part));
+ }
+ else {
+ parsedMessage.append(std::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 */
+ for (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;
+ for (std::shared_ptr<ChatWindow::ChatMessagePart> part : parsedMessage.getParts()) {
+ std::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
+ if ((textPart = std::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(std::make_shared<ChatWindow::ChatTextMessagePart>(std::string(start, matchStart)));
+ }
+ std::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart = std::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(std::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.setParts(newMessage.getParts());
+ }
+ 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);
+ for (const boost::regex& regex : keywordRegex) {
+ ChatWindow::ChatMessage newMessage;
+ for (std::shared_ptr<ChatWindow::ChatMessagePart> part : parsedMessage.getParts()) {
+ std::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
+ if ((textPart = std::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(std::make_shared<ChatWindow::ChatTextMessagePart>(std::string(start, matchStart)));
+ }
+ std::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart = std::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(std::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.setParts(newMessage.getParts());
+ }
+ }
+
+ 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..f55df1e 100644
--- a/Swift/Controllers/Chat/ChatsManager.cpp
+++ b/Swift/Controllers/Chat/ChatsManager.cpp
@@ -6,6 +6,8 @@
#include <Swift/Controllers/Chat/ChatsManager.h>
+#include <memory>
+
#include <boost/algorithm/string.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
@@ -15,18 +17,20 @@
#include <boost/serialization/split_free.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Avatars/AvatarManager.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/ClientBlockListManager.h>
#include <Swiften/Client/NickResolver.h>
#include <Swiften/Client/StanzaChannel.h>
#include <Swiften/Disco/DiscoServiceWalker.h>
+#include <Swiften/Disco/FeatureOracle.h>
+#include <Swiften/Elements/CarbonsReceived.h>
+#include <Swiften/Elements/CarbonsSent.h>
#include <Swiften/Elements/ChatState.h>
#include <Swiften/Elements/DeliveryReceipt.h>
#include <Swiften/Elements/DeliveryReceiptRequest.h>
+#include <Swiften/Elements/Forwarded.h>
#include <Swiften/Elements/MUCInvitationPayload.h>
#include <Swiften/Elements/MUCUserPayload.h>
#include <Swiften/MUC/MUCBookmarkManager.h>
@@ -56,43 +60,43 @@
#include <Swift/Controllers/UIEvents/RemoveMUCBookmarkUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestChatUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h>
+#include <Swift/Controllers/UIEvents/SendFileUIEvent.h>
#include <Swift/Controllers/UIInterfaces/ChatListWindowFactory.h>
#include <Swift/Controllers/UIInterfaces/JoinMUCWindow.h>
#include <Swift/Controllers/UIInterfaces/JoinMUCWindowFactory.h>
#include <Swift/Controllers/WhiteboardManager.h>
#include <Swift/Controllers/XMPPEvents/EventController.h>
-#include <Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h>
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 +108,1008 @@ 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_ = nullptr;
+ serverDiscoInfo_ = std::make_shared<DiscoInfo>();
+ presenceSender_ = presenceSender;
+ uiEventStream_ = uiEventStream;
+ mucBookmarkManager_ = nullptr;
+ 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_ = nullptr;
+ 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));
+ ftOverview_->onNewFileTransferController.disconnect(boost::bind(&ChatsManager::handleNewFileTransferController, this, _1));
+ delete joinMUCWindow_;
+ for (JIDChatControllerPair controllerPair : chatControllers_) {
+ delete controllerPair.second;
+ }
+ for (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_) {
+ for (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(nullptr);
}
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. */
+ for (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;
+ for (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;
+ }
+
+ for (auto chat : recentChats) {
+ chat.statusType = StatusShow::None;
+ chat = updateChatStatusAndAvatarHelper(chat);
+ prependRecent(chat);
+ }
+ }
+ handleUnreadCountChanged(nullptr);
}
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(nullptr);
+ 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());
+ for (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_;
+ for (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) {
+ for (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();
+ for (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);
+ }
+ for (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();
- }
+void ChatsManager::handleUIEvent(std::shared_ptr<UIEvent> event) {
+ std::shared_ptr<RequestChatUIEvent> chatEvent = std::dynamic_pointer_cast<RequestChatUIEvent>(event);
+ if (chatEvent) {
+ handleChatRequest(chatEvent->getContact());
+ return;
+ }
+ std::shared_ptr<RemoveMUCBookmarkUIEvent> removeMUCBookmarkEvent = std::dynamic_pointer_cast<RemoveMUCBookmarkUIEvent>(event);
+ if (removeMUCBookmarkEvent) {
+ mucBookmarkManager_->removeBookmark(removeMUCBookmarkEvent->getBookmark());
+ return;
+ }
+ std::shared_ptr<AddMUCBookmarkUIEvent> addMUCBookmarkEvent = std::dynamic_pointer_cast<AddMUCBookmarkUIEvent>(event);
+ if (addMUCBookmarkEvent) {
+ mucBookmarkManager_->addBookmark(addMUCBookmarkEvent->getBookmark());
+ return;
+ }
+ std::shared_ptr<SendFileUIEvent> sendFileEvent = std::dynamic_pointer_cast<SendFileUIEvent>(event);
+ if (sendFileEvent) {
+ JID fileReceiver = sendFileEvent->getJID();
+ if (fileReceiver.isBare()) {
+ // See if there is a chat controller for a conversation with a bound
+ // full JID. Check if this JID supports file transfer and use it instead
+ // of the bare JID.
+ ChatController* controller = getChatControllerIfExists(fileReceiver, false);
+ if (controller) {
+ JID controllerJID = controller->getToJID();
+ if (!controllerJID.isBare() && (FeatureOracle(entityCapsProvider_, presenceOracle_).isFileTransferSupported(controllerJID) == Yes)) {
+ fileReceiver = controllerJID;
+ }
+ }
+ }
+ ftOverview_->sendFile(fileReceiver, sendFileEvent->getFilename());
+ return;
+ }
+
+ std::shared_ptr<CreateImpromptuMUCUIEvent> createImpromptuMUCEvent = std::dynamic_pointer_cast<CreateImpromptuMUCUIEvent>(event);
+ if (createImpromptuMUCEvent) {
+ assert(!localMUCServiceJID_.toString().empty());
+ // The room JID is random for new impromptu rooms, or a predefined JID for impromptu rooms resumed from the 'Recent chats' list.
+ 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();
+ }
+
+ std::shared_ptr<EditMUCBookmarkUIEvent> editMUCBookmarkEvent = std::dynamic_pointer_cast<EditMUCBookmarkUIEvent>(event);
+ if (editMUCBookmarkEvent) {
+ mucBookmarkManager_->replaceBookmark(editMUCBookmarkEvent->getOldBookmark(), editMUCBookmarkEvent->getNewBookmark());
+ }
+ else if (JoinMUCUIEvent::ref joinEvent = std::dynamic_pointer_cast<JoinMUCUIEvent>(event)) {
+ handleJoinMUCRequest(joinEvent->getJID(), joinEvent->getPassword(), joinEvent->getNick(), joinEvent->getShouldJoinAutomatically(), joinEvent->getCreateAsReservedRoomIfNew(), joinEvent->isImpromptu());
+ mucControllers_[joinEvent->getJID()]->activateChatWindow();
+ }
+ else if (std::shared_ptr<RequestJoinMUCUIEvent> joinEvent = std::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);
- }
+ for (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);
+void ChatsManager::handlePresenceChange(std::shared_ptr<Presence> newPresence) {
+ if (mucRegistry_->isMUC(newPresence->getFrom().toBare())) return;
+
+ for (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;
+ for (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;
- }
- }
+ for (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);
- }
+void ChatsManager::setServerDiscoInfo(std::shared_ptr<DiscoInfo> info) {
+ serverDiscoInfo_ = info;
+ for (JIDChatControllerPair pair : chatControllers_) {
+ pair.second->setAvailableServerFeatures(info);
+ }
+ for (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);
- }
+ for (JIDChatControllerPair controllerPair : chatControllers_) {
+ controllerPair.second->setOnline(enabled);
+ }
+ for (JIDMUCControllerPair controllerPair : mucControllers_) {
+ controllerPair.second->setOnline(enabled);
+ if (enabled) {
+ controllerPair.second->rejoin();
+ }
+ }
+ if (!enabled) {
+ markAllRecentsOffline();
+ } else {
+ setupBookmarks();
+ localMUCServiceJID_ = JID();
+ localMUCServiceFinderWalker_ = std::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())) {
+ for (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());
+ std::shared_ptr<ChatMessageParser> chatMessageParser = std::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 nullptr;
+ }
+ //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 {
+ for (JIDChatControllerPair pair : chatControllers_) {
+ if (pair.first.toBare() == contact.toBare()) {
+ if (rebindIfNeeded) {
+ rebindControllerJID(pair.first, contact);
+ return chatControllers_[contact];
+ } else {
+ return pair.second;
+ }
+ }
+ }
+ return nullptr;
+ }
+ }
+ 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 = nullptr;
+ SingleChatWindowFactoryAdapter* chatWindowFactoryAdapter = nullptr;
+ if (reuseChatwindow) {
+ chatWindowFactoryAdapter = new SingleChatWindowFactoryAdapter(reuseChatwindow);
+ }
+ std::shared_ptr<ChatMessageParser> chatMessageParser = std::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));
+ }
+}
+
+bool ChatsManager::messageCausesSessionBinding(std::shared_ptr<Message> message) {
+ bool causesRebind = false;
+ ChatState::ref chatState = message->getPayload<ChatState>();
+ if (!message->getBody().get_value_or("").empty() || (chatState && chatState->getChatState() == ChatState::Composing)) {
+ causesRebind = true;
+ }
+ return causesRebind;
}
-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);
- }
+void ChatsManager::handleIncomingMessage(std::shared_ptr<Message> incomingMessage) {
+ std::shared_ptr<Message> message = incomingMessage;
+ if (message->getFrom().toBare() == jid_.toBare()) {
+ CarbonsReceived::ref carbonsReceived;
+ CarbonsSent::ref carbonsSent;
+ Forwarded::ref forwarded;
+ Message::ref forwardedMessage;
+ if ((carbonsReceived = incomingMessage->getPayload<CarbonsReceived>()) &&
+ (forwarded = carbonsReceived->getForwarded()) &&
+ (forwardedMessage = std::dynamic_pointer_cast<Message>(forwarded->getStanza()))) {
+ message = forwardedMessage;
+ }
+ else if ((carbonsSent = incomingMessage->getPayload<CarbonsSent>()) &&
+ (forwarded = carbonsSent->getForwarded()) &&
+ (forwardedMessage = std::dynamic_pointer_cast<Message>(forwarded->getStanza()))) {
+ JID toJID = forwardedMessage->getTo();
+
+ ChatController* controller = getChatControllerOrCreate(toJID);
+ if (controller) {
+ controller->handleIncomingOwnMessage(forwardedMessage);
+ }
+ else {
+ SWIFT_LOG(error) << "Carbons message ignored." << std::endl;
+ }
+ return;
+ }
+ }
+ JID fromJID = message->getFrom();
+
+ std::shared_ptr<MessageEvent> event(new MessageEvent(message));
+ bool isInvite = !!message->getPayload<MUCInvitationPayload>();
+ bool isMediatedInvite = (message->getPayload<MUCUserPayload>() && message->getPayload<MUCUserPayload>()->getInvite());
+ if (isMediatedInvite) {
+ fromJID = (*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 MUC errors to a MUC PM window if a suitable window is open.
+ if (message->getType() == Message::Error) {
+ auto controller = getChatControllerIfExists(fromJID, messageCausesSessionBinding(message));
+ if (controller) {
+ controller->handleIncomingMessage(event);
+ return;
+ }
+ }
+
+ // Try to deliver it to a MUC.
+ if (message->getType() == Message::Groupchat || message->getType() == Message::Error) {
+ // Try to deliver it to a MUC room.
+ std::map<JID, MUCController*>::iterator i = mucControllers_.find(fromJID.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(fromJID);
+ if (controller) {
+ ChatWindow* window = controller->detachChatWindow();
+ chatControllers_.erase(fromJID);
+ 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.
+ ChatController* controller = getChatControllerIfExists(fromJID, messageCausesSessionBinding(message));
+ if (controller) {
+ controller->handleIncomingMessage(event);
+ }
+ } else {
+ getChatControllerOrCreate(fromJID)->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(std::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);
+ if (!ftc->isIncoming()) {
+ chatController->activateChatWindow();
+ }
}
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;
+ for (StringJIDPair pair : chat.impromptuJIDs) {
+ inviteJIDs.push_back(pair.second);
+ }
+ uiEventStream_->send(std::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(std::make_shared<JoinMUCUIEvent>(chat.jid, boost::optional<std::string>(), chat.nick));
+ }
+ else {
+ uiEventStream_->send(std::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;
- }
- }
+void ChatsManager::handleLocalServiceFound(const JID& service, std::shared_ptr<DiscoInfo> info) {
+ for (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();
+ for (JIDChatControllerPair controllerPair : chatControllers_) {
+ controllerPair.second->setCanStartImpromptuChats(impromptuMUCSupported);
+ }
+ for (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;
+ for (ChatListWindow::Chat chat : recentChats_) {
+ if (!chat.isMUC) {
+ result.push_back(std::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;
+ for (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;
+ for (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(std::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..593624d 100644
--- a/Swift/Controllers/Chat/ChatsManager.h
+++ b/Swift/Controllers/Chat/ChatsManager.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,10 +7,9 @@
#pragma once
#include <map>
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
-
#include <Swiften/Base/IDGenerator.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/Message.h>
@@ -27,159 +26,160 @@
#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(std::shared_ptr<DiscoInfo> info);
+ void handleIncomingMessage(std::shared_ptr<Message> incomingMessage);
+ std::vector<ChatListWindow::Chat> getRecentChats() const;
+ virtual std::vector<Contact::ref> getContacts(bool withMUCNicks);
+
+ boost::signals2::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 = nullptr);
+ void handleSearchMUCRequest();
+ void handleMUCSelectedAfterSearch(const JID&);
+ void rebindControllerJID(const JID& from, const JID& to);
+ void handlePresenceChange(std::shared_ptr<Presence> newPresence);
+ void handleUIEvent(std::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);
+ bool messageCausesSessionBinding(std::shared_ptr<Message> message);
+ 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, std::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_;
+ std::shared_ptr<DiscoInfo> serverDiscoInfo_;
+ ChatListWindow* chatListWindow_;
+ JoinMUCWindow* joinMUCWindow_;
+ boost::signals2::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_;
+ std::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 409fe1f..ceed776 100644
--- a/Swift/Controllers/Chat/MUCController.cpp
+++ b/Swift/Controllers/Chat/MUCController.cpp
@@ -7,14 +7,15 @@
#include <Swift/Controllers/Chat/MUCController.h>
#include <algorithm>
+#include <memory>
#include <boost/bind.hpp>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
+#include <boost/range/adaptor/reversed.hpp>
#include <Swiften/Avatars/AvatarManager.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/format.h>
#include <Swiften/Base/Tristate.h>
#include <Swiften/Client/BlockList.h>
@@ -58,1163 +59,1158 @@
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,
+ std::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_ = std::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_ != nullptr) {
+ 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(nullptr);
+ delete rosterVCardProvider_;
+ delete roster_;
+ if (loginCheckTimer_) {
+ loginCheckTimer_->stop();
+ }
+ chatWindow_->setTabComplete(nullptr);
+ 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(std::make_shared<RequestAddUserDialogUIEvent>(realJID, occupant.getNick()));break;
+ case ChatWindow::ShowProfile: events_->send(std::make_shared<ShowProfileForRosterItemUIEvent>(mucJID));break;
+ }
}
void MUCController::handleBareJIDCapsChanged(const JID& /*jid*/) {
- Tristate support = Yes;
- bool any = false;
- foreach (const std::string& nick, currentOccupants_) {
- 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;
+ for (const auto& nick : currentOccupants_) {
+ DiscoInfo::ref disco = entityCapsProvider_->getCaps(toJID_.toBare().toString() + "/" + nick);
+ if (disco && disco->hasFeature(DiscoInfo::MessageCorrectionFeature)) {
+ any = true;
+ } else {
+ support = Maybe;
+ }
+ }
+ if (!any) {
+ support = No;
+ }
+ chatWindow_->setCorrectionEnabled(support);
}
/**
* Join the MUC if not already in it.
*/
void MUCController::rejoin() {
- if (parting_) {
- joined_ = false;
- parting_ = false;
- if (password_) {
- muc_->setPassword(*password_);
- }
- //FIXME: check for received activity
+ 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;
+ std::map<std::string, MUCOccupant> occupants = muc_->getOccupants();
+ for (const auto& occupant : occupants) {
+ if (occupant.first != nick_) {
+ participants[occupant.first] = occupant.second.getRealJID().is_initialized() ? occupant.second.getRealJID().get().toBare() : JID();
+ }
+ }
+ return participants;
}
void MUCController::sendInvites(const std::vector<JID>& jids, const std::string& reason) const {
- foreach (const JID& jid, jids) {
- muc_->invitePerson(jid, reason, isImpromptu_);
- }
+ for (const auto& jid : jids) {
+ muc_->invitePerson(jid, reason, isImpromptu_);
+ }
}
void MUCController::handleJoinTimeoutTick() {
- receivedActivity();
- chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "Room %1% is not responding. This operation may never complete.")) % toJID_.toString())), ChatWindow::DefaultDirection);
+ 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();
- }
+void MUCController::handleJoinFailed(std::shared_ptr<ErrorPayload> error) {
+ receivedActivity();
+ std::string errorMessage = QT_TRANSLATE_NOOP("", "Unable to enter this room");
+ std::string rejoinNick;
+ if (error) {
+ switch (error->getCondition()) {
+ case ErrorPayload::Conflict:
+ rejoinNick = nick_ + "_";
+ errorMessage = str(format(QT_TRANSLATE_NOOP("", "Unable to enter this room as %1%, retrying as %2%")) % nick_ % rejoinNick);
+ break;
+ case ErrorPayload::JIDMalformed:
+ errorMessage += ": ";
+ 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_ != nullptr) {
+ 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);
-}
-
-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);
-}
-
-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();
- }
-}
-
-void MUCController::addMessageHandleIncomingMessage(const JID& from, const std::string& message, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const boost::posix_time::ptime& time, const HighlightAction& highlight) {
- if (from.isBare()) {
- chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "%1%")) % message)), ChatWindow::DefaultDirection);
- }
- else {
- ChatControllerBase::addMessageHandleIncomingMessage(from, message, senderIsSelf, label, time, highlight);
- }
-}
-
-void MUCController::postHandleIncomingMessage(boost::shared_ptr<MessageEvent> messageEvent, const HighlightAction& highlight) {
- 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()) {
- highlighter_->handleHighlightAction(highlight);
- }
- }
+ return muc_->getJID().withResource(nick);
+}
+
+bool MUCController::messageTargetsMe(std::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);
+}
+
+void MUCController::preHandleIncomingMessage(std::shared_ptr<MessageEvent> messageEvent) {
+ if (messageEvent->getStanza()->getType() == Message::Groupchat) {
+ lastActivity_ = boost::posix_time::microsec_clock::universal_time();
+ }
+ clearPresenceQueue();
+ std::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, std::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);
+ }
+}
+
+void MUCController::postHandleIncomingMessage(std::shared_ptr<MessageEvent> messageEvent, const ChatWindow::ChatMessage& chatMessage) {
+ std::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;
+ std::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);
+ 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 occupants
+ currentOccupants_.erase(oldNickname);
+ currentOccupants_.insert(newNickname);
- // adjust completer
- completer_->removeWord(oldNickname);
- completer_->addWord(newNickname);
+ // adjust completer
+ completer_->removeWord(oldNickname);
+ completer_->addWord(newNickname);
- // update contact
- roster_->removeContact(oldJID);
- MUCOccupant occupant = muc_->getOccupant(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);
- }
+ 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_ != nullptr) {
+ handleAvatarChanged(newJID);
+ }
- clearPresenceQueue();
- onUserNicknameChanged(oldNickname, newNickname);
+ clearPresenceQueue();
+ onUserNicknameChanged(oldNickname, newNickname);
}
-void MUCController::handleOccupantPresenceChange(boost::shared_ptr<Presence> presence) {
- receivedActivity();
- roster_->applyOnItems(SetPresence(presence, JID::WithResource));
+void MUCController::handleOccupantPresenceChange(std::shared_ptr<Presence> presence) {
+ receivedActivity();
+ roster_->applyOnItems(SetPresence(presence, JID::WithResource));
}
-bool MUCController::isIncomingMessageFromMe(boost::shared_ptr<Message> message) {
- JID from = message->getFrom();
- return nick_ == from.getResource();
+bool MUCController::isIncomingMessageFromMe(std::shared_ptr<Message> message) {
+ 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);
+void MUCController::preSendMessageRequest(std::shared_ptr<Message> message) {
+ message->setType(Swift::Message::Groupchat);
}
-boost::optional<boost::posix_time::ptime> MUCController::getMessageTimestamp(boost::shared_ptr<Message> message) const {
- return message->getTimestampFrom(toJID_);
+boost::optional<boost::posix_time::ptime> MUCController::getMessageTimestamp(std::shared_ptr<Message> message) const {
+ 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];
+ for (const auto& event : joinParts) {
+ sorted[event.type].push_back(event);
+ }
+ std::string result;
+ std::vector<JoinPart> populatedEvents;
+ for (size_t i = 0; i < 4; i++) {
+ std::string names = concatenateListOfNames(sorted[i]);
+ if (!names.empty()) {
+ std::string eventString;
+ switch (i) {
+ case Join:
+ if (sorted[i].size() > 1) {
+ eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have joined the chat") : QT_TRANSLATE_NOOP("", "%1% have entered the room"));
+ }
+ else {
+ eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% has joined the chat") : QT_TRANSLATE_NOOP("", "%1% has entered the room"));
+ }
+ break;
+ case Part:
+ if (sorted[i].size() > 1) {
+ eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have left the chat") : QT_TRANSLATE_NOOP("", "%1% have left the room"));
+ }
+ else {
+ eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have left the chat") : QT_TRANSLATE_NOOP("", "%1% has left the room"));
+ }
+ break;
+ case JoinThenPart:
+ if (sorted[i].size() > 1) {
+ eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have joined then left the chat") : QT_TRANSLATE_NOOP("", "%1% have entered then left the room"));
+ }
+ else {
+ 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();
+ for (const auto& 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;
+ eventStream_->send(std::make_shared<RequestInviteToMUCUIEvent>(getToJID(), jidsToInvite, mode));
}
-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_);
- }
- }
+void MUCController::handleUIEvent(std::shared_ptr<UIEvent> event) {
+ std::shared_ptr<InviteToMUCUIEvent> inviteEvent = std::dynamic_pointer_cast<InviteToMUCUIEvent>(event);
+ if (inviteEvent && inviteEvent->getOriginator() == muc_->getJID()) {
+ for (const auto& jid : inviteEvent->getInvites()) {
+ muc_->invitePerson(jid, inviteEvent->getReason(), isImpromptu_);
+ }
+ }
}
void MUCController::handleGetAffiliationsRequest() {
- muc_->requestAffiliationList(MUCOccupant::Owner);
- muc_->requestAffiliationList(MUCOccupant::Admin);
- muc_->requestAffiliationList(MUCOccupant::Member);
- muc_->requestAffiliationList(MUCOccupant::Outcast);
+ 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;
+ for (const auto& change : changes) {
+ if (change.first != MUCOccupant::NoAffiliation) {
+ addedJIDs.insert(change.second);
+ }
+ }
+ for (const auto& change : changes) {
+ if (change.first != MUCOccupant::NoAffiliation || addedJIDs.find(change.second) == addedJIDs.end()) {
+ muc_->changeAffiliation(change.second, change.first);
+ }
+ }
}
void MUCController::handleUnblockUserRequest() {
- eventStream_->send(boost::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, muc_->getJID()));
+ eventStream_->send(std::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);
- }
- }
+ std::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
+ if (blockList->getState() == BlockList::Available) {
+ if (blockList->isBlocked(toJID_)) {
+ if (!blockedContactAlert_) {
+ blockedContactAlert_ = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "You've blocked this room. To enter the room, first unblock it using the cog menu and try again"));
+ }
+ chatWindow_->setBlockingState(ChatWindow::IsBlocked);
+ } else {
+ if (blockedContactAlert_) {
+ chatWindow_->removeAlert(*blockedContactAlert_);
+ blockedContactAlert_.reset();
+ }
+ chatWindow_->setBlockingState(ChatWindow::IsUnblocked);
+ }
+ }
}
void MUCController::handleAffiliationListReceived(MUCOccupant::Affiliation affiliation, const std::vector<JID>& jids) {
- chatWindow_->setAffiliations(affiliation, jids);
+ 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();
+ for (const auto& message : joinContext_) {
+ bool senderIsSelf = nick_ == message.getFromJID().getResource();
- // the chatWindow uses utc timestamps
- addMessage(message.getMessage(), senderDisplayNameFromMessage(message.getFromJID()), senderIsSelf, boost::shared_ptr<SecurityLabel>(new SecurityLabel()), avatarManager_->getAvatarPath(message.getFromJID()), message.getTime() - boost::posix_time::hours(message.getOffset()), HighlightAction());
- }
+ // the chatWindow uses utc timestamps
+ addMessage(chatMessageParser_->parseMessageBody(message.getMessage()), senderDisplayNameFromMessage(message.getFromJID()), senderIsSelf, std::make_shared<SecurityLabel>(), avatarManager_->getAvatarPath(message.getFromJID()), message.getTime() - boost::posix_time::hours(message.getOffset()));
+ }
}
-void MUCController::checkDuplicates(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();
+void MUCController::checkDuplicates(std::shared_ptr<Message> newMessage) {
+ std::string body = newMessage->getBody().get_value_or("");
+ JID jid = newMessage->getFrom();
+ boost::optional<boost::posix_time::ptime> time = newMessage->getTimestamp();
- reverse_foreach (const HistoryMessage& message, joinContext_) {
- 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;
- }
+ for (const auto& message : boost::adaptors::reverse(joinContext_)) {
+ boost::posix_time::ptime messageTime = message.getTime() - boost::posix_time::hours(message.getOffset());
+ if (time && time < messageTime) {
+ break;
+ }
+ if (time && time != messageTime) {
+ continue;
+ }
+ if (message.getFromJID() != jid) {
+ continue;
+ }
+ if (message.getMessage() != body) {
+ continue;
+ }
- // Mark the message as unreadable
- newMessage->setBody("");
- }
+ // 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 = std::make_shared<Form>(Form::SubmitType);
+ std::string impromptuConfigs[] = { "muc#roomconfig_enablelogging", "muc#roomconfig_persistentroom", "muc#roomconfig_publicroom", "muc#roomconfig_whois"};
+ std::set<std::string> impromptuConfigsMissing(impromptuConfigs, impromptuConfigs + 4);
+ for (const auto& field : roomConfigurationForm->getFields()) {
+ std::shared_ptr<FormField> resultField;
+ if (field->getName() == "muc#roomconfig_enablelogging") {
+ resultField = std::make_shared<FormField>(FormField::BooleanType, "0");
+ }
+ if (field->getName() == "muc#roomconfig_persistentroom") {
+ resultField = std::make_shared<FormField>(FormField::BooleanType, "0");
+ }
+ if (field->getName() == "muc#roomconfig_publicroom") {
+ resultField = std::make_shared<FormField>(FormField::BooleanType, "0");
+ }
+ if (field->getName() == "muc#roomconfig_whois") {
+ resultField = std::make_shared<FormField>(FormField::ListSingleType, "anyone");
+ }
+
+ if (field->getName() == "FORM_TYPE") {
+ resultField = std::make_shared<FormField>(FormField::HiddenType, "http://jabber.org/protocol/muc#roomconfig");
+ }
+
+ if (resultField) {
+ impromptuConfigsMissing.erase(field->getName());
+ resultField->setName(field->getName());
+ result->addField(resultField);
+ }
+ }
+
+ for (const auto& config : impromptuConfigsMissing) {
+ if (config == "muc#roomconfig_publicroom") {
+ chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "This server doesn't support hiding your chat from other users.")), ChatWindow::DefaultDirection);
+ } else if (config == "muc#roomconfig_whois") {
+ chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "This server doesn't support sharing people's real identity in this chat.")), ChatWindow::DefaultDirection);
+ }
+ }
+
+ return result;
}
void MUCController::setImpromptuWindowTitle() {
- std::string title;
- typedef std::pair<std::string, MUCOccupant> StringMUCOccupantPair;
- std::map<std::string, MUCOccupant> occupants = muc_->getOccupants();
- if (occupants.size() <= 1) {
- title = QT_TRANSLATE_NOOP("", "Empty Chat");
- } else {
- foreach (StringMUCOccupantPair pair, occupants) {
- if (pair.first != nick_) {
- title += (title.empty() ? "" : ", ") + pair.first;
- }
- }
- }
- chatWindow_->setName(title);
+ std::string title;
+ std::map<std::string, MUCOccupant> occupants = muc_->getOccupants();
+ if (occupants.size() <= 1) {
+ title = QT_TRANSLATE_NOOP("", "Empty Chat");
+ } else {
+ for (const auto& pair : occupants) {
+ if (pair.first != nick_) {
+ title += (title.empty() ? "" : ", ") + pair.first;
+ }
+ }
+ }
+ chatWindow_->setName(title);
}
void MUCController::handleRoomUnlocked() {
- // Handle buggy MUC implementations where the joined room already exists and is unlocked.
- // Configure the room again in this case.
- if (!isImpromptuAlreadyConfigured_) {
- if (isImpromptu_ && (muc_->getOccupant(nick_).getAffiliation() == MUCOccupant::Owner)) {
- muc_->requestConfigurationForm();
- } else if (isImpromptu_) {
- onImpromptuConfigCompleted();
- }
- }
+ // 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();
+void MUCController::setAvailableServerFeatures(std::shared_ptr<DiscoInfo> info) {
+ ChatControllerBase::setAvailableServerFeatures(info);
+ if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::BlockingCommandFeature)) {
+ std::shared_ptr<BlockList> blockList = clientBlockListManager_->getBlockList();
- blockingOnStateChangedConnection_ = blockList->onStateChanged.connect(boost::bind(&MUCController::handleBlockingStateChanged, this));
- blockingOnItemAddedConnection_ = blockList->onItemAdded.connect(boost::bind(&MUCController::handleBlockingStateChanged, this));
- blockingOnItemRemovedConnection_ = blockList->onItemRemoved.connect(boost::bind(&MUCController::handleBlockingStateChanged, this));
+ 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 a08d541..e0ffd7e 100644
--- a/Swift/Controllers/Chat/MUCController.h
+++ b/Swift/Controllers/Chat/MUCController.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <map>
+#include <memory>
#include <set>
#include <string>
-#include <boost/shared_ptr.hpp>
-#include <boost/signals/connection.hpp>
+#include <boost/signals2.hpp>
+#include <boost/signals2/connection.hpp>
#include <Swiften/Base/Override.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/MUCOccupant.h>
#include <Swiften/Elements/Message.h>
@@ -27,159 +27,158 @@
#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 std::string& message, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const boost::posix_time::ptime& time, const HighlightAction& highlight) SWIFTEN_OVERRIDE;
- virtual void postHandleIncomingMessage(boost::shared_ptr<MessageEvent>, const HighlightAction&) 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, std::shared_ptr<ChatMessageParser> chatMessageParser, bool isImpromptu, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider, VCardManager* vcardManager, MUCBookmarkManager* mucBookmarkManager);
+ virtual ~MUCController();
+ boost::signals2::signal<void ()> onUserLeft;
+ boost::signals2::signal<void ()> onUserJoined;
+ boost::signals2::signal<void ()> onImpromptuConfigCompleted;
+ boost::signals2::signal<void (const std::string&, const std::string& )> onUserNicknameChanged;
+ virtual void setOnline(bool online) SWIFTEN_OVERRIDE;
+ virtual void setAvailableServerFeatures(std::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(std::shared_ptr<Message> message) SWIFTEN_OVERRIDE;
+ virtual bool isIncomingMessageFromMe(std::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(std::shared_ptr<Message> message) const SWIFTEN_OVERRIDE;
+ virtual void preHandleIncomingMessage(std::shared_ptr<MessageEvent>) SWIFTEN_OVERRIDE;
+ virtual void addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, std::shared_ptr<SecurityLabel> label, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE;
+ virtual void postHandleIncomingMessage(std::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(std::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(std::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(std::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(std::shared_ptr<UIEvent> event);
+ void addRecentLogs();
+ void checkDuplicates(std::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 shouldJoinOnReconnect_;
+ bool doneGettingHistory_;
+ boost::signals2::scoped_connection avatarChangedConnection_;
+ std::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::signals2::scoped_connection blockingOnStateChangedConnection_;
+ boost::signals2::scoped_connection blockingOnItemAddedConnection_;
+ boost::signals2::scoped_connection blockingOnItemRemovedConnection_;
+
+ boost::optional<ChatWindow::AlertID> blockedContactAlert_;
+
+ MUCBookmarkManager* mucBookmarkManager_;
+ boost::signals2::scoped_connection mucBookmarkManagerBookmarkAddedConnection_;
+ boost::signals2::scoped_connection mucBookmarkManagerBookmarkRemovedConnection_;
+ };
}
diff --git a/Swift/Controllers/Chat/MUCSearchController.cpp b/Swift/Controllers/Chat/MUCSearchController.cpp
index d40f427..5db917a 100644
--- a/Swift/Controllers/Chat/MUCSearchController.cpp
+++ b/Swift/Controllers/Chat/MUCSearchController.cpp
@@ -1,183 +1,183 @@
/*
- * Copyright (c) 2010-2011 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/Chat/MUCSearchController.h"
+#include <Swift/Controllers/Chat/MUCSearchController.h>
#include <iostream>
+#include <memory>
#include <boost/bind.hpp>
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Disco/GetDiscoItemsRequest.h>
#include <Swiften/Base/Log.h>
#include <Swiften/Base/String.h>
+#include <Swiften/Client/NickResolver.h>
+#include <Swiften/Disco/DiscoServiceWalker.h>
+#include <Swiften/Disco/GetDiscoItemsRequest.h>
+
#include <Swift/Controllers/UIEvents/UIEventStream.h>
#include <Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h>
-#include <Swiften/Disco/DiscoServiceWalker.h>
-#include <Swiften/Client/NickResolver.h>
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();
+MUCSearchController::MUCSearchController(const JID& jid, MUCSearchWindowFactory* factory, IQRouter* iqRouter, ProfileSettingsProvider* settings) : jid_(jid), factory_(factory), iqRouter_(iqRouter), settings_(settings), window_(nullptr), walker_(nullptr) {
+ 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();
+ for (auto&& 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;
+ for (auto&& 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();
+void MUCSearchController::handleDiscoServiceFound(const JID& jid, std::shared_ptr<DiscoInfo> info) {
+ bool isMUC = false;
+ std::string name;
+ for (auto&& 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();
+void MUCSearchController::handleRoomsItemsResponse(std::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();
+ for (auto&& 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();
+ for (auto&& 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 068c930..f853bcd 100644
--- a/Swift/Controllers/Chat/MUCSearchController.h
+++ b/Swift/Controllers/Chat/MUCSearchController.h
@@ -1,124 +1,124 @@
/*
- * Copyright (c) 2010-2011 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <map>
+#include <memory>
+#include <string>
+#include <vector>
-#include <boost/shared_ptr.hpp>
-#include "Swiften/Base/boost_bsignals.h"
+#include <boost/signals2.hpp>
-#include <string>
-#include "Swiften/JID/JID.h"
+#include <Swiften/Elements/DiscoInfo.h>
+#include <Swiften/Elements/DiscoItems.h>
+#include <Swiften/Elements/ErrorPayload.h>
+#include <Swiften/JID/JID.h>
-#include "Swift/Controllers/UIEvents/UIEvent.h"
-#include "Swift/Controllers/ProfileSettingsProvider.h"
-#include "Swiften/Elements/DiscoInfo.h"
-#include "Swiften/Elements/DiscoItems.h"
-#include "Swiften/Elements/ErrorPayload.h"
+#include <Swift/Controllers/ProfileSettingsProvider.h>
+#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::signals2::signal<void (const JID&)> onMUCSelected;
+
+ private:
+ void handleSearchService(const JID& jid);
+ void handleRoomsItemsResponse(std::shared_ptr<DiscoItems> items, ErrorPayload::ref error, const JID& jid);
+ void handleDiscoError(const JID& jid, ErrorPayload::ref error);
+ void handleDiscoServiceFound(const JID&, std::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 1b92bb6..bc72b33 100644
--- a/Swift/Controllers/Chat/UnitTest/ChatMessageParserTest.cpp
+++ b/Swift/Controllers/Chat/UnitTest/ChatMessageParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,266 +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 assertHighlight(const ChatWindow::ChatMessage& result, size_t index, const std::string& text) {
- boost::shared_ptr<ChatWindow::ChatHighlightingMessagePart> part = boost::dynamic_pointer_cast<ChatWindow::ChatHighlightingMessagePart>(result.getParts()[index]);
- CPPUNIT_ASSERT_EQUAL(text, part->text);
- }
-
- 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);
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, false));
- 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");
- 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");
- 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");
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, false));
- result = testling.parseMessageBody("partialTrIgGeRmatch");
- assertText(result, 0, "partial");
- assertHighlight(result, 1, "TrIgGeR");
- 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");
- assertText(result, 2, " two ");
- assertHighlight(result, 3, "three");
-
- 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");
- assertText(result, 2, " two ");
- assertHighlight(result, 3, "tHrEe");
-
- 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");
- 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");
- assertText(result, 2, "two");
- assertHighlight(result, 3, "three");
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", true, false), ruleFromKeyword("three", false, false)));
- result = testling.parseMessageBody("zeroOnEtwoThReE");
- assertText(result, 0, "zeroOnEtwo");
- assertHighlight(result, 1, "ThReE");
-
- testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, true), ruleFromKeyword("three", false, false)));
- result = testling.parseMessageBody("zeroonetwothree");
- assertText(result, 0, "zeroonetwo");
- assertHighlight(result, 1, "three");
-
- 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");
-
- 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");
- assertText(result, 2, " Text");
-
- testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight());
- result = testling.parseMessageBody("Alice Text", "Alice");
- assertHighlight(result, 0, "Alice");
- assertText(result, 1, " Text");
-
- testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight());
- result = testling.parseMessageBody("Text Alice", "Alice");
- assertText(result, 0, "Text ");
- assertHighlight(result, 1, "Alice");
- }
-
- 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");
- }
+ 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) {
+ std::shared_ptr<ChatWindow::ChatTextMessagePart> part = std::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) {
+ std::shared_ptr<ChatWindow::ChatEmoticonMessagePart> part = std::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) \
+ { \
+ std::shared_ptr<ChatWindow::ChatHighlightingMessagePart> part = std::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) {
+ std::shared_ptr<ChatWindow::ChatURIMessagePart> part = std::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)
+ {
+ std::shared_ptr<HighlightManager::HighlightRulesList> list = std::make_shared<HighlightManager::HighlightRulesList>();
+ list->addRule(ruleFromKeyword(keyword, matchCase, matchWholeWord));
+ return list;
+ }
+
+ static const HighlightRulesListPtr ruleListFromKeywords(const HighlightRule &rule1, const HighlightRule &rule2)
+ {
+ std::shared_ptr<HighlightManager::HighlightRulesList> list = std::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");
+ }
+ std::shared_ptr<HighlightManager::HighlightRulesList> list = std::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_, std::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_, std::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_, std::make_shared<HighlightManager::HighlightRulesList>());
+ ChatWindow::ChatMessage result = testling.parseMessageBody(":)");
+ assertEmoticon(result, 0, smile1_, smile1Path_);
+ }
+
+ void testHiddenEmoticon() {
+ ChatMessageParser testling(emoticons_, std::make_shared<HighlightManager::HighlightRulesList>());
+ ChatWindow::ChatMessage result = testling.parseMessageBody("b:)a");
+ assertText(result, 0, "b:)a");
+ }
+
+ void testEndlineEmoticon() {
+ ChatMessageParser testling(emoticons_, std::make_shared<HighlightManager::HighlightRulesList>());
+ ChatWindow::ChatMessage result = testling.parseMessageBody("Lazy:)");
+ assertText(result, 0, "Lazy");
+ assertEmoticon(result, 1, smile1_, smile1Path_);
+ }
+
+ void testBoundedEmoticons() {
+ ChatMessageParser testling(emoticons_, std::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_, std::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 4f8cf5a..cff54f8 100644
--- a/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp
+++ b/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp
@@ -4,6 +4,9 @@
* See the COPYING file for more information.
*/
+#include <map>
+#include <set>
+
#include <boost/bind.hpp>
#include <cppunit/extensions/HelperMacros.h>
@@ -20,8 +23,13 @@
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
#include <Swiften/Disco/DummyEntityCapsProvider.h>
+#include <Swiften/Elements/CarbonsReceived.h>
+#include <Swiften/Elements/CarbonsSent.h>
#include <Swiften/Elements/DeliveryReceipt.h>
#include <Swiften/Elements/DeliveryReceiptRequest.h>
+#include <Swiften/Elements/Forwarded.h>
+#include <Swiften/Elements/MUCInvitationPayload.h>
+#include <Swiften/Elements/MUCUserPayload.h>
#include <Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h>
#include <Swiften/Jingle/JingleSessionManager.h>
#include <Swiften/MUC/MUCManager.h>
@@ -58,723 +66,1124 @@
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_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(testLocalMUCServiceDiscoveryResetOnDisconnect);
+ CPPUNIT_TEST(testPresenceChangeDoesNotReplaceMUCInvite);
+
+ // MUC PM Tests
+ CPPUNIT_TEST(testChatControllerPMPresenceHandling);
+ CPPUNIT_TEST(testChatControllerMucPmUnavailableErrorHandling);
+
+ // Highlighting tests
+ CPPUNIT_TEST(testChatControllerHighlightingNotificationTesting);
+ CPPUNIT_TEST(testChatControllerHighlightingNotificationDeduplicateSounds);
+ CPPUNIT_TEST(testChatControllerMeMessageHandling);
+ CPPUNIT_TEST(testRestartingMUCComponentCrash);
+ CPPUNIT_TEST(testChatControllerMeMessageHandlingInMUC);
+
+ // Carbons tests
+ CPPUNIT_TEST(testCarbonsForwardedIncomingMessageToSecondResource);
+ CPPUNIT_TEST(testCarbonsForwardedOutgoingMessageFromSecondResource);
+
+ CPPUNIT_TEST_SUITE_END();
public:
- void setUp() {
- mocks_ = new MockRepository();
- jid_ = JID("test@test.com/resource");
- stanzaChannel_ = new DummyStanzaChannel();
- 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_);
-
- 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_->InterfaceMock<ChatWindow>();
- 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 setUp() {
+ mocks_ = new MockRepository();
+ jid_ = JID("test@test.com/resource");
+ stanzaChannel_ = new DummyStanzaChannel();
+ iqRouter_ = new IQRouter(stanzaChannel_);
+ eventController_ = new EventController();
+ chatWindowFactory_ = mocks_->InterfaceMock<ChatWindowFactory>();
+ joinMUCWindowFactory_ = mocks_->InterfaceMock<JoinMUCWindowFactory>();
+ xmppRoster_ = new XMPPRosterImpl();
+ mucRegistry_ = new MUCRegistry();
+ nickResolver_ = new NickResolver(jid_.toBare(), xmppRoster_, nullptr, mucRegistry_);
+ presenceOracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_);
+ serverDiscoInfo_ = std::make_shared<DiscoInfo>();
+ presenceSender_ = new StanzaChannelPresenceSender(stanzaChannel_);
+ directedPresenceSender_ = new DirectedPresenceSender(presenceSender_);
+ mucManager_ = new MUCManager(stanzaChannel_, iqRouter_, directedPresenceSender_, mucRegistry_);
+ uiEventStream_ = new UIEventStream();
+ entityCapsProvider_ = new DummyEntityCapsProvider();
+ chatListWindowFactory_ = mocks_->InterfaceMock<ChatListWindowFactory>();
+ mucSearchWindowFactory_ = mocks_->InterfaceMock<MUCSearchWindowFactory>();
+ settings_ = new DummySettingsProvider();
+ 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_);
+ highlightManager_->resetToDefaultRulesList();
+ 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, nullptr, mucRegistry_, entityCapsProvider_, mucManager_, mucSearchWindowFactory_, profileSettings_, ftOverview_, xmppRoster_, false, settings_, nullptr, wbManager_, highlightManager_, clientBlockListManager_, emoticons_, vcardManager_);
+
+ manager_->setAvatarManager(avatarManager_);
+ }
+
+ void tearDown() {
+ delete highlightManager_;
+ 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 iqRouter_;
+ delete stanzaChannel_;
+ delete eventController_;
+ 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);
+
+ std::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, MockChatWindow::bodyFromMessage(window->lastAddedMessage_));
+ }
+
+ void testSecondOpenWindowIncoming() {
+ JID messageJID1("testling@test.com/resource1");
+
+ MockChatWindow* window1 = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID1, uiEventStream_).Return(window1);
+
+ std::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, MockChatWindow::bodyFromMessage(window1->lastAddedMessage_));
+
+ JID messageJID2("testling@test.com/resource2");
+
+ std::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, MockChatWindow::bodyFromMessage(window1->lastAddedMessage_));
+ }
+
+ void testFirstOpenWindowOutgoing() {
+ std::string messageJIDString("testling@test.com");
+
+ ChatWindow* window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString), uiEventStream_).Return(window);
+
+ uiEventStream_->send(std::make_shared<RequestChatUIEvent>(JID(messageJIDString)));
+ }
+
+
+ void testFirstOpenWindowBareToFull() {
+ std::string bareJIDString("testling@test.com");
+ std::string fullJIDString("testling@test.com/resource1");
+
+ MockChatWindow* window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(bareJIDString), uiEventStream_).Return(window);
+ uiEventStream_->send(std::make_shared<RequestChatUIEvent>(JID(bareJIDString)));
+
+ std::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, MockChatWindow::bodyFromMessage(window->lastAddedMessage_));
+ }
+
+ void testSecondWindow() {
+ std::string messageJIDString1("testling1@test.com");
+ ChatWindow* window1 = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString1), uiEventStream_).Return(window1);
+ uiEventStream_->send(std::make_shared<RequestChatUIEvent>(JID(messageJIDString1)));
+
+ std::string messageJIDString2("testling2@test.com");
+ ChatWindow* window2 = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString2), uiEventStream_).Return(window2);
+
+ uiEventStream_->send(std::make_shared<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_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(bareJIDString), uiEventStream_).Return(window);
+ uiEventStream_->send(std::make_shared<RequestChatUIEvent>(JID(bareJIDString)));
+
+ std::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, MockChatWindow::bodyFromMessage(window->lastAddedMessage_));
+
+ std::shared_ptr<Presence> jid1Online(new Presence());
+ jid1Online->setFrom(JID(fullJIDString1));
+ std::shared_ptr<Presence> jid1Offline(new Presence());
+ jid1Offline->setFrom(JID(fullJIDString1));
+ jid1Offline->setType(Presence::Unavailable);
+ presenceOracle_->onPresenceChange(jid1Offline);
+
+ std::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, MockChatWindow::bodyFromMessage(window->lastAddedMessage_));
+ }
+
+ /**
+ * 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(std::make_shared<JoinMUCUIEvent>(muc, std::string("nick")));
+
+
+ std::string messageJIDString1("testling@test.com/1");
+ ChatWindow* window1 = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString1), uiEventStream_).Return(window1);
+ uiEventStream_->send(std::make_shared<RequestChatUIEvent>(JID(messageJIDString1)));
+
+ std::string messageJIDString2("testling@test.com/2");
+ ChatWindow* window2 = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString2), uiEventStream_).Return(window2);
+
+ uiEventStream_->send(std::make_shared<RequestChatUIEvent>(JID(messageJIDString2)));
+
+ std::string messageJIDString3("testling@test.com/3");
+ ChatWindow* window3 = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString3), uiEventStream_).Return(window3);
+
+ uiEventStream_->send(std::make_shared<RequestChatUIEvent>(JID(messageJIDString3)));
+
+ /* Refetch an earlier window */
+ /* We do not expect a new window to be created */
+ uiEventStream_->send(std::make_shared<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_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID1, uiEventStream_).Return(window1);
+
+ std::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");
+
+ std::shared_ptr<Message> message2(new Message());
+ message2->setFrom(messageJID2);
+ message2->setBody("This is a legible message2.");
+ manager_->handleIncomingMessage(message2);
+
+ std::shared_ptr<Presence> jid1Online(new Presence());
+ jid1Online->setFrom(JID(messageJID1));
+ std::shared_ptr<Presence> jid1Offline(new Presence());
+ jid1Offline->setFrom(JID(messageJID1));
+ jid1Offline->setType(Presence::Unavailable);
+ presenceOracle_->onPresenceChange(jid1Offline);
+
+ std::shared_ptr<Presence> jid2Online(new Presence());
+ jid2Online->setFrom(JID(messageJID2));
+ std::shared_ptr<Presence> jid2Offline(new Presence());
+ jid2Offline->setFrom(JID(messageJID2));
+ jid2Offline->setType(Presence::Unavailable);
+ presenceOracle_->onPresenceChange(jid2Offline);
+
+ JID messageJID3("testling@test.com/resource3");
+
+ std::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, MockChatWindow::bodyFromMessage(window1->lastAddedMessage_));
+
+ std::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, MockChatWindow::bodyFromMessage(window1->lastAddedMessage_));
+ }
+
+ /**
+ * 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);
+
+ std::shared_ptr<Message> message = makeDeliveryReceiptTestMessage(messageJID, "1");
+ manager_->handleIncomingMessage(message);
+ Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex<Stanza>(1);
+ CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->countSentStanzaOfType<Message>());
+ CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload<DeliveryReceipt>() != nullptr);
+
+ xmppRoster_->removeContact(messageJID);
+
+ message->setID("2");
+ manager_->handleIncomingMessage(message);
+ CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->countSentStanzaOfType<Message>());
+ }
+
+ /**
+ * 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_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
+ settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true);
+
+ std::shared_ptr<Message> message = makeDeliveryReceiptTestMessage(messageJID, "1");
+ manager_->handleIncomingMessage(message);
+
+ CPPUNIT_ASSERT_EQUAL(st(0), stanzaChannel_->countSentStanzaOfType<Message>());
+
+ xmppRoster_->addContact(messageJID, "foo", std::vector<std::string>(), RosterItemPayload::Both);
+ message->setID("2");
+ manager_->handleIncomingMessage(message);
+
+ CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->countSentStanzaOfType<Message>());
+ Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex<Stanza>(1);
+ CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload<DeliveryReceipt>() != nullptr);
+ }
+
+ /**
+ * Test that ChatController sends receipts if requested after change from subscription state To to subscription state Both.
+ */
+ void testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToBoth() {
+ testhelperChatControllerPresenceAccessUpdatedOnSubscriptionChangeReceiptsAllowed(RosterItemPayload::To, RosterItemPayload::Both);
+ }
+
+ /**
+ * Test that ChatController sends receipts if requested after change from subscription state To to subscription state From.
+ */
+ void testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToFrom() {
+ testhelperChatControllerPresenceAccessUpdatedOnSubscriptionChangeReceiptsAllowed(RosterItemPayload::To, RosterItemPayload::From);
+ }
+
+ void testChatControllerFullJIDBindingOnMessageAndNotReceipt() {
+ JID ownJID("test@test.com/resource");
+ JID sender("foo@test.com");
+ std::vector<JID> senderResource;
+ senderResource.push_back(sender.withResource("resourceA"));
+ senderResource.push_back(sender.withResource("resourceB"));
+
+ // We support delivery receipts.
+ settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true);
+
+ // Open chat window to a sender.
+ MockChatWindow* window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(sender, uiEventStream_).Return(window);
+
+ uiEventStream_->send(std::make_shared<RequestChatUIEvent>(sender));
+
+ for (const auto& senderJID : senderResource) {
+ // The sender supports delivery receipts.
+ DiscoInfo::ref disco = std::make_shared<DiscoInfo>();
+ disco->addFeature(DiscoInfo::MessageDeliveryReceiptsFeature);
+ entityCapsProvider_->caps[senderJID] = disco;
+
+ // The sender is online.
+ Presence::ref senderPresence = std::make_shared<Presence>();
+ senderPresence->setFrom(senderJID);
+ senderPresence->setTo(ownJID);
+ stanzaChannel_->onPresenceReceived(senderPresence);
+
+ entityCapsProvider_->onCapsChanged(senderJID);
+ }
+
+ // Send first message.
+ window->onSendMessageRequest("hello there", false);
+
+ // A bare message is send because no resources is bound.
+ CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex<Message>(1)->getTo());
+ CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(1)->getPayload<DeliveryReceiptRequest>());
+
+ // Two resources respond with message receipts.
+ for (const auto& senderJID : senderResource) {
+ Message::ref receiptReply = std::make_shared<Message>();
+ receiptReply->setFrom(senderJID);
+ receiptReply->setTo(ownJID);
+
+ std::shared_ptr<DeliveryReceipt> receipt = std::make_shared<DeliveryReceipt>();
+ receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex<Message>(1)->getID());
+ receiptReply->addPayload(receipt);
+ manager_->handleIncomingMessage(receiptReply);
+ }
+
+ // Send second message.
+ window->onSendMessageRequest("how are you?", false);
+
+ // A bare message is send because no resources is bound.
+ CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex<Message>(1)->getTo());
+ CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(1)->getPayload<DeliveryReceiptRequest>());
+
+ // Two resources respond with message receipts.
+ for (const auto& senderJID : senderResource) {
+ Message::ref receiptReply = std::make_shared<Message>();
+ receiptReply->setFrom(senderJID);
+ receiptReply->setTo(ownJID);
+
+ std::shared_ptr<DeliveryReceipt> receipt = std::make_shared<DeliveryReceipt>();
+ receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex<Message>(1)->getID());
+ receiptReply->addPayload(receipt);
+ manager_->handleIncomingMessage(receiptReply);
+ }
+
+ // Reply with a message including a body text.
+ Message::ref reply = std::make_shared<Message>();
+ reply->setFrom(senderResource[0]);
+ reply->setTo(ownJID);
+ reply->setBody("fine.");
+ manager_->handleIncomingMessage(reply);
+
+ // Send third message.
+ window->onSendMessageRequest("great to hear.", false);
+
+ // The chat session is bound to the full JID of the first resource.
+ CPPUNIT_ASSERT_EQUAL(senderResource[0], stanzaChannel_->getStanzaAtIndex<Message>(3)->getTo());
+ CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(2)->getPayload<DeliveryReceiptRequest>());
+
+ // Receive random receipt from second sender resource.
+ reply = std::make_shared<Message>();
+ reply->setFrom(senderResource[1]);
+ reply->setTo(ownJID);
+
+ std::shared_ptr<DeliveryReceipt> receipt = std::make_shared<DeliveryReceipt>();
+ 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 = std::make_shared<Message>();
+ reply->setFrom(senderResource[1]);
+ reply->setTo(ownJID);
+ reply->setBody("nothing.");
+ manager_->handleIncomingMessage(reply);
+
+ // Send fifth message.
+ window->onSendMessageRequest("okay", false);
+
+ // The chat session is now bound to the full JID of the second resource.
+ CPPUNIT_ASSERT_EQUAL(senderResource[1], stanzaChannel_->getStanzaAtIndex<Message>(5)->getTo());
+ CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(5)->getPayload<DeliveryReceiptRequest>());
+ }
+
+ void testChatControllerFullJIDBindingOnTypingAndNotActive() {
+ JID ownJID("test@test.com/resource");
+ JID sender("foo@test.com");
+ std::vector<JID> senderResource;
+ senderResource.push_back(sender.withResource("resourceA"));
+ senderResource.push_back(sender.withResource("resourceB"));
+
+ // We support delivery receipts.
+ settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true);
+
+ // Open chat window to a sender.
+ MockChatWindow* window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(sender, uiEventStream_).Return(window);
+
+ uiEventStream_->send(std::make_shared<RequestChatUIEvent>(sender));
+
+ for (const auto& senderJID : senderResource) {
+ // The sender supports delivery receipts.
+ DiscoInfo::ref disco = std::make_shared<DiscoInfo>();
+ disco->addFeature(DiscoInfo::MessageDeliveryReceiptsFeature);
+ entityCapsProvider_->caps[senderJID] = disco;
+
+ // The sender is online.
+ Presence::ref senderPresence = std::make_shared<Presence>();
+ senderPresence->setFrom(senderJID);
+ senderPresence->setTo(ownJID);
+ stanzaChannel_->onPresenceReceived(senderPresence);
+
+ entityCapsProvider_->onCapsChanged(senderJID);
+ }
+
+ // Send first message.
+ window->onSendMessageRequest("hello there", false);
+
+ // A bare message is send because no resources is bound.
+ CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex<Message>(1)->getTo());
+ CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(1)->getPayload<DeliveryReceiptRequest>());
+
+ // Two resources respond with message receipts.
+ for (const auto& senderJID : senderResource) {
+ Message::ref reply = std::make_shared<Message>();
+ reply->setFrom(senderJID);
+ reply->setTo(ownJID);
+
+ std::shared_ptr<ChatState> csn = std::make_shared<ChatState>();
+ csn->setChatState(ChatState::Active);
+ reply->addPayload(csn);
+ manager_->handleIncomingMessage(reply);
+ }
+
+ // Send second message.
+ window->onSendMessageRequest("how are you?", false);
+
+ // A bare message is send because no resources is bound.
+ CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex<Message>(1)->getTo());
+ CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(1)->getPayload<DeliveryReceiptRequest>());
+
+ // Two resources respond with message receipts.
+ for (const auto& senderJID : senderResource) {
+ Message::ref receiptReply = std::make_shared<Message>();
+ receiptReply->setFrom(senderJID);
+ receiptReply->setTo(ownJID);
+
+ std::shared_ptr<DeliveryReceipt> receipt = std::make_shared<DeliveryReceipt>();
+ receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex<Message>(1)->getID());
+ receiptReply->addPayload(receipt);
+ manager_->handleIncomingMessage(receiptReply);
+ }
+
+ // Reply with a message including a CSN.
+ Message::ref reply = std::make_shared<Message>();
+ reply->setFrom(senderResource[0]);
+ reply->setTo(ownJID);
+
+ std::shared_ptr<ChatState> csn = std::make_shared<ChatState>();
+ csn->setChatState(ChatState::Composing);
+ reply->addPayload(csn);
+ manager_->handleIncomingMessage(reply);
+
+ // Send third message.
+ window->onSendMessageRequest("great to hear.", false);
+
+ // The chat session is now bound to the full JID of the first resource due to its recent composing message.
+ CPPUNIT_ASSERT_EQUAL(senderResource[0], stanzaChannel_->getStanzaAtIndex<Message>(3)->getTo());
+ CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(3)->getPayload<DeliveryReceiptRequest>());
+
+ // Reply with a message including a CSN from the other resource.
+ reply = std::make_shared<Message>();
+ reply->setFrom(senderResource[1]);
+ reply->setTo(ownJID);
+
+ csn = std::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>(4)->getTo());
+ CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex<Message>(4)->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(std::make_shared<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 testChatControllerMucPmUnavailableErrorHandling() {
+ auto mucJID = JID("test@rooms.test.com");
+ auto participantA = mucJID.withResource("participantA");
+ auto participantB = mucJID.withResource("participantB");
+
+ auto mucWindow = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(mucJID, uiEventStream_).Return(mucWindow);
+ uiEventStream_->send(std::make_shared<JoinMUCUIEvent>(mucJID, participantB.getResource()));
+ CPPUNIT_ASSERT_EQUAL(true, mucWindow->mucType_.is_initialized());
+
+ auto window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(participantA, uiEventStream_).Return(window);
+ uiEventStream_->send(std::make_shared<RequestChatUIEvent>(participantA));
+ CPPUNIT_ASSERT_EQUAL(false, window->mucType_.is_initialized());
+
+ 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_));
+
+ // send message to participantA
+ auto messageBody = std::string("message body to send");
+ window->onSendMessageRequest(messageBody, false);
+ auto sendMessageStanza = stanzaChannel_->getStanzaAtIndex<Message>(2);
+ CPPUNIT_ASSERT_EQUAL(messageBody, *sendMessageStanza->getBody());
+
+ // receive reply with error
+ auto messageErrorReply = std::make_shared<Message>();
+ messageErrorReply->setID(stanzaChannel_->getNewIQID());
+ messageErrorReply->setType(Message::Error);
+ messageErrorReply->setFrom(participantA);
+ messageErrorReply->setTo(jid_);
+ messageErrorReply->addPayload(std::make_shared<ErrorPayload>(ErrorPayload::ItemNotFound, ErrorPayload::Cancel, "Recipient not in room"));
+
+ auto lastMUCWindowErrorMessageBeforeError = MockChatWindow::bodyFromMessage(mucWindow->lastAddedErrorMessage_);
+ manager_->handleIncomingMessage(messageErrorReply);
+
+ // assert that error is not routed to MUC window
+ CPPUNIT_ASSERT_EQUAL(lastMUCWindowErrorMessageBeforeError, MockChatWindow::bodyFromMessage(mucWindow->lastAddedErrorMessage_));
+ // assert that error is routed to PM
+ CPPUNIT_ASSERT_EQUAL(std::string("This user could not be found in the room."), MockChatWindow::bodyFromMessage(window->lastAddedErrorMessage_));
+ }
+
+ 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(std::make_shared<RequestChatUIEvent>(sender));
+
+ CPPUNIT_ASSERT_EQUAL(false, window->impromptuMUCSupported_);
+
+ std::shared_ptr<IQ> infoRequest = std::dynamic_pointer_cast<IQ>(stanzaChannel_->sentStanzas[1]);
+ std::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(std::make_shared<DiscoInfo>(info));
+ stanzaChannel_->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);
+
+ std::shared_ptr<Message> message = makeDeliveryReceiptTestMessage(messageJID, "1");
+ manager_->handleIncomingMessage(message);
+
+ CPPUNIT_ASSERT_EQUAL(st(0), stanzaChannel_->countSentStanzaOfType<Message>());
+
+ xmppRoster_->addContact(messageJID, "foo", std::vector<std::string>(), to);
+ message->setID("2");
+ manager_->handleIncomingMessage(message);
+
+ CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->countSentStanzaOfType<Message>());
+ Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex<Stanza>(1);
+ CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload<DeliveryReceipt>() != nullptr);
+ }
+
+ 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);
+
+ std::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);
+
+ std::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 testChatControllerMeMessageHandling() {
+ JID messageJID("testling@test.com/resource1");
+
+ MockChatWindow* window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
+
+ std::shared_ptr<Message> message(new Message());
+ message->setFrom(messageJID);
+ std::string body("/me is feeling delighted.");
+ message->setBody(body);
+ manager_->handleIncomingMessage(message);
+ CPPUNIT_ASSERT_EQUAL(std::string("is feeling delighted."), window->bodyFromMessage(window->lastAddedAction_));
+ }
+
+ void testRestartingMUCComponentCrash() {
+ JID mucJID = JID("teaparty@rooms.wonderland.lit");
+ JID self = JID("girl@wonderland.lit/rabbithole");
+ std::string nick = "aLiCe";
+
+ MockChatWindow* window;
+
+ auto genRemoteMUCPresence = [=]() {
+ auto presence = Presence::create();
+ presence->setFrom(mucJID.withResource(nick));
+ presence->setTo(self);
+ return presence;
+ };
+
+ // User rejoins.
+ window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(mucJID, uiEventStream_).Return(window);
+
+ // Join room
+ {
+ auto joinRoomEvent = std::make_shared<JoinMUCUIEvent>(mucJID, boost::optional<std::string>(), nick);
+ uiEventStream_->send(joinRoomEvent);
+ }
+
+ {
+ auto firstPresence = genRemoteMUCPresence();
+ firstPresence->setType(Presence::Unavailable);
+ auto userPayload = std::make_shared<MUCUserPayload>();
+ userPayload->addItem(MUCItem(MUCOccupant::Owner, MUCOccupant::NoRole));
+ firstPresence->addPayload(userPayload);
+ stanzaChannel_->onPresenceReceived(firstPresence);
+ }
+ CPPUNIT_ASSERT_EQUAL(std::string("Couldn't enter room: Unable to enter this room."), MockChatWindow::bodyFromMessage(window->lastAddedErrorMessage_));
+
+ {
+ auto presence = genRemoteMUCPresence();
+ presence->setType(Presence::Unavailable);
+ auto userPayload = std::make_shared<MUCUserPayload>();
+ userPayload->addStatusCode(303);
+ auto item = MUCItem(MUCOccupant::Owner, self, MUCOccupant::Moderator);
+ item.nick = nick;
+ userPayload->addItem(item);
+ userPayload->addStatusCode(110);
+ presence->addPayload(userPayload);
+ stanzaChannel_->onPresenceReceived(presence);
+ }
+ }
+
+ void testChatControllerMeMessageHandlingInMUC() {
+ JID mucJID("mucroom@rooms.test.com");
+ std::string nickname = "toodles";
+
+ // add highlight rule for 'foo'
+ HighlightRule fooHighlight;
+ fooHighlight.setKeywords({"foo"});
+ fooHighlight.setMatchMUC(true);
+ fooHighlight.getAction().setTextBackground("green");
+ highlightManager_->insertRule(0, fooHighlight);
+
+ MockChatWindow* window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(mucJID, uiEventStream_).Return(window);
+
+ uiEventStream_->send(std::make_shared<JoinMUCUIEvent>(mucJID, boost::optional<std::string>(), nickname));
+
+ auto genRemoteMUCPresence = [=]() {
+ auto presence = Presence::create();
+ presence->setFrom(mucJID.withResource(nickname));
+ presence->setTo(jid_);
+ return presence;
+ };
+
+ {
+ auto presence = genRemoteMUCPresence();
+ auto userPayload = std::make_shared<MUCUserPayload>();
+ userPayload->addStatusCode(110);
+ userPayload->addItem(MUCItem(MUCOccupant::Owner, jid_, MUCOccupant::Moderator));
+ presence->addPayload(userPayload);
+ stanzaChannel_->onPresenceReceived(presence);
+ }
+
+ {
+ auto presence = genRemoteMUCPresence();
+ presence->setFrom(mucJID.withResource("someDifferentNickname"));
+ auto userPayload = std::make_shared<MUCUserPayload>();
+ userPayload->addItem(MUCItem(MUCOccupant::Member, JID("foo@bar.com"), MUCOccupant::Moderator));
+ presence->addPayload(userPayload);
+ stanzaChannel_->onPresenceReceived(presence);
+ }
+
+ window->onSendMessageRequest("/me sends a test message with foo", false);
+
+ window->resetLastMessages();
+ {
+ Message::ref mucMirrored = std::make_shared<Message>();
+ mucMirrored->setFrom(mucJID.withResource(nickname));
+ mucMirrored->setTo(jid_);
+ mucMirrored->setType(Message::Groupchat);
+ mucMirrored->setBody("/me sends a test message with foo");
+ manager_->handleIncomingMessage(mucMirrored);
+ }
+ CPPUNIT_ASSERT_EQUAL(std::string("sends a test message with foo"), window->bodyFromMessage(window->lastAddedAction_));
+
+ window->resetLastMessages();
+ {
+ Message::ref mucMirrored = std::make_shared<Message>();
+ mucMirrored->setFrom(mucJID.withResource("someDifferentNickname"));
+ mucMirrored->setTo(jid_);
+ mucMirrored->setType(Message::Groupchat);
+ mucMirrored->setBody("/me says hello with a test message with foo and foo");
+ manager_->handleIncomingMessage(mucMirrored);
+ }
+ CPPUNIT_ASSERT_EQUAL(std::string("says hello with a test message with foo and foo"), window->bodyFromMessage(window->lastAddedAction_));
+ }
+
+ void testPresenceChangeDoesNotReplaceMUCInvite() {
+ JID messageJID("testling@test.com/resource1");
+
+ auto generateIncomingPresence = [=](Presence::Type type) {
+ auto presence = std::make_shared<Presence>();
+ presence->setType(type);
+ presence->setFrom(messageJID);
+ presence->setTo(jid_);
+ return presence;
+ };
+
+ stanzaChannel_->onPresenceReceived(generateIncomingPresence(Presence::Available));
+
+ MockChatWindow* window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
+
+ std::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, MockChatWindow::bodyFromMessage(window->lastAddedMessage_));
+
+ auto incomingMUCInvite = std::make_shared<Message>();
+ incomingMUCInvite->setFrom(messageJID);
+
+ auto invitePayload = std::make_shared<MUCInvitationPayload>();
+ invitePayload->setJID("room@muc.service.com");
+ incomingMUCInvite->addPayload(invitePayload);
+
+ stanzaChannel_->onPresenceReceived(generateIncomingPresence(Presence::Unavailable));
+ stanzaChannel_->onPresenceReceived(generateIncomingPresence(Presence::Available));
+
+ window->resetLastMessages();
+
+ manager_->handleIncomingMessage(incomingMUCInvite);
+ CPPUNIT_ASSERT_EQUAL(JID("room@muc.service.com"), window->lastMUCInvitationJID_);
+
+ stanzaChannel_->onPresenceReceived(generateIncomingPresence(Presence::Unavailable));
+ CPPUNIT_ASSERT_EQUAL(std::string(""), MockChatWindow::bodyFromMessage(window->lastReplacedMessage_));
+ CPPUNIT_ASSERT_EQUAL(std::string("testling@test.com has gone offline."), MockChatWindow::bodyFromMessage(window->lastAddedPresence_));
+ }
+
+ template <typename CarbonsType>
+ Message::ref createCarbonsMessage(std::shared_ptr<CarbonsType> carbons, std::shared_ptr<Message> forwardedMessage) {
+ auto messageWrapper = std::make_shared<Message>();
+ messageWrapper->setFrom(jid_.toBare());
+ messageWrapper->setTo(jid_);
+ messageWrapper->setType(Message::Chat);
+
+ messageWrapper->addPayload(carbons);
+ auto forwarded = std::make_shared<Forwarded>();
+ carbons->setForwarded(forwarded);
+ forwarded->setStanza(forwardedMessage);
+ return messageWrapper;
+ }
+
+ void testCarbonsForwardedIncomingMessageToSecondResource() {
+ JID messageJID("testling@test.com/resource1");
+ JID jid2 = jid_.toBare().withResource("someOtherResource");
+
+ MockChatWindow* window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
+
+ std::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, MockChatWindow::bodyFromMessage(window->lastAddedMessage_));
+
+ // incoming carbons message from another resource
+ {
+ auto originalMessage = std::make_shared<Message>();
+ originalMessage->setFrom(messageJID);
+ originalMessage->setTo(jid2);
+ originalMessage->setType(Message::Chat);
+ std::string forwardedBody = "Some further text.";
+ originalMessage->setBody(forwardedBody);
+
+ auto messageWrapper = createCarbonsMessage(std::make_shared<CarbonsReceived>(), originalMessage);
+
+ manager_->handleIncomingMessage(messageWrapper);
+
+ CPPUNIT_ASSERT_EQUAL(forwardedBody, MockChatWindow::bodyFromMessage(window->lastAddedMessage_));
+ CPPUNIT_ASSERT_EQUAL(false, window->lastAddedMessageSenderIsSelf_);
+ }
+ }
+
+ void testCarbonsForwardedOutgoingMessageFromSecondResource() {
+ JID messageJID("testling@test.com/resource1");
+ JID jid2 = jid_.toBare().withResource("someOtherResource");
+
+ MockChatWindow* window = new MockChatWindow();
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window);
+
+ std::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, MockChatWindow::bodyFromMessage(window->lastAddedMessage_));
+
+ // incoming carbons message from another resource
+ {
+ auto originalMessage = std::make_shared<Message>();
+ originalMessage->setFrom(jid2);
+ originalMessage->setTo(messageJID);
+ originalMessage->setType(Message::Chat);
+ originalMessage->setID("abcdefg123456");
+ std::string forwardedBody = "Some text my other resource sent.";
+ originalMessage->setBody(forwardedBody);
+ originalMessage->addPayload(std::make_shared<DeliveryReceiptRequest>());
+
+ auto messageWrapper = createCarbonsMessage(std::make_shared<CarbonsSent>(), originalMessage);
+
+ manager_->handleIncomingMessage(messageWrapper);
+
+ CPPUNIT_ASSERT_EQUAL(forwardedBody, MockChatWindow::bodyFromMessage(window->lastAddedMessage_));
+ CPPUNIT_ASSERT_EQUAL(true, window->lastAddedMessageSenderIsSelf_);
+ CPPUNIT_ASSERT_EQUAL(size_t(1), window->receiptChanges_.size());
+ CPPUNIT_ASSERT_EQUAL(ChatWindow::ReceiptRequested, window->receiptChanges_[0].second);
+ }
+
+ // incoming carbons message for the received delivery receipt to the other resource
+ {
+ auto originalMessage = std::make_shared<Message>();
+ originalMessage->setFrom(messageJID);
+ originalMessage->setTo(jid2);
+ originalMessage->setType(Message::Chat);
+ originalMessage->addPayload(std::make_shared<DeliveryReceipt>("abcdefg123456"));
+
+ auto messageWrapper = createCarbonsMessage(std::make_shared<CarbonsReceived>(), originalMessage);
+
+ manager_->handleIncomingMessage(messageWrapper);
+
+ CPPUNIT_ASSERT_EQUAL(size_t(2), window->receiptChanges_.size());
+ CPPUNIT_ASSERT_EQUAL(ChatWindow::ReceiptReceived, window->receiptChanges_[1].second);
+ }
+ }
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);
- }
+ std::shared_ptr<Message> makeDeliveryReceiptTestMessage(const JID& from, const std::string& id) {
+ std::shared_ptr<Message> message = std::make_shared<Message>();
+ message->setFrom(from);
+ message->setID(id);
+ message->setBody("This will cause the window to open");
+ message->addPayload(std::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_;
+ JID jid_;
+ ChatsManager* manager_;
+ DummyStanzaChannel* stanzaChannel_;
+ IQRouter* iqRouter_;
+ EventController* eventController_;
+ ChatWindowFactory* chatWindowFactory_;
+ JoinMUCWindowFactory* joinMUCWindowFactory_;
+ NickResolver* nickResolver_;
+ PresenceOracle* presenceOracle_;
+ AvatarManager* avatarManager_;
+ std::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..32639f6 100644
--- a/Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp
+++ b/Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp
@@ -11,7 +11,6 @@
#include <hippomocks.h>
#include <Swiften/Avatars/NullAvatarManager.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/ClientBlockListManager.h>
#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/Client/NickResolver.h>
@@ -48,509 +47,508 @@
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_ = std::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 = nullptr;
+ window_ = new MockChatWindow();
+ mucRegistry_ = new MUCRegistry();
+ entityCapsProvider_ = new DummyEntityCapsProvider();
+ settings_ = new DummySettingsProvider();
+ highlightManager_ = new HighlightManager(settings_);
+ muc_ = std::make_shared<MockMUC>(mucJID_);
+ mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(muc_->getJID(), uiEventStream_).Return(window_);
+ chatMessageParser_ = std::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_, nullptr, nullptr, mucRegistry_, highlightManager_, clientBlockListManager_, chatMessageParser_, false, nullptr, 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;
+ std::shared_ptr<DiscoInfo> features = std::make_shared<DiscoInfo>();
+ features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature);
+ controller_->setAvailableServerFeatures(features);
+ IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1];
+ SecurityLabelsCatalog::ref labelPayload = std::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);
+ std::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ Message::ref message = std::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() {
+ std::shared_ptr<SecurityLabel> label = std::make_shared<SecurityLabel>();
+ label->setLabel("a");
+ SecurityLabelsCatalog::Item labelItem;
+ labelItem.setSelector("Bob");
+ labelItem.setLabel(label);
+ window_->label_ = labelItem;
+ std::shared_ptr<DiscoInfo> features = std::make_shared<DiscoInfo>();
+ features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature);
+ controller_->setAvailableServerFeatures(features);
+ IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1];
+ SecurityLabelsCatalog::ref labelPayload = std::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);
+ std::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ Message::ref message = std::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() {
+ std::shared_ptr<SecurityLabel> label = std::make_shared<SecurityLabel>();
+ label->setLabel("a");
+ SecurityLabelsCatalog::Item labelItem;
+ labelItem.setSelector("Bob");
+ labelItem.setLabel(label);
+ std::shared_ptr<SecurityLabel> label2 = std::make_shared<SecurityLabel>();
+ label->setLabel("b");
+ SecurityLabelsCatalog::Item labelItem2;
+ labelItem2.setSelector("Charlie");
+ labelItem2.setLabel(label2);
+ window_->label_ = labelItem;
+ std::shared_ptr<DiscoInfo> features = std::make_shared<DiscoInfo>();
+ features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature);
+ controller_->setAvailableServerFeatures(features);
+ IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1];
+ SecurityLabelsCatalog::ref labelPayload = std::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);
+ std::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ Message::ref message = std::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 = std::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 */
+ for (auto&& occupant : occupants) {
+ muc_->insertOccupant(occupant.second);
+ }
+
+ std::vector<MUCOccupant> alterations;
+ alterations.push_back(MUCOccupant("Kev", MUCOccupant::Visitor, MUCOccupant::Admin));
+ alterations.push_back(MUCOccupant("Remko", MUCOccupant::Moderator, MUCOccupant::Member));
+ alterations.push_back(MUCOccupant("Bert", MUCOccupant::Visitor, MUCOccupant::Outcast));
+ alterations.push_back(MUCOccupant("Ernie", MUCOccupant::NoRole, MUCOccupant::Member));
+ alterations.push_back(MUCOccupant("Bert", MUCOccupant::Moderator, MUCOccupant::Owner));
+ alterations.push_back(MUCOccupant("Kev", MUCOccupant::Participant, MUCOccupant::Outcast));
+ alterations.push_back(MUCOccupant("Bert", MUCOccupant::Visitor, MUCOccupant::NoAffiliation));
+ alterations.push_back(MUCOccupant("Remko", MUCOccupant::NoRole, MUCOccupant::NoAffiliation));
+ alterations.push_back(MUCOccupant("Ernie", MUCOccupant::Visitor, MUCOccupant::Outcast));
+
+ for (const auto& alteration : alterations) {
+ /* perform an alteration to a user's role and affiliation */
+ occupant_map::iterator occupant = occupants.find(alteration.getNick());
+ CPPUNIT_ASSERT(occupant != occupants.end());
+ const JID jid = jidFromOccupant(occupant->second);
+ /* change the affiliation, leave the role in place */
+ muc_->changeAffiliation(jid, alteration.getAffiliation());
+ occupant->second = MUCOccupant(occupant->first, occupant->second.getRole(), alteration.getAffiliation());
+ testRoleAffiliationStatesVerify(occupants);
+ /* change the role, leave the affiliation in place */
+ muc_->changeOccupantRole(jid, alteration.getRole());
+ occupant->second = MUCOccupant(occupant->first, alteration.getRole(), occupant->second.getAffiliation());
+ testRoleAffiliationStatesVerify(occupants);
+ }
+ }
+
+ void testSubjectChangeCorrect() {
+ std::string messageBody("test message");
+ window_->onSendMessageRequest(messageBody, false);
+ std::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ Message::ref message = std::dynamic_pointer_cast<Message>(rawStanza);
+ CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */
+ CPPUNIT_ASSERT(message);
+ CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get_value_or(""));
+
+ {
+ Message::ref message = std::make_shared<Message>();
+ message->setType(Message::Groupchat);
+ message->setTo(self_);
+ message->setFrom(mucJID_.withResource("SomeNickname"));
+ message->setID(iqChannel_->getNewIQID());
+ message->setSubject("New Room Subject");
+
+ controller_->handleIncomingMessage(std::make_shared<MessageEvent>(message));
+ CPPUNIT_ASSERT_EQUAL(std::string("The room subject is now: New Room Subject"), std::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);
+ std::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ Message::ref message = std::dynamic_pointer_cast<Message>(rawStanza);
+ CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */
+ CPPUNIT_ASSERT(message);
+ CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get_value_or(""));
+
+ {
+ Message::ref message = std::make_shared<Message>();
+ message->setType(Message::Groupchat);
+ message->setTo(self_);
+ message->setFrom(mucJID_.withResource("SomeNickname"));
+ message->setID(iqChannel_->getNewIQID());
+ message->setSubject("New Room Subject");
+ message->setBody("Some body text that prevents this stanza from being a subject change.");
+
+ controller_->handleIncomingMessage(std::make_shared<MessageEvent>(message));
+ CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), std::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(window_->lastAddedSystemMessage_.getParts()[0])->text);
+ }
+ }
+
+ /*
+ * 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);
+ std::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ Message::ref message = std::dynamic_pointer_cast<Message>(rawStanza);
+ CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */
+ CPPUNIT_ASSERT(message);
+ CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get_value_or(""));
+
+ {
+ Message::ref message = std::make_shared<Message>();
+ message->setType(Message::Groupchat);
+ message->setTo(self_);
+ message->setFrom(mucJID_.withResource("SomeNickname"));
+ message->setID(iqChannel_->getNewIQID());
+ message->setSubject("New Room Subject");
+ message->addPayload(std::make_shared<Thread>("Thread that prevents the subject change."));
+
+ controller_->handleIncomingMessage(std::make_shared<MessageEvent>(message));
+ CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), std::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(window_->lastAddedSystemMessage_.getParts()[0])->text);
+ }
+ }
+
+ /*
+ * Test that message stanzas with subject element and empty body element do not cause a subject change.
+ */
+ void testSubjectChangeIncorrectC() {
+ std::string messageBody("test message");
+ window_->onSendMessageRequest(messageBody, false);
+ std::shared_ptr<Stanza> rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1];
+ Message::ref message = std::dynamic_pointer_cast<Message>(rawStanza);
+ CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */
+ CPPUNIT_ASSERT(message);
+ CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get_value_or(""));
+
+ {
+ Message::ref message = std::make_shared<Message>();
+ message->setType(Message::Groupchat);
+ message->setTo(self_);
+ message->setFrom(mucJID_.withResource("SomeNickname"));
+ message->setID(iqChannel_->getNewIQID());
+ message->setSubject("New Room Subject");
+ message->setBody("");
+
+ controller_->handleIncomingMessage(std::make_shared<MessageEvent>(message));
+ CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), std::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(window_->lastAddedSystemMessage_.getParts()[0])->text);
+ }
+ }
+
+ void testRoleAffiliationStatesVerify(const std::map<std::string, MUCOccupant> &occupants) {
+ /* verify that the roster is in sync */
+ GroupRosterItem* group = window_->getRosterModel()->getRoot();
+ for (auto rosterItem : group->getChildren()) {
+ GroupRosterItem* child = dynamic_cast<GroupRosterItem*>(rosterItem);
+ CPPUNIT_ASSERT(child);
+ for (auto childItem : child->getChildren()) {
+ ContactRosterItem* item = dynamic_cast<ContactRosterItem*>(childItem);
+ CPPUNIT_ASSERT(item);
+ std::map<std::string, MUCOccupant>::const_iterator occupant = occupants.find(item->getJID().getResource());
+ CPPUNIT_ASSERT(occupant != occupants.end());
+ CPPUNIT_ASSERT(item->getMUCRole() == occupant->second.getRole());
+ CPPUNIT_ASSERT(item->getMUCAffiliation() == occupant->second.getAffiliation());
+ }
+ }
+ }
private:
- JID self_;
- JID mucJID_;
- MockMUC::ref muc_;
- std::string nick_;
- DummyStanzaChannel* stanzaChannel_;
- DummyIQChannel* iqChannel_;
- IQRouter* iqRouter_;
- EventController* eventController_;
- ChatWindowFactory* chatWindowFactory_;
- UserSearchWindowFactory* userSearchWindowFactory_;
- MUCController* controller_;
-// NickResolver* nickResolver_;
- PresenceOracle* presenceOracle_;
- AvatarManager* avatarManager_;
- StanzaChannelPresenceSender* presenceSender_;
- DirectedPresenceSender* directedPresenceSender_;
- MockRepository* mocks_;
- UIEventStream* uiEventStream_;
- MockChatWindow* window_;
- 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_;
+ std::shared_ptr<ChatMessageParser> chatMessageParser_;
+ std::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 c1410f3..395b050 100644
--- a/Swift/Controllers/Chat/UnitTest/MockChatListWindow.h
+++ b/Swift/Controllers/Chat/UnitTest/MockChatListWindow.h
@@ -1,28 +1,28 @@
/*
- * Copyright (c) 2011-2014 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/UIInterfaces/ChatListWindow.h"
+#include <Swift/Controllers/UIInterfaces/ChatListWindow.h>
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..91de670 100644
--- a/Swift/Controllers/Chat/UserSearchController.cpp
+++ b/Swift/Controllers/Chat/UserSearchController.cpp
@@ -1,18 +1,17 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Chat/UserSearchController.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Avatars/AvatarManager.h>
#include <Swiften/Base/String.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Disco/DiscoServiceWalker.h>
#include <Swiften/Disco/GetDiscoInfoRequest.h>
#include <Swiften/Disco/GetDiscoItemsRequest.h>
@@ -36,357 +35,359 @@ 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_ = nullptr;
+ discoWalker_ = nullptr;
+ 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;
- }
+void UserSearchController::handleUIEvent(std::shared_ptr<UIEvent> event) {
+ bool handle = false;
+ std::shared_ptr<RequestAddUserDialogUIEvent> addUserRequest = std::shared_ptr<RequestAddUserDialogUIEvent>();
+ auto inviteToMUCRequest = RequestInviteToMUCUIEvent::ref();
+ switch (type_) {
+ case AddContact:
+ if ((addUserRequest = std::dynamic_pointer_cast<RequestAddUserDialogUIEvent>(event))) {
+ handle = true;
+ }
+ break;
+ case StartChat:
+ if (std::dynamic_pointer_cast<RequestChatWithUserDialogUIEvent>(event)) {
+ handle = true;
+ }
+ break;
+ case InviteToChat:
+ if ((inviteToMUCRequest = std::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_->setOriginator(inviteToMUCRequest->getOriginator());
+ }
+ 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();
- }
+void UserSearchController::handleDiscoServiceFound(const JID& jid, std::shared_ptr<DiscoInfo> info) {
+ //bool isUserDirectory = false;
+ bool supports55 = false;
+ // TODO: Cleanup code
+ for (const auto& identity : info->getIdentities()) {
+ if ((identity.getCategory() == "directory"
+ && identity.getType() == "user")) {
+ //isUserDirectory = true;
+ }
+ }
+ std::vector<std::string> features = info->getFeatures();
+ supports55 = std::find(features.begin(), features.end(), DiscoInfo::JabberSearchFeature) != features.end();
+ if (/*isUserDirectory && */supports55) { //FIXME: once M-Link correctly advertises directoryness.
+ /* Abort further searches.*/
+ endDiscoWalker();
+ std::shared_ptr<GenericRequest<SearchPayload> > searchRequest(new GenericRequest<SearchPayload>(IQ::Get, jid, std::make_shared<SearchPayload>(), iqRouter_));
+ searchRequest->onResponse.connect(boost::bind(&UserSearchController::handleFormResponse, this, _1, _2));
+ searchRequest->send();
+ }
}
-void UserSearchController::handleFormResponse(boost::shared_ptr<SearchPayload> fields, ErrorPayload::ref error) {
- if (error || !fields) {
- window_->setServerSupportsSearch(false);
- return;
- }
- window_->setSearchFields(fields);
+void UserSearchController::handleFormResponse(std::shared_ptr<SearchPayload> fields, ErrorPayload::ref error) {
+ 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();
+void UserSearchController::handleSearch(std::shared_ptr<SearchPayload> fields, const JID& jid) {
+ addToSavedDirectories(jid);
+ std::shared_ptr<GenericRequest<SearchPayload> > searchRequest(new GenericRequest<SearchPayload>(IQ::Set, jid, fields, iqRouter_));
+ searchRequest->onResponse.connect(boost::bind(&UserSearchController::handleSearchResponse, this, _1, _2));
+ searchRequest->send();
}
-void UserSearchController::handleSearchResponse(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);
- }
+void UserSearchController::handleSearchResponse(std::shared_ptr<SearchPayload> resultsPayload, ErrorPayload::ref error) {
+ if (error || !resultsPayload) {
+ window_->setSearchError(true);
+ return;
+ }
+
+ std::vector<UserSearchResult> results;
+
+ if (resultsPayload->getForm()) {
+ window_->setResultsForm(resultsPayload->getForm());
+ } else {
+ for (auto&& item : resultsPayload->getItems()) {
+ JID jid(item.jid);
+ std::map<std::string, std::string> fields;
+ fields["first"] = item.first;
+ fields["last"] = item.last;
+ fields["nick"] = item.nick;
+ fields["email"] = item.email;
+ UserSearchResult result(jid, fields);
+ results.push_back(result);
+ }
+ window_->setResults(results);
+ }
}
void UserSearchController::handleNameSuggestionRequest(const JID &jid) {
- suggestionsJID_= jid;
- VCard::ref vcard = vcardManager_->getVCardAndRequestWhenNeeded(jid);
- if (vcard) {
- handleVCardChanged(jid, vcard);
- }
+ 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;
+ for (const auto& jid : existingJIDs) {
+ if ((*i)->jid == jid) {
+ found = true;
+ break;
+ }
+ }
+
+ // remove contact suggestions which are already on the contact list in add-contact-mode
+ if (type_ == AddContact) {
+ if (!found && !!rosterController_->getItem((*i)->jid)) {
+ found = true;
+ }
+ }
+
+ if (found) {
+ i = suggestions.erase(i);
+ } else {
+ i++;
+ }
+ }
+ window_->setContactSuggestions(suggestions);
}
void UserSearchController::handleVCardChanged(const JID& jid, VCard::ref vcard) {
- if (jid == suggestionsJID_) {
- window_->setNameSuggestions(ContactEditController::nameSuggestionsFromVCard(vcard));
- suggestionsJID_ = JID();
- }
- handleJIDUpdateRequested(std::vector<JID>(1, jid));
+ 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;
+ for (const auto& jid : jids) {
+ updates.push_back(convertJIDtoContact(jid));
+ }
+ window_->updateContacts(updates);
+ }
}
void UserSearchController::handleJIDAddRequested(const std::vector<JID>& jids) {
- std::vector<Contact::ref> contacts;
- foreach(const JID& jid, jids) {
- contacts.push_back(convertJIDtoContact(jid));
- }
- window_->addContacts(contacts);
+ std::vector<Contact::ref> contacts;
+ for (const auto& 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 = std::make_shared<Contact>();
+ contact->jid = jid;
+
+ // name lookup
+ boost::optional<XMPPRosterItem> rosterItem = rosterController_->getItem(jid);
+ if (rosterItem && !rosterItem->getName().empty()) {
+ contact->name = rosterItem->getName();
+ } else {
+ VCard::ref vcard = vcardManager_->getVCard(jid);
+ if (vcard && !vcard->getFullName().empty()) {
+ contact->name = vcard->getFullName();
+ } else {
+ contact->name = jid.toString();
+ }
+ }
+
+ // presence lookup
+ Presence::ref presence = presenceOracle_->getAccountPresence(jid);
+ if (presence) {
+ contact->statusType = presence->getShow();
+ } else {
+ contact->statusType = StatusShow::None;
+ }
+
+ // 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();
+ for (auto&& stringItem : String::split(settings_->getStringSetting(SEARCHED_DIRECTORIES), '\n')) {
+ if(!stringItem.empty()) {
+ savedDirectories_.push_back(JID(stringItem));
+ }
+ }
}
void UserSearchController::addToSavedDirectories(const JID& jid) {
- if (!jid.isValid()) {
- return;
- }
-
- savedDirectories_.erase(std::remove(savedDirectories_.begin(), savedDirectories_.end(), jid), savedDirectories_.end());
- savedDirectories_.insert(savedDirectories_.begin(), jid);
-
- std::string collapsed;
- int i = 0;
- foreach (JID jidItem, savedDirectories_) {
- 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;
+ for (const auto& jidItem : savedDirectories_) {
+ if (i >= 15) {
+ break;
+ }
+ if (!collapsed.empty()) {
+ collapsed += "\n";
+ }
+ collapsed += jidItem.toString();
+ ++i;
+ }
+ settings_->storeString(SEARCHED_DIRECTORIES, collapsed);
+ window_->addSavedServices(savedDirectories_);
}
}
diff --git a/Swift/Controllers/Chat/UserSearchController.h b/Swift/Controllers/Chat/UserSearchController.h
index 0423a65..4658301 100644
--- a/Swift/Controllers/Chat/UserSearchController.h
+++ b/Swift/Controllers/Chat/UserSearchController.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,12 +7,12 @@
#pragma once
#include <map>
+#include <memory>
#include <string>
#include <vector>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/DiscoItems.h>
#include <Swiften/Elements/ErrorPayload.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(std::shared_ptr<UIEvent> event);
+ void handleFormRequested(const JID& service);
+ void handleDiscoServiceFound(const JID& jid, std::shared_ptr<DiscoInfo> info);
+ void handleDiscoWalkFinished();
+ void handleFormResponse(std::shared_ptr<SearchPayload> items, ErrorPayload::ref error);
+ void handleSearch(std::shared_ptr<SearchPayload> fields, const JID& jid);
+ void handleSearchResponse(std::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 34524ac..ac3d896 100644
--- a/Swift/Controllers/ChatMessageSummarizer.cpp
+++ b/Swift/Controllers/ChatMessageSummarizer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2013 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,39 +7,39 @@
#include <Swift/Controllers/ChatMessageSummarizer.h>
#include <Swiften/Base/format.h>
+
#include <Swift/Controllers/Intl.h>
-#include <Swiften/Base/foreach.h>
using namespace Swift;
using namespace std;
string ChatMessageSummarizer::getSummary(const string& current, const vector<UnreadPair>& unreads) {
- vector<UnreadPair> others;
- int currentUnread = 0;
- int otherCount = 0;
- foreach (UnreadPair unread, unreads) {
- 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;
+ for (const auto& unread : unreads) {
+ if (unread.first == current) {
+ currentUnread += unread.second;
+ } else {
+ if (unread.second > 0) {
+ otherCount += unread.second;
+ others.push_back(unread);
+ }
+ }
+ }
+ string myString(current);
- if (currentUnread > 0) {
- string result(QT_TRANSLATE_NOOP("", "%1% (%2%)"));
- myString = str(format(result) % current % currentUnread);
- }
+ if (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 aab7bc6..0b4df21 100644
--- a/Swift/Controllers/ChatMessageSummarizer.h
+++ b/Swift/Controllers/ChatMessageSummarizer.h
@@ -1,20 +1,20 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
-#include <utility>
#include <string>
+#include <utility>
+#include <vector>
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 b3e27f1..b9b98c3 100644
--- a/Swift/Controllers/Contact.cpp
+++ b/Swift/Controllers/Contact.cpp
@@ -4,9 +4,16 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/Controllers/Contact.h>
+
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/find.hpp>
-#include <Swift/Controllers/Contact.h>
namespace Swift {
@@ -17,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..47dda43 100644
--- a/Swift/Controllers/Contact.h
+++ b/Swift/Controllers/Contact.h
@@ -5,14 +5,15 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/enable_shared_from_this.hpp>
+#include <memory>
+
#include <boost/filesystem/path.hpp>
#include <Swiften/Elements/StatusShow.h>
@@ -20,22 +21,22 @@
namespace Swift {
-class Contact : public boost::enable_shared_from_this<Contact> {
- public:
- typedef boost::shared_ptr<Contact> ref;
+class Contact : public std::enable_shared_from_this<Contact> {
+ public:
+ typedef std::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 1163735..2ea1f7e 100644
--- a/Swift/Controllers/ContactEditController.cpp
+++ b/Swift/Controllers/ContactEditController.cpp
@@ -1,109 +1,110 @@
/*
- * Copyright (c) 2010-2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/ContactEditController.h>
+#include <memory>
+
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <Swiften/VCards/VCardManager.h>
+
+#include <Swift/Controllers/Roster/RosterController.h>
+#include <Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
-#include <Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h>
#include <Swift/Controllers/UIInterfaces/ContactEditWindowFactory.h>
-#include <Swift/Controllers/Roster/RosterController.h>
-#include <Swiften/VCards/VCardManager.h>
-
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));
+ContactEditController::ContactEditController(RosterController* rosterController, VCardManager* vcardManager, ContactEditWindowFactory* contactEditWindowFactory, UIEventStream* uiEventStream) : rosterController(rosterController), vcardManager(vcardManager), contactEditWindowFactory(contactEditWindowFactory), uiEventStream(uiEventStream), contactEditWindow(nullptr) {
+ 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 = std::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(std::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 800da27..ab2b52e 100644
--- a/Swift/Controllers/ContactEditController.h
+++ b/Swift/Controllers/ContactEditController.h
@@ -1,54 +1,56 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <set>
+#include <string>
+#include <vector>
+
#include <boost/optional.hpp>
-#include <Swiften/JID/JID.h>
-#include <string>
#include <Swiften/Elements/VCard.h>
-#include <Swift/Controllers/UIEvents/UIEvent.h>
+#include <Swiften/JID/JID.h>
#include <Swiften/Roster/XMPPRosterItem.h>
+#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 1f61286..eb27ed4 100644
--- a/Swift/Controllers/ContactSuggester.cpp
+++ b/Swift/Controllers/ContactSuggester.cpp
@@ -5,29 +5,28 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/ContactSuggester.h>
+#include <algorithm>
+#include <set>
+#include <vector>
+
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/bind.hpp>
-#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
+#include <boost/lambda/lambda.hpp>
#include <Swiften/Base/Algorithm.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/JID/JID.h>
#include <Swift/Controllers/ContactProvider.h>
-#include <algorithm>
-#include <vector>
-#include <set>
-
namespace lambda = boost::lambda;
namespace Swift {
@@ -39,49 +38,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));
- }
+ for (auto provider : contactProviders_) {
+ append(results, provider->getContacts(withMUCNicks));
+ }
- std::sort(results.begin(), results.end(), Contact::lexicographicalSortPredicate);
- results.erase(std::unique(results.begin(), results.end(), Contact::equalityPredicate), results.end());
- results.erase(std::remove_if(results.begin(), results.end(), !lambda::bind(&matchContact, search, lambda::_1)),
- results.end());
- std::sort(results.begin(), results.end(), boost::bind(&Contact::sortPredicate, _1, _2, search));
+ 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 (char i : lowerMatch) {
+ size_t where = lowerText.find_first_of(i, lastMatch);
+ if (where == std::string::npos) {
+ return false;
+ }
+ lastMatch = where + 1;
+ }
+ return true;
}
}
diff --git a/Swift/Controllers/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..1d1ccd4 100644
--- a/Swift/Controllers/ContactsFromXMPPRoster.cpp
+++ b/Swift/Controllers/ContactsFromXMPPRoster.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,7 +13,6 @@
#include <Swift/Controllers/ContactsFromXMPPRoster.h>
#include <Swiften/Avatars/AvatarManager.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Presence/PresenceOracle.h>
#include <Swiften/Roster/XMPPRoster.h>
#include <Swiften/Roster/XMPPRosterItem.h>
@@ -27,15 +26,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();
+ for (const auto& rosterItem : rosterItems) {
+ Contact::ref contact = std::make_shared<Contact>(rosterItem.getName().empty() ? rosterItem.getJID().toString() : rosterItem.getName(), rosterItem.getJID(), StatusShow::None,"");
+ contact->statusType = presenceOracle_->getAccountPresence(contact->jid) ? presenceOracle_->getAccountPresence(contact->jid)->getShow() : StatusShow::None;
+ contact->avatarPath = avatarManager_->getAvatarPath(contact->jid);
+ results.push_back(contact);
+ }
+ return results;
}
}
diff --git a/Swift/Controllers/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 10b7c33..b36ed28 100644
--- a/Swift/Controllers/DummySystemTray.h
+++ b/Swift/Controllers/DummySystemTray.h
@@ -1,18 +1,18 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/SystemTray.h"
+#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 626fd40..6ea2ea5 100644
--- a/Swift/Controllers/EventNotifier.cpp
+++ b/Swift/Controllers/EventNotifier.cpp
@@ -10,71 +10,71 @@
#include <boost/bind.hpp>
#include <Swiften/Avatars/AvatarManager.h>
-#include <Swiften/Client/NickResolver.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Base/String.h>
#include <Swiften/Base/format.h>
+#include <Swiften/Client/NickResolver.h>
+#include <Swiften/JID/JID.h>
+#include <Swift/Controllers/Intl.h>
#include <Swift/Controllers/Settings/SettingsProvider.h>
#include <Swift/Controllers/XMPPEvents/ErrorEvent.h>
#include <Swift/Controllers/XMPPEvents/EventController.h>
#include <Swift/Controllers/XMPPEvents/MUCInviteEvent.h>
#include <Swift/Controllers/XMPPEvents/MessageEvent.h>
#include <Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h>
-#include <Swift/Controllers/Intl.h>
#include <SwifTools/Notifier/Notifier.h>
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()));
- }
+void EventNotifier::handleEventAdded(std::shared_ptr<StanzaEvent> event) {
+ if (event->getConcluded()) {
+ return;
+ }
+ if (std::shared_ptr<MessageEvent> messageEvent = std::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(std::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = std::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(std::shared_ptr<ErrorEvent> errorEvent = std::dynamic_pointer_cast<ErrorEvent>(event)) {
+ notifier->showMessage(Notifier::SystemMessage, QT_TRANSLATE_NOOP("", "Error"), errorEvent->getText(), boost::filesystem::path(), boost::function<void()>());
+ }
+ else if (std::shared_ptr<MUCInviteEvent> mucInviteEvent = std::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 4f7c430..b44615d 100644
--- a/Swift/Controllers/EventNotifier.h
+++ b/Swift/Controllers/EventNotifier.h
@@ -1,42 +1,45 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include "SwifTools/Notifier/Notifier.h"
-#include "Swiften/Base/boost_bsignals.h"
-#include "Swift/Controllers/XMPPEvents/StanzaEvent.h"
-#include "Swiften/JID/JID.h"
+#include <boost/signals2.hpp>
+
+#include <Swiften/JID/JID.h>
+
+#include <Swift/Controllers/XMPPEvents/StanzaEvent.h>
+
+#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::signals2::signal<void (const JID&)> onNotificationActivated;
+
+ private:
+ void handleEventAdded(std::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 3acd7a5..412bb71 100644
--- a/Swift/Controllers/EventWindowController.cpp
+++ b/Swift/Controllers/EventWindowController.cpp
@@ -1,53 +1,54 @@
/*
- * Copyright (c) 2010-2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/EventWindowController.h>
+#include <boost/bind.hpp>
+
#include <Swift/Controllers/XMPPEvents/MessageEvent.h>
#include <Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h>
-#include <boost/bind.hpp>
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);
- }
- }
+void EventWindowController::handleEventQueueEventAdded(std::shared_ptr<StanzaEvent> event) {
+ if (event->getConcluded()) {
+ handleEventConcluded(event);
+ } else {
+ std::shared_ptr<MessageEvent> message = std::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));
+void EventWindowController::handleEventConcluded(std::shared_ptr<StanzaEvent> event) {
+ window_->removeEvent(event);
+ bool includeAsCompleted = true;
+ /* Because subscription requests get duplicated, don't add them back */
+ if (std::dynamic_pointer_cast<SubscriptionRequestEvent>(event) || std::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 f9477c5..aa730d0 100644
--- a/Swift/Controllers/EventWindowController.h
+++ b/Swift/Controllers/EventWindowController.h
@@ -1,30 +1,29 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/UIInterfaces/EventWindowFactory.h"
-#include "Swift/Controllers/UIInterfaces/EventWindow.h"
-#include "Swift/Controllers/XMPPEvents/EventController.h"
-
+#include <Swift/Controllers/UIInterfaces/EventWindow.h>
+#include <Swift/Controllers/UIInterfaces/EventWindowFactory.h>
+#include <Swift/Controllers/XMPPEvents/EventController.h>
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(std::shared_ptr<StanzaEvent> event);
+ void handleEventConcluded(std::shared_ptr<StanzaEvent> event);
- EventController* eventController_;
- EventWindowFactory* windowFactory_;
- EventWindow* window_;
- boost::bsignals::scoped_connection eventAddedConnection_;
- };
+ EventController* eventController_;
+ EventWindowFactory* windowFactory_;
+ EventWindow* window_;
+ boost::signals2::scoped_connection eventAddedConnection_;
+ };
}
diff --git a/Swift/Controllers/FileTransfer/FileTransferController.cpp b/Swift/Controllers/FileTransfer/FileTransferController.cpp
index 89e9a91..65c2892 100644
--- a/Swift/Controllers/FileTransfer/FileTransferController.cpp
+++ b/Swift/Controllers/FileTransfer/FileTransferController.cpp
@@ -5,19 +5,20 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/FileTransfer/FileTransferController.h>
+#include <memory>
+
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/FileTransfer/FileReadBytestream.h>
#include <Swiften/FileTransfer/FileTransferManager.h>
#include <Swiften/FileTransfer/OutgoingJingleFileTransfer.h>
@@ -28,135 +29,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(nullptr), chatWindow(nullptr), 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(nullptr), ftProgressInfo(nullptr), chatWindow(nullptr), 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 = std::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 = std::dynamic_pointer_cast<IncomingFileTransfer>(transfer);
+ if (incomingTransfer) {
+ fileWriteStream = std::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..38dde0e 100644
--- a/Swift/Controllers/FileTransfer/FileTransferController.h
+++ b/Swift/Controllers/FileTransfer/FileTransferController.h
@@ -5,17 +5,17 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
#include <boost/cstdint.hpp>
-#include <boost/shared_ptr.hpp>
#include <Swiften/FileTransfer/FileReadBytestream.h>
#include <Swiften/FileTransfer/FileTransfer.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::signals2::signal<void ()> onStateChanged;
+ boost::signals2::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;
+ std::shared_ptr<FileReadBytestream> fileReadStream;
+ std::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 b2afea9..fcc35e4 100644
--- a/Swift/Controllers/FileTransfer/FileTransferOverview.cpp
+++ b/Swift/Controllers/FileTransfer/FileTransferOverview.cpp
@@ -5,88 +5,87 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "FileTransferOverview.h"
+#include <Swift/Controllers/FileTransfer/FileTransferOverview.h>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/FileTransfer/FileTransferManager.h>
namespace Swift {
FileTransferOverview::FileTransferOverview(FileTransferManager* ftm) : fileTransferManager(ftm) {
- fileTransferManager->onIncomingFileTransfer.connect(boost::bind(&FileTransferOverview::handleIncomingFileTransfer, this, _1));
- onNewFileTransferController.connect(boost::bind(&FileTransferOverview::handleNewFileTransferController, this, _1));
+ 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));
+ for (auto controller : fileTransfers) {
+ controller->onStateChanged.disconnect(boost::bind(&FileTransferOverview::handleFileTransferStateChanged, this));
+ }
}
-
+
void FileTransferOverview::sendFile(const JID& jid, const std::string& filename) {
- if (boost::filesystem::exists(filename) && boost::filesystem::file_size(filename) > 0) {
- FileTransferController* controller = new FileTransferController(jid, filename, fileTransferManager);
- onNewFileTransferController(controller);
- }
+ 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;
+ for (auto controller : fileTransfers) {
+ if(controller->getState().type == FileTransfer::State::Finished
+ || controller->getState().type == FileTransfer::State::Failed
+ || controller->getState().type == FileTransfer::State::Canceled) {
+ isClearable = true;
+ break;
+ }
+ }
+ return isClearable;
}
}
diff --git a/Swift/Controllers/FileTransfer/FileTransferOverview.h b/Swift/Controllers/FileTransfer/FileTransferOverview.h
index e3cbf81..c311cb7 100644
--- a/Swift/Controllers/FileTransfer/FileTransferOverview.h
+++ b/Swift/Controllers/FileTransfer/FileTransferOverview.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,7 +14,7 @@
#include <vector>
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
#include <Swift/Controllers/FileTransfer/FileTransferController.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::signals2::signal<void (FileTransferController*)> onNewFileTransferController;
+ boost::signals2::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 3081f71..b073017 100644
--- a/Swift/Controllers/FileTransfer/FileTransferProgressInfo.cpp
+++ b/Swift/Controllers/FileTransfer/FileTransferProgressInfo.cpp
@@ -4,7 +4,13 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "FileTransferProgressInfo.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/Controllers/FileTransfer/FileTransferProgressInfo.h>
#include <boost/numeric/conversion/cast.hpp>
@@ -13,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 e324e33..5fb955c 100644
--- a/Swift/Controllers/FileTransfer/FileTransferProgressInfo.h
+++ b/Swift/Controllers/FileTransfer/FileTransferProgressInfo.h
@@ -4,27 +4,33 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
#include <boost/cstdint.hpp>
+#include <boost/signals2.hpp>
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::signals2::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 093a3c4..4f85b81 100644
--- a/Swift/Controllers/FileTransferListController.cpp
+++ b/Swift/Controllers/FileTransferListController.cpp
@@ -4,42 +4,48 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "Swift/Controllers/FileTransferListController.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/Controllers/FileTransferListController.h>
#include <boost/bind.hpp>
-#include "Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h"
-#include "Swift/Controllers/UIEvents/RequestFileTransferListUIEvent.h"
+#include <Swift/Controllers/UIEvents/RequestFileTransferListUIEvent.h>
+#include <Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h>
namespace Swift {
-FileTransferListController::FileTransferListController(UIEventStream* uiEventStream, FileTransferListWidgetFactory* fileTransferListWidgetFactory) : fileTransferListWidgetFactory(fileTransferListWidgetFactory), fileTransferListWidget(NULL), fileTransferOverview(0) {
- uiEventStream->onUIEvent.connect(boost::bind(&FileTransferListController::handleUIEvent, this, _1));
+FileTransferListController::FileTransferListController(UIEventStream* uiEventStream, FileTransferListWidgetFactory* fileTransferListWidgetFactory) : fileTransferListWidgetFactory(fileTransferListWidgetFactory), fileTransferListWidget(nullptr), fileTransferOverview(nullptr) {
+ 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();
- }
+void FileTransferListController::handleUIEvent(std::shared_ptr<UIEvent> rawEvent) {
+ std::shared_ptr<RequestFileTransferListUIEvent> event = std::dynamic_pointer_cast<RequestFileTransferListUIEvent>(rawEvent);
+ if (event != nullptr) {
+ if (fileTransferListWidget == nullptr) {
+ 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 c5c8893..832a99c 100644
--- a/Swift/Controllers/FileTransferListController.h
+++ b/Swift/Controllers/FileTransferListController.h
@@ -4,11 +4,17 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include "Swift/Controllers/UIEvents/UIEventStream.h"
+#include <Swift/Controllers/UIEvents/UIEventStream.h>
namespace Swift {
@@ -18,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(std::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 35eb404..1f5f928 100644
--- a/Swift/Controllers/HighlightEditorController.cpp
+++ b/Swift/Controllers/HighlightEditorController.cpp
@@ -5,52 +5,53 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swift/Controllers/HighlightEditorController.h>
+
#include <boost/bind.hpp>
-#include <Swift/Controllers/HighlightEditorController.h>
+#include <Swift/Controllers/ContactSuggester.h>
#include <Swift/Controllers/UIEvents/RequestHighlightEditorUIEvent.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
-#include <Swift/Controllers/UIInterfaces/HighlightEditorWindowFactory.h>
#include <Swift/Controllers/UIInterfaces/HighlightEditorWindow.h>
-#include <Swift/Controllers/ContactSuggester.h>
+#include <Swift/Controllers/UIInterfaces/HighlightEditorWindowFactory.h>
namespace Swift {
HighlightEditorController::HighlightEditorController(UIEventStream* uiEventStream, HighlightEditorWindowFactory* highlightEditorWindowFactory, HighlightManager* highlightManager)
-: highlightEditorWindowFactory_(highlightEditorWindowFactory), highlightEditorWindow_(NULL), highlightManager_(highlightManager), contactSuggester_(0)
+: highlightEditorWindowFactory_(highlightEditorWindowFactory), highlightEditorWindow_(nullptr), highlightManager_(highlightManager), contactSuggester_(nullptr)
{
- 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_ = nullptr;
}
-void HighlightEditorController::handleUIEvent(boost::shared_ptr<UIEvent> rawEvent)
+void HighlightEditorController::handleUIEvent(std::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();
- }
+ std::shared_ptr<RequestHighlightEditorUIEvent> event = std::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..a699751 100644
--- a/Swift/Controllers/HighlightEditorController.h
+++ b/Swift/Controllers/HighlightEditorController.h
@@ -5,44 +5,45 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <string>
#include <Swift/Controllers/UIEvents/UIEvent.h>
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(std::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 e5c8cef..9176301 100644
--- a/Swift/Controllers/HighlightManager.cpp
+++ b/Swift/Controllers/HighlightManager.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,6 +13,7 @@
#include <Swift/Controllers/HighlightManager.h>
#include <cassert>
+#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/archive/text_iarchive.hpp>
@@ -22,8 +23,6 @@
#include <boost/regex.hpp>
#include <boost/serialization/vector.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Swift/Controllers/Highlighter.h>
#include <Swift/Controllers/SettingConstants.h>
#include <Swift/Controllers/Settings/SettingsProvider.h>
@@ -48,113 +47,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_ = std::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();
- }
+void HighlightManager::handleSettingChanged(const std::string& settingPath) {
+ 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::string HighlightManager::rulesToString() const {
+ 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> 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;
}
-HighlightRule HighlightManager::getRule(int index) const
-{
- assert(index >= 0 && static_cast<size_t>(index) < rules_->getSize());
- return rules_->getRule(static_cast<size_t>(index));
+HighlightRule HighlightManager::getRule(int index) const {
+ 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;
+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;
}
-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);
+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);
}
-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);
+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);
}
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;
+void HighlightManager::storeSettings() {
+ 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();
- }
+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();
+ }
}
-Highlighter* HighlightManager::createHighlighter()
-{
- return new Highlighter(this);
+Highlighter* HighlightManager::createHighlighter() {
+ 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 c55990b..a35e253 100644
--- a/Swift/Controllers/HighlightManager.h
+++ b/Swift/Controllers/HighlightManager.h
@@ -5,76 +5,77 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <string>
+#include <vector>
+
+#include <boost/signals2.hpp>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swift/Controllers/HighlightRule.h>
namespace Swift {
- class SettingsProvider;
- class Highlighter;
+ class SettingsProvider;
+ class Highlighter;
- class HighlightManager {
- public:
+ 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_;
- };
+ 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);
+ HighlightManager(SettingsProvider* settings);
- Highlighter* createHighlighter();
+ Highlighter* createHighlighter();
- boost::shared_ptr<const HighlightManager::HighlightRulesList> getRules() const { return rules_; }
+ std::shared_ptr<const HighlightManager::HighlightRulesList> getRules() const { return rules_; }
- bool isDefaultRulesList() const;
- void resetToDefaultRulesList();
+ 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();
+ 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;
+ boost::signals2::signal<void (const HighlightAction&)> onHighlight;
- private:
- void handleSettingChanged(const std::string& settingPath);
+ private:
+ void handleSettingChanged(const std::string& settingPath);
- std::string rulesToString() const;
- static std::vector<HighlightRule> getDefaultRules();
+ std::string rulesToString() const;
+ static std::vector<HighlightRule> getDefaultRules();
- private:
- SettingsProvider* settings_;
- bool storingSettings_;
+ private:
+ SettingsProvider* settings_;
+ bool storingSettings_;
- boost::shared_ptr<HighlightManager::HighlightRulesList> rules_;
- boost::bsignals::scoped_connection handleSettingChangedConnection_;
- };
+ std::shared_ptr<HighlightManager::HighlightRulesList> rules_;
+ boost::signals2::scoped_connection handleSettingChangedConnection_;
+ };
- typedef boost::shared_ptr<const HighlightManager::HighlightRulesList> HighlightRulesListPtr;
+ typedef std::shared_ptr<const HighlightManager::HighlightRulesList> HighlightRulesListPtr;
}
diff --git a/Swift/Controllers/HighlightRule.cpp b/Swift/Controllers/HighlightRule.cpp
index 021e15d..a8cb7e4 100644
--- a/Swift/Controllers/HighlightRule.cpp
+++ b/Swift/Controllers/HighlightRule.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -18,184 +18,183 @@
#include <boost/lambda/lambda.hpp>
#include <Swiften/Base/Regex.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
HighlightRule::HighlightRule()
- : nickIsKeyword_(false)
- , matchCase_(false)
- , matchWholeWords_(false)
- , matchChat_(false)
- , matchMUC_(false)
+ : 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();
+ for (const auto& k : keywords_) {
+ keywordRegex_.push_back(regexFromString(k));
+ }
+ senderRegex_.clear();
+ for (const auto& 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()) {
+ for (const auto& keyword : keywordRegex_) {
+ if (boost::regex_search(body, keyword)) {
+ matchesKeyword = true;
+ break;
+ }
+ }
+ }
+ }
+
+ for (const auto& rx : senderRegex_) {
+ if (boost::regex_search(sender, rx)) {
+ matchesSender = true;
+ break;
+ }
+ }
+
+ if (matchesKeyword && matchesSender) {
+ return true;
+ }
+ }
+
+ return false;
}
void HighlightRule::setSenders(const std::vector<std::string>& senders)
{
- senders_ = senders;
- updateRegex();
+ 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 02b4864..bffdc41 100644
--- a/Swift/Controllers/HighlightRule.h
+++ b/Swift/Controllers/HighlightRule.h
@@ -5,99 +5,99 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <string>
+#include <vector>
-#include <boost/regex.hpp>
-#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
+#include <boost/archive/text_oarchive.hpp>
+#include <boost/regex.hpp>
#include <Swift/Controllers/HighlightAction.h>
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 13ee951..cea077e 100644
--- a/Swift/Controllers/Highlighter.cpp
+++ b/Swift/Controllers/Highlighter.cpp
@@ -5,45 +5,47 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/foreach.h>
#include <Swift/Controllers/Highlighter.h>
+
#include <Swift/Controllers/HighlightManager.h>
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::findAction(const std::string& body, const std::string& sender) const
+HighlightAction Highlighter::findFirstFullMessageMatchAction(const std::string& body, const std::string& sender) const
{
- 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_)) {
- return rule.getAction();
- }
- }
-
- return HighlightAction();
+ 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 d5d846b..9ad3339 100644
--- a/Swift/Controllers/Highlighter.h
+++ b/Swift/Controllers/Highlighter.h
@@ -4,35 +4,42 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <string>
+#include <vector>
#include <Swift/Controllers/HighlightRule.h>
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 findAction(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..af70505 100644
--- a/Swift/Controllers/HistoryController.h
+++ b/Swift/Controllers/HistoryController.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -15,31 +15,31 @@
#include <vector>
#include <boost/date_time/posix_time/posix_time.hpp>
+#include <boost/signals2.hpp>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/History/HistoryMessage.h>
#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::signals2::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..669b002 100644
--- a/Swift/Controllers/HistoryViewController.cpp
+++ b/Swift/Controllers/HistoryViewController.cpp
@@ -5,16 +5,17 @@
*/
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* Licensed under the GNU General Public License.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/HistoryViewController.h>
+#include <boost/range/adaptor/reversed.hpp>
+
#include <Swiften/Avatars/AvatarManager.h>
#include <Swiften/Base/Path.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/NickResolver.h>
#include <Swiften/History/HistoryMessage.h>
@@ -25,335 +26,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_(nullptr),
+ selectedItem_(nullptr),
+ 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();
- }
+void HistoryViewController::handleUIEvent(std::shared_ptr<UIEvent> rawEvent) {
+ std::shared_ptr<RequestHistoryUIEvent> event = std::dynamic_pointer_cast<RequestHistoryUIEvent>(rawEvent);
+ if (event != nullptr) {
+ if (historyWindow_ == nullptr) {
+ 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_);
+
+ for (const auto& message : messages) {
+ addNewMessage(message, false);
+ }
}
void HistoryViewController::handleNewMessage(const HistoryMessage& message) {
- JID contactJID = message.getFromJID().toBare() == selfJID_ ? message.getToJID() : message.getFromJID();
-
- JID displayJID;
- if (message.getType() == HistoryMessage::PrivateMessage) {
- displayJID = contactJID;
- }
- else {
- displayJID = contactJID.toBare();
- }
-
- // check current conversation
- if (selectedItem_ && selectedItem_->getJID() == displayJID) {
- if (historyWindow_->getLastVisibleDate() == message.getTime().date()) {
- addNewMessage(message, false);
- }
- }
-
- // check if the new message matches the query
- if (message.getMessage().find(historyWindow_->getSearchBoxText()) == std::string::npos) {
- return;
- }
-
- // update contacts
- if (!contacts_[message.getType()].count(displayJID)) {
- roster_->addContact(displayJID, displayJID, nickResolver_->jidToNick(displayJID), category[message.getType()], avatarManager_->getAvatarPath(displayJID));
- }
-
- 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();
+ for (const auto& 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);
- }
+ for (const auto& 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);
- }
+ for (const auto& 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);
- }
+ for (const auto& message : messages) {
+ addNewMessage(message, false);
+ }
}
void HistoryViewController::reset() {
- roster_->removeAll();
- contacts_.clear();
- selectedItem_ = NULL;
- historyWindow_->resetConversationView();
+ roster_->removeAll();
+ contacts_.clear();
+ selectedItem_ = nullptr;
+ historyWindow_->resetConversationView();
}
void HistoryViewController::handleCalendarClicked(const boost::gregorian::date& date) {
- if (!selectedItem_) {
- return;
- }
-
- boost::gregorian::date newDate;
- if (contacts_[selectedItemType_][selectedItem_->getJID()].count(date)) {
- newDate = date;
- }
- else if (date < currentResultDate_) {
- foreach(const boost::gregorian::date& current, contacts_[selectedItemType_][selectedItem_->getJID()]) {
- 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_) {
+ for (const auto& current : contacts_[selectedItemType_][selectedItem_->getJID()]) {
+ if (current > date) {
+ newDate = current;
+ break;
+ }
+ }
+ }
+ else {
+ for (const auto& current : boost::adaptors::reverse(contacts_[selectedItemType_][selectedItem_->getJID()])) {
+ if (current < date) {
+ newDate = current;
+ break;
+ }
+ }
+ }
+
+ historyWindow_->setDate(newDate);
+ if (newDate == currentResultDate_) {
+ return;
+ }
+ currentResultDate_ = newDate;
+ historyWindow_->resetConversationView();
+
+ std::vector<HistoryMessage> messages = historyController_->getMessagesFromDate(selfJID_, selectedItem_->getJID(), selectedItemType_, currentResultDate_);
+ historyWindow_->setDate(currentResultDate_);
+
+ for (const auto& message : messages) {
+ addNewMessage(message, false);
+ }
}
void HistoryViewController::handlePresenceChanged(Presence::ref presence) {
- JID jid = presence->getFrom();
-
- if (contacts_[HistoryMessage::Chat].count(jid.toBare())) {
- roster_->applyOnItems(SetPresence(presence, JID::WithoutResource));
- return;
- }
-
- if (contacts_[HistoryMessage::Groupchat].count(jid.toBare())) {
- Presence::ref availablePresence = 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 = std::make_shared<Presence>(Presence());
+ availablePresence->setFrom(jid.toBare());
+ roster_->applyOnItems(SetPresence(availablePresence, JID::WithResource));
+ }
+
+ if (contacts_[HistoryMessage::PrivateMessage].count(jid)) {
+ roster_->applyOnItems(SetPresence(presence, JID::WithResource));
+ }
}
void HistoryViewController::handleAvatarChanged(const JID& jid) {
- roster_->applyOnItems(SetAvatar(jid, avatarManager_->getAvatarPath(jid)));
+ 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 = std::make_shared<Presence>(Presence());
+ presence->setFrom(jid);
+ return presence;
+ }
- foreach (Presence::ref presence, mucPresence) {
- if (presence.get() && presence->getFrom() == jid) {
- return presence;
- }
- }
+ for (auto&& 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 f44c968..75fc460 100644
--- a/Swift/Controllers/HistoryViewController.h
+++ b/Swift/Controllers/HistoryViewController.h
@@ -4,64 +4,72 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
+#include <memory>
+#include <set>
+
#include <boost/bind.hpp>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
-#include <Swift/Controllers/UIEvents/UIEventStream.h>
+#include <Swiften/History/HistoryStorage.h>
#include <Swiften/JID/JID.h>
#include <Swiften/Presence/PresenceOracle.h>
-#include <Swiften/History/HistoryStorage.h>
-#include <set>
+
+#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(std::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_ = HistoryMessage::Chat;
+ boost::gregorian::date currentResultDate_;
+ };
}
diff --git a/Swift/Controllers/Intl.h b/Swift/Controllers/Intl.h
index 1c8204a..c599493 100644
--- a/Swift/Controllers/Intl.h
+++ b/Swift/Controllers/Intl.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,6 +7,5 @@
#pragma once
#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..0d9f1b8 100644
--- a/Swift/Controllers/MainController.cpp
+++ b/Swift/Controllers/MainController.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,15 +7,14 @@
#include <Swift/Controllers/MainController.h>
#include <cstdlib>
+#include <memory>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/Algorithm.h>
+#include <Swiften/Base/Log.h>
#include <Swiften/Base/String.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/format.h>
#include <Swiften/Client/Client.h>
#include <Swiften/Client/ClientBlockListManager.h>
@@ -35,6 +34,7 @@
#include <Swiften/Network/NetworkFactories.h>
#include <Swiften/Network/TimerFactory.h>
#include <Swiften/Presence/PresenceSender.h>
+#include <Swiften/Queries/Requests/EnableCarbonsRequest.h>
#include <Swiften/StringCodecs/Base64.h>
#include <Swiften/StringCodecs/Hexify.h>
#include <Swiften/VCards/GetVCardRequest.h>
@@ -99,749 +99,766 @@ 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_(nullptr) ,
+ useDelayForLatency_(useDelayForLatency),
+ ftOverview_(nullptr),
+ emoticons_(emoticons) {
+ storages_ = nullptr;
+ certificateStorage_ = nullptr;
+ certificateTrustChecker_ = nullptr;
+ statusTracker_ = nullptr;
+ presenceNotifier_ = nullptr;
+ eventNotifier_ = nullptr;
+ rosterController_ = nullptr;
+ chatsManager_ = nullptr;
+ historyController_ = nullptr;
+ historyViewController_ = nullptr;
+ eventWindowController_ = nullptr;
+ profileController_ = nullptr;
+ blockListController_ = nullptr;
+ showProfileController_ = nullptr;
+ contactEditController_ = nullptr;
+ userSearchControllerChat_ = nullptr;
+ userSearchControllerAdd_ = nullptr;
+ userSearchControllerInvite_ = nullptr;
+ contactsFromRosterProvider_ = nullptr;
+ contactSuggesterWithoutRoster_ = nullptr;
+ contactSuggesterWithRoster_ = nullptr;
+ whiteboardManager_ = nullptr;
+ adHocManager_ = nullptr;
+ 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) {
+ for (auto&& 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_ = nullptr;
+ }
}
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_ = nullptr;
+ delete profileController_;
+ profileController_ = nullptr;
+ delete showProfileController_;
+ showProfileController_ = nullptr;
+ delete eventWindowController_;
+ eventWindowController_ = nullptr;
+ delete chatsManager_;
+ chatsManager_ = nullptr;
#ifdef SWIFT_EXPERIMENTAL_HISTORY
- delete historyViewController_;
- historyViewController_ = NULL;
- delete historyController_;
- historyController_ = NULL;
+ delete historyViewController_;
+ historyViewController_ = nullptr;
+ delete historyController_;
+ historyController_ = nullptr;
#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(nullptr);
+ delete ftOverview_;
+ ftOverview_ = nullptr;
+ delete blockListController_;
+ blockListController_ = nullptr;
+ delete rosterController_;
+ rosterController_ = nullptr;
+ delete eventNotifier_;
+ eventNotifier_ = nullptr;
+ delete presenceNotifier_;
+ presenceNotifier_ = nullptr;
+ delete certificateTrustChecker_;
+ certificateTrustChecker_ = nullptr;
+ delete certificateStorage_;
+ certificateStorage_ = nullptr;
+ delete storages_;
+ storages_ = nullptr;
+ delete statusTracker_;
+ statusTracker_ = nullptr;
+ delete profileSettings_;
+ profileSettings_ = nullptr;
+ delete userSearchControllerChat_;
+ userSearchControllerChat_ = nullptr;
+ delete userSearchControllerAdd_;
+ userSearchControllerAdd_ = nullptr;
+ delete userSearchControllerInvite_;
+ userSearchControllerInvite_ = nullptr;
+ delete contactSuggesterWithoutRoster_;
+ contactSuggesterWithoutRoster_ = nullptr;
+ delete contactSuggesterWithRoster_;
+ contactSuggesterWithRoster_ = nullptr;
+ delete contactsFromRosterProvider_;
+ contactsFromRosterProvider_ = nullptr;
+ delete adHocManager_;
+ adHocManager_ = nullptr;
+ delete whiteboardManager_;
+ whiteboardManager_ = nullptr;
+ 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_ = std::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_ == nullptr;
+ 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(), 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_, nullptr, 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);
- }
+ std::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();
- }
+void MainController::sendPresence(std::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(std::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;
+ std::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_ = std::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_);
+ }
+ std::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_ = std::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();
- }
- }
+void MainController::handleServerDiscoInfoResponse(std::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 (info->hasFeature(DiscoInfo::MessageCarbonsFeature)) {
+ enableMessageCarbons();
+ }
+ }
+}
+
+void MainController::enableMessageCarbons() {
+ auto enableCarbonsRequest = EnableCarbonsRequest::create(client_->getIQRouter());
+ enableCarbonsRequestHandlerConnection_ = enableCarbonsRequest->onResponse.connect([&](Payload::ref /*payload*/, ErrorPayload::ref error) {
+ if (error) {
+ SWIFT_LOG(warning) << "Failed to enable carbons." << std::endl;
+ }
+ else {
+ SWIFT_LOG(debug) << "Successfully enabled carbons." << std::endl;
+ }
+ enableCarbonsRequestHandlerConnection_.disconnect();
+ });
+ enableCarbonsRequest->send();
}
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(std::make_shared<JoinMUCUIEvent>(jid));
+ }
+ else {
+ uiEventStream_->send(std::make_shared<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 +868,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 +910,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 cdf9436..cc3d45f 100644
--- a/Swift/Controllers/MainController.h
+++ b/Swift/Controllers/MainController.h
@@ -1,200 +1,201 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <map>
+#include <memory>
#include <string>
+#include <vector>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/Network/Timer.h>
#include <Swiften/Client/ClientError.h>
-#include <Swiften/JID/JID.h>
+#include <Swiften/Client/ClientXMLTracer.h>
+#include <Swiften/Elements/CapsInfo.h>
#include <Swiften/Elements/DiscoInfo.h>
-#include <Swiften/Elements/VCard.h>
#include <Swiften/Elements/ErrorPayload.h>
#include <Swiften/Elements/Presence.h>
-#include <Swiften/Elements/CapsInfo.h>
-#include <Swiften/Client/ClientXMLTracer.h>
+#include <Swiften/Elements/VCard.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/Network/Timer.h>
-#include <Swift/Controllers/Settings/SettingsProvider.h>
#include <Swift/Controllers/ProfileSettingsProvider.h>
-#include <Swift/Controllers/XMPPEvents/ErrorEvent.h>
+#include <Swift/Controllers/Settings/SettingsProvider.h>
#include <Swift/Controllers/UIEvents/UIEvent.h>
-
+#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(std::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(std::shared_ptr<Presence> presence);
+ void handleInputIdleChanged(bool);
+ void handleShowCertificateRequest();
+ void logout();
+ void signOut();
+ void setReconnectTimer();
+ void resetPendingReconnects();
+ void resetCurrentError();
+ void enableMessageCarbons();
- 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);
+ 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_;
- };
+ private:
+ EventLoop* eventLoop_;
+ NetworkFactories* networkFactories_;
+ UIFactory* uiFactory_;
+ StoragesFactory* storagesFactory_;
+ Storages* storages_;
+ CertificateStorageFactory* certificateStorageFactory_;
+ CertificateStorage* certificateStorage_;
+ CertificateStorageTrustChecker* certificateTrustChecker_;
+ bool clientInitialized_;
+ std::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_;
+ std::shared_ptr<ErrorEvent> lastDisconnectError_;
+ bool useDelayForLatency_;
+ UserSearchController* userSearchControllerChat_;
+ UserSearchController* userSearchControllerAdd_;
+ UserSearchController* userSearchControllerInvite_;
+ int timeBeforeNextReconnect_;
+ Timer::ref reconnectTimer_;
+ StatusTracker* statusTracker_;
+ bool myStatusLooksOnline_ = false;
+ bool quitRequested_;
+ bool offlineRequested_;
+ static const int SecondsToWaitBeforeForceQuitting;
+ FileTransferOverview* ftOverview_;
+ WhiteboardManager* whiteboardManager_;
+ HighlightManager* highlightManager_;
+ HighlightEditorController* highlightEditorController_;
+ std::map<std::string, std::string> emoticons_;
+ boost::signals2::connection enableCarbonsRequestHandlerConnection_;
+ };
}
diff --git a/Swift/Controllers/PresenceNotifier.cpp b/Swift/Controllers/PresenceNotifier.cpp
index 0073720..91deae6 100644
--- a/Swift/Controllers/PresenceNotifier.cpp
+++ b/Swift/Controllers/PresenceNotifier.cpp
@@ -1,136 +1,137 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/PresenceNotifier.h"
+#include <Swift/Controllers/PresenceNotifier.h>
#include <boost/bind.hpp>
-#include "Swiften/Client/StanzaChannel.h"
-#include "Swiften/Base/ByteArray.h"
-#include "Swiften/MUC/MUCRegistry.h"
-#include "Swiften/Roster/XMPPRoster.h"
-#include "Swiften/Presence/PresenceOracle.h"
-#include "Swiften/Network/TimerFactory.h"
-#include "Swiften/Client/NickResolver.h"
+#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Client/NickResolver.h>
+#include <Swiften/Client/StanzaChannel.h>
+#include <Swiften/MUC/MUCRegistry.h>
+#include <Swiften/Network/TimerFactory.h>
+#include <Swiften/Presence/PresenceOracle.h>
+#include <Swiften/Roster/XMPPRoster.h>
+
#include <Swift/Controllers/StatusUtil.h>
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);
- }
- }
+void PresenceNotifier::handlePresenceReceived(std::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);
+ }
+ }
}
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 a1e1461..82678be 100644
--- a/Swift/Controllers/PresenceNotifier.h
+++ b/Swift/Controllers/PresenceNotifier.h
@@ -1,60 +1,62 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <set>
-#include "Swiften/Base/boost_bsignals.h"
-#include "Swiften/Elements/Presence.h"
-#include "Swiften/JID/JID.h"
-#include "SwifTools/Notifier/Notifier.h"
-#include "Swiften/Avatars/AvatarManager.h"
-#include "Swiften/Network/Timer.h"
+#include <boost/signals2.hpp>
+
+#include <Swiften/Avatars/AvatarManager.h>
+#include <Swiften/Elements/Presence.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/Network/Timer.h>
+
+#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::signals2::signal<void (const JID&)> onNotificationActivated;
+
+ private:
+ void handlePresenceReceived(std::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;
+ std::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 5886bdf..0b2d437 100644
--- a/Swift/Controllers/PreviousStatusStore.cpp
+++ b/Swift/Controllers/PreviousStatusStore.cpp
@@ -1,12 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "PreviousStatusStore.h"
-
-#include "Swiften/Base/foreach.h"
+#include <Swift/Controllers/PreviousStatusStore.h>
namespace Swift {
@@ -19,35 +17,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;
+ for (auto&& status : store_) {
+ if (status.second == message) {
+ suggestions.clear();
+ suggestions.push_back(status);
+ break;
+ } else if (status.second.find(message) != std::string::npos) {
+ suggestions.push_back(status);
+ }
+ }
+ if (suggestions.empty()) {
+ TypeStringPair suggestion(StatusShow::Online, message);
+ suggestions.push_back(suggestion);
+ }
+ if (suggestions.size() == 1) {
+ suggestions = exactMatchSuggestions(suggestions[0].first, suggestions[0].second);
+ }
+ return suggestions;
}
}
diff --git a/Swift/Controllers/PreviousStatusStore.h b/Swift/Controllers/PreviousStatusStore.h
index 69531a5..b106445 100644
--- a/Swift/Controllers/PreviousStatusStore.h
+++ b/Swift/Controllers/PreviousStatusStore.h
@@ -1,28 +1,29 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
#include <utility> /* std::pair */
#include <vector>
-#include <string>
-#include "Swiften/Elements/StatusShow.h"
+#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 49818b0..d000164 100644
--- a/Swift/Controllers/ProfileController.cpp
+++ b/Swift/Controllers/ProfileController.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -17,87 +17,98 @@
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));
+ProfileController::ProfileController(VCardManager* vcardManager, ProfileWindowFactory* profileWindowFactory, UIEventStream* uiEventStream) : vcardManager(vcardManager), profileWindowFactory(profileWindowFactory), uiEventStream(uiEventStream), available(true), profileWindow(nullptr), gettingVCard(false) {
+ uiEventStream->onUIEvent.connect(boost::bind(&ProfileController::handleUIEvent, this, _1));
}
ProfileController::~ProfileController() {
- if (profileWindow) {
- vcardManager->onOwnVCardChanged.disconnect(boost::bind(&ProfileController::handleOwnVCardChanged, this, _1));
- 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));
- }
- gettingVCard = true;
- updateDialogStatus();
- vcardManager->requestOwnVCard();
- profileWindow->show();
+ if (!std::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(std::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 = nullptr;
}
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 c6f5420..3bb1fce 100644
--- a/Swift/Controllers/ProfileController.h
+++ b/Swift/Controllers/ProfileController.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,35 +13,36 @@
#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class UIEventStream;
- class ProfileWindowFactory;
- class ProfileWindow;
- 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 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 180ffba..b979555 100644
--- a/Swift/Controllers/ProfileSettingsProvider.cpp
+++ b/Swift/Controllers/ProfileSettingsProvider.cpp
@@ -1,66 +1,68 @@
/*
- * Copyright (c) 2010-2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/ProfileSettingsProvider.h"
+#include <Swift/Controllers/ProfileSettingsProvider.h>
+
+#include <Swift/Controllers/Settings/SettingsProvider.h>
namespace Swift {
ProfileSettingsProvider::ProfileSettingsProvider(const std::string& profile, SettingsProvider* provider) :
- profile_(profile) {
- provider_ = provider;
- bool found = false;
- foreach (std::string existingProfile, provider->getAvailableProfiles()) {
- if (existingProfile == profile) {
- found = true;
- }
- }
- if (!found) {
- provider_->createProfile(profile);
- }
+ profile_(profile) {
+ provider_ = provider;
+ bool found = false;
+ for (const auto& existingProfile : provider->getAvailableProfiles()) {
+ if (existingProfile == profile) {
+ found = true;
+ }
+ }
+ if (!found) {
+ provider_->createProfile(profile);
+ }
}
ProfileSettingsProvider::~ProfileSettingsProvider() {
}
std::string ProfileSettingsProvider::getStringSetting(const std::string &settingPath) {
- //FIXME: Remove shim
- SettingsProvider::Setting<std::string> setting(profileSettingPath(settingPath), "");
- return provider_->getSetting(setting);
+ //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..e309c11 100644
--- a/Swift/Controllers/ProfileSettingsProvider.h
+++ b/Swift/Controllers/ProfileSettingsProvider.h
@@ -1,32 +1,34 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/foreach.h>
-
-#include <Swift/Controllers/Settings/SettingsProvider.h>
+#include <string>
namespace Swift {
+class SettingsProvider;
+
class ProfileSettingsProvider {
- public:
- ProfileSettingsProvider(const std::string& profile, SettingsProvider* provider);
- virtual ~ProfileSettingsProvider();
- virtual std::string getStringSetting(const std::string &settingPath);
- virtual void storeString(const std::string &settingPath, const std::string &settingValue);
- virtual int getIntSetting(const std::string& settingPath, int defaultValue);
- virtual void storeInt(const std::string& settingPath, int settingValue);
- /** See \ref SettingsProvider::getIsSettingFinal for discussion of what this means.*/
- virtual bool getIsSettingFinal(const std::string& settingPath);
-
- private:
- std::string profileSettingPath(const std::string &settingPath);
- 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);
+
+ private:
+ SettingsProvider* provider_;
+ std::string profile_;
};
}
diff --git a/Swift/Controllers/Roster/ContactRosterItem.cpp b/Swift/Controllers/Roster/ContactRosterItem.cpp
index 3258fb5..8fdf183 100644
--- a/Swift/Controllers/Roster/ContactRosterItem.cpp
+++ b/Swift/Controllers/Roster/ContactRosterItem.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,8 +9,8 @@
#include <boost/date_time/posix_time/posix_time.hpp>
#include <Swiften/Base/DateTime.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/Idle.h>
+#include <Swiften/Elements/Presence.h>
#include <Swift/Controllers/Intl.h>
#include <Swift/Controllers/Roster/GroupRosterItem.h>
@@ -27,149 +27,168 @@ 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());
- }
+ boost::posix_time::ptime idleTime = getIdle();
+ if (idleTime.is_not_a_date_time()) {
+ return "";
+ } else {
+ return dateTimeToLocalString(idleTime);
+ }
+}
+
+boost::posix_time::ptime ContactRosterItem::getIdle() const {
+ Idle::ref idle = presence_ ? presence_->getPayload<Idle>() : Idle::ref();
+ if (idle) {
+ return idle->getSince();
+ }
+ else {
+ return boost::posix_time::not_a_date_time;
+ }
}
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 "";
+ boost::posix_time::ptime offlineSince = getOfflineSince();
+ if (!offlineSince.is_not_a_date_time()) {
+ return dateTimeToLocalString(offlineSince);
+ }
+ return "";
+}
+
+boost::posix_time::ptime ContactRosterItem::getOfflineSince() const {
+ boost::posix_time::ptime offlineSince = boost::posix_time::not_a_date_time;
+ if (presence_ && presence_->getType() == Presence::Unavailable) {
+ boost::optional<boost::posix_time::ptime> delay = presence_->getTimestamp();
+ if (delay) {
+ offlineSince = delay.get();
+ }
+ }
+ return offlineSince;
}
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;
+typedef std::pair<std::string, std::shared_ptr<Presence> > StringPresencePair;
void ContactRosterItem::clearPresence() {
- presence_.reset();
- onDataChanged();
+ presence_.reset();
+ onDataChanged();
}
-void ContactRosterItem::applyPresence(boost::shared_ptr<Presence> presence) {
- presence_ = presence;
- onDataChanged();
+void ContactRosterItem::applyPresence(std::shared_ptr<Presence> presence) {
+ 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..37c3840 100644
--- a/Swift/Controllers/Roster/ContactRosterItem.h
+++ b/Swift/Controllers/Roster/ContactRosterItem.h
@@ -1,11 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <set>
#include <string>
#include <vector>
@@ -13,11 +14,9 @@
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/filesystem/path.hpp>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Elements/MUCOccupant.h>
-#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/StatusShow.h>
#include <Swiften/Elements/VCard.h>
#include <Swiften/JID/JID.h>
@@ -27,70 +26,73 @@
namespace Swift {
class GroupRosterItem;
+class Presence;
+
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;
+ boost::posix_time::ptime getIdle() const;
+ std::string getOfflineSinceText() const;
+ boost::posix_time::ptime getOfflineSince() 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(std::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::signals2::signal<void ()> onVCardRequested;
+
+ private:
+ JID jid_;
+ JID displayJID_;
+ boost::filesystem::path avatarPath_;
+ std::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 6710084..8c45935 100644
--- a/Swift/Controllers/Roster/FuzzyRosterFilter.h
+++ b/Swift/Controllers/Roster/FuzzyRosterFilter.h
@@ -4,33 +4,39 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <string>
#include <Swift/Controllers/ContactSuggester.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
-#include <Swift/Controllers/Roster/RosterItem.h>
#include <Swift/Controllers/Roster/RosterFilter.h>
+#include <Swift/Controllers/Roster/RosterItem.h>
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 a241dec..ac40afd 100644
--- a/Swift/Controllers/Roster/GroupRosterItem.cpp
+++ b/Swift/Controllers/Roster/GroupRosterItem.cpp
@@ -1,11 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/Roster/GroupRosterItem.h"
-
+#include <Swift/Controllers/Roster/GroupRosterItem.h>
#include <boost/bind.hpp>
//#include <boost/algorithm.hpp>
#include <iostream>
@@ -13,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() {
@@ -21,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();
}
/**
@@ -99,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 = nullptr;
+ 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 = nullptr;
+ 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 (auto& i : displayedChildren_) {
+ if (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 (auto& i : displayedChildren_) {
+ if (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 90ba471..a4e008f 100644
--- a/Swift/Controllers/Roster/GroupRosterItem.h
+++ b/Swift/Controllers/Roster/GroupRosterItem.h
@@ -1,49 +1,49 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/Roster/RosterItem.h"
#include <string>
-#include "Swift/Controllers/Roster/ContactRosterItem.h"
-
#include <vector>
+#include <Swift/Controllers/Roster/ContactRosterItem.h>
+#include <Swift/Controllers/Roster/RosterItem.h>
+
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::signals2::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::signals2::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 6438a8e..c57974b 100644
--- a/Swift/Controllers/Roster/ItemOperations/AppearOffline.h
+++ b/Swift/Controllers/Roster/ItemOperations/AppearOffline.h
@@ -1,29 +1,29 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
+#include <Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h>
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 da81d2b..c633c20 100644
--- a/Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h
+++ b/Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h
@@ -1,30 +1,32 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/Roster/RosterItem.h"
+#include <Swiften/JID/JID.h>
+
+#include <Swift/Controllers/Roster/RosterItem.h>
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 620a1ae..29f9722 100644
--- a/Swift/Controllers/Roster/ItemOperations/SetAvailableFeatures.h
+++ b/Swift/Controllers/Roster/ItemOperations/SetAvailableFeatures.h
@@ -4,33 +4,39 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/JID/JID.h>
-#include <Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
+#include <Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h>
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 910a651..d47c921 100644
--- a/Swift/Controllers/Roster/ItemOperations/SetAvatar.h
+++ b/Swift/Controllers/Roster/ItemOperations/SetAvatar.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -11,29 +11,29 @@
#include <Swiften/Elements/Presence.h>
#include <Swiften/JID/JID.h>
-#include <Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
+#include <Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h>
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 ddb2c7a..818d9b4 100644
--- a/Swift/Controllers/Roster/ItemOperations/SetBlockingState.h
+++ b/Swift/Controllers/Roster/ItemOperations/SetBlockingState.h
@@ -4,42 +4,48 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/JID/JID.h>
-#include <Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
+#include <Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h>
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 5919144..7640c24 100644
--- a/Swift/Controllers/Roster/ItemOperations/SetMUC.h
+++ b/Swift/Controllers/Roster/ItemOperations/SetMUC.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013-2014 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,31 +8,31 @@
#include <Swiften/JID/JID.h>
-#include <Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
+#include <Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h>
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 5708740..fa0694d 100644
--- a/Swift/Controllers/Roster/ItemOperations/SetName.h
+++ b/Swift/Controllers/Roster/ItemOperations/SetName.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,29 +8,29 @@
#include <Swiften/JID/JID.h>
-#include <Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
+#include <Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h>
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 8ee73f9..278ae56 100644
--- a/Swift/Controllers/Roster/ItemOperations/SetVCard.h
+++ b/Swift/Controllers/Roster/ItemOperations/SetVCard.h
@@ -4,34 +4,40 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Elements/VCard.h>
#include <Swiften/JID/JID.h>
-#include <Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
+#include <Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h>
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 0b5aa0a..8daa20c 100644
--- a/Swift/Controllers/Roster/LeastCommonSubsequence.h
+++ b/Swift/Controllers/Roster/LeastCommonSubsequence.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2013 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,101 +7,102 @@
#pragma once
#include <vector>
+
#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 61ac3f4..033eecb 100644
--- a/Swift/Controllers/Roster/OfflineRosterFilter.h
+++ b/Swift/Controllers/Roster/OfflineRosterFilter.h
@@ -1,25 +1,26 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/Roster/ContactRosterItem.h"
-#include "Swift/Controllers/Roster/RosterItem.h"
-#include "Swift/Controllers/Roster/RosterFilter.h"
-#include "Swiften/Elements/StatusShow.h"
+#include <Swiften/Elements/StatusShow.h>
+
+#include <Swift/Controllers/Roster/ContactRosterItem.h>
+#include <Swift/Controllers/Roster/RosterFilter.h>
+#include <Swift/Controllers/Roster/RosterItem.h>
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..68297a4 100644
--- a/Swift/Controllers/Roster/Roster.cpp
+++ b/Swift/Controllers/Roster/Roster.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,12 +7,12 @@
#include <Swift/Controllers/Roster/Roster.h>
#include <deque>
+#include <memory>
#include <set>
#include <string>
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/JID/JID.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
@@ -22,253 +22,250 @@
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_));
+Roster::Roster(bool sortByStatus, bool fullJIDMapping) : fullJIDMapping_(fullJIDMapping), sortByStatus_(sortByStatus), root_(std::unique_ptr<GroupRosterItem>(new GroupRosterItem("Dummy-Root", nullptr, sortByStatus_))) {
+ root_->onChildrenChanged.connect(boost::bind(&Roster::handleChildrenChanged, this, root_.get()));
}
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;
+ 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_.get();
}
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_.get());
+ 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;
+ for (auto* item : root_->getChildren()) {
+ GroupRosterItem *group = dynamic_cast<GroupRosterItem*>(item);
+ if (group && group->getDisplayName() == groupName) {
+ return group;
+ }
+ }
+ GroupRosterItem* group = new GroupRosterItem(groupName, root_.get(), 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_) {
+ for (auto i : itemMap_) {
+ for (auto* 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()) {
+ for (const auto& 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);
+
+ for (auto* 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_.get());
+ onDataChanged(root_.get());
}
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()) {
+ for (auto* 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;
+ }
+ for (auto* 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_.get());
+ 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;
+ for (auto* 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);
- }
- }
+ for (auto* 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_.get());
+ 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..d22b38d 100644
--- a/Swift/Controllers/Roster/Roster.h
+++ b/Swift/Controllers/Roster/Roster.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,13 +7,13 @@
#pragma once
#include <map>
+#include <memory>
#include <set>
#include <string>
#include <vector>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/JID/JID.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
@@ -27,46 +27,48 @@ 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::signals2::signal<void (GroupRosterItem*)> onChildrenChanged;
+ boost::signals2::signal<void (GroupRosterItem*)> onGroupAdded;
+ boost::signals2::signal<void (RosterItem*)> onDataChanged;
+ boost::signals2::signal<void (JID&)> onVCardUpdateRequested;
+ boost::signals2::signal<void (RosterFilter* filter)> onFilterAdded;
+ boost::signals2::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();
+
+ private:
+ std::vector<RosterFilter*> filters_;
+ typedef std::map<JID, std::vector<ContactRosterItem*> > ItemMap;
+ ItemMap itemMap_;
+ bool fullJIDMapping_;
+ bool sortByStatus_;
+ bool blockingSupported_ = false;
+ const std::unique_ptr<GroupRosterItem> root_;
};
}
diff --git a/Swift/Controllers/Roster/RosterController.cpp b/Swift/Controllers/Roster/RosterController.cpp
index 4fbdea4..1d20c4a 100644
--- a/Swift/Controllers/Roster/RosterController.cpp
+++ b/Swift/Controllers/Roster/RosterController.cpp
@@ -1,22 +1,23 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Roster/RosterController.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Avatars/AvatarManager.h>
#include <Swiften/Base/Path.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/format.h>
#include <Swiften/Client/ClientBlockListManager.h>
#include <Swiften/Client/NickManager.h>
#include <Swiften/Client/NickResolver.h>
#include <Swiften/Disco/EntityCapsManager.h>
+#include <Swiften/Disco/FeatureOracle.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/FileTransfer/FileTransferManager.h>
#include <Swiften/JID/JID.h>
@@ -30,7 +31,6 @@
#include <Swiften/Roster/XMPPRosterItem.h>
#include <Swiften/VCards/VCardManager.h>
-#include <Swift/Controllers/FileTransfer/FileTransferOverview.h>
#include <Swift/Controllers/Intl.h>
#include <Swift/Controllers/Roster/GroupRosterItem.h>
#include <Swift/Controllers/Roster/ItemOperations/AppearOffline.h>
@@ -49,7 +49,6 @@
#include <Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h>
#include <Swift/Controllers/UIEvents/RenameGroupUIEvent.h>
#include <Swift/Controllers/UIEvents/RenameRosterItemUIEvent.h>
-#include <Swift/Controllers/UIEvents/SendFileUIEvent.h>
#include <Swift/Controllers/UIInterfaces/MainWindow.h>
#include <Swift/Controllers/UIInterfaces/MainWindowFactory.h>
#include <Swift/Controllers/XMPPEvents/ErrorEvent.h>
@@ -61,355 +60,347 @@ 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_);
+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, 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), clientBlockListManager_(clientBlockListManager) {
+ 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));
+
+ featureOracle_ = std::unique_ptr<FeatureOracle>(new FeatureOracle(entityCapsManager_, presenceOracle_));
+
+ 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_ = std::make_shared<ContactRosterItem>(myJID_.toBare(), myJID_.toBare(), nickManager_->getOwnNick(), static_cast<GroupRosterItem*>(nullptr));
+ 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));
+
+ delete offlineFilter_;
+ delete expandiness_;
- mainWindow_->setRosterModel(NULL);
- if (mainWindow_->canDelete()) {
- delete mainWindow_;
- }
- delete rosterVCardProvider_;
- delete roster_;
+ mainWindow_->setRosterModel(nullptr);
+ 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()) {
+ for (const auto& 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));
- }
+ for (auto&& 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);
+ }
+ for (const auto& group : groups) {
+ if (std::find(oldGroups.begin(), oldGroups.end(), group) == oldGroups.end()) {
+ roster_->addContact(jid, jid, name, group, avatarManager_->getAvatarPath(jid));
+ }
+ }
+ for (const auto& 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) {
+ for (const auto& 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());
- }
+void RosterController::handleUIEvent(std::shared_ptr<UIEvent> event) {
+ if (std::shared_ptr<AddContactUIEvent> addContactEvent = std::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()));
+ std::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 (std::shared_ptr<RemoveRosterItemUIEvent> removeEvent = std::dynamic_pointer_cast<RemoveRosterItemUIEvent>(event)) {
+ RosterItemPayload item(removeEvent->getJID(), "", RosterItemPayload::Remove);
+ std::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 (std::shared_ptr<RenameRosterItemUIEvent> renameEvent = std::dynamic_pointer_cast<RenameRosterItemUIEvent>(event)) {
+ JID contact(renameEvent->getJID());
+ RosterItemPayload item(contact, renameEvent->getNewName(), xmppRoster_->getSubscriptionStateForJID(contact));
+ item.setGroups(xmppRoster_->getGroupsForJID(contact));
+ std::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 (std::shared_ptr<RenameGroupUIEvent> renameGroupEvent = std::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 = "";
+ }
+ for (auto& 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);
+ }
+ }
+ }
}
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 = std::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));
- }
- }
+ std::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) {
+ for (const auto& 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));
- }
- }
+void RosterController::handleRosterItemUpdated(ErrorPayload::ref error, std::shared_ptr<RosterPayload> rosterPayload) {
+ if (!!error) {
+ handleRosterSetError(error, rosterPayload);
+ }
+ std::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);
+void RosterController::handleRosterSetError(ErrorPayload::ref error, std::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();
+ }
+ std::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));
+ std::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_);
+ }
+ 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));
- }
+ std::set<ContactRosterItem::Feature> features;
+ if (featureOracle_->isFileTransferSupported(jid.toBare()) == Tristate::Yes || featureOracle_->isFileTransferSupported(jid.toBare()) == Tristate::Maybe) {
+ features.insert(ContactRosterItem::FileTransferFeature);
+ }
+ if (featureOracle_->isWhiteboardSupported(jid.toBare()) == Tristate::Yes) {
+ 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..ca2ecdc 100644
--- a/Swift/Controllers/Roster/RosterController.h
+++ b/Swift/Controllers/Roster/RosterController.h
@@ -1,18 +1,18 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <set>
#include <string>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Avatars/AvatarManager.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Elements/ErrorPayload.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/RosterPayload.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 FeatureOracle;
+ class FileTransferManager;
+ 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, ClientBlockListManager* clientBlockListManager, VCardManager* vcardManager);
+ ~RosterController();
+ void showRosterWindow();
+ void setJID(const JID& jid) { myJID_ = jid; }
+ MainWindow* getWindow() {return mainWindow_;}
+ boost::signals2::signal<void (StatusShow::Type, const std::string&)> onChangeStatusRequest;
+ boost::signals2::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(std::shared_ptr<Presence> newPresence);
+ void handleSubscriptionRequest(const JID& jid, const std::string& message);
+ void handleSubscriptionRequestAccepted(SubscriptionRequestEvent* event);
+ void handleSubscriptionRequestDeclined(SubscriptionRequestEvent* event);
+ void handleUIEvent(std::shared_ptr<UIEvent> event);
+ void handleRosterItemUpdated(ErrorPayload::ref error, std::shared_ptr<RosterPayload> rosterPayload);
+ void handleRosterSetError(ErrorPayload::ref error, std::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_;
+ ClientBlockListManager* clientBlockListManager_;
+ RosterVCardProvider* rosterVCardProvider_;
+ std::shared_ptr<ContactRosterItem> ownContact_;
+ std::unique_ptr<FeatureOracle> featureOracle_;
+
+ boost::signals2::scoped_connection blockingOnStateChangedConnection_;
+ boost::signals2::scoped_connection blockingOnItemAddedConnection_;
+ boost::signals2::scoped_connection blockingOnItemRemovedConnection_;
+ boost::signals2::scoped_connection changeStatusConnection_;
+ boost::signals2::scoped_connection signOutConnection_;
+ boost::signals2::scoped_connection uiEventConnection_;
+ };
}
diff --git a/Swift/Controllers/Roster/RosterFilter.h b/Swift/Controllers/Roster/RosterFilter.h
index 8712569..6075c66 100644
--- a/Swift/Controllers/Roster/RosterFilter.h
+++ b/Swift/Controllers/Roster/RosterFilter.h
@@ -1,19 +1,19 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/Roster/RosterItem.h"
+#include <Swift/Controllers/Roster/RosterItem.h>
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 79ad812..0f07c0b 100644
--- a/Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp
+++ b/Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp
@@ -1,61 +1,62 @@
/*
- * Copyright (c) 2010-2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Roster/RosterGroupExpandinessPersister.h>
-#include <boost/bind.hpp>
#include <vector>
-#include <Swiften/Base/foreach.h>
+#include <boost/bind.hpp>
+
#include <Swiften/Base/String.h>
+
#include <Swift/Controllers/Roster/GroupRosterItem.h>
#include <Swift/Controllers/SettingConstants.h>
namespace Swift {
RosterGroupExpandinessPersister::RosterGroupExpandinessPersister(Roster* roster, SettingsProvider* settings) : roster_(roster), settings_(settings) {
- load();
- roster_->onGroupAdded.connect(boost::bind(&RosterGroupExpandinessPersister::handleGroupAdded, this, _1));
+ 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;
+ for (const auto& group : collapsed_) {
+ if (!setting.empty()) {
+ setting += "\n";
+ }
+ setting += group;
+ }
+ settings_->storeSetting(SettingConstants::EXPANDED_ROSTER_GROUPS, setting);
}
void RosterGroupExpandinessPersister::load() {
- std::string saved = settings_->getSetting(SettingConstants::EXPANDED_ROSTER_GROUPS);
- std::vector<std::string> collapsed = String::split(saved, '\n');
- collapsed_.insert(collapsed.begin(), collapsed.end());
+ 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 6addc81..4cc08a7 100644
--- a/Swift/Controllers/Roster/RosterGroupExpandinessPersister.h
+++ b/Swift/Controllers/Roster/RosterGroupExpandinessPersister.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,20 +7,21 @@
#pragma once
#include <set>
-#include "Swift/Controllers/Roster/Roster.h"
-#include "Swift/Controllers/Settings/SettingsProvider.h"
+
+#include <Swift/Controllers/Roster/Roster.h>
+#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 7864fd9..685613f 100644
--- a/Swift/Controllers/Roster/RosterItem.cpp
+++ b/Swift/Controllers/Roster/RosterItem.cpp
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/Roster/RosterItem.h"
+#include <Swift/Controllers/Roster/RosterItem.h>
#include <boost/algorithm/string.hpp>
-#include "Swift/Controllers/Roster/GroupRosterItem.h"
+#include <Swift/Controllers/Roster/GroupRosterItem.h>
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 84cba2c..b834785 100644
--- a/Swift/Controllers/Roster/RosterItem.h
+++ b/Swift/Controllers/Roster/RosterItem.h
@@ -1,31 +1,31 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swiften/Base/boost_bsignals.h"
-#include <boost/shared_ptr.hpp>
-
+#include <memory>
#include <string>
+#include <boost/signals2.hpp>
+
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::signals2::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 954ac68..2aa82a9 100644
--- a/Swift/Controllers/Roster/RosterVCardProvider.cpp
+++ b/Swift/Controllers/Roster/RosterVCardProvider.cpp
@@ -4,32 +4,38 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swift/Controllers/Roster/RosterVCardProvider.h>
#include <Swiften/VCards/VCardManager.h>
-#include <Swift/Controllers/Roster/Roster.h>
#include <Swift/Controllers/Roster/ItemOperations/SetVCard.h>
+#include <Swift/Controllers/Roster/Roster.h>
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..337b0b2 100644
--- a/Swift/Controllers/Roster/RosterVCardProvider.h
+++ b/Swift/Controllers/Roster/RosterVCardProvider.h
@@ -4,11 +4,17 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <boost/signals/connection.hpp>
+#include <boost/signals2.hpp>
+#include <boost/signals2/connection.hpp>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Elements/VCard.h>
#include <Swiften/JID/JID.h>
@@ -18,20 +24,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::signals2::scoped_connection vcardUpdateRequestedConnection;
+ boost::signals2::scoped_connection vcardChangedConnection;
};
}
diff --git a/Swift/Controllers/Roster/TableRoster.cpp b/Swift/Controllers/Roster/TableRoster.cpp
index 9f3cd54..713f390 100644
--- a/Swift/Controllers/Roster/TableRoster.cpp
+++ b/Swift/Controllers/Roster/TableRoster.cpp
@@ -1,185 +1,186 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Roster/TableRoster.h>
-#include <boost/cast.hpp>
-#include <cassert>
#include <algorithm>
+#include <cassert>
+
+#include <boost/cast.hpp>
#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Network/TimerFactory.h>
#include <Swiften/Network/Timer.h>
-#include <Swift/Controllers/Roster/Roster.h>
+#include <Swiften/Network/TimerFactory.h>
+
#include <Swift/Controllers/Roster/GroupRosterItem.h>
#include <Swift/Controllers/Roster/LeastCommonSubsequence.h>
+#include <Swift/Controllers/Roster/Roster.h>
namespace Swift {
- struct SectionNameEquals {
- bool operator()(const TableRoster::Section& s1, const TableRoster::Section& s2) const {
- return s1.name == s2.name;
- }
- };
-
- template<typename T>
- struct True {
- bool operator()(const T&, const T&) const {
- return true;
- }
- };
-
- struct ItemEquals {
- bool operator()(const TableRoster::Item& i1, const TableRoster::Item& i2) const {
- return i1.jid == i2.jid;
- }
- };
-
-
- struct ItemNeedsUpdate {
- bool operator()(const TableRoster::Item& i1, const TableRoster::Item& i2) const {
- 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) {
+ for (auto item : model->getRoot()->getDisplayedChildren()) {
+ if (GroupRosterItem* groupItem = boost::polymorphic_downcast<GroupRosterItem*>(item)) {
+ //std::cerr << "* " << groupItem->getDisplayName() << std::endl;
+ Section section(groupItem->getDisplayName());
+ for (auto groupChildItem : groupItem->getDisplayedChildren()) {
+ if (ContactRosterItem* contact = boost::polymorphic_downcast<ContactRosterItem*>(groupChildItem)) {
+ //std::cerr << " - " << contact->getDisplayJID() << std::endl;
+ section.items.push_back(Item(contact->getDisplayName(), contact->getStatusText(), contact->getDisplayJID(), contact->getStatusShow(), contact->getAvatarPath()));
+ }
+ }
+ newSections.push_back(section);
+ }
+ }
+ }
+
+ // Do a diff with the previous roster
+ Update update;
+ std::vector<size_t> sectionUpdates;
+ std::vector<size_t> sectionPostUpdates;
+ computeIndexDiff<Section,SectionNameEquals,True<Section> >(sections, newSections, sectionUpdates, sectionPostUpdates, update.deletedSections, update.insertedSections);
+ assert(sectionUpdates.size() == sectionPostUpdates.size());
+ for (size_t i = 0; i < sectionUpdates.size(); ++i) {
+ assert(sectionUpdates[i] < sections.size());
+ assert(sectionPostUpdates[i] < newSections.size());
+ std::vector<size_t> itemUpdates;
+ std::vector<size_t> itemPostUpdates;
+ std::vector<size_t> itemRemoves;
+ std::vector<size_t> itemInserts;
+ computeIndexDiff<Item, ItemEquals, ItemNeedsUpdate >(sections[sectionUpdates[i]].items, newSections[sectionPostUpdates[i]].items, itemUpdates, itemPostUpdates, itemRemoves, itemInserts);
+ size_t end = update.insertedRows.size();
+ update.insertedRows.resize(update.insertedRows.size() + itemInserts.size());
+ std::transform(itemInserts.begin(), itemInserts.end(), update.insertedRows.begin() + boost::numeric_cast<long long>(end), CreateIndexForSection(sectionPostUpdates[i]));
+ end = update.deletedRows.size();
+ update.deletedRows.resize(update.deletedRows.size() + itemRemoves.size());
+ std::transform(itemRemoves.begin(), itemRemoves.end(), update.deletedRows.begin() + boost::numeric_cast<long long>(end), CreateIndexForSection(sectionUpdates[i]));
+ 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 f0010f5..22c9ca9 100644
--- a/Swift/Controllers/Roster/TableRoster.h
+++ b/Swift/Controllers/Roster/TableRoster.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,77 +8,78 @@
#include <string>
#include <vector>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Elements/StatusShow.h>
#include <boost/filesystem/path.hpp>
+#include <boost/signals2.hpp>
+
+#include <Swiften/Elements/StatusShow.h>
+#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::signals2::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;
+ std::shared_ptr<Timer> updateTimer;
+ };
}
diff --git a/Swift/Controllers/Roster/UnitTest/LeastCommonSubsequenceTest.cpp b/Swift/Controllers/Roster/UnitTest/LeastCommonSubsequenceTest.cpp
index 996b460..5844ebe 100644
--- a/Swift/Controllers/Roster/UnitTest/LeastCommonSubsequenceTest.cpp
+++ b/Swift/Controllers/Roster/UnitTest/LeastCommonSubsequenceTest.cpp
@@ -1,308 +1,311 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/assign/list_of.hpp>
#include <functional>
+#include <boost/assign/list_of.hpp>
+
#include <QA/Checker/IO.h>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
+
#include <Swift/Controllers/Roster/LeastCommonSubsequence.h>
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..ddbd7d3 100644
--- a/Swift/Controllers/Roster/UnitTest/RosterControllerTest.cpp
+++ b/Swift/Controllers/Roster/UnitTest/RosterControllerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,17 +9,19 @@
#include <Swiften/Avatars/NullAvatarManager.h>
#include <Swiften/Base/Algorithm.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/ClientBlockListManager.h>
#include <Swiften/Client/DummyNickManager.h>
#include <Swiften/Client/DummyStanzaChannel.h>
+#include <Swiften/Client/MemoryStorages.h>
#include <Swiften/Client/NickResolver.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/Disco/CapsInfoGenerator.h>
+#include <Swiften/Disco/CapsManager.h>
#include <Swiften/Disco/CapsProvider.h>
+#include <Swiften/Disco/ClientDiscoManager.h>
#include <Swiften/Disco/EntityCapsManager.h>
#include <Swiften/EventLoop/DummyEventLoop.h>
-#include <Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h>
#include <Swiften/Jingle/JingleSessionManager.h>
#include <Swiften/MUC/MUCRegistry.h>
#include <Swiften/Presence/PresenceOracle.h>
@@ -30,7 +32,6 @@
#include <Swiften/VCards/VCardManager.h>
#include <Swiften/VCards/VCardMemoryStorage.h>
-#include <Swift/Controllers/FileTransfer/FileTransferOverview.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
#include <Swift/Controllers/Roster/GroupRosterItem.h>
#include <Swift/Controllers/Roster/Roster.h>
@@ -43,354 +44,438 @@
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(testOwnContactInRosterPresence);
+ CPPUNIT_TEST(testMultiResourceFileTransferFeature);
+ 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();
+ crypto_ = PlatformCryptoProvider::create();
+ storages_ = std::unique_ptr<MemoryStorages>(new MemoryStorages(crypto_));
+ nickResolver_ = new NickResolver(jid_.toBare(), xmppRoster_, nullptr, 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();
+ capsManager_ = std::unique_ptr<CapsManager>(new CapsManager(storages_->getCapsStorage(), stanzaChannel_, router_, crypto_));
+ entityCapsManager_ = new EntityCapsManager(capsManager_.get(), stanzaChannel_);
+ jingleSessionManager_ = new JingleSessionManager(router_);
+
+ clientBlockListManager_ = new ClientBlockListManager(router_);
+ 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_, clientBlockListManager_, vcardManager_);
+ mainWindow_ = mainWindowFactory_->last;
+ capsInfoGenerator_ = std::unique_ptr<CapsInfoGenerator>(new CapsInfoGenerator("", crypto_));
+ }
+
+ void tearDown() {
+ delete rosterController_;
+ delete vcardManager_;
+ delete vcardStorage_;
+ delete crypto_;
+ delete clientBlockListManager_;
+ delete jingleSessionManager_;
+ delete entityCapsManager_;
+ 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*>(getUIRosterChildren()[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*>(getUIRosterChildren()[0])->getChildren()[0]);
+ CPPUNIT_ASSERT(item);
+ CPPUNIT_ASSERT_EQUAL(presence->getStatus(), item->getStatusText());
+ ContactRosterItem* item2 = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(getUIRosterChildren()[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*>(getUIRosterChildren()[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*>(getUIRosterChildren()[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*>(getUIRosterChildren()[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*>(getUIRosterChildren()[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>(getUIRosterChildren().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>(getUIRosterChildren().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>(getUIRosterChildren().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>(getUIRosterChildren().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>(getUIRosterChildren().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>(getUIRosterChildren().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>(getUIRosterChildren().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>(getUIRosterChildren().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>(getUIRosterChildren().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(std::make_shared<RenameRosterItemUIEvent>(jid, "Robert"));
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), channel_->iqs_.size());
+ CPPUNIT_ASSERT_EQUAL(IQ::Set, channel_->iqs_[0]->getType());
+ std::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 testOwnContactInRosterPresence() {
+ std::vector<std::string> groups;
+ groups.push_back("testGroup1");
+ groups.push_back("testGroup2");
+ JID from = jid_;
+ xmppRoster_->addContact(from.toBare(), "name", groups, RosterItemPayload::Both);
+ Presence::ref presence(new Presence());
+ presence->setFrom(from);
+ presence->setPriority(2);
+ presence->setStatus("So totally here");
+ stanzaChannel_->onPresenceReceived(presence);
+ ContactRosterItem* item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(getUIRosterChildren()[0])->getChildren()[0]);
+ CPPUNIT_ASSERT(item);
+ CPPUNIT_ASSERT_EQUAL(presence->getStatus(), item->getStatusText());
+ ContactRosterItem* item2 = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(getUIRosterChildren()[1])->getChildren()[0]);
+ CPPUNIT_ASSERT(item2);
+ CPPUNIT_ASSERT_EQUAL(presence->getStatus(), item2->getStatusText());
+ }
+
+ // This tests a scenario of a contact having a resource supporting Jingle File Transfer and
+ // one resource not supporting it, and the contact features being set correctly.
+ void testMultiResourceFileTransferFeature() {
+ JID contact("test@testdomain.com");
+ xmppRoster_->addContact(contact, "Name", {}, RosterItemPayload::Both);
+
+ auto sendPresenceAndAnswerCaps = [=](const JID& from, const DiscoInfo& discoInfo) {
+ auto capsInfo = capsInfoGenerator_->generateCapsInfo(discoInfo);
+
+ auto ftClientPresence = std::make_shared<Presence>();
+ ftClientPresence->setFrom(from);
+ ftClientPresence->setPriority(0);
+ ftClientPresence->setShow(StatusShow::Online);
+ ftClientPresence->addPayload(std::make_shared<CapsInfo>(capsInfo));
+ stanzaChannel_->onPresenceReceived(ftClientPresence);
+
+ // disco reply
+ auto discoRequest = channel_->iqs_.back();
+ CPPUNIT_ASSERT(discoRequest);
+ auto discoReply = IQ::createResult(discoRequest->getFrom(), ftClientPresence->getFrom(), discoRequest->getID(), std::make_shared<DiscoInfo>(discoInfo));
+ channel_->onIQReceived(discoReply);
+ };
+
+ auto ftDiscoInfo = DiscoInfo();
+ ftDiscoInfo.addFeature(DiscoInfo::JingleFeature);
+ ftDiscoInfo.addFeature(DiscoInfo::JingleFTFeature);
+ ftDiscoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature);
+
+ sendPresenceAndAnswerCaps(contact.withResource("ft-supported"), ftDiscoInfo);
+
+ auto* item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(getUIRosterChildren()[0])->getChildren()[0]);
+ CPPUNIT_ASSERT(item);
+ CPPUNIT_ASSERT_EQUAL(contact, item->getJID());
+ CPPUNIT_ASSERT_EQUAL(true, item->supportsFeature(ContactRosterItem::FileTransferFeature));
+
+ sendPresenceAndAnswerCaps(contact.withResource("ft-unsupported"), DiscoInfo());
+
+ item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(getUIRosterChildren()[0])->getChildren()[0]);
+ CPPUNIT_ASSERT(item);
+ CPPUNIT_ASSERT_EQUAL(contact, item->getJID());
+ CPPUNIT_ASSERT_EQUAL(true, item->supportsFeature(ContactRosterItem::FileTransferFeature));
+
+ auto unavailablePresence = std::make_shared<Presence>();
+ unavailablePresence->setFrom(contact.withResource("ft-unsupported"));
+ unavailablePresence->setPriority(0);
+ unavailablePresence->setType(Presence::Unavailable);
+ stanzaChannel_->onPresenceReceived(unavailablePresence);
+
+ item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(getUIRosterChildren()[0])->getChildren()[0]);
+ CPPUNIT_ASSERT(item);
+ CPPUNIT_ASSERT_EQUAL(contact, item->getJID());
+ CPPUNIT_ASSERT_EQUAL(true, item->supportsFeature(ContactRosterItem::FileTransferFeature));
+
+ unavailablePresence = std::make_shared<Presence>();
+ unavailablePresence->setFrom(contact.withResource("ft-supported"));
+ unavailablePresence->setPriority(0);
+ unavailablePresence->setType(Presence::Unavailable);
+ stanzaChannel_->onPresenceReceived(unavailablePresence);
+
+ item = dynamic_cast<ContactRosterItem*>(dynamic_cast<GroupRosterItem*>(getUIRosterChildren()[0])->getChildren()[0]);
+ CPPUNIT_ASSERT(item);
+ CPPUNIT_ASSERT_EQUAL(contact, item->getJID());
+ CPPUNIT_ASSERT_EQUAL(false, item->supportsFeature(ContactRosterItem::FileTransferFeature));
+ }
+
+ void assertVectorsEqual(const std::vector<std::string>& v1, const std::vector<std::string>& v2, int line) {
+ for (const auto& 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());
+ }
+ }
+ }
+
+ const std::vector<RosterItem*>& getUIRosterChildren() const {
+ return mainWindow_->roster->getRoot()->getChildren();
+ }
+
+ private:
+ JID jid_;
+ std::unique_ptr<MemoryStorages> storages_;
+ 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_;
+ std::unique_ptr<CapsManager> capsManager_;
+ EntityCapsManager* entityCapsManager_;
+ JingleSessionManager* jingleSessionManager_;
+ ClientBlockListManager* clientBlockListManager_;
+ CryptoProvider* crypto_;
+ VCardStorage* vcardStorage_;
+ VCardManager* vcardManager_;
+ std::unique_ptr<CapsInfoGenerator> capsInfoGenerator_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(RosterControllerTest);
diff --git a/Swift/Controllers/Roster/UnitTest/RosterTest.cpp b/Swift/Controllers/Roster/UnitTest/RosterTest.cpp
index d905d9f..5f500d4 100644
--- a/Swift/Controllers/Roster/UnitTest/RosterTest.cpp
+++ b/Swift/Controllers/Roster/UnitTest/RosterTest.cpp
@@ -1,145 +1,141 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/shared_ptr.hpp>
-
-#include <Swift/Controllers/Roster/Roster.h>
#include <Swift/Controllers/Roster/GroupRosterItem.h>
#include <Swift/Controllers/Roster/ItemOperations/SetPresence.h>
+#include <Swift/Controllers/Roster/Roster.h>
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_ = std::unique_ptr<Roster>(new 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", "");
+ std::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 = std::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 = std::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:
+ std::unique_ptr<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..ddc8785 100644
--- a/Swift/Controllers/Roster/UnitTest/TableRosterTest.cpp
+++ b/Swift/Controllers/Roster/UnitTest/TableRosterTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,14 +9,15 @@
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 <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/shared_ptr.hpp>
#include <boost/variant.hpp>
#include <Swiften/Network/DummyTimerFactory.h>
@@ -27,67 +28,62 @@ 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 = std::unique_ptr<DummyTimerFactory>(new DummyTimerFactory());
+ roster = std::unique_ptr<Roster>(new Roster());
+ jid1 = JID("jid1@example.com");
+ jid2 = JID("jid2@example.com");
+ }
+
+ void testAddContact_EmptyRoster() {
+ /*
+ std::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.get(), timerFactory.get(), 10);
+ result->onUpdate.connect(boost::bind(&TableRosterTest::handleUpdate, this, _1));
+ return result;
+ }
+
+ void handleUpdate(const TableRoster::Update& update) {
+ updates.push_back(update);
+ }
+
+ private:
+ std::unique_ptr<DummyTimerFactory> timerFactory;
+ std::unique_ptr<Roster> roster;
+ JID jid1;
+ JID jid2;
+ std::vector<TableRoster::Update> updates;
};
CPPUNIT_TEST_SUITE_REGISTRATION(TableRosterTest);
diff --git a/Swift/Controllers/SConscript b/Swift/Controllers/SConscript
index 5ebbdd3..105b44b 100644
--- a/Swift/Controllers/SConscript
+++ b/Swift/Controllers/SConscript
@@ -6,10 +6,10 @@ import Version
################################################################################
if env["SCONS_STAGE"] == "flags" :
- env["SWIFT_CONTROLLERS_FLAGS"] = {
- "LIBPATH": [Dir(".")],
- "LIBS": ["SwiftControllers"]
- }
+ env["SWIFT_CONTROLLERS_FLAGS"] = {
+ "LIBPATH": [Dir(".")],
+ "LIBS": ["SwiftControllers"]
+ }
################################################################################
@@ -17,95 +17,95 @@ if env["SCONS_STAGE"] == "flags" :
################################################################################
if env["SCONS_STAGE"] == "build" :
- myenv = env.Clone()
- myenv.BuildVersion("BuildVersion.h", project = "swift")
- myenv.UseFlags(env["SWIFTEN_FLAGS"])
- myenv.UseFlags(env["SWIFTEN_DEP_FLAGS"])
- myenv.StaticLibrary("SwiftControllers", [
- "Chat/ChatController.cpp",
- "Chat/ChatControllerBase.cpp",
- "Chat/ChatsManager.cpp",
- "Chat/MUCController.cpp",
- "Chat/MUCSearchController.cpp",
- "Chat/UserSearchController.cpp",
- "Chat/ChatMessageParser.cpp",
- "ContactSuggester.cpp",
- "MainController.cpp",
- "ProfileController.cpp",
- "ShowProfileController.cpp",
- "ContactEditController.cpp",
- "FileTransfer/FileTransferController.cpp",
- "FileTransfer/FileTransferOverview.cpp",
- "FileTransfer/FileTransferProgressInfo.cpp",
- "Roster/RosterController.cpp",
- "Roster/RosterGroupExpandinessPersister.cpp",
- "Roster/ContactRosterItem.cpp",
- "Roster/GroupRosterItem.cpp",
- "Roster/RosterItem.cpp",
- "Roster/Roster.cpp",
- "Roster/RosterVCardProvider.cpp",
- "Roster/TableRoster.cpp",
- "EventWindowController.cpp",
- "SoundEventController.cpp",
- "SystemTrayController.cpp",
- "XMLConsoleController.cpp",
- "HistoryViewController.cpp",
- "HistoryController.cpp",
- "FileTransferListController.cpp",
- "BlockListController.cpp",
- "StatusTracker.cpp",
- "PresenceNotifier.cpp",
- "EventNotifier.cpp",
- "AdHocManager.cpp",
- "AdHocController.cpp",
- "XMPPEvents/EventController.cpp",
- "UIEvents/UIEvent.cpp",
- "UIInterfaces/XMLConsoleWidget.cpp",
- "UIInterfaces/ChatListWindow.cpp",
- "UIInterfaces/HighlightEditorWindow.cpp",
- "PreviousStatusStore.cpp",
- "ProfileSettingsProvider.cpp",
- "Settings/SettingsProviderHierachy.cpp",
- "Settings/XMLSettingsProvider.cpp",
- "Storages/CertificateStorageFactory.cpp",
- "Storages/CertificateStorage.cpp",
- "Storages/CertificateFileStorage.cpp",
- "Storages/CertificateMemoryStorage.cpp",
- "Storages/AvatarFileStorage.cpp",
- "Storages/FileStorages.cpp",
- "Storages/RosterFileStorage.cpp",
- "Storages/CapsFileStorage.cpp",
- "Storages/VCardFileStorage.cpp",
- "StatusUtil.cpp",
- "Translator.cpp",
- "XMPPURIController.cpp",
- "ChatMessageSummarizer.cpp",
- "SettingConstants.cpp",
- "WhiteboardManager.cpp",
- "StatusCache.cpp",
- "HighlightAction.cpp",
- "HighlightEditorController.cpp",
- "HighlightManager.cpp",
- "HighlightRule.cpp",
- "Highlighter.cpp",
- "ContactsFromXMPPRoster.cpp",
- "ContactProvider.cpp",
- "Contact.cpp"
- ])
+ myenv = env.Clone()
+ myenv.BuildVersion("BuildVersion.h", project = "swift")
+ myenv.UseFlags(env["SWIFTEN_FLAGS"])
+ myenv.UseFlags(env["SWIFTEN_DEP_FLAGS"])
+ myenv.StaticLibrary("SwiftControllers", [
+ "Chat/ChatController.cpp",
+ "Chat/ChatControllerBase.cpp",
+ "Chat/ChatsManager.cpp",
+ "Chat/MUCController.cpp",
+ "Chat/MUCSearchController.cpp",
+ "Chat/UserSearchController.cpp",
+ "Chat/ChatMessageParser.cpp",
+ "ContactSuggester.cpp",
+ "MainController.cpp",
+ "ProfileController.cpp",
+ "ShowProfileController.cpp",
+ "ContactEditController.cpp",
+ "FileTransfer/FileTransferController.cpp",
+ "FileTransfer/FileTransferOverview.cpp",
+ "FileTransfer/FileTransferProgressInfo.cpp",
+ "Roster/RosterController.cpp",
+ "Roster/RosterGroupExpandinessPersister.cpp",
+ "Roster/ContactRosterItem.cpp",
+ "Roster/GroupRosterItem.cpp",
+ "Roster/RosterItem.cpp",
+ "Roster/Roster.cpp",
+ "Roster/RosterVCardProvider.cpp",
+ "Roster/TableRoster.cpp",
+ "EventWindowController.cpp",
+ "SoundEventController.cpp",
+ "SystemTrayController.cpp",
+ "XMLConsoleController.cpp",
+ "HistoryViewController.cpp",
+ "HistoryController.cpp",
+ "FileTransferListController.cpp",
+ "BlockListController.cpp",
+ "StatusTracker.cpp",
+ "PresenceNotifier.cpp",
+ "EventNotifier.cpp",
+ "AdHocManager.cpp",
+ "AdHocController.cpp",
+ "XMPPEvents/EventController.cpp",
+ "UIEvents/UIEvent.cpp",
+ "UIInterfaces/XMLConsoleWidget.cpp",
+ "UIInterfaces/ChatListWindow.cpp",
+ "UIInterfaces/HighlightEditorWindow.cpp",
+ "PreviousStatusStore.cpp",
+ "ProfileSettingsProvider.cpp",
+ "Settings/SettingsProviderHierachy.cpp",
+ "Settings/XMLSettingsProvider.cpp",
+ "Storages/CertificateStorageFactory.cpp",
+ "Storages/CertificateStorage.cpp",
+ "Storages/CertificateFileStorage.cpp",
+ "Storages/CertificateMemoryStorage.cpp",
+ "Storages/AvatarFileStorage.cpp",
+ "Storages/FileStorages.cpp",
+ "Storages/RosterFileStorage.cpp",
+ "Storages/CapsFileStorage.cpp",
+ "Storages/VCardFileStorage.cpp",
+ "StatusUtil.cpp",
+ "Translator.cpp",
+ "XMPPURIController.cpp",
+ "ChatMessageSummarizer.cpp",
+ "SettingConstants.cpp",
+ "WhiteboardManager.cpp",
+ "StatusCache.cpp",
+ "HighlightAction.cpp",
+ "HighlightEditorController.cpp",
+ "HighlightManager.cpp",
+ "HighlightRule.cpp",
+ "Highlighter.cpp",
+ "ContactsFromXMPPRoster.cpp",
+ "ContactProvider.cpp",
+ "Contact.cpp"
+ ])
- env.Append(UNITTEST_SOURCES = [
- File("Roster/UnitTest/RosterControllerTest.cpp"),
- File("Roster/UnitTest/RosterTest.cpp"),
- File("Roster/UnitTest/LeastCommonSubsequenceTest.cpp"),
- File("Roster/UnitTest/TableRosterTest.cpp"),
- File("UnitTest/PreviousStatusStoreTest.cpp"),
- File("UnitTest/PresenceNotifierTest.cpp"),
- File("Chat/UnitTest/ChatsManagerTest.cpp"),
- File("Chat/UnitTest/MUCControllerTest.cpp"),
- File("Chat/UnitTest/ChatMessageParserTest.cpp"),
- File("UnitTest/MockChatWindow.cpp"),
- File("UnitTest/ChatMessageSummarizerTest.cpp"),
- File("Settings/UnitTest/SettingsProviderHierachyTest.cpp"),
- File("UnitTest/HighlightRuleTest.cpp"),
- File("UnitTest/ContactSuggesterTest.cpp")
- ])
+ env.Append(UNITTEST_SOURCES = [
+ File("Roster/UnitTest/RosterControllerTest.cpp"),
+ File("Roster/UnitTest/RosterTest.cpp"),
+ File("Roster/UnitTest/LeastCommonSubsequenceTest.cpp"),
+ File("Roster/UnitTest/TableRosterTest.cpp"),
+ File("UnitTest/PreviousStatusStoreTest.cpp"),
+ File("UnitTest/PresenceNotifierTest.cpp"),
+ File("Chat/UnitTest/ChatsManagerTest.cpp"),
+ File("Chat/UnitTest/MUCControllerTest.cpp"),
+ File("Chat/UnitTest/ChatMessageParserTest.cpp"),
+ File("UnitTest/MockChatWindow.cpp"),
+ File("UnitTest/ChatMessageSummarizerTest.cpp"),
+ File("Settings/UnitTest/SettingsProviderHierachyTest.cpp"),
+ File("UnitTest/HighlightRuleTest.cpp"),
+ File("UnitTest/ContactSuggesterTest.cpp")
+ ])
diff --git a/Swift/Controllers/SettingConstants.cpp b/Swift/Controllers/SettingConstants.cpp
index 9807abc..dedf56b 100644
--- a/Swift/Controllers/SettingConstants.cpp
+++ b/Swift/Controllers/SettingConstants.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -20,13 +20,8 @@ const SettingsProvider::Setting<bool> SettingConstants::SHOW_OFFLINE("showOfflin
const SettingsProvider::Setting<std::string> SettingConstants::EXPANDED_ROSTER_GROUPS("GroupExpandiness", "");
const SettingsProvider::Setting<bool> SettingConstants::PLAY_SOUNDS("playSounds", true);
const SettingsProvider::Setting<std::string> SettingConstants::HIGHLIGHT_RULES("highlightRules", "@");
-const SettingsProvider::Setting<bool> SettingConstants::SPELL_CHECKER("spellChecker", false);
-const SettingsProvider::Setting<std::string> SettingConstants::DICT_PATH("dictPath", "/usr/share/myspell/dicts/");
-const SettingsProvider::Setting<std::string> SettingConstants::PERSONAL_DICT_PATH("personaldictPath", "/home/");
-const SettingsProvider::Setting<std::string> SettingConstants::DICT_FILE("dictFile", "en_US.dic");
const SettingsProvider::Setting<std::string> SettingConstants::INVITE_AUTO_ACCEPT_MODE("inviteAutoAcceptMode", "presence");
-const SettingsProvider::Setting<std::string> SettingConstants::TRELLIS_GRID_SIZE("trellisGridSize", "");
-const SettingsProvider::Setting<std::string> SettingConstants::TRELLIS_GRID_POSITIONS("trellisGridPositions", "");
const SettingsProvider::Setting<bool> SettingConstants::DISCONNECT_ON_CARD_REMOVAL("disconnectOnCardRemoval", true);
const SettingsProvider::Setting<bool> SettingConstants::SINGLE_SIGN_ON("singleSignOn", false);
+
}
diff --git a/Swift/Controllers/SettingConstants.h b/Swift/Controllers/SettingConstants.h
index c4ac4ad..3f15c44 100644
--- a/Swift/Controllers/SettingConstants.h
+++ b/Swift/Controllers/SettingConstants.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,100 +9,82 @@
#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;
+ /**
+ * 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 #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 340855a..134aadc 100644
--- a/Swift/Controllers/Settings/DummySettingsProvider.h
+++ b/Swift/Controllers/Settings/DummySettingsProvider.h
@@ -1,56 +1,58 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swift/Controllers/Settings/SettingsProvider.h>
-
#include <map>
+#include <set>
+#include <string>
+
+#include <Swift/Controllers/Settings/SettingsProvider.h>
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 1e62d2e..1e9805a 100644
--- a/Swift/Controllers/Settings/SettingsProvider.h
+++ b/Swift/Controllers/Settings/SettingsProvider.h
@@ -1,71 +1,71 @@
/*
- * Copyright (c) 2010-2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-
#include <string>
#include <vector>
+#include <boost/signals2.hpp>
+
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::signals2::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..a05fabc 100644
--- a/Swift/Controllers/Settings/SettingsProviderHierachy.cpp
+++ b/Swift/Controllers/Settings/SettingsProviderHierachy.cpp
@@ -1,115 +1,115 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Settings/SettingsProviderHierachy.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/Log.h>
+
namespace Swift {
SettingsProviderHierachy::~SettingsProviderHierachy() {
}
bool SettingsProviderHierachy::hasSetting(const std::string& key) {
- foreach (SettingsProvider* provider, providers_) {
- if (provider->hasSetting(key)) {
- return true;
- }
- }
- return false;
+ for (auto provider : providers_) {
+ if (provider->hasSetting(key)) {
+ return true;
+ }
+ }
+ return false;
}
std::string SettingsProviderHierachy::getSetting(const Setting<std::string>& setting) {
- std::string value = setting.getDefaultValue();
- foreach (SettingsProvider* provider, providers_) {
- 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();
+ for (auto provider : providers_) {
+ std::string providerSetting = provider->getSetting(setting);
+ if (provider->hasSetting(setting.getKey())) {
+ value = providerSetting;
+ }
+ if (provider->getIsSettingFinal(setting.getKey())) {
+ return value;
+ }
+ }
+ return value;
}
void SettingsProviderHierachy::storeSetting(const Setting<std::string>& setting, const std::string& settingValue) {
- if (!getIsSettingFinal(setting.getKey())) {
- getWritableProvider()->storeSetting(setting, settingValue);
- }
+ 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();
+ for (auto provider : providers_) {
+ bool providerSetting = provider->getSetting(setting);
+ if (provider->hasSetting(setting.getKey())) {
+ value = providerSetting;
+ if (provider->getIsSettingFinal(setting.getKey())) {
+ return providerSetting;
+ }
+ }
+ }
+ return value;
}
void SettingsProviderHierachy::storeSetting(const Setting<bool>& setting, const bool& settingValue) {
- if (!getIsSettingFinal(setting.getKey())) {
- getWritableProvider()->storeSetting(setting, settingValue);
- }
+ 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();
+ for (auto provider : providers_) {
+ int providerSetting = provider->getSetting(setting);
+ if (provider->hasSetting(setting.getKey())) {
+ value = providerSetting;
+ if (provider->getIsSettingFinal(setting.getKey())) {
+ return providerSetting;
+ }
+ }
+ }
+ return value;
}
void SettingsProviderHierachy::storeSetting(const Setting<int>& setting, const int& settingValue) {
- if (!getIsSettingFinal(setting.getKey())) {
- getWritableProvider()->storeSetting(setting, settingValue);
- }
+ 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;
+ for (auto 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 dc9a92d..3cfebc7 100644
--- a/Swift/Controllers/Settings/UnitTest/SettingsProviderHierachyTest.cpp
+++ b/Swift/Controllers/Settings/UnitTest/SettingsProviderHierachyTest.cpp
@@ -1,91 +1,87 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swift/Controllers/Settings/SettingsProviderHierachy.h>
#include <Swift/Controllers/Settings/DummySettingsProvider.h>
+#include <Swift/Controllers/Settings/SettingsProviderHierachy.h>
#include <Swift/Controllers/Settings/XMLSettingsProvider.h>
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) {}
-
- void setUp() {
- bottom = new DummySettingsProvider();
- top = new DummySettingsProvider();
- testling = new SettingsProviderHierachy();
- testling->addProviderToTopOfStack(bottom);
- testling->addProviderToTopOfStack(top);
- }
+ SettingsProviderHierachyTest() : setting1("somekey", 42) {}
- void tearDown() {
- delete testling;
- delete top;
- delete bottom;
- }
+ void setUp() {
+ bottom = std::unique_ptr<DummySettingsProvider>(new DummySettingsProvider());
+ top = std::unique_ptr<DummySettingsProvider>(new DummySettingsProvider());
+ testling = std::unique_ptr<SettingsProviderHierachy>(new SettingsProviderHierachy());
+ testling->addProviderToTopOfStack(bottom.get());
+ testling->addProviderToTopOfStack(top.get());
+ }
- 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;
+ std::unique_ptr<SettingsProviderHierachy> testling;
+ std::unique_ptr<DummySettingsProvider> bottom;
+ std::unique_ptr<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 d28947f..4dfb8bd 100644
--- a/Swift/Controllers/Settings/XMLSettingsProvider.cpp
+++ b/Swift/Controllers/Settings/XMLSettingsProvider.cpp
@@ -1,35 +1,35 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Settings/XMLSettingsProvider.h>
-#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
+#include <boost/lexical_cast.hpp>
+#include <Swiften/Base/Log.h>
#include <Swiften/Parser/PlatformXMLParserFactory.h>
#include <Swiften/Parser/XMLParser.h>
-#include <Swiften/Base/Log.h>
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 24689b7..5fd82cf 100644
--- a/Swift/Controllers/Settings/XMLSettingsProvider.h
+++ b/Swift/Controllers/Settings/XMLSettingsProvider.h
@@ -1,54 +1,55 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swift/Controllers/Settings/SettingsProvider.h>
-#include <Swiften/Parser/XMLParserClient.h>
-
#include <map>
#include <set>
+#include <Swiften/Parser/XMLParserClient.h>
+
+#include <Swift/Controllers/Settings/SettingsProvider.h>
+
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 88d6e69..b379141 100644
--- a/Swift/Controllers/ShowProfileController.cpp
+++ b/Swift/Controllers/ShowProfileController.cpp
@@ -5,17 +5,16 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "ShowProfileController.h"
+#include <Swift/Controllers/ShowProfileController.h>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/VCards/VCardManager.h>
#include <Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h>
@@ -25,57 +24,56 @@
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;
- }
+ for (const auto& jidWndPair : openedProfileWindows) {
+ jidWndPair.second->onWindowAboutToBeClosed.disconnect(boost::bind(&ShowProfileController::handleProfileWindowAboutToBeClosed, this, _1));
+ delete jidWndPair.second;
+ }
- vcardManager->onVCardChanged.disconnect(boost::bind(&ShowProfileController::handleVCardChanged, this, _1, _2));
- uiEventStream->onUIEvent.disconnect(boost::bind(&ShowProfileController::handleUIEvent, this, _1));
+ 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 = std::dynamic_pointer_cast<ShowProfileForRosterItemUIEvent>(event);
+ if (!showProfileEvent) {
+ return;
+ }
- if (openedProfileWindows.find(showProfileEvent->getJID()) == openedProfileWindows.end()) {
- ProfileWindow* newProfileWindow = profileWindowFactory->createProfileWindow();
- newProfileWindow->setJID(showProfileEvent->getJID());
- newProfileWindow->onWindowAboutToBeClosed.connect(boost::bind(&ShowProfileController::handleProfileWindowAboutToBeClosed, this, _1));
- openedProfileWindows[showProfileEvent->getJID()] = newProfileWindow;
- VCard::ref vcard = vcardManager->getVCardAndRequestWhenNeeded(showProfileEvent->getJID(), boost::posix_time::minutes(5));
- if (vcard) {
- newProfileWindow->setVCard(vcard);
- } else {
- newProfileWindow->setProcessing(true);
- }
- newProfileWindow->show();
- } else {
- openedProfileWindows[showProfileEvent->getJID()]->show();
- }
+ 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 27a0cf4..4f23c19 100644
--- a/Swift/Controllers/ShowProfileController.h
+++ b/Swift/Controllers/ShowProfileController.h
@@ -4,33 +4,39 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/VCard.h>
+#include <Swiften/JID/JID.h>
#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..5c7568f 100644
--- a/Swift/Controllers/SoundEventController.cpp
+++ b/Swift/Controllers/SoundEventController.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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, "");
- }
+void SoundEventController::handleEventQueueEventAdded(std::shared_ptr<StanzaEvent> event) {
+ if (playSounds_ && std::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 17924cd..e5b43b4 100644
--- a/Swift/Controllers/SoundEventController.h
+++ b/Swift/Controllers/SoundEventController.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2010-2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swift/Controllers/XMPPEvents/StanzaEvent.h>
-#include <Swift/Controllers/Settings/SettingsProvider.h>
#include <Swift/Controllers/HighlightAction.h>
+#include <Swift/Controllers/Settings/SettingsProvider.h>
+#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(std::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 e40ac7f..3c6baed 100644
--- a/Swift/Controllers/StatusCache.cpp
+++ b/Swift/Controllers/StatusCache.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,25 +7,22 @@
#include <Swift/Controllers/StatusCache.h>
#include <boost/algorithm/string.hpp>
-#include <boost/lexical_cast.hpp>
#include <boost/filesystem/fstream.hpp>
-#include <boost/lambda/lambda.hpp>
-#include <boost/lambda/bind.hpp>
+#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/ByteArray.h>
-#include <SwifTools/Application/ApplicationPathProvider.h>
+#include <Swiften/Base/Log.h>
-namespace lambda = boost::lambda;
+#include <SwifTools/Application/ApplicationPathProvider.h>
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() {
@@ -33,71 +30,78 @@ 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;
+ for (const auto& 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([&](const PreviousStatus& previousStatus) {
+ return previousStatus.first == text && previousStatus.second == 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"));
+ for (const auto& line : lines) {
+ std::vector<std::string> bits;
+ boost::split(bits, line, boost::is_any_of("\t"));
+ if (bits.size() < 2) {
+ continue;
+ }
+ StatusShow::Type type;
+ try {
+ 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::bad_lexical_cast& e) {
+ SWIFT_LOG(error) << "Failed to load recent status cache entry: " << e.what() << std::endl;
+ }
+ }
+ }
+ }
+ catch (const boost::filesystem::filesystem_error& e) {
+ SWIFT_LOG(error) << "Failed to load recents: " << 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_);
+ for (const auto& 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) {
+ SWIFT_LOG(error) << "Failed to save recents: " << e.what() << std::endl;
+ }
}
}
diff --git a/Swift/Controllers/StatusCache.h b/Swift/Controllers/StatusCache.h
index 94c8efc..83fd17a 100644
--- a/Swift/Controllers/StatusCache.h
+++ b/Swift/Controllers/StatusCache.h
@@ -1,40 +1,41 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <list>
#include <string>
#include <utility>
-#include <vector>
-#include <list>
-#include <iostream>
#include <boost/filesystem/path.hpp>
#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 1f4f783..56cd27f 100644
--- a/Swift/Controllers/StatusTracker.cpp
+++ b/Swift/Controllers/StatusTracker.cpp
@@ -1,58 +1,58 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/StatusTracker.h"
+#include <Swift/Controllers/StatusTracker.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Elements/Idle.h>
namespace Swift {
StatusTracker::StatusTracker() {
- isAutoAway_ = false;
- queuedPresence_ = boost::make_shared<Presence>();
+ isAutoAway_ = false;
+ queuedPresence_ = std::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;
+std::shared_ptr<Presence> StatusTracker::getNextPresence() {
+ std::shared_ptr<Presence> presence;
+ if (isAutoAway_) {
+ presence = std::make_shared<Presence>();
+ presence->setShow(StatusShow::Away);
+ presence->setStatus(queuedPresence_->getStatus());
+ presence->addPayload(std::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>();
-// }
+void StatusTracker::setRequestedPresence(std::shared_ptr<Presence> presence) {
+ isAutoAway_ = false;
+ queuedPresence_ = presence;
+// if (presence->getType() == Presence::Unavailable) {
+// queuedPresence_ = std::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 472f30c..a74ab6e 100644
--- a/Swift/Controllers/StatusTracker.h
+++ b/Swift/Controllers/StatusTracker.h
@@ -1,29 +1,29 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-
-#include "Swiften/Elements/Presence.h"
+#include <memory>
#include <boost/date_time/posix_time/posix_time_types.hpp>
+#include <Swiften/Elements/Presence.h>
+
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();
+ std::shared_ptr<Presence> getNextPresence();
+ void setRequestedPresence(std::shared_ptr<Presence> presence);
+ bool goAutoAway(const int& seconds);
+ bool goAutoUnAway();
+ private:
+ std::shared_ptr<Presence> queuedPresence_;
+ bool isAutoAway_;
+ boost::posix_time::ptime isAutoAwaySince_;
+ };
}
diff --git a/Swift/Controllers/StatusUtil.cpp b/Swift/Controllers/StatusUtil.cpp
index 6c049a2..1034863 100644
--- a/Swift/Controllers/StatusUtil.cpp
+++ b/Swift/Controllers/StatusUtil.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,21 +7,22 @@
#include <Swift/Controllers/StatusUtil.h>
#include <cassert>
+
#include <Swift/Controllers/Intl.h>
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 39c3468..a103920 100644
--- a/Swift/Controllers/Storages/AvatarFileStorage.cpp
+++ b/Swift/Controllers/Storages/AvatarFileStorage.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,99 +7,99 @@
#include <Swift/Controllers/Storages/AvatarFileStorage.h>
#include <iostream>
-#include <boost/filesystem/fstream.hpp>
+
#include <boost/filesystem.hpp>
+#include <boost/filesystem/fstream.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/String.h>
-#include <Swiften/StringCodecs/Hexify.h>
#include <Swiften/Crypto/CryptoProvider.h>
+#include <Swiften/StringCodecs/Hexify.h>
namespace Swift {
AvatarFileStorage::AvatarFileStorage(const boost::filesystem::path& avatarsDir, const boost::filesystem::path& avatarsFile, CryptoProvider* crypto) : avatarsDir(avatarsDir), avatarsFile(avatarsFile), crypto(crypto) {
- if (boost::filesystem::exists(avatarsFile)) {
- try {
- boost::filesystem::ifstream file(avatarsFile);
- std::string line;
- if (file.is_open()) {
- while (!file.eof()) {
- getline(file, line);
- std::pair<std::string, std::string> r = String::getSplittedAtFirst(line, ' ');
- JID jid(r.second);
- if (jid.isValid()) {
- jidAvatars.insert(std::make_pair(jid, r.first));
- }
- else if (!r.first.empty() || !r.second.empty()) {
- std::cerr << "Invalid entry in avatars file: " << r.second << std::endl;
- }
- }
- }
- }
- catch (...) {
- std::cerr << "Error reading avatars file" << std::endl;
- }
- }
+ 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 ecb9370..41c7106 100644
--- a/Swift/Controllers/Storages/AvatarFileStorage.h
+++ b/Swift/Controllers/Storages/AvatarFileStorage.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,37 +8,38 @@
#include <map>
#include <string>
+
#include <boost/filesystem/path.hpp>
+#include <Swiften/Avatars/AvatarStorage.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/JID/JID.h>
-#include "Swiften/Base/ByteArray.h"
-#include "Swiften/Avatars/AvatarStorage.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 f5d3a2e..21a99bc 100644
--- a/Swift/Controllers/Storages/CapsFileStorage.cpp
+++ b/Swift/Controllers/Storages/CapsFileStorage.cpp
@@ -1,16 +1,16 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/Storages/CapsFileStorage.h"
+#include <Swift/Controllers/Storages/CapsFileStorage.h>
#include <Swiften/Entity/GenericPayloadPersister.h>
-#include "Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h"
-#include "Swiften/Parser/PayloadParsers/DiscoInfoParser.h"
-#include "Swiften/StringCodecs/Hexify.h"
-#include "Swiften/StringCodecs/Base64.h"
+#include <Swiften/Parser/PayloadParsers/DiscoInfoParser.h>
+#include <Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h>
+#include <Swiften/StringCodecs/Base64.h>
+#include <Swiften/StringCodecs/Hexify.h>
using namespace Swift;
@@ -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 b8aaac2..7df23f1 100644
--- a/Swift/Controllers/Storages/CapsFileStorage.h
+++ b/Swift/Controllers/Storages/CapsFileStorage.h
@@ -1,28 +1,29 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <boost/filesystem/path.hpp>
-#include "Swiften/Disco/CapsStorage.h"
-#include <string>
+#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 52f4013..3fe6d54 100644
--- a/Swift/Controllers/Storages/CertificateFileStorage.cpp
+++ b/Swift/Controllers/Storages/CertificateFileStorage.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,13 +7,14 @@
#include <Swift/Controllers/Storages/CertificateFileStorage.h>
#include <iostream>
+
#include <boost/filesystem/fstream.hpp>
#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/StringCodecs/Hexify.h>
-#include <Swiften/TLS/CertificateFactory.h>
#include <Swiften/Base/Log.h>
#include <Swiften/Crypto/CryptoProvider.h>
+#include <Swiften/StringCodecs/Hexify.h>
+#include <Swiften/TLS/CertificateFactory.h>
namespace Swift {
@@ -21,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 e8d0fda..d2c228d 100644
--- a/Swift/Controllers/Storages/CertificateFileStorage.h
+++ b/Swift/Controllers/Storages/CertificateFileStorage.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,26 +8,26 @@
#include <boost/filesystem.hpp>
-#include "Swift/Controllers/Storages/CertificateStorage.h"
+#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 43f0866..6f466dc 100644
--- a/Swift/Controllers/Storages/CertificateFileStorageFactory.h
+++ b/Swift/Controllers/Storages/CertificateFileStorageFactory.h
@@ -1,30 +1,32 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swift/Controllers/Storages/CertificateStorageFactory.h>
+#include <Swiften/JID/JID.h>
+
#include <Swift/Controllers/Storages/CertificateFileStorage.h>
+#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..545ca65 100644
--- a/Swift/Controllers/Storages/CertificateMemoryStorage.cpp
+++ b/Swift/Controllers/Storages/CertificateMemoryStorage.cpp
@@ -1,27 +1,25 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/Storages/CertificateMemoryStorage.h>
-#include <Swiften/Base/foreach.h>
-
using namespace Swift;
CertificateMemoryStorage::CertificateMemoryStorage() {
}
bool CertificateMemoryStorage::hasCertificate(Certificate::ref certificate) const {
- foreach(Certificate::ref storedCert, certificates) {
- if (storedCert->toDER() == certificate->toDER()) {
- return true;
- }
- }
- return false;
+ for (auto&& 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.cpp b/Swift/Controllers/Storages/CertificateStorage.cpp
index 041c5a1..38ed564 100644
--- a/Swift/Controllers/Storages/CertificateStorage.cpp
+++ b/Swift/Controllers/Storages/CertificateStorage.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/Storages/CertificateStorage.h"
+#include <Swift/Controllers/Storages/CertificateStorage.h>
namespace Swift {
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 caf4d1f..3c708a3 100644
--- a/Swift/Controllers/Storages/CertificateStorageTrustChecker.h
+++ b/Swift/Controllers/Storages/CertificateStorageTrustChecker.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,28 +7,29 @@
#pragma once
#include <Swiften/TLS/CertificateTrustChecker.h>
+
#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 4fb2034..49f9ecf 100644
--- a/Swift/Controllers/Storages/FileStorages.cpp
+++ b/Swift/Controllers/Storages/FileStorages.cpp
@@ -1,61 +1,63 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/Storages/FileStorages.h"
-#include "Swift/Controllers/Storages/VCardFileStorage.h"
-#include "Swift/Controllers/Storages/AvatarFileStorage.h"
-#include "Swift/Controllers/Storages/CapsFileStorage.h"
-#include "Swift/Controllers/Storages/RosterFileStorage.h"
-#include <Swiften/History/SQLiteHistoryStorage.h>
+#include <Swift/Controllers/Storages/FileStorages.h>
+
#include <Swiften/Base/Path.h>
+#include <Swiften/History/SQLiteHistoryStorage.h>
+
+#include <Swift/Controllers/Storages/AvatarFileStorage.h>
+#include <Swift/Controllers/Storages/CapsFileStorage.h>
+#include <Swift/Controllers/Storages/RosterFileStorage.h>
+#include <Swift/Controllers/Storages/VCardFileStorage.h>
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 = nullptr;
#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 nullptr;
#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 7269810..ec0106e 100644
--- a/Swift/Controllers/Storages/FileStoragesFactory.h
+++ b/Swift/Controllers/Storages/FileStoragesFactory.h
@@ -1,27 +1,27 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/Storages/StoragesFactory.h"
-#include "Swift/Controllers/Storages/FileStorages.h"
+#include <Swift/Controllers/Storages/FileStorages.h>
+#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 8c68f19..28e9138 100644
--- a/Swift/Controllers/Storages/MemoryStoragesFactory.h
+++ b/Swift/Controllers/Storages/MemoryStoragesFactory.h
@@ -1,26 +1,27 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/Storages/StoragesFactory.h"
-#include "Swiften/Client/MemoryStorages.h"
+#include <Swiften/Client/MemoryStorages.h>
+
+#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 a7f6810..1f0a90b 100644
--- a/Swift/Controllers/Storages/RosterFileStorage.cpp
+++ b/Swift/Controllers/Storages/RosterFileStorage.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,8 +7,8 @@
#include <Swift/Controllers/Storages/RosterFileStorage.h>
#include <Swiften/Entity/GenericPayloadPersister.h>
-#include <Swiften/Serializer/PayloadSerializers/RosterSerializer.h>
#include <Swiften/Parser/PayloadParsers/RosterParser.h>
+#include <Swiften/Serializer/PayloadSerializers/RosterSerializer.h>
using namespace Swift;
@@ -17,10 +17,10 @@ typedef GenericPayloadPersister<RosterPayload, RosterParser, RosterSerializer> R
RosterFileStorage::RosterFileStorage(const boost::filesystem::path& path) : path(path) {
}
-boost::shared_ptr<RosterPayload> RosterFileStorage::getRoster() const {
- return RosterPersister().loadPayloadGeneric(path);
+std::shared_ptr<RosterPayload> RosterFileStorage::getRoster() const {
+ return RosterPersister().loadPayloadGeneric(path);
}
-void RosterFileStorage::setRoster(boost::shared_ptr<RosterPayload> roster) {
- RosterPersister().savePayload(roster, path);
+void RosterFileStorage::setRoster(std::shared_ptr<RosterPayload> roster) {
+ RosterPersister().savePayload(roster, path);
}
diff --git a/Swift/Controllers/Storages/RosterFileStorage.h b/Swift/Controllers/Storages/RosterFileStorage.h
index d100793..38e26c9 100644
--- a/Swift/Controllers/Storages/RosterFileStorage.h
+++ b/Swift/Controllers/Storages/RosterFileStorage.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::shared_ptr<RosterPayload> getRoster() const;
+ virtual void setRoster(std::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 95f2575..2fdadf6 100644
--- a/Swift/Controllers/Storages/VCardFileStorage.cpp
+++ b/Swift/Controllers/Storages/VCardFileStorage.cpp
@@ -1,126 +1,126 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/Storages/VCardFileStorage.h"
+#include <Swift/Controllers/Storages/VCardFileStorage.h>
-#include <boost/filesystem/fstream.hpp>
-#include <boost/filesystem.hpp>
#include <iostream>
-#include <Swiften/Entity/GenericPayloadPersister.h>
-#include <Swiften/Base/String.h>
-#include <Swiften/StringCodecs/Hexify.h>
-#include <Swiften/Base/foreach.h>
+#include <boost/filesystem.hpp>
+#include <boost/filesystem/fstream.hpp>
+
#include <Swiften/Base/Path.h>
+#include <Swiften/Base/String.h>
#include <Swiften/Crypto/CryptoProvider.h>
-#include "Swiften/JID/JID.h"
-#include "Swiften/Elements/VCard.h"
-#include "Swiften/Serializer/PayloadSerializers/VCardSerializer.h"
-#include "Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h"
-#include "Swiften/Parser/PayloadParsers/VCardParser.h"
+#include <Swiften/Elements/VCard.h>
+#include <Swiften/Entity/GenericPayloadPersister.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h>
+#include <Swiften/Parser/PayloadParsers/VCardParser.h>
+#include <Swiften/Serializer/PayloadSerializers/VCardSerializer.h>
+#include <Swiften/StringCodecs/Hexify.h>
using namespace Swift;
typedef GenericPayloadPersister<VCard, VCardParser, VCardSerializer> VCardPersister;
VCardFileStorage::VCardFileStorage(boost::filesystem::path dir, CryptoProvider* crypto) : VCardStorage(crypto), vcardsPath(dir), crypto(crypto) {
- cacheFile = vcardsPath / "phashes";
- if (boost::filesystem::exists(cacheFile)) {
- try {
- boost::filesystem::ifstream file(cacheFile);
- std::string line;
- if (file.is_open()) {
- while (!file.eof()) {
- getline(file, line);
- std::pair<std::string, std::string> r = String::getSplittedAtFirst(line, ' ');
- JID jid(r.second);
- if (jid.isValid()) {
- photoHashes.insert(std::make_pair(jid, r.first));
- }
- else if (!r.first.empty() || !r.second.empty()) {
- std::cerr << "Invalid entry in phashes file" << std::endl;
- }
- }
- }
- }
- 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;
+std::shared_ptr<VCard> VCardFileStorage::getVCard(const JID& jid) const {
+ std::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 85cf3fe..a91e914 100644
--- a/Swift/Controllers/Storages/VCardFileStorage.h
+++ b/Swift/Controllers/Storages/VCardFileStorage.h
@@ -1,43 +1,44 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/filesystem/path.hpp>
-#include <string>
#include <map>
+#include <memory>
+#include <string>
+
+#include <boost/filesystem/path.hpp>
-#include "Swiften/VCards/VCardStorage.h"
+#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 b85de99..094857f 100644
--- a/Swift/Controllers/SystemTray.h
+++ b/Swift/Controllers/SystemTray.h
@@ -1,19 +1,19 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swiften/Elements/StatusShow.h"
+#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 aa87537..8d4b2b7 100644
--- a/Swift/Controllers/SystemTrayController.cpp
+++ b/Swift/Controllers/SystemTrayController.cpp
@@ -1,42 +1,42 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/SystemTrayController.h"
+#include <Swift/Controllers/SystemTrayController.h>
#include <boost/bind.hpp>
-#include "Swift/Controllers/XMPPEvents/EventController.h"
-#include "Swift/Controllers/SystemTray.h"
+#include <Swift/Controllers/SystemTray.h>
+#include <Swift/Controllers/XMPPEvents/EventController.h>
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 (auto& event : events) {
+ if (std::dynamic_pointer_cast<MessageEvent>(event)) {
+ 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 202e0ec..850ac71 100644
--- a/Swift/Controllers/SystemTrayController.h
+++ b/Swift/Controllers/SystemTrayController.h
@@ -1,27 +1,27 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swiften/Elements/StatusShow.h"
+#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..f03c533 100644
--- a/Swift/Controllers/Translator.cpp
+++ b/Swift/Controllers/Translator.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,12 +8,18 @@
#include <cassert>
+#include <Swiften/Base/DateTime.h>
+
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;
+ }
+
+ virtual std::string ptimeToHumanReadableString(const boost::posix_time::ptime& time) {
+ return dateTimeToLocalString(time);
+ }
} defaultTranslator;
Translator* Translator::translator = &defaultTranslator;
@@ -22,7 +28,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..f37e059 100644
--- a/Swift/Controllers/Translator.h
+++ b/Swift/Controllers/Translator.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,20 +8,24 @@
#include <string>
+#include <boost/date_time/posix_time/posix_time_types.hpp>
+
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;
+ virtual std::string ptimeToHumanReadableString(const boost::posix_time::ptime& time) = 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..ac76ec4 100644
--- a/Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h
+++ b/Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h
@@ -4,21 +4,27 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/JID/JID.h>
#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 std::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 50a8761..df5bf36 100644
--- a/Swift/Controllers/UIEvents/AddContactUIEvent.h
+++ b/Swift/Controllers/UIEvents/AddContactUIEvent.h
@@ -1,36 +1,38 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <string>
#include <set>
+#include <string>
+
+#include <Swiften/JID/JID.h>
-#include "Swift/Controllers/UIEvents/UIEvent.h"
+#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 8523a78..e1d6744 100644
--- a/Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h
+++ b/Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h
@@ -1,23 +1,24 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include "Swift/Controllers/UIEvents/UIEvent.h"
-#include "Swiften/MUC/MUCBookmark.h"
+#include <Swiften/MUC/MUCBookmark.h>
+
+#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..1e9491f 100644
--- a/Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h
+++ b/Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h
@@ -4,21 +4,27 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/JID/JID.h>
#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 std::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..e420bad 100644
--- a/Swift/Controllers/UIEvents/CreateImpromptuMUCUIEvent.h
+++ b/Swift/Controllers/UIEvents/CreateImpromptuMUCUIEvent.h
@@ -4,23 +4,44 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
+#include <string>
+#include <vector>
+
+#include <Swiften/JID/JID.h>
+
#include <Swift/Controllers/UIEvents/UIEvent.h>
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) { }
-
- 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_;
+ public:
+ /**
+ * @brief CreateImpromptuMUCUIEvent
+ * @param jids A vector of JIDs that are invited to the imprompto MUC.
+ * Useful when the event is used to recreate an old impromptu
+ * chat room.
+ * @param roomJID The full JID of the impromtu MUC. Useful when the event
+ * is used to recreate an old impromptu chat room.
+ * @param reason
+ */
+ 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_;
};
}
diff --git a/Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h b/Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h
index 01c59a3..33f38f2 100644
--- a/Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h
+++ b/Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h
@@ -1,26 +1,27 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include "Swift/Controllers/UIEvents/UIEvent.h"
-#include "Swiften/MUC/MUCBookmark.h"
+#include <Swiften/MUC/MUCBookmark.h>
+
+#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 cb9d20b..e38eab8 100644
--- a/Swift/Controllers/UIEvents/InviteToMUCUIEvent.h
+++ b/Swift/Controllers/UIEvents/InviteToMUCUIEvent.h
@@ -4,37 +4,44 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <vector>
-#include <Swift/Controllers/UIEvents/UIEvent.h>
#include <Swiften/JID/JID.h>
+#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 std::shared_ptr<InviteToMUCUIEvent> ref;
+
+ InviteToMUCUIEvent(const JID& originator, const std::vector<JID>& JIDsToInvite, const std::string& reason) : originator_(originator), invite_(JIDsToInvite), reason_(reason) {
+ }
+
+ const JID& getOriginator() const {
+ return originator_;
+ }
+
+ const std::vector<JID> getInvites() const {
+ return invite_;
+ }
+
+ const std::string getReason() const {
+ return reason_;
+ }
+
+ private:
+ JID originator_;
+ std::vector<JID> invite_;
+ std::string reason_;
+ };
}
diff --git a/Swift/Controllers/UIEvents/JoinMUCUIEvent.h b/Swift/Controllers/UIEvents/JoinMUCUIEvent.h
index a1f91f6..5d6df55 100644
--- a/Swift/Controllers/UIEvents/JoinMUCUIEvent.h
+++ b/Swift/Controllers/UIEvents/JoinMUCUIEvent.h
@@ -1,39 +1,40 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
+#include <boost/optional.hpp>
+
#include <Swiften/JID/JID.h>
#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 std::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 f253c2a..b73eda5 100644
--- a/Swift/Controllers/UIEvents/RemoveMUCBookmarkUIEvent.h
+++ b/Swift/Controllers/UIEvents/RemoveMUCBookmarkUIEvent.h
@@ -1,23 +1,24 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include "Swift/Controllers/UIEvents/UIEvent.h"
-#include "Swiften/MUC/MUCBookmark.h"
+#include <Swiften/MUC/MUCBookmark.h>
+
+#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 30c2c39..0f4a89d 100644
--- a/Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h
+++ b/Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h
@@ -1,23 +1,24 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swiften/JID/JID.h"
-#include "Swift/Controllers/UIEvents/UIEvent.h"
+#include <Swiften/JID/JID.h>
+
+#include <Swift/Controllers/UIEvents/UIEvent.h>
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 13d2516..ea19efe 100644
--- a/Swift/Controllers/UIEvents/RenameGroupUIEvent.h
+++ b/Swift/Controllers/UIEvents/RenameGroupUIEvent.h
@@ -1,30 +1,31 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swift/Controllers/UIEvents/UIEvent.h>
#include <string>
+#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 b47575a..1a71cb4 100644
--- a/Swift/Controllers/UIEvents/RenameRosterItemUIEvent.h
+++ b/Swift/Controllers/UIEvents/RenameRosterItemUIEvent.h
@@ -1,26 +1,27 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include "Swift/Controllers/UIEvents/UIEvent.h"
-#include "Swiften/MUC/MUCBookmark.h"
+#include <Swiften/MUC/MUCBookmark.h>
+
+#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 284a1bd..f6fa1c7 100644
--- a/Swift/Controllers/UIEvents/RequestAdHocUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestAdHocUIEvent.h
@@ -1,21 +1,20 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swift/Controllers/UIInterfaces/MainWindow.h>
-
#include <Swift/Controllers/UIEvents/UIEvent.h>
+#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 2a01d47..6fe2342 100644
--- a/Swift/Controllers/UIEvents/RequestAdHocWithJIDUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestAdHocWithJIDUIEvent.h
@@ -1,21 +1,25 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/UIEvents/UIEvent.h"
+#include <string>
+
+#include <Swiften/JID/JID.h>
+
+#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 ba821a7..474d155 100644
--- a/Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h
@@ -1,29 +1,30 @@
/*
- * Copyright (c) 2010-2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/UIEvents/UIEvent.h"
#include <string>
+
#include <Swiften/JID/JID.h>
+#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 9b7abcb..4dcf8be 100644
--- a/Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h
@@ -4,34 +4,40 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#pragma once
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
-#include <Swift/Controllers/UIEvents/UIEvent.h>
+#pragma once
#include <Swiften/JID/JID.h>
+#include <Swift/Controllers/UIEvents/UIEvent.h>
+
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 9ed9863..4eca5d4 100644
--- a/Swift/Controllers/UIEvents/RequestChatUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestChatUIEvent.h
@@ -1,21 +1,21 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swiften/JID/JID.h"
+#include <Swiften/JID/JID.h>
-#include "Swift/Controllers/UIEvents/UIEvent.h"
+#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 758dabc..08804f4 100644
--- a/Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h
@@ -1,15 +1,15 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/UIEvents/UIEvent.h"
+#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 ff67774..25a5e42 100644
--- a/Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,21 +7,22 @@
#pragma once
#include <Swiften/JID/JID.h>
+
#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 std::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 a6f8e7d..a8e4bb7 100644
--- a/Swift/Controllers/UIEvents/RequestInviteToMUCUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestInviteToMUCUIEvent.h
@@ -5,48 +5,59 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <vector>
-#include <Swift/Controllers/UIEvents/UIEvent.h>
#include <Swiften/JID/JID.h>
+#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 std::shared_ptr<RequestInviteToMUCUIEvent> ref;
+
+ enum ImpromptuMode {
+ Impromptu,
+ NotImpromptu
+ };
+
+ /**
+ * @brief RequestInviteToMUCUIEvent
+ * @param originator This can be a MUC JID if the user wants to invite
+ * people to an existing MUC, or a contact JID if this is the
+ * start of an impromptu group chat.
+ * @param JIDsToInvite This is a std::vector of JIDs which are prefilled
+ * in the invite dialog.
+ * @param impromptu This flag indicates whether it is a normal MUC invite
+ * or an impromptu MUC invite.
+ */
+ RequestInviteToMUCUIEvent(const JID& originator, const std::vector<JID>& JIDsToInvite, ImpromptuMode impromptu) : originator_(originator), invite_(JIDsToInvite) {
+ isImpromptu_ = impromptu == Impromptu;
+ }
+
+ const JID& getOriginator() const {
+ return originator_;
+ }
+
+ const std::vector<JID> getInvites() const {
+ return invite_;
+ }
+
+ bool isImpromptu() const {
+ return isImpromptu_;
+ }
+
+ private:
+ JID originator_;
+ std::vector<JID> invite_;
+ bool isImpromptu_;
+ };
}
diff --git a/Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h b/Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h
index b592187..5e94290 100644
--- a/Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h
@@ -1,30 +1,31 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
-#include <Swift/Controllers/UIEvents/UIEvent.h>
#include <Swiften/JID/JID.h>
+#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 std::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 a9aedd5..1a02af4 100644
--- a/Swift/Controllers/UIEvents/RequestProfileEditorUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestProfileEditorUIEvent.h
@@ -1,16 +1,16 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/UIEvents/UIEvent.h"
+#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 5c44da7..9c2b01d 100644
--- a/Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h
@@ -4,18 +4,24 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include "Swiften/JID/JID.h"
+#include <Swiften/JID/JID.h>
-#include "Swift/Controllers/UIEvents/UIEvent.h"
+#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 12b8deb..4d780be 100644
--- a/Swift/Controllers/UIEvents/RequestXMLConsoleUIEvent.h
+++ b/Swift/Controllers/UIEvents/RequestXMLConsoleUIEvent.h
@@ -1,14 +1,14 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/UIEvents/UIEvent.h"
+#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 3bfa69d..26e4940 100644
--- a/Swift/Controllers/UIEvents/SendFileUIEvent.h
+++ b/Swift/Controllers/UIEvents/SendFileUIEvent.h
@@ -4,31 +4,38 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <string>
#include <Swiften/JID/JID.h>
+
#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 std::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 4a603ea..9b2f60f 100644
--- a/Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h
+++ b/Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h
@@ -4,22 +4,29 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/JID/JID.h>
+
#include <Swift/Controllers/UIEvents/UIEvent.h>
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 std::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 bb72d9b..a1b6efb 100644
--- a/Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h
+++ b/Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h
@@ -4,19 +4,25 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include "Swiften/JID/JID.h"
+#include <Swiften/JID/JID.h>
-#include "Swift/Controllers/UIEvents/UIEvent.h"
+#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.cpp b/Swift/Controllers/UIEvents/UIEvent.cpp
index 4827332..b1e870d 100644
--- a/Swift/Controllers/UIEvents/UIEvent.cpp
+++ b/Swift/Controllers/UIEvents/UIEvent.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/UIEvents/UIEvent.h"
+#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
UIEvent::~UIEvent() {
diff --git a/Swift/Controllers/UIEvents/UIEvent.h b/Swift/Controllers/UIEvents/UIEvent.h
index 548f356..5363a49 100644
--- a/Swift/Controllers/UIEvents/UIEvent.h
+++ b/Swift/Controllers/UIEvents/UIEvent.h
@@ -1,18 +1,18 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
namespace Swift {
- class UIEvent {
- public:
- typedef boost::shared_ptr<UIEvent> ref;
+ class UIEvent {
+ public:
+ typedef std::shared_ptr<UIEvent> ref;
- virtual ~UIEvent();
- };
+ virtual ~UIEvent();
+ };
}
diff --git a/Swift/Controllers/UIEvents/UIEventStream.h b/Swift/Controllers/UIEvents/UIEventStream.h
index 31a5f1c..e6e3f80 100644
--- a/Swift/Controllers/UIEvents/UIEventStream.h
+++ b/Swift/Controllers/UIEvents/UIEventStream.h
@@ -1,23 +1,24 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swiften/Base/boost_bsignals.h"
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include "Swift/Controllers/UIEvents/UIEvent.h"
+#include <boost/signals2.hpp>
+
+#include <Swift/Controllers/UIEvents/UIEvent.h>
namespace Swift {
- class UIEventStream {
- public:
- boost::signal<void (boost::shared_ptr<UIEvent>)> onUIEvent;
+ class UIEventStream {
+ public:
+ boost::signals2::signal<void (std::shared_ptr<UIEvent>)> onUIEvent;
- void send(boost::shared_ptr<UIEvent> event) {
- onUIEvent(event);
- }
- };
+ void send(std::shared_ptr<UIEvent> event) {
+ onUIEvent(event);
+ }
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/AdHocCommandWindow.h b/Swift/Controllers/UIInterfaces/AdHocCommandWindow.h
index e5d95fa..ceb1531 100644
--- a/Swift/Controllers/UIInterfaces/AdHocCommandWindow.h
+++ b/Swift/Controllers/UIInterfaces/AdHocCommandWindow.h
@@ -1,18 +1,18 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
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::signals2::signal<void ()> onClosing;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h b/Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h
index f6f37b3..7b9b6f7 100644
--- a/Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h
@@ -1,19 +1,20 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swift/Controllers/UIInterfaces/AdHocCommandWindow.h>
#include <Swiften/AdHoc/OutgoingAdHocCommandSession.h>
+#include <Swift/Controllers/UIInterfaces/AdHocCommandWindow.h>
+
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(std::shared_ptr<OutgoingAdHocCommandSession> command) = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/BlockListEditorWidget.h b/Swift/Controllers/UIInterfaces/BlockListEditorWidget.h
index dab5081..58b45d0 100644
--- a/Swift/Controllers/UIInterfaces/BlockListEditorWidget.h
+++ b/Swift/Controllers/UIInterfaces/BlockListEditorWidget.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,27 +14,28 @@
#include <vector>
+#include <boost/signals2.hpp>
+
#include <Swiften/JID/JID.h>
-#include <Swiften/Base/boost_bsignals.h>
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::signals2::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.cpp b/Swift/Controllers/UIInterfaces/ChatListWindow.cpp
index 6391d32..5ad40fe 100644
--- a/Swift/Controllers/UIInterfaces/ChatListWindow.cpp
+++ b/Swift/Controllers/UIInterfaces/ChatListWindow.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/UIInterfaces/ChatListWindow.h"
+#include <Swift/Controllers/UIInterfaces/ChatListWindow.h>
namespace Swift {
diff --git a/Swift/Controllers/UIInterfaces/ChatListWindow.h b/Swift/Controllers/UIInterfaces/ChatListWindow.h
index 111c22c..dde596e 100644
--- a/Swift/Controllers/UIInterfaces/ChatListWindow.h
+++ b/Swift/Controllers/UIInterfaces/ChatListWindow.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,93 +7,93 @@
#pragma once
#include <list>
-#include <set>
#include <map>
-#include <boost/shared_ptr.hpp>
-#include <Swiften/MUC/MUCBookmark.h>
-#include <Swiften/Elements/StatusShow.h>
+#include <memory>
+#include <set>
+
#include <boost/filesystem/path.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
+
+#include <Swiften/Elements/StatusShow.h>
+#include <Swiften/MUC/MUCBookmark.h>
namespace Swift {
- class ChatListWindow {
- public:
- class Chat {
- public:
- Chat() : statusType(StatusShow::None), isMUC(false), unreadCount(0), isPrivateMessage(false) {}
- Chat(const JID& jid, const std::string& chatName, const std::string& activity, int unreadCount, StatusShow::Type statusType, const boost::filesystem::path& avatarPath, bool isMUC, bool isPrivateMessage = false, const std::string& nick = "", const boost::optional<std::string> password = boost::optional<std::string>())
- : jid(jid), chatName(chatName), activity(activity), statusType(statusType), isMUC(isMUC), nick(nick), password(password), unreadCount(unreadCount), avatarPath(avatarPath), isPrivateMessage(isPrivateMessage) {}
- /** Assume that nicks and other transient features aren't important for equality */
- bool operator==(const Chat& other) const {
- if (impromptuJIDs.empty()) {
- return jid.toBare() == other.jid.toBare()
- && isMUC == other.isMUC;
- } else { /* compare the chat occupant lists */
- typedef std::map<std::string, JID> JIDMap;
- foreach (const JIDMap::value_type& jid, impromptuJIDs) {
- 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 */
+ for (const auto& jid : impromptuJIDs) {
+ bool found = false;
+ for (const auto& otherJID : other.impromptuJIDs) {
+ if (jid.second.toBare() == otherJID.second.toBare()) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+ void setUnreadCount(int unread) {
+ unreadCount = unread;
+ }
+ void setStatusType(StatusShow::Type type) {
+ statusType = type;
+ }
+ void setAvatarPath(const boost::filesystem::path& path) {
+ avatarPath = path;
+ }
+ std::string getImpromptuTitle() const {
+ std::string title;
+ for (auto& pair : impromptuJIDs) {
+ if (title.empty()) {
+ title += pair.first;
+ } else {
+ title += ", " + pair.first;
+ }
+ }
+ return title;
+ }
+ JID jid;
+ std::string chatName;
+ std::string activity;
+ StatusShow::Type statusType;
+ bool isMUC;
+ std::string nick;
+ boost::optional<std::string> password;
+ int unreadCount;
+ boost::filesystem::path avatarPath;
+ std::map<std::string, JID> impromptuJIDs;
+ bool isPrivateMessage;
+ };
+ virtual ~ChatListWindow();
- virtual void setBookmarksEnabled(bool enabled) = 0;
- virtual void addMUCBookmark(const MUCBookmark& bookmark) = 0;
- virtual void addWhiteboardSession(const ChatListWindow::Chat& chat) = 0;
- virtual void removeWhiteboardSession(const JID& jid) = 0;
- virtual void removeMUCBookmark(const MUCBookmark& bookmark) = 0;
- virtual void setRecents(const std::list<Chat>& recents) = 0;
- virtual void setUnreadCount(int unread) = 0;
- virtual void clearBookmarks() = 0;
- 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::signals2::signal<void (const MUCBookmark&)> onMUCBookmarkActivated;
+ boost::signals2::signal<void (const Chat&)> onRecentActivated;
+ boost::signals2::signal<void (const JID&)> onWhiteboardActivated;
+ boost::signals2::signal<void ()> onClearRecentsRequested;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/ChatListWindowFactory.h b/Swift/Controllers/UIInterfaces/ChatListWindowFactory.h
index 34dc7a9..3ae1ec6 100644
--- a/Swift/Controllers/UIInterfaces/ChatListWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/ChatListWindowFactory.h
@@ -1,18 +1,18 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/UIInterfaces/ChatListWindow.h"
+#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 3a1acdf..8ee083d 100644
--- a/Swift/Controllers/UIInterfaces/ChatWindow.h
+++ b/Swift/Controllers/UIInterfaces/ChatWindow.h
@@ -1,21 +1,21 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
#include <vector>
+#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
-#include <boost/make_shared.hpp>
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/Tristate.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Elements/ChatState.h>
#include <Swiften/Elements/Form.h>
#include <Swiften/Elements/MUCOccupant.h>
@@ -25,211 +25,234 @@
#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_;
- }
- private:
- std::vector<boost::shared_ptr<ChatMessagePart> > parts_;
- };
-
- 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:
- std::string foregroundColor;
- std::string backgroundColor;
- 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, const HighlightAction& highlight) = 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, const HighlightAction& highlight) = 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, const HighlightAction& highlight) = 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, const HighlightAction& highlight) = 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(std::make_shared<ChatTextMessagePart>(text));
+ }
+
+ void append(const std::shared_ptr<ChatMessagePart>& part) {
+ parts_.push_back(part);
+ }
+
+ const std::vector<std::shared_ptr<ChatMessagePart> >& getParts() const {
+ return parts_;
+ }
+
+ void setParts(const std::vector<std::shared_ptr<ChatMessagePart> >& parts) {
+ parts_ = parts;
+ }
+
+ void setFullMessageHighlightAction(const HighlightAction& action) {
+ fullMessageHighlightAction_ = action;
+ }
+
+ const HighlightAction& getFullMessageHighlightAction() const {
+ return fullMessageHighlightAction_;
+ }
+
+ bool isMeCommand() const {
+ return isMeCommand_;
+ }
+
+ void setIsMeCommand(bool isMeCommand) {
+ isMeCommand_ = isMeCommand;
+ }
+
+ private:
+ std::vector<std::shared_ptr<ChatMessagePart> > parts_;
+ HighlightAction fullMessageHighlightAction_;
+ bool isMeCommand_ = false;
+ };
+
+ 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, std::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, std::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).
+ * @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::signals2::signal<void ()> onClosed;
+ boost::signals2::signal<void ()> onAllMessagesRead;
+ boost::signals2::signal<void (const std::string&, bool isCorrection)> onSendMessageRequest;
+ boost::signals2::signal<void ()> onSendCorrectionMessageRequest;
+ boost::signals2::signal<void ()> onUserTyping;
+ boost::signals2::signal<void ()> onUserCancelsTyping;
+ boost::signals2::signal<void ()> onAlertButtonClicked;
+ boost::signals2::signal<void (ContactRosterItem*)> onOccupantSelectionChanged;
+ boost::signals2::signal<void (ChatWindow::OccupantAction, ContactRosterItem*)> onOccupantActionSelected;
+ boost::signals2::signal<void (const std::string&)> onChangeSubjectRequest;
+ boost::signals2::signal<void ()> onBookmarkRequest;
+ boost::signals2::signal<void (Form::ref)> onConfigureRequest;
+ boost::signals2::signal<void ()> onDestroyRequest;
+ boost::signals2::signal<void (const std::vector<JID>&)> onInviteToChat;
+ boost::signals2::signal<void ()> onConfigurationFormCancelled;
+ boost::signals2::signal<void ()> onGetAffiliationsRequest;
+ boost::signals2::signal<void (MUCOccupant::Affiliation, const JID&)> onSetAffiliationRequest;
+ boost::signals2::signal<void (const std::vector<std::pair<MUCOccupant::Affiliation, JID> >& changes)> onChangeAffiliationsRequest;
+ boost::signals2::signal<void ()> onLogCleared;
+
+ // File transfer related
+ boost::signals2::signal<void (std::string /* id */)> onFileTransferCancel;
+ boost::signals2::signal<void (std::string /* id */, std::string /* description */)> onFileTransferStart;
+ boost::signals2::signal<void (std::string /* id */, std::string /* path */)> onFileTransferAccept;
+ boost::signals2::signal<void (std::string /* path */)> onSendFileRequest;
+
+ //Whiteboard related
+ boost::signals2::signal<void ()> onWhiteboardSessionAccept;
+ boost::signals2::signal<void ()> onWhiteboardSessionCancel;
+ boost::signals2::signal<void ()> onWhiteboardWindowShow;
+
+ // Blocking Command related
+ boost::signals2::signal<void ()> onBlockUserRequest;
+ boost::signals2::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 2d15375..1e311c5 100644
--- a/Swift/Controllers/UIInterfaces/ContactEditWindow.h
+++ b/Swift/Controllers/UIInterfaces/ContactEditWindow.h
@@ -1,35 +1,35 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <set>
+#include <string>
#include <vector>
-#include <string>
+#include <boost/signals2.hpp>
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::signals2::signal<void ()> onRemoveContactRequest;
+ boost::signals2::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 96ea4a1..c05976b 100644
--- a/Swift/Controllers/UIInterfaces/EventWindow.h
+++ b/Swift/Controllers/UIInterfaces/EventWindow.h
@@ -1,29 +1,29 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include "Swift/Controllers/XMPPEvents/StanzaEvent.h"
+#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(std::shared_ptr<StanzaEvent> event, bool active) = 0;
+ virtual void removeEvent(std::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 0b08fb3..da9fd37 100644
--- a/Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h
+++ b/Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h
@@ -4,17 +4,23 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include "Swift/Controllers/UIInterfaces/FileTransferListWidget.h"
+#include <Swift/Controllers/UIInterfaces/FileTransferListWidget.h>
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..cae54dc 100644
--- a/Swift/Controllers/UIInterfaces/HighlightEditorWindow.h
+++ b/Swift/Controllers/UIInterfaces/HighlightEditorWindow.h
@@ -1,11 +1,15 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#pragma once
+
#include <vector>
-#include <Swiften/Base/boost_bsignals.h>
+
+#include <boost/signals2.hpp>
+
#include <Swift/Controllers/Contact.h>
namespace Swift {
@@ -14,14 +18,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::signals2::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..413d9d6 100644
--- a/Swift/Controllers/UIInterfaces/HistoryWindow.h
+++ b/Swift/Controllers/UIInterfaces/HistoryWindow.h
@@ -4,31 +4,37 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#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::signals2::signal<void (RosterItem*)> onSelectedContactChanged;
+ boost::signals2::signal<void (const std::string&)> onReturnPressed;
+ boost::signals2::signal<void (const boost::gregorian::date&)> onScrollReachedTop;
+ boost::signals2::signal<void (const boost::gregorian::date&)> onScrollReachedBottom;
+ boost::signals2::signal<void ()> onPreviousButtonClicked;
+ boost::signals2::signal<void ()> onNextButtonClicked;
+ boost::signals2::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 3fcf999..7a71195 100644
--- a/Swift/Controllers/UIInterfaces/JoinMUCWindow.h
+++ b/Swift/Controllers/UIInterfaces/JoinMUCWindow.h
@@ -1,26 +1,27 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
#include <vector>
-#include <string>
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
+
#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::signals2::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 6baa5d8..d11aadb 100644
--- a/Swift/Controllers/UIInterfaces/LoginWindow.h
+++ b/Swift/Controllers/UIInterfaces/LoginWindow.h
@@ -1,41 +1,42 @@
/*
- * Copyright (c) 2010-2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
-
+#include <memory>
#include <string>
+
+#include <boost/signals2.hpp>
+
+#include <Swiften/Client/ClientOptions.h>
#include <Swiften/TLS/Certificate.h>
#include <Swiften/TLS/CertificateWithKey.h>
-#include <Swiften/Client/ClientOptions.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::signals2::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::signals2::signal<void ()> onCancelLoginRequest;
+ boost::signals2::signal<void ()> onQuitRequest;
+ boost::signals2::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 9c3816e..045c2df 100644
--- a/Swift/Controllers/UIInterfaces/MUCSearchWindow.h
+++ b/Swift/Controllers/UIInterfaces/MUCSearchWindow.h
@@ -1,34 +1,35 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swiften/Base/boost_bsignals.h"
-
+#include <string>
#include <vector>
#include <boost/optional.hpp>
-#include <string>
-#include "Swiften/JID/JID.h"
+#include <boost/signals2.hpp>
+
+#include <Swiften/JID/JID.h>
+
#include <Swift/Controllers/Chat/MUCSearchController.h>
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::signals2::signal<void (const JID&)> onSearchService;
+ boost::signals2::signal<void (const boost::optional<JID>&)> onFinished;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h b/Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h
index 96d96b8..6e26ac3 100644
--- a/Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h
@@ -1,19 +1,19 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/UIInterfaces/MUCSearchWindow.h"
+#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 8717021..bfd8c67 100644
--- a/Swift/Controllers/UIInterfaces/MainWindow.h
+++ b/Swift/Controllers/UIInterfaces/MainWindow.h
@@ -1,53 +1,54 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Elements/StatusShow.h>
#include <Swiften/Elements/DiscoItems.h>
+#include <Swiften/Elements/StatusShow.h>
+#include <Swiften/JID/JID.h>
#include <Swiften/TLS/Certificate.h>
-#include <Swiften/Base/boost_bsignals.h>
+
#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(std::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::signals2::signal<void (StatusShow::Type, const std::string&)> onChangeStatusRequest;
+ boost::signals2::signal<void ()> onSignOutRequest;
+ boost::signals2::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 e2c9da4..c2bcdae 100644
--- a/Swift/Controllers/UIInterfaces/ProfileWindow.h
+++ b/Swift/Controllers/UIInterfaces/ProfileWindow.h
@@ -1,35 +1,36 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#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::signals2::signal<void (VCard::ref)> onVCardChangeRequest;
+ boost::signals2::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 7e05657..a0976dc 100644
--- a/Swift/Controllers/UIInterfaces/UIFactory.h
+++ b/Swift/Controllers/UIInterfaces/UIFactory.h
@@ -1,49 +1,49 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h>
+#include <Swift/Controllers/UIInterfaces/BlockListEditorWidgetFactory.h>
#include <Swift/Controllers/UIInterfaces/ChatListWindowFactory.h>
#include <Swift/Controllers/UIInterfaces/ChatWindowFactory.h>
-#include <Swift/Controllers/UIInterfaces/HistoryWindowFactory.h>
+#include <Swift/Controllers/UIInterfaces/ContactEditWindowFactory.h>
#include <Swift/Controllers/UIInterfaces/EventWindowFactory.h>
+#include <Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h>
+#include <Swift/Controllers/UIInterfaces/HighlightEditorWindowFactory.h>
+#include <Swift/Controllers/UIInterfaces/HistoryWindowFactory.h>
+#include <Swift/Controllers/UIInterfaces/JoinMUCWindowFactory.h>
#include <Swift/Controllers/UIInterfaces/LoginWindowFactory.h>
-#include <Swift/Controllers/UIInterfaces/MainWindowFactory.h>
#include <Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h>
-#include <Swift/Controllers/UIInterfaces/JoinMUCWindowFactory.h>
-#include <Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h>
-#include <Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h>
+#include <Swift/Controllers/UIInterfaces/MainWindowFactory.h>
#include <Swift/Controllers/UIInterfaces/ProfileWindowFactory.h>
-#include <Swift/Controllers/UIInterfaces/ContactEditWindowFactory.h>
-#include <Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h>
-#include <Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h>
+#include <Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h>
#include <Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h>
-#include <Swift/Controllers/UIInterfaces/HighlightEditorWindowFactory.h>
-#include <Swift/Controllers/UIInterfaces/BlockListEditorWidgetFactory.h>
+#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 9e17ba9..279f4f3 100644
--- a/Swift/Controllers/UIInterfaces/UserSearchWindow.h
+++ b/Swift/Controllers/UIInterfaces/UserSearchWindow.h
@@ -1,56 +1,58 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-
-#include <vector>
#include <string>
+#include <vector>
+
+#include <boost/signals2.hpp>
#include <Swiften/JID/JID.h>
+
#include <Swift/Controllers/Chat/UserSearchController.h>
#include <Swift/Controllers/Contact.h>
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(std::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 setOriginator(const JID& originator) = 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::signals2::signal<void (const JID&)> onFormRequested;
+ boost::signals2::signal<void (std::shared_ptr<SearchPayload>, const JID&)> onSearchRequested;
+ boost::signals2::signal<void (const JID&)> onNameSuggestionRequested;
+ boost::signals2::signal<void (const std::string&)> onContactSuggestionsRequested;
+ boost::signals2::signal<void (const std::vector<JID>&)> onJIDUpdateRequested;
+ boost::signals2::signal<void (const std::vector<JID>&)> onJIDAddRequested;
+ boost::signals2::signal<void (const JID&)> onJIDEditFieldChanged;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h b/Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h
index b3a325e..d5d6135 100644
--- a/Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,14 +8,14 @@
#include <set>
-#include "Swift/Controllers/UIInterfaces/UserSearchWindow.h"
+#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 a4a9ef0..a904ee1 100644
--- a/Swift/Controllers/UIInterfaces/WhiteboardWindow.h
+++ b/Swift/Controllers/UIInterfaces/WhiteboardWindow.h
@@ -4,23 +4,29 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#pragma once
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
-#include "Swiften/Base/boost_bsignals.h"
+#pragma once
#include <string>
+#include <boost/signals2.hpp>
+
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(std::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..9868ceb 100644
--- a/Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h
+++ b/Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h
@@ -4,16 +4,24 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
+#include <memory>
+
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(std::shared_ptr<WhiteboardSession> whiteboardSession) = 0;
+ };
}
diff --git a/Swift/Controllers/UIInterfaces/XMLConsoleWidget.cpp b/Swift/Controllers/UIInterfaces/XMLConsoleWidget.cpp
index 503cef8..0916d0b 100644
--- a/Swift/Controllers/UIInterfaces/XMLConsoleWidget.cpp
+++ b/Swift/Controllers/UIInterfaces/XMLConsoleWidget.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/UIInterfaces/XMLConsoleWidget.h"
+#include <Swift/Controllers/UIInterfaces/XMLConsoleWidget.h>
namespace Swift {
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 33b577f..bbc055e 100644
--- a/Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h
+++ b/Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h
@@ -1,19 +1,19 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/UIInterfaces/XMLConsoleWidget.h"
+#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 2711034..59c57b9 100644
--- a/Swift/Controllers/UnitTest/ChatMessageSummarizerTest.cpp
+++ b/Swift/Controllers/UnitTest/ChatMessageSummarizerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,115 +7,115 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include "Swift/Controllers/ChatMessageSummarizer.h"
+#include <Swift/Controllers/ChatMessageSummarizer.h>
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 b68fd43..6ac51b2 100644
--- a/Swift/Controllers/UnitTest/ContactSuggesterTest.cpp
+++ b/Swift/Controllers/UnitTest/ContactSuggesterTest.cpp
@@ -1,127 +1,127 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <memory>
#include <boost/bind.hpp>
#include <boost/function.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Base/foreach.h>
-#include "Swift/Controllers/ContactSuggester.h"
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
+#include <Swift/Controllers/ContactSuggester.h>
using namespace Swift;
class ContactSuggesterTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ContactSuggesterTest);
- CPPUNIT_TEST(equalityTest);
- CPPUNIT_TEST(lexicographicalSortTest);
- CPPUNIT_TEST(sortTest);
- CPPUNIT_TEST_SUITE_END();
+ 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();
+ for (const auto& name : words) {
+ for (const auto& jid : words) {
+ for (const auto& status : statuses) {
+ contacts.push_back(std::make_shared<Contact>(name, jid, status, ""));
+ }
+ }
+ }
+ return contacts;
+ }
+
+ /* a = a */
+ bool isReflexive(const boost::function<bool (const Contact::ref&, const Contact::ref&)>& comparitor) {
+ std::vector<Contact::ref> contacts = contactList();
+ for (const auto& a : contacts) {
+ if (!comparitor(a, a)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /* a = b -> b = a */
+ bool isSymmetric(const boost::function<bool (const Contact::ref&, const Contact::ref&)>& comparitor) {
+ std::vector<Contact::ref> contacts = contactList();
+ for (const auto& a : contacts) {
+ for (const auto& b : contacts) {
+ if (comparitor(a, b)) {
+ if (!comparitor(b, a)) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+ }
+
+ /* a = b && b = c -> a = c */
+ bool isTransitive(const boost::function<bool (const Contact::ref&, const Contact::ref&)>& comparitor) {
+ std::vector<Contact::ref> contacts = contactList();
+ for (const auto& a : contacts) {
+ for (const auto& b : contacts) {
+ for (const auto& c : contacts) {
+ if (comparitor(a, b) && comparitor(b, c)) {
+ if (!comparitor(a, c)) {
+ return false;
+ }
+ }
+ }
+ }
+ }
+ return true;
+ }
+
+ void equalityTest() {
+ CPPUNIT_ASSERT(isReflexive(Contact::equalityPredicate));
+ CPPUNIT_ASSERT(isSymmetric(Contact::equalityPredicate));
+ CPPUNIT_ASSERT(isTransitive(Contact::equalityPredicate));
+ }
+
+ void lexicographicalSortTest() {
+ CPPUNIT_ASSERT(isTransitive(Contact::lexicographicalSortPredicate));
+ }
+
+ void sortTest() {
+ std::vector<std::string> words = wordList();
+ for (const auto& 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 707524c..8d49d5d 100644
--- a/Swift/Controllers/UnitTest/HighlightRuleTest.cpp
+++ b/Swift/Controllers/UnitTest/HighlightRuleTest.cpp
@@ -5,13 +5,13 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <vector>
#include <string>
+#include <vector>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -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.cpp b/Swift/Controllers/UnitTest/MockChatWindow.cpp
index d97d903..f0f666a 100644
--- a/Swift/Controllers/UnitTest/MockChatWindow.cpp
+++ b/Swift/Controllers/UnitTest/MockChatWindow.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/UnitTest/MockChatWindow.h"
+#include <Swift/Controllers/UnitTest/MockChatWindow.h>
namespace Swift {
MockChatWindow::~MockChatWindow() {
diff --git a/Swift/Controllers/UnitTest/MockChatWindow.h b/Swift/Controllers/UnitTest/MockChatWindow.h
index dddea6c..76e5194 100644
--- a/Swift/Controllers/UnitTest/MockChatWindow.h
+++ b/Swift/Controllers/UnitTest/MockChatWindow.h
@@ -6,110 +6,149 @@
#pragma once
-#include <boost/shared_ptr.hpp>
-
-#include <Swiften/Base/foreach.h>
+#include <memory>
+#include <string>
#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*/, const HighlightAction& /*highlight*/) {
- 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*/, const HighlightAction& /*highlight*/) {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*/, const HighlightAction& /*highlight*/) {}
- virtual void replaceWithAction(const ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/, const HighlightAction& /*highlight*/) {}
- 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() {}
+ virtual ~MockChatWindow();
+
+ virtual std::string addMessage(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, std::shared_ptr<SecurityLabel> /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/) {
+ lastAddedMessage_ = message;
+ lastAddedMessageSenderName_ = senderName;
+ lastAddedMessageSenderIsSelf_ = senderIsSelf;
+ return "id";
+ }
+
+ virtual std::string addAction(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, std::shared_ptr<SecurityLabel> /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/) {
+ lastAddedAction_ = message;
+ lastAddedActionSenderName_ = senderName;
+ lastAddedActionSenderIsSelf_ = senderIsSelf;
+ 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) {
+ lastAddedErrorMessage_ = 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*/) {
+ lastReplacedSystemMessage_ = message;
+ }
+
+ // 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 nullptr; }
+ 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) {
+ receiptChanges_.emplace_back(id, 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) {
+ 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) {
+ lastMUCInvitationJID_ = jid;
+ }
+
+ 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) {
+ std::string body;
+ std::shared_ptr<ChatTextMessagePart> text;
+ std::shared_ptr<ChatHighlightingMessagePart> highlight;
+ for (auto &&part : message.getParts()) {
+ if ((text = std::dynamic_pointer_cast<ChatTextMessagePart>(part))) {
+ body += text->text;
+ }
+ else if ((highlight = std::dynamic_pointer_cast<ChatHighlightingMessagePart>(part))) {
+ body += highlight->text;
+ }
+ }
+ return body;
+ }
+
+ void resetLastMessages() {
+ lastAddedMessage_ = lastAddedAction_ = lastAddedPresence_ = lastReplacedMessage_ = lastAddedSystemMessage_ = lastReplacedSystemMessage_ = ChatMessage();
+ lastAddedMessageSenderName_ = lastAddedActionSenderName_ = "";
+ lastAddedMessageSenderIsSelf_ = lastAddedActionSenderIsSelf_ = false;
+ }
+
+ std::string name_;
+ ChatMessage lastAddedMessage_;
+ std::string lastAddedMessageSenderName_;
+ bool lastAddedMessageSenderIsSelf_ = false;
+ ChatMessage lastAddedAction_;
+ std::string lastAddedActionSenderName_;
+ bool lastAddedActionSenderIsSelf_ = false;
+ ChatMessage lastAddedPresence_;
+ ChatMessage lastReplacedMessage_;
+ ChatMessage lastAddedSystemMessage_;
+ ChatMessage lastReplacedSystemMessage_;
+ ChatMessage lastAddedErrorMessage_;
+ JID lastMUCInvitationJID_;
+ std::vector<SecurityLabelsCatalog::Item> labels_;
+ bool labelsEnabled_ = false;
+ bool impromptuMUCSupported_ = false;
+ SecurityLabelsCatalog::Item label_;
+ Roster* roster_ = nullptr;
+ std::vector<std::pair<std::string, ReceiptState>> receiptChanges_;
+ boost::optional<MUCType> mucType_;
+ };
}
diff --git a/Swift/Controllers/UnitTest/MockMainWindow.h b/Swift/Controllers/UnitTest/MockMainWindow.h
index af4267f..6ae2aa7 100644
--- a/Swift/Controllers/UnitTest/MockMainWindow.h
+++ b/Swift/Controllers/UnitTest/MockMainWindow.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(nullptr) {}
+ 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(std::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 5f9d590..adf4fdf 100644
--- a/Swift/Controllers/UnitTest/MockMainWindowFactory.h
+++ b/Swift/Controllers/UnitTest/MockMainWindowFactory.h
@@ -1,28 +1,28 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/UIInterfaces/MainWindowFactory.h"
-#include "Swift/Controllers/UnitTest/MockMainWindow.h"
+#include <Swift/Controllers/UIInterfaces/MainWindowFactory.h>
+#include <Swift/Controllers/UnitTest/MockMainWindow.h>
namespace Swift {
- class MockMainWindowFactory : public MainWindowFactory {
- public:
- MockMainWindowFactory() : last(NULL) {}
+ class MockMainWindowFactory : public MainWindowFactory {
+ public:
+ MockMainWindowFactory() : last(nullptr) {}
- virtual ~MockMainWindowFactory() {}
+ virtual ~MockMainWindowFactory() {}
- /**
- * Transfers ownership of result.
- */
- virtual MainWindow* createMainWindow(UIEventStream*) {last = new MockMainWindow();return last;}
- MockMainWindow* last;
- };
+ /**
+ * 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..1375475 100644
--- a/Swift/Controllers/UnitTest/PresenceNotifierTest.cpp
+++ b/Swift/Controllers/UnitTest/PresenceNotifierTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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, nullptr, 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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::shared_ptr<PresenceNotifier> testling = createNotifier();
+
+ sendUnavailablePresence(user1);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(notifier->notifications.size()));
+ }
+
+ void testReceiveAvailablePresenceAfterUnavailableCreatesAvailableNotification() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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:
+ std::shared_ptr<PresenceNotifier> createNotifier() {
+ std::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) {
+ std::shared_ptr<Presence> presence(new Presence());
+ presence->setFrom(jid);
+ presence->setShow(type);
+ presence->setStatus("Status Message");
+ stanzaChannel->onPresenceReceived(presence);
+ }
+
+ void sendUnavailablePresence(const JID& jid) {
+ std::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 4c9941d..be35468 100644
--- a/Swift/Controllers/UnitTest/PreviousStatusStoreTest.cpp
+++ b/Swift/Controllers/UnitTest/PreviousStatusStoreTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,38 +7,38 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include "Swift/Controllers/PreviousStatusStore.h"
+#include <Swift/Controllers/PreviousStatusStore.h>
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 d8d89eb..37fe8e3 100644
--- a/Swift/Controllers/WhiteboardManager.cpp
+++ b/Swift/Controllers/WhiteboardManager.cpp
@@ -4,135 +4,139 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swift/Controllers/WhiteboardManager.h>
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h>
+#include <Swiften/Client/NickResolver.h>
+#include <Swiften/Client/StanzaChannel.h>
+#include <Swiften/Whiteboard/WhiteboardSessionManager.h>
+
#include <Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h>
#include <Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h>
+#include <Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h>
#include <Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h>
-#include "Swiften/Client/NickResolver.h"
-#include <Swiften/Client/StanzaChannel.h>
-#include <Swiften/Whiteboard/WhiteboardSessionManager.h>
namespace Swift {
- typedef std::pair<JID, WhiteboardWindow*> JIDWhiteboardWindowPair;
-
- WhiteboardManager::WhiteboardManager(WhiteboardWindowFactory* whiteboardWindowFactory, UIEventStream* uiEventStream, NickResolver* nickResolver, WhiteboardSessionManager* whiteboardSessionManager) : whiteboardWindowFactory_(whiteboardWindowFactory), uiEventStream_(uiEventStream), nickResolver_(nickResolver), whiteboardSessionManager_(whiteboardSessionManager) {
+ 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() {
+ for (auto&& whiteboardWindowPair : whiteboardWindows_) {
+ delete whiteboardWindowPair.second;
+ }
+ }
+
+ WhiteboardWindow* WhiteboardManager::createNewWhiteboardWindow(const JID& contact, WhiteboardSession::ref session) {
+ WhiteboardWindow *window = whiteboardWindowFactory_->createWhiteboardWindow(session);
+ window->setName(nickResolver_->jidToNick(contact));
+ whiteboardWindows_[contact.toBare()] = window;
+ return window;
+ }
+
+ WhiteboardWindow* WhiteboardManager::findWhiteboardWindow(const JID& contact) {
+ if (whiteboardWindows_.find(contact.toBare()) == whiteboardWindows_.end()) {
+ return nullptr;
+ }
+ return whiteboardWindows_[contact.toBare()];
+ }
+
+ void WhiteboardManager::handleUIEvent(std::shared_ptr<UIEvent> event) {
+ std::shared_ptr<RequestWhiteboardUIEvent> requestWhiteboardEvent = std::dynamic_pointer_cast<RequestWhiteboardUIEvent>(event);
+ if (requestWhiteboardEvent) {
+ requestSession(requestWhiteboardEvent->getContact());
+ }
+ std::shared_ptr<AcceptWhiteboardSessionUIEvent> sessionAcceptEvent = std::dynamic_pointer_cast<AcceptWhiteboardSessionUIEvent>(event);
+ if (sessionAcceptEvent) {
+ acceptSession(sessionAcceptEvent->getContact());
+ }
+ std::shared_ptr<CancelWhiteboardSessionUIEvent> sessionCancelEvent = std::dynamic_pointer_cast<CancelWhiteboardSessionUIEvent>(event);
+ if (sessionCancelEvent) {
+ cancelSession(sessionCancelEvent->getContact());
+ }
+ std::shared_ptr<ShowWhiteboardUIEvent> showWindowEvent = std::dynamic_pointer_cast<ShowWhiteboardUIEvent>(event);
+ if (showWindowEvent) {
+ WhiteboardWindow* window = findWhiteboardWindow(showWindowEvent->getContact());
+ if (window != nullptr) {
+ window->activateWindow();
+ }
+ }
+ }
+
+ void WhiteboardManager::acceptSession(const JID& from) {
+ IncomingWhiteboardSession::ref session = std::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 == nullptr) {
+ 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 == nullptr) {
+ 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 != nullptr) {
+ 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 2f5767b..3ef14ab 100644
--- a/Swift/Controllers/WhiteboardManager.h
+++ b/Swift/Controllers/WhiteboardManager.h
@@ -4,56 +4,61 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <map>
-
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/JID/JID.h>
+#include <Swiften/Whiteboard/IncomingWhiteboardSession.h>
+#include <Swiften/Whiteboard/WhiteboardSession.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
-#include <Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h>
#include <Swift/Controllers/UIInterfaces/WhiteboardWindow.h>
-#include <Swiften/Whiteboard/WhiteboardSession.h>
-#include <Swiften/Whiteboard/IncomingWhiteboardSession.h>
+#include <Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h>
namespace Swift {
- class WhiteboardSessionManager;
- class NickResolver;
-
- class WhiteboardManager {
- public:
- WhiteboardManager(WhiteboardWindowFactory* whiteboardWindowFactory, UIEventStream* uiEventStream, NickResolver* nickResolver, WhiteboardSessionManager* whiteboardSessionManager);
- ~WhiteboardManager();
-
- 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;
-
- 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_;
- };
+ class WhiteboardSessionManager;
+ class NickResolver;
+
+ class WhiteboardManager {
+ public:
+ WhiteboardManager(WhiteboardWindowFactory* whiteboardWindowFactory, UIEventStream* uiEventStream, NickResolver* nickResolver, WhiteboardSessionManager* whiteboardSessionManager);
+ ~WhiteboardManager();
+
+ WhiteboardWindow* createNewWhiteboardWindow(const JID& contact, WhiteboardSession::ref session);
+
+ public:
+ boost::signals2::signal< void (const JID&, bool senderIsSelf)> onSessionRequest;
+ boost::signals2::signal< void (const JID&)> onSessionTerminate;
+ boost::signals2::signal< void (const JID&)> onRequestAccepted;
+ boost::signals2::signal< void (const JID&)> onRequestRejected;
+
+ private:
+ void handleUIEvent(std::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::signals2::scoped_connection uiEventConnection_;
+ WhiteboardSessionManager* whiteboardSessionManager_;
+ };
}
diff --git a/Swift/Controllers/XMLConsoleController.cpp b/Swift/Controllers/XMLConsoleController.cpp
index b9edcb8..b72fde3 100644
--- a/Swift/Controllers/XMLConsoleController.cpp
+++ b/Swift/Controllers/XMLConsoleController.cpp
@@ -1,45 +1,45 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/Controllers/XMLConsoleController.h"
+#include <Swift/Controllers/XMLConsoleController.h>
-#include "Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h"
-#include "Swift/Controllers/UIEvents/RequestXMLConsoleUIEvent.h"
+#include <Swift/Controllers/UIEvents/RequestXMLConsoleUIEvent.h>
+#include <Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h>
namespace Swift {
-XMLConsoleController::XMLConsoleController(UIEventStream* uiEventStream, XMLConsoleWidgetFactory* xmlConsoleWidgetFactory) : xmlConsoleWidgetFactory(xmlConsoleWidgetFactory), xmlConsoleWidget(NULL) {
- uiEventStream->onUIEvent.connect(boost::bind(&XMLConsoleController::handleUIEvent, this, _1));
+XMLConsoleController::XMLConsoleController(UIEventStream* uiEventStream, XMLConsoleWidgetFactory* xmlConsoleWidgetFactory) : xmlConsoleWidgetFactory(xmlConsoleWidgetFactory), xmlConsoleWidget(nullptr) {
+ 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();
- }
+void XMLConsoleController::handleUIEvent(std::shared_ptr<UIEvent> rawEvent) {
+ std::shared_ptr<RequestXMLConsoleUIEvent> event = std::dynamic_pointer_cast<RequestXMLConsoleUIEvent>(rawEvent);
+ if (event != nullptr) {
+ if (xmlConsoleWidget == nullptr) {
+ 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 7a11577..56202b4 100644
--- a/Swift/Controllers/XMLConsoleController.h
+++ b/Swift/Controllers/XMLConsoleController.h
@@ -1,37 +1,39 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swiften/Base/boost_bsignals.h"
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
-#include "Swift/Controllers/UIEvents/UIEventStream.h"
#include <Swiften/Base/SafeByteArray.h>
+#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(std::shared_ptr<UIEvent> event);
+
+ private:
+ XMLConsoleWidgetFactory* xmlConsoleWidgetFactory;
+ XMLConsoleWidget* xmlConsoleWidget;
+ };
}
diff --git a/Swift/Controllers/XMPPEvents/ErrorEvent.h b/Swift/Controllers/XMPPEvents/ErrorEvent.h
index ee0284e..c0b5e52 100644
--- a/Swift/Controllers/XMPPEvents/ErrorEvent.h
+++ b/Swift/Controllers/XMPPEvents/ErrorEvent.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,25 +7,26 @@
#pragma once
#include <cassert>
+#include <memory>
+#include <string>
-#include "Swiften/Base/boost_bsignals.h"
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
-#include "Swift/Controllers/XMPPEvents/StanzaEvent.h"
-#include <string>
-#include "Swiften/JID/JID.h"
+#include <Swiften/JID/JID.h>
+
+#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..f8fb192 100644
--- a/Swift/Controllers/XMPPEvents/EventController.cpp
+++ b/Swift/Controllers/XMPPEvents/EventController.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -11,8 +11,6 @@
#include <boost/bind.hpp>
#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/Base/foreach.h>
-
#include <Swift/Controllers/XMPPEvents/ErrorEvent.h>
#include <Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h>
#include <Swift/Controllers/XMPPEvents/MUCInviteEvent.h>
@@ -25,56 +23,56 @@ EventController::EventController() {
}
EventController::~EventController() {
- foreach(boost::shared_ptr<StanzaEvent> event, events_) {
- event->onConclusion.disconnect(boost::bind(&EventController::handleEventConcluded, this, event));
- }
+ for (auto&& 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);
+void EventController::handleIncomingEvent(std::shared_ptr<StanzaEvent> sourceEvent) {
+ std::shared_ptr<MessageEvent> messageEvent = std::dynamic_pointer_cast<MessageEvent>(sourceEvent);
+ std::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = std::dynamic_pointer_cast<SubscriptionRequestEvent>(sourceEvent);
+ std::shared_ptr<ErrorEvent> errorEvent = std::dynamic_pointer_cast<ErrorEvent>(sourceEvent);
+ std::shared_ptr<MUCInviteEvent> mucInviteEvent = std::dynamic_pointer_cast<MUCInviteEvent>(sourceEvent);
+ std::shared_ptr<IncomingFileTransferEvent> incomingFileTransferEvent = std::dynamic_pointer_cast<IncomingFileTransferEvent>(sourceEvent);
- /* If it's a duplicate subscription request, remove the previous request first */
- if (subscriptionEvent) {
- EventList existingEvents(events_);
- foreach(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_);
+ for (auto&& existingEvent : existingEvents) {
+ std::shared_ptr<SubscriptionRequestEvent> existingSubscriptionEvent = std::dynamic_pointer_cast<SubscriptionRequestEvent>(existingEvent);
+ if (existingSubscriptionEvent) {
+ if (existingSubscriptionEvent->getJID() == subscriptionEvent->getJID()) {
+ existingEvent->conclude();
+ }
+ }
+ }
+ }
- if ((messageEvent && messageEvent->isReadable()) || subscriptionEvent || errorEvent || mucInviteEvent || incomingFileTransferEvent) {
- events_.push_back(sourceEvent);
- sourceEvent->onConclusion.connect(boost::bind(&EventController::handleEventConcluded, this, sourceEvent));
- onEventQueueLengthChange(boost::numeric_cast<int>(events_.size()));
- onEventQueueEventAdded(sourceEvent);
- if (sourceEvent->getConcluded()) {
- handleEventConcluded(sourceEvent);
- }
- }
+ 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()));
+void EventController::handleEventConcluded(std::shared_ptr<StanzaEvent> event) {
+ event->onConclusion.disconnect(boost::bind(&EventController::handleEventConcluded, this, event));
+ events_.erase(std::remove(events_.begin(), events_.end(), event), events_.end());
+ onEventQueueLengthChange(boost::numeric_cast<int>(events_.size()));
}
void EventController::disconnectAll() {
- onEventQueueLengthChange.disconnect_all_slots();
- onEventQueueEventAdded.disconnect_all_slots();
+ 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..8a095d9 100644
--- a/Swift/Controllers/XMPPEvents/EventController.h
+++ b/Swift/Controllers/XMPPEvents/EventController.h
@@ -1,36 +1,35 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <vector>
-#include <boost/shared_ptr.hpp>
-
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
#include <Swift/Controllers/XMPPEvents/MessageEvent.h>
#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<std::shared_ptr<StanzaEvent> > EventList;
+ class EventController {
+ public:
+ EventController();
+ ~EventController();
+
+ void handleIncomingEvent(std::shared_ptr<StanzaEvent> sourceEvent);
+ boost::signals2::signal<void (int)> onEventQueueLengthChange;
+ boost::signals2::signal<void (std::shared_ptr<StanzaEvent>)> onEventQueueEventAdded;
+ const EventList& getEvents() const {return events_;}
+ void disconnectAll();
+ void clear();
+
+ private:
+ void handleEventConcluded(std::shared_ptr<StanzaEvent> event);
+ EventList events_;
+ };
}
diff --git a/Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h b/Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h
index 24af640..3d4303d 100644
--- a/Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h
+++ b/Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h
@@ -1,30 +1,30 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/JID/JID.h>
#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 std::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..4cdbbff 100644
--- a/Swift/Controllers/XMPPEvents/MUCInviteEvent.h
+++ b/Swift/Controllers/XMPPEvents/MUCInviteEvent.h
@@ -5,43 +5,42 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
-
#include <Swiften/JID/JID.h>
#include <Swift/Controllers/XMPPEvents/StanzaEvent.h>
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 std::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..7af2be6 100644
--- a/Swift/Controllers/XMPPEvents/MessageEvent.h
+++ b/Swift/Controllers/XMPPEvents/MessageEvent.h
@@ -4,45 +4,44 @@
* See the COPYING file for more information.
*/
-#pragma once
+#pragma once
#include <cassert>
-
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Elements/Message.h>
#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 std::shared_ptr<MessageEvent> ref;
- MessageEvent(boost::shared_ptr<Message> stanza) : stanza_(stanza), targetsMe_(true) {}
+ MessageEvent(std::shared_ptr<Message> stanza) : stanza_(stanza), targetsMe_(true) {}
- boost::shared_ptr<Message> getStanza() {return stanza_;}
+ std::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:
+ std::shared_ptr<Message> stanza_;
+ bool targetsMe_;
+ };
}
diff --git a/Swift/Controllers/XMPPEvents/StanzaEvent.h b/Swift/Controllers/XMPPEvents/StanzaEvent.h
index a16aac9..56c4ea3 100644
--- a/Swift/Controllers/XMPPEvents/StanzaEvent.h
+++ b/Swift/Controllers/XMPPEvents/StanzaEvent.h
@@ -1,29 +1,29 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/date_time/posix_time/posix_time.hpp>
+#include <memory>
-#include "Swiften/Base/boost_bsignals.h"
+#include <boost/date_time/posix_time/posix_time.hpp>
+#include <boost/signals2.hpp>
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::signals2::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 1eb9cb1..8e3fd32 100644
--- a/Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h
+++ b/Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,40 +7,41 @@
#pragma once
#include <cassert>
+#include <memory>
+#include <string>
-#include "Swiften/Base/boost_bsignals.h"
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
-#include "Swift/Controllers/XMPPEvents/StanzaEvent.h"
-#include <string>
-#include "Swiften/JID/JID.h"
+#include <Swiften/JID/JID.h>
+
+#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::signals2::signal<void()> onAccept;
+ boost::signals2::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 06062e6..aaebd56 100644
--- a/Swift/Controllers/XMPPURIController.cpp
+++ b/Swift/Controllers/XMPPURIController.cpp
@@ -1,38 +1,40 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/Controllers/XMPPURIController.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swift/Controllers/UIEvents/RequestChatUIEvent.h>
+#include <Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h>
+#include <Swift/Controllers/UIEvents/UIEventStream.h>
#include <SwifTools/URIHandler/URIHandler.h>
#include <SwifTools/URIHandler/XMPPURI.h>
-#include <Swift/Controllers/UIEvents/UIEventStream.h>
-#include <Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h>
-#include <Swift/Controllers/UIEvents/RequestChatUIEvent.h>
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(std::make_shared<RequestJoinMUCUIEvent>(uri.getPath()));
+ }
+ else {
+ uiEventStream->send(std::make_shared<RequestChatUIEvent>(uri.getPath()));
+ }
+ }
}
diff --git a/Swift/Controllers/XMPPURIController.h b/Swift/Controllers/XMPPURIController.h
index b8a64de..941441f 100644
--- a/Swift/Controllers/XMPPURIController.h
+++ b/Swift/Controllers/XMPPURIController.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,26 +7,27 @@
#pragma once
#include <string>
-#include <Swiften/Base/boost_bsignals.h>
+
+#include <boost/signals2.hpp>
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::signals2::signal<void (const JID&)> onStartChat;
+ boost::signals2::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/Packaging/Debian/debian/control.in b/Swift/Packaging/Debian/debian/control.in
index 8583ebf..68a52de 100644
--- a/Swift/Packaging/Debian/debian/control.in
+++ b/Swift/Packaging/Debian/debian/control.in
@@ -3,7 +3,7 @@ Section: net
Priority: optional
Maintainer: Swift Package Maintainer <packages@swift.im>
Uploaders: Remko Tronçon <dev@el-tramo.be>, Kevin Smith <kevin@kismith.co.uk>
-Build-Depends: debhelper (>= 9), scons (>= 1.2.0), libssl-dev (>= 0.9.8g), qtbase5-dev (>= 5.0.0), qtchooser, qtbase5-dev-tools (>= 5.0.0), libqt5x11extras5-dev (>= 5.0.0), libqt5webkit5-dev (>= 5.0.0), qtmultimedia5-dev (>=5.0.0), qttools5-dev-tools (>=5.0.0), libxml2-dev (>= 2.7.6), libxss-dev (>= 1.2.0), libboost-dev (>= 1.34.1), libboost-filesystem-dev (>= 1.34.1), libboost-program-options-dev (>= 1.34.1), libboost-regex-dev (>= 1.34.1), libboost-signals-dev (>= 1.34.1), libboost-system-dev (>= 1.34.1), libboost-thread-dev (>= 1.34.1), libboost-date-time-dev (>= 1.34.1), libidn11-dev (>= 1.10), docbook-xsl (>= 1.75.0), docbook-xml (>= 4.5), xsltproc, libxml2-utils, libnatpmp-dev, libminiupnpc-dev, libsqlite3-dev, zlib1g-dev
+Build-Depends: debhelper (>= 9), scons (>= 1.2.0), libssl-dev (>= 0.9.8g), qtbase5-dev (>= 5.0.0), qtchooser, qtbase5-dev-tools (>= 5.0.0), libqt5x11extras5-dev (>= 5.0.0), libqt5webkit5-dev (>= 5.0.0), qtmultimedia5-dev (>=5.0.0), qttools5-dev-tools (>=5.0.0), qt5-image-formats-plugins (>=5.0.0), libqt5svg5 (>=5.0.0), libxml2-dev (>= 2.7.6), libxss-dev (>= 1.2.0), libboost-dev (>= 1.34.1), libboost-filesystem-dev (>= 1.34.1), libboost-program-options-dev (>= 1.34.1), libboost-regex-dev (>= 1.34.1), libboost-signals-dev (>= 1.34.1), libboost-system-dev (>= 1.34.1), libboost-thread-dev (>= 1.34.1), libboost-date-time-dev (>= 1.34.1), libidn11-dev (>= 1.10), docbook-xsl (>= 1.75.0), docbook-xml (>= 4.5), xsltproc, libxml2-utils, libnatpmp-dev, libminiupnpc-dev, libsqlite3-dev, libhunspell-dev, zlib1g-dev
Standards-Version: 3.9.8
Vcs-Git: git://swift.im/swift
Vcs-Browser: http://swift.im/git/swift
diff --git a/Swift/Packaging/Debian/package_all_platforms.sh b/Swift/Packaging/Debian/package_all_platforms.sh
index 1773515..4d1ef3c 100755
--- a/Swift/Packaging/Debian/package_all_platforms.sh
+++ b/Swift/Packaging/Debian/package_all_platforms.sh
@@ -24,7 +24,7 @@ export SWIFT_FORCE_LUCID="yep"
unset SWIFT_FORCE_LUCID
./package.sh
-for distro in trusty wily jessie sid; do
+for distro in trusty xenial jessie sid; do
for arch in amd64; do
pbuilder-dist $distro $arch build *.dsc
done
diff --git a/Swift/Packaging/MacOSX/Swift.dmg.gz b/Swift/Packaging/MacOSX/Swift.dmg.gz
index ba8ccf7..ca2b520 100644
--- a/Swift/Packaging/MacOSX/Swift.dmg.gz
+++ b/Swift/Packaging/MacOSX/Swift.dmg.gz
Binary files differ
diff --git a/Swift/Packaging/MacOSX/package.sh b/Swift/Packaging/MacOSX/package.sh
index a13a03c..7a63237 100755
--- a/Swift/Packaging/MacOSX/package.sh
+++ b/Swift/Packaging/MacOSX/package.sh
@@ -4,6 +4,7 @@ APP=$1
TEMPLATE=$2
TARGET=$3
QTDIR=$4
+CODESIGN_IDENTITY=$5
if [[ ! -f "$TEMPLATE" || ! -d "$APP" || ! -d "$QTDIR" || -z "$TARGET" ]]; then
echo "Error"
@@ -30,6 +31,11 @@ rm "$WC_DIR"/`basename $APP`/Contents/PlugIns/bearer/*.dylib
# Remove debugging symbols from the application bundle
rm -rf "$WC_DIR"/`basename $APP`/Contents/MacOS/*.dSYM
+# Codesign the app bundle if requested by caller
+if [ ! -z "$CODESIGN_IDENTITY" ]; then
+ codesign --verbose --force --deep --sign "$CODESIGN_IDENTITY" "$WC_DIR"/`basename $APP`
+fi
+
hdiutil detach "$WC_DIR" -quiet -force
rm -f $TARGET
hdiutil convert "$WC_DMG" -quiet -format UDZO -imagekey zlib-level=9 -o "$TARGET"
diff --git a/Swift/Packaging/Source/package.sh b/Swift/Packaging/Source/package.sh
index 16a9a1f..3872b35 100755
--- a/Swift/Packaging/Source/package.sh
+++ b/Swift/Packaging/Source/package.sh
@@ -3,9 +3,13 @@
## For a Swiften-only tarball, try
## EXCLUDE_FOLDERS="Swift Sluift Limber Slimber" ./package.sh
+## This script will require GPG and a suitable signing key by default.
+## To disable tarball signature generation, pass the --nosign parameter to package.sh.
+
export PYTHONPATH=../../../BuildTools/SCons
VERSION=`../../../BuildTools/GetBuildVersion.py swift`
DIRNAME=swift-$VERSION
+FIRST_ARGUMENT=$1
if [ -z "$VERSION" ]; then
echo "Unable to determine version"
@@ -40,3 +44,20 @@ done
echo "Creating tarball ..."
$TAR -czf $DIRNAME.tar.gz --owner=swift --group=swift $DIRNAME
+
+if [ "$FIRST_ARGUMENT" != "--nosign" ]; then
+ echo "Creating armored GPG signature ..."
+ which gpg
+ if [ $? -eq 0 ]; then
+ gpg --list-keys packages@swift.im
+ if [ $? -eq 0 ]; then
+ gpg --armor --default-key packages@swift.im --detach-sign $DIRNAME.tar.gz
+ else
+ echo "Key for packages@swift.im missing. Not signing tar archive."
+ exit 1
+ fi
+ else
+ echo "GPG not found. Not signing tar archive."
+ exit 1
+ fi
+fi \ No newline at end of file
diff --git a/Swift/QtUI/ApplicationTest/main.cpp b/Swift/QtUI/ApplicationTest/main.cpp
index abaddf6..782bbf1 100644
--- a/Swift/QtUI/ApplicationTest/main.cpp
+++ b/Swift/QtUI/ApplicationTest/main.cpp
@@ -1,45 +1,48 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <string>
+
#include <QApplication>
-#include <QWidget>
-#include <QVBoxLayout>
#include <QLineEdit>
-#include "../QtSwiftUtil.h"
-#include <string>
-#include "SwifTools/Application/Platform/PlatformApplication.h"
+#include <QVBoxLayout>
+#include <QWidget>
+
+#include <SwifTools/Application/Platform/PlatformApplication.h>
+
+#include <Swift/QtUI/QtSwiftUtil.h>
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..f818e50 100644
--- a/Swift/QtUI/ChatList/ChatListDelegate.cpp
+++ b/Swift/QtUI/ChatList/ChatListDelegate.cpp
@@ -1,11 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/ChatList/ChatListDelegate.h>
+#include <QColor>
#include <QPainter>
#include <QPen>
@@ -18,126 +19,130 @@
namespace Swift {
+namespace {
+ const QColor secondLineColor = QColor(160,160,160);
+}
+
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(secondLineColor));
+
+ 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 eca22d8..44ca947 100644
--- a/Swift/QtUI/ChatList/ChatListDelegate.h
+++ b/Swift/QtUI/ChatList/ChatListDelegate.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2011 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,31 +8,31 @@
#include <QStyledItemDelegate>
-#include "Swift/QtUI/Roster/GroupItemDelegate.h"
+#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 2b6534a..a9bb9b1 100644
--- a/Swift/QtUI/ChatList/ChatListGroupItem.h
+++ b/Swift/QtUI/ChatList/ChatListGroupItem.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,38 +8,35 @@
#include <QList>
-#include <Swiften/Base/foreach.h>
-
-#include "Swift/QtUI/ChatList/ChatListItem.h"
+#include <Swift/QtUI/ChatList/ChatListItem.h>
namespace Swift {
- class ChatListGroupItem : public ChatListItem {
- public:
- ChatListGroupItem(const QString& name, ChatListGroupItem* parent, bool sorted = true) : ChatListItem(parent), name_(name), sorted_(sorted) {}
- virtual ~ChatListGroupItem() {clear();}
- void addItem(ChatListItem* item) {items_.push_back(item); if (sorted_) {qStableSort(items_.begin(), items_.end(), pointerItemLessThan);}}
- void remove(int index) {items_.removeAt(index);}
- int rowCount() {return items_.size();}
- ChatListItem* item(int i) {return items_[i];}
- int row(ChatListItem* item) {return items_.indexOf(item);}
- QVariant data(int role) const {return (role == Qt::DisplayRole) ? name_ : QVariant();}
- void clear() {
- foreach (ChatListItem* item, items_) {
- 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() {
+ for (auto item : items_) {
+ delete item;
+ }
+ items_.clear();
+ }
+
+ private:
+ static bool pointerItemLessThan(const ChatListItem* first, const ChatListItem* second) {
+ QString myName = first->data(Qt::DisplayRole).toString().toLower();
+ QString theirName = second->data(Qt::DisplayRole).toString().toLower();
+ return myName < theirName;
+ }
+
+ QString name_;
+ QList<ChatListItem*> items_;
+ bool sorted_;
+ };
}
diff --git a/Swift/QtUI/ChatList/ChatListItem.h b/Swift/QtUI/ChatList/ChatListItem.h
index 423e0ec..c6fd762 100644
--- a/Swift/QtUI/ChatList/ChatListItem.h
+++ b/Swift/QtUI/ChatList/ChatListItem.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,19 +7,20 @@
#pragma once
#include <QVariant>
+
#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 1eb614b..e701ddc 100644
--- a/Swift/QtUI/ChatList/ChatListMUCItem.cpp
+++ b/Swift/QtUI/ChatList/ChatListMUCItem.cpp
@@ -1,12 +1,14 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/QtUI/ChatList/ChatListMUCItem.h"
+#include <Swift/QtUI/ChatList/ChatListMUCItem.h>
-#include "Swift/QtUI/QtSwiftUtil.h"
+#include <QColor>
+
+#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
ChatListMUCItem::ChatListMUCItem(const MUCBookmark& bookmark, ChatListGroupItem* parent) : ChatListItem(parent), bookmark_(bookmark) {
@@ -14,21 +16,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 QColor(89,89,89);
+ /*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 7e9177a..c77c284 100644
--- a/Swift/QtUI/ChatList/ChatListMUCItem.h
+++ b/Swift/QtUI/ChatList/ChatListMUCItem.h
@@ -1,33 +1,33 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QList>
+#include <memory>
-#include <boost/shared_ptr.hpp>
+#include <QList>
-#include "Swiften/MUC/MUCBookmark.h"
+#include <Swiften/MUC/MUCBookmark.h>
-#include "Swift/QtUI/ChatList/ChatListItem.h"
+#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..416b786 100644
--- a/Swift/QtUI/ChatList/ChatListModel.cpp
+++ b/Swift/QtUI/ChatList/ChatListModel.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -16,173 +16,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);
+ChatListModel::ChatListModel() : whiteboards_(nullptr) {
+ root_ = new ChatListGroupItem("", nullptr, 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());
+ for (const auto& 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 == nullptr) {
+ return data;
+ }
+
+ QByteArray itemData;
+ QDataStream dataStream(&itemData, QIODevice::WriteOnly);
+ const ChatListWindow::Chat& chat = item->getChat();
+
+ QString mimeType = "application/vnd.swift.contact-jid-list";
+ if (!chat.impromptuJIDs.size()) {
+ if (chat.isMUC) {
+ mimeType = "application/vnd.swift.contact-jid-muc";
+ }
+ dataStream << P2QSTRING(chat.jid.toString());
+ } else {
+ for (const auto& jid : chat.impromptuJIDs) {
+ dataStream << P2QSTRING(jid.second.toString());
+ }
+ }
+
+ data->setData(mimeType, itemData);
+ return data;
}
const ChatListMUCItem* ChatListModel::getChatListMUCItem(const JID& roomJID) const {
- const ChatListMUCItem* mucItem = 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 = nullptr;
+ for (int i = 0; i < mucBookmarks_->rowCount(); i++) {
+ ChatListMUCItem* item = dynamic_cast<ChatListMUCItem*>(mucBookmarks_->item(i));
+ if (item->getBookmark().getRoom() == roomJID) {
+ mucItem = item;
+ break;
+ }
+ }
+ return mucItem;
}
int ChatListModel::columnCount(const QModelIndex& /*parent*/) const {
- return 1;
+ 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()) : nullptr;
}
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 = nullptr;
+ 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 a1446e3..faac937 100644
--- a/Swift/QtUI/ChatList/ChatListRecentItem.cpp
+++ b/Swift/QtUI/ChatList/ChatListRecentItem.cpp
@@ -1,12 +1,13 @@
/*
- * Copyright (c) 2011-2013 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swift/QtUI/ChatList/ChatListRecentItem.h>
+
#include <Swiften/Base/Path.h>
-#include <Swift/QtUI/ChatList/ChatListRecentItem.h>
#include <Swift/QtUI/QtResourceHelper.h>
#include <Swift/QtUI/QtSwiftUtil.h>
@@ -16,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 QColor(89,89,89);
+ /*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 74c8024..3c9635b 100644
--- a/Swift/QtUI/ChatList/ChatListRecentItem.h
+++ b/Swift/QtUI/ChatList/ChatListRecentItem.h
@@ -1,36 +1,37 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QList>
-#include <QIcon>
+#include <memory>
-#include <boost/shared_ptr.hpp>
+#include <QIcon>
+#include <QList>
#include <Swiften/MUC/MUCBookmark.h>
+
#include <Swift/Controllers/UIInterfaces/ChatListWindow.h>
#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 287ccaf..8a4447e 100644
--- a/Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp
+++ b/Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp
@@ -5,42 +5,46 @@
*/
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swift/QtUI/ChatList/ChatListWhiteboardItem.h>
+
+#include <QColor>
+
#include <Swiften/Base/Path.h>
-#include <Swift/QtUI/ChatList/ChatListWhiteboardItem.h>
-#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/QtResourceHelper.h>
+#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 QColor(89,89,89);
+ /*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 0281cb0..6dbc5f6 100644
--- a/Swift/QtUI/ChatList/ChatListWhiteboardItem.h
+++ b/Swift/QtUI/ChatList/ChatListWhiteboardItem.h
@@ -1,35 +1,36 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QList>
-#include <QIcon>
+#include <memory>
-#include <boost/shared_ptr.hpp>
+#include <QIcon>
+#include <QList>
#include <Swiften/MUC/MUCBookmark.h>
+
#include <Swift/Controllers/UIInterfaces/ChatListWindow.h>
#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..3caed57 100644
--- a/Swift/QtUI/ChatList/QtChatListWindow.cpp
+++ b/Swift/QtUI/ChatList/QtChatListWindow.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::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(std::make_shared<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(std::make_shared<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()) : nullptr;
+ contextMenuItem_ = baseItem;
+
+ for (auto action : onlineOnlyActions_) {
+ action->setEnabled(isOnline_);
+ }
+
+ if (!baseItem) {
+ emptyMenu_->exec(QCursor::pos());
+ return;
+ }
+
+ ChatListMUCItem* mucItem = dynamic_cast<ChatListMUCItem*>(baseItem);
+ if (mucItem) {
+ if (!bookmarksEnabled_) {
+ return;
+ }
+ mucMenu_->exec(QCursor::pos());
+ return;
+ }
+
+ ChatListRecentItem* recentItem = dynamic_cast<ChatListRecentItem*>(baseItem);
+ if (recentItem) {
+ const ChatListWindow::Chat& chat = recentItem->getChat();
+ if (chat.isMUC) {
+ QMenu mucRecentsMenu;
+ QAction* bookmarkAction = nullptr;
+ const ChatListMUCItem* mucItem = model_->getChatListMUCItem(chat.jid);
+ if (mucItem) {
+ contextMenuItem_ = mucItem;
+ bookmarkAction = mucRecentsMenu.addAction(tr("Edit Bookmark"), this, SLOT(handleEditBookmark()));
+ }
+ else {
+ bookmarkAction = mucRecentsMenu.addAction(tr("Add to Bookmarks"), this, SLOT(handleAddBookmarkFromRecents()));
+ }
+ 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..834e318 100644
--- a/Swift/QtUI/ChatList/QtChatListWindow.h
+++ b/Swift/QtUI/ChatList/QtChatListWindow.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 = nullptr);
+ 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..87dfac2 100644
--- a/Swift/QtUI/ChatSnippet.cpp
+++ b/Swift/QtUI/ChatSnippet.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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);
+ std::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
+ std::string text = "";
+ for (auto&& part : message.getParts()) {
+ if ((textPart = std::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
+ text = textPart->text;
+ break;
+ }
+ }
+ return getDirection(text);
}
ChatSnippet::Direction ChatSnippet::getDirection(const std::string& message) {
- return getDirection(P2QSTRING(message));
+ 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 5d94917..d8bc209 100644
--- a/Swift/QtUI/ChatSnippet.h
+++ b/Swift/QtUI/ChatSnippet.h
@@ -1,70 +1,70 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <QString>
#include <QDateTime>
+#include <QString>
-#include <Swiften/Base/foreach.h>
#include <Swift/Controllers/UIInterfaces/ChatWindow.h>
-#include <Swift/QtUI/QtChatTheme.h>
+#include <Swift/QtUI/QtChatTheme.h>
namespace Swift {
- class ChatSnippet {
- public:
- enum Direction {
- RTL,
- LTR
- };
-
- ChatSnippet(bool appendToPrevious);
- virtual ~ChatSnippet();
-
- virtual const QString& getContent() const = 0;
- virtual QString getContinuationElementID() const { return ""; }
-
- 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("\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 ""; }
+
+ std::shared_ptr<ChatSnippet> getContinuationFallbackSnippet() const {return continuationFallback_;}
+
+ bool getAppendToPrevious() const {
+ return appendToPrevious_;
+ }
+
+ static QString escape(const QString& original) {
+ QString result(original);
+ result.replace("%message%", "&#37;message&#37;");
+ result.replace("%sender%", "&#37;sender&#37;");
+ result.replace("%wrapped_sender%", "&#37;wrapped_sender&#37;");
+ result.replace("%time%", "%&#37;time&#37;");
+ 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(std::shared_ptr<ChatSnippet> continuationFallback) {
+ continuationFallback_ = continuationFallback;
+ }
+ private:
+ bool appendToPrevious_;
+ std::shared_ptr<ChatSnippet> continuationFallback_;
+ };
}
diff --git a/Swift/QtUI/ChatView/main.cpp b/Swift/QtUI/ChatView/main.cpp
index d845958..aa3255e 100644
--- a/Swift/QtUI/ChatView/main.cpp
+++ b/Swift/QtUI/ChatView/main.cpp
@@ -1,178 +1,180 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <QtDebug>
-#include <QApplication>
#include <iostream>
-#include <QWidget>
-#include <QFile>
+
+#include <QApplication>
#include <QDateTime>
+#include <QFile>
#include <QLineEdit>
+#include <QNetworkAccessManager>
+#include <QNetworkReply>
+#include <QNetworkRequest>
#include <QVBoxLayout>
-#include <QWebView>
#include <QWebFrame>
-#include <QNetworkRequest>
-#include <QNetworkReply>
-#include <QNetworkAccessManager>
-#include "../QtChatView.h"
-#include "../MessageSnippet.h"
-#include "../SystemMessageSnippet.h"
+#include <QWebView>
+#include <QWidget>
+#include <QtDebug>
+
+#include <Swift/QtUI/MessageSnippet.h>
+#include <Swift/QtUI/QtChatView.h>
+#include <Swift/QtUI/SystemMessageSnippet.h>
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..83fa886 100644
--- a/Swift/QtUI/CocoaApplicationActivateHelper.h
+++ b/Swift/QtUI/CocoaApplicationActivateHelper.h
@@ -1,28 +1,30 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#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;
+ const std::unique_ptr<Private> p;
+ };
}
diff --git a/Swift/QtUI/CocoaApplicationActivateHelper.mm b/Swift/QtUI/CocoaApplicationActivateHelper.mm
index 9f12fba..2bd985a 100644
--- a/Swift/QtUI/CocoaApplicationActivateHelper.mm
+++ b/Swift/QtUI/CocoaApplicationActivateHelper.mm
@@ -1,15 +1,19 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Cocoa/Cocoa.h>
-#include "CocoaApplicationActivateHelper.h"
+#include <Swift/QtUI/CocoaApplicationActivateHelper.h>
+
+#include <memory>
#include <boost/function.hpp>
+
#include <QApplication>
+#include <Cocoa/Cocoa.h>
+
@interface CocoaApplicationActivateHelperDelegate : NSObject {
}
- (void) handleActivate: (NSAppleEventDescriptor*) event withReply: (NSAppleEventDescriptor*) reply;
@@ -17,37 +21,35 @@
@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);
+CocoaApplicationActivateHelper::CocoaApplicationActivateHelper() : 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];
}
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 25da0e3..8d96bd9 100644
--- a/Swift/QtUI/CocoaUIHelpers.h
+++ b/Swift/QtUI/CocoaUIHelpers.h
@@ -4,16 +4,24 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <Swiften/TLS/Certificate.h>
#include <QWidget>
+#include <Swiften/TLS/Certificate.h>
+
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);
+ static void sendCocoaApplicationWillTerminateNotification();
};
}
diff --git a/Swift/QtUI/CocoaUIHelpers.mm b/Swift/QtUI/CocoaUIHelpers.mm
index 3cb62f3..1f4ffc1 100644
--- a/Swift/QtUI/CocoaUIHelpers.mm
+++ b/Swift/QtUI/CocoaUIHelpers.mm
@@ -4,9 +4,16 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include "CocoaUIHelpers.h"
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/type_traits.hpp>
#include <Cocoa/Cocoa.h>
@@ -14,30 +21,31 @@
#include <Security/Security.h>
#include <SecurityInterface/SFCertificatePanel.h>
-#include <Swiften/Base/foreach.h>
-
#pragma GCC diagnostic ignored "-Wold-style-cast"
namespace Swift {
void CocoaUIHelpers::displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain) {
- NSWindow* parentWindow = [((NSView*)parent->winId()) window];
- NSMutableArray* certificates = [[NSMutableArray alloc] init];
- foreach(Certificate::ref cert, chain) {
- // 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];
+ for (auto&& cert : chain) {
+ // convert chain to SecCertificateRef
+ ByteArray certAsDER = cert->toDER();
+ std::shared_ptr<boost::remove_pointer<CFDataRef>::type> certData(CFDataCreate(nullptr, certAsDER.data(), certAsDER.size()), CFRelease);
+ std::shared_ptr<OpaqueSecCertificateRef> macCert(SecCertificateCreateWithData(nullptr, certData.get()), CFRelease);
+
+ // add to NSMutable array
+ [certificates addObject: (id)macCert.get()];
+ }
+
+ SFCertificatePanel* panel = [[SFCertificatePanel alloc] init];
+ //[panel setPolicies:(id)policies.get()];
+ [panel beginSheetForWindow:parentWindow modalDelegate:nil didEndSelector:nullptr contextInfo:nullptr certificates:certificates showGroup:YES];
+ [certificates release];
+}
+
+void CocoaUIHelpers::sendCocoaApplicationWillTerminateNotification() {
+ [[NSNotificationCenter defaultCenter] postNotificationName:@"NSApplicationWillTerminateNotification" object:nil];
}
}
diff --git a/Swift/QtUI/EventViewer/EventDelegate.cpp b/Swift/QtUI/EventViewer/EventDelegate.cpp
index cd657b8..1c3ed7f 100644
--- a/Swift/QtUI/EventViewer/EventDelegate.cpp
+++ b/Swift/QtUI/EventViewer/EventDelegate.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+EventType EventDelegate::getEventType(std::shared_ptr<StanzaEvent> event) const {
+ std::shared_ptr<MessageEvent> messageEvent = std::dynamic_pointer_cast<MessageEvent>(event);
+ if (messageEvent) {
+ return MessageEventType;
+ }
+ std::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = std::dynamic_pointer_cast<SubscriptionRequestEvent>(event);
+ if (subscriptionEvent) {
+ return SubscriptionEventType;
+ }
+ std::shared_ptr<ErrorEvent> errorEvent = std::dynamic_pointer_cast<ErrorEvent>(event);
+ if (errorEvent) {
+ return ErrorEventType;
+ }
+ std::shared_ptr<MUCInviteEvent> mucInviteEvent = std::dynamic_pointer_cast<MUCInviteEvent>(event);
+ if (mucInviteEvent) {
+ return MUCInviteEventType;
+ }
+ std::shared_ptr<IncomingFileTransferEvent> incomingFileTransferEvent = std::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..79ee8ed 100644
--- a/Swift/QtUI/EventViewer/EventDelegate.h
+++ b/Swift/QtUI/EventViewer/EventDelegate.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::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..5b97b3e 100644
--- a/Swift/QtUI/EventViewer/EventModel.cpp
+++ b/Swift/QtUI/EventViewer/EventModel.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
- }
+ for (auto event : activeEvents_) {
+ delete event;
+ }
+ for (auto 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 = nullptr;
+ if (row < activeEvents_.size()) {
+ event = activeEvents_[row];
+ }
+ else {
+ int inactiveRow = row - activeEvents_.size();
+ if (inactiveRow < inactiveEvents_.size()) {
+ event = inactiveEvents_[inactiveRow];
+ }
+ else {
+ SWIFT_LOG(error) << "Misbehaving EventModel requests row index outside of range";
+ }
+ }
+ return event;
}
int EventModel::getNewEventCount() {
- return activeEvents_.size();
+ 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();
+void EventModel::addEvent(std::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();
}
-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();
+void EventModel::removeEvent(std::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();
}
}
diff --git a/Swift/QtUI/EventViewer/EventModel.h b/Swift/QtUI/EventViewer/EventModel.h
index cf259f2..de72c1b 100644
--- a/Swift/QtUI/EventViewer/EventModel.h
+++ b/Swift/QtUI/EventViewer/EventModel.h
@@ -1,37 +1,37 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <QAbstractListModel>
#include <QList>
-#include "Swift/Controllers/XMPPEvents/StanzaEvent.h"
+#include <Swift/Controllers/XMPPEvents/StanzaEvent.h>
-#include "Swift/QtUI/EventViewer/QtEvent.h"
+#include <Swift/QtUI/EventViewer/QtEvent.h>
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(std::shared_ptr<StanzaEvent> event, bool active);
+ void removeEvent(std::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 7e89f04..4d56548 100644
--- a/Swift/QtUI/EventViewer/EventView.cpp
+++ b/Swift/QtUI/EventViewer/EventView.cpp
@@ -1,14 +1,14 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/QtUI/EventViewer/EventView.h"
+#include <Swift/QtUI/EventViewer/EventView.h>
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 4830aec..5bd0fad 100644
--- a/Swift/QtUI/EventViewer/QtEvent.cpp
+++ b/Swift/QtUI/EventViewer/QtEvent.cpp
@@ -15,84 +15,84 @@
#include <Swift/Controllers/XMPPEvents/MessageEvent.h>
#include <Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h>
-#include "Swift/QtUI/QtSwiftUtil.h"
+#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
-QtEvent::QtEvent(boost::shared_ptr<StanzaEvent> event, bool active) : event_(event) {
- active_ = active;
+QtEvent::QtEvent(std::shared_ptr<StanzaEvent> event, bool active) : event_(event) {
+ 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 "";
+ std::shared_ptr<MessageEvent> messageEvent = std::dynamic_pointer_cast<MessageEvent>(event_);
+ if (messageEvent) {
+ return P2QSTRING(messageEvent->getStanza()->getFrom().toString());
+ }
+ std::shared_ptr<SubscriptionRequestEvent> subscriptionRequestEvent = std::dynamic_pointer_cast<SubscriptionRequestEvent>(event_);
+ if (subscriptionRequestEvent) {
+ return P2QSTRING(subscriptionRequestEvent->getJID().toBare().toString());
+ }
+ std::shared_ptr<ErrorEvent> errorEvent = std::dynamic_pointer_cast<ErrorEvent>(event_);
+ if (errorEvent) {
+ return P2QSTRING(errorEvent->getJID().toBare().toString());
+ }
+ std::shared_ptr<MUCInviteEvent> mucInviteEvent = std::dynamic_pointer_cast<MUCInviteEvent>(event_);
+ if (mucInviteEvent) {
+ return P2QSTRING(mucInviteEvent->getInviter().toString());
+ }
+ std::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = std::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 "";
+ std::shared_ptr<MessageEvent> messageEvent = std::dynamic_pointer_cast<MessageEvent>(event_);
+ if (messageEvent) {
+ return P2QSTRING(messageEvent->getStanza()->getBody().get_value_or(""));
+ }
+ std::shared_ptr<SubscriptionRequestEvent> subscriptionRequestEvent = std::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;
+ }
+ std::shared_ptr<ErrorEvent> errorEvent = std::dynamic_pointer_cast<ErrorEvent>(event_);
+ if (errorEvent) {
+ return P2QSTRING(errorEvent->getText());
+ }
+ std::shared_ptr<MUCInviteEvent> mucInviteEvent = std::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;
+ }
+ std::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = std::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 8959452..cb78b00 100644
--- a/Swift/QtUI/EventViewer/QtEvent.h
+++ b/Swift/QtUI/EventViewer/QtEvent.h
@@ -1,32 +1,32 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <QVariant>
-#include "Swift/Controllers/XMPPEvents/StanzaEvent.h"
+#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(std::shared_ptr<StanzaEvent> event, bool active);
+ QVariant data(int role);
+ std::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();
+ std::shared_ptr<StanzaEvent> event_;
+ bool active_;
+ };
}
diff --git a/Swift/QtUI/EventViewer/QtEventWindow.cpp b/Swift/QtUI/EventViewer/QtEventWindow.cpp
index f92cd07..c8d1f0c 100644
--- a/Swift/QtUI/EventViewer/QtEventWindow.cpp
+++ b/Swift/QtUI/EventViewer/QtEventWindow.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,12 +9,13 @@
#include <QBoxLayout>
#include <QMessageBox>
#include <QPushButton>
-#include <QtDebug>
+#include <QTreeView>
#include <Swiften/Base/Platform.h>
#include <Swift/Controllers/UIEvents/JoinMUCUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestChatUIEvent.h>
+#include <Swift/Controllers/UIEvents/UIEventStream.h>
#include <Swift/Controllers/XMPPEvents/ErrorEvent.h>
#include <Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h>
#include <Swift/Controllers/XMPPEvents/MUCInviteEvent.h>
@@ -26,97 +27,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());
+ std::shared_ptr<MessageEvent> messageEvent = std::dynamic_pointer_cast<MessageEvent>(event->getEvent());
+ std::shared_ptr<SubscriptionRequestEvent> subscriptionEvent = std::dynamic_pointer_cast<SubscriptionRequestEvent>(event->getEvent());
+ std::shared_ptr<MUCInviteEvent> mucInviteEvent = std::dynamic_pointer_cast<MUCInviteEvent>(event->getEvent());
+ std::shared_ptr<IncomingFileTransferEvent> incomingFTEvent = std::dynamic_pointer_cast<IncomingFileTransferEvent>(event->getEvent());
+ std::shared_ptr<ErrorEvent> errorEvent = std::dynamic_pointer_cast<ErrorEvent>(event->getEvent());
+
+ if (messageEvent) {
+ if (messageEvent->getStanza()->getType() == Message::Groupchat) {
+ eventStream_->send(std::make_shared<JoinMUCUIEvent>(messageEvent->getStanza()->getFrom().toBare(), messageEvent->getStanza()->getTo().getResource()));
+ } else {
+ eventStream_->send(std::make_shared<RequestChatUIEvent>(messageEvent->getStanza()->getFrom()));
+ }
+ } else if (subscriptionEvent) {
+ QtSubscriptionRequestWindow* window = QtSubscriptionRequestWindow::getWindow(subscriptionEvent, this);
+ window->show();
+ } else if (mucInviteEvent) {
+ eventStream_->send(std::make_shared<RequestChatUIEvent>(mucInviteEvent->getInviter()));
+ mucInviteEvent->conclude();
+ } else if (incomingFTEvent) {
+ eventStream_->send(std::make_shared<RequestChatUIEvent>(incomingFTEvent->getSender()));
+ incomingFTEvent->conclude();
+ } else {
+ if (errorEvent) {
+ errorEvent->conclude();
+ }
+ QMessageBox msgBox;
+ msgBox.setText(event->data(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);
+void QtEventWindow::addEvent(std::shared_ptr<StanzaEvent> event, bool active) {
+ 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);
+void QtEventWindow::removeEvent(std::shared_ptr<StanzaEvent> event) {
+ 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 68c3456..7ae33ec 100644
--- a/Swift/QtUI/EventViewer/QtEventWindow.h
+++ b/Swift/QtUI/EventViewer/QtEventWindow.h
@@ -1,44 +1,48 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <QTreeView>
+#include <Swift/Controllers/UIInterfaces/EventWindow.h>
-#include "Swift/Controllers/UIInterfaces/EventWindow.h"
-#include "Swift/Controllers/UIEvents/UIEventStream.h"
-#include "Swift/QtUI/EventViewer/EventView.h"
-#include "Swift/QtUI/EventViewer/EventModel.h"
-#include "Swift/QtUI/EventViewer/EventDelegate.h"
+#include <Swift/QtUI/EventViewer/EventDelegate.h>
+#include <Swift/QtUI/EventViewer/EventModel.h>
+#include <Swift/QtUI/EventViewer/EventView.h>
class QPushButton;
+class QTreeView;
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 UIEventStream;
+
+ class QtEventWindow : public QWidget, public EventWindow {
+ Q_OBJECT
+ public:
+ QtEventWindow(UIEventStream* eventStream);
+ ~QtEventWindow();
+ void addEvent(std::shared_ptr<StanzaEvent> event, bool active);
+ void removeEvent(std::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 662f5f8..5ba24ec 100644
--- a/Swift/QtUI/EventViewer/TwoLineDelegate.cpp
+++ b/Swift/QtUI/EventViewer/TwoLineDelegate.cpp
@@ -1,20 +1,25 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "TwoLineDelegate.h"
+#include <Swift/QtUI/EventViewer/TwoLineDelegate.h>
-#include <QPen>
+#include <QColor>
#include <QPainter>
-#include <QDebug>
+#include <QPen>
namespace Swift {
+
+namespace {
+ const QColor secondLineColor = QColor(160,160,160);
+}
+
TwoLineDelegate::TwoLineDelegate(int firstRole, int secondRole, bool wrap) {
- firstRole_ = firstRole;
- secondRole_ = secondRole;
- wrap_ = wrap;
+ firstRole_ = firstRole;
+ secondRole_ = secondRole;
+ wrap_ = wrap;
}
TwoLineDelegate::~TwoLineDelegate() {
@@ -22,41 +27,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(secondLineColor));
+
+ 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 e1e3c7a..089f97a 100644
--- a/Swift/QtUI/EventViewer/TwoLineDelegate.h
+++ b/Swift/QtUI/EventViewer/TwoLineDelegate.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,22 +8,22 @@
#include <QStyledItemDelegate>
-#include "Swift/QtUI/Roster/DelegateCommons.h"
-#include "QtEvent.h"
+#include <Swift/QtUI/EventViewer/QtEvent.h>
+#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 278dfa8..492599e 100644
--- a/Swift/QtUI/EventViewer/main.cpp
+++ b/Swift/QtUI/EventViewer/main.cpp
@@ -1,31 +1,33 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <QtGui>
-#include "EventView.h"
-#include "EventModel.h"
-#include "QtEventWindow.h"
-#include "Swiften/Events/MessageEvent.h"
-#include "Swiften/Events/ErrorEvent.h"
-#include "Swiften/JID/JID.h"
+#include <EventModel.h>
+#include <EventView.h>
+
+#include <Swiften/Events/ErrorEvent.h>
+#include <Swiften/Events/MessageEvent.h>
+#include <Swiften/JID/JID.h>
+
+#include <Swift/QtUI/EventViewer/QtEventWindow.h>
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();
+ std::shared_ptr<Swift::Message> message1(new Swift::Message());
+ message1->setBody("Oooh, shiny");
+ std::shared_ptr<Swift::MessageEvent> event1(new Swift::MessageEvent(message1));
+ viewer->addEvent(std::dynamic_pointer_cast<Swift::StanzaEvent>(event1), true);
+ for (int i = 0; i < 100; i++) {
+ viewer->addEvent(std::dynamic_pointer_cast<Swift::StanzaEvent>(event1), false);
+ }
+ viewer->addEvent(std::dynamic_pointer_cast<Swift::StanzaEvent>(std::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 aebe405..dab7e73 100644
--- a/Swift/QtUI/FreeDesktopNotifier.h
+++ b/Swift/QtUI/FreeDesktopNotifier.h
@@ -1,24 +1,25 @@
/*
- * Copyright (c) 2010 -2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "SwifTools/Notifier/Notifier.h"
-#include "QtCachedImageScaler.h"
+#include <SwifTools/Notifier/Notifier.h>
+
+#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 828b89a..0163e03 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp
+++ b/Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp
@@ -1,17 +1,18 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <QPen>
+#include <Swift/QtUI/MUCSearch/MUCSearchDelegate.h>
+
#include <QPainter>
+#include <QPen>
-#include "Swift/QtUI/MUCSearch/MUCSearchDelegate.h"
-#include "Swift/QtUI/Roster/GroupItemDelegate.h"
-#include "Swift/QtUI/MUCSearch/MUCSearchItem.h"
-#include "Swift/QtUI/MUCSearch/MUCSearchRoomItem.h"
-#include "Swift/QtUI/MUCSearch/MUCSearchServiceItem.h"
+#include <Swift/QtUI/MUCSearch/MUCSearchItem.h>
+#include <Swift/QtUI/MUCSearch/MUCSearchRoomItem.h>
+#include <Swift/QtUI/MUCSearch/MUCSearchServiceItem.h>
+#include <Swift/QtUI/Roster/GroupItemDelegate.h>
namespace Swift {
@@ -24,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 57dcaee..5bf9646 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchDelegate.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchDelegate.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,21 +8,21 @@
#include <QStyledItemDelegate>
-#include "Swift/QtUI/Roster/DelegateCommons.h"
+#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 492971a..3a3b841 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp
+++ b/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp
@@ -1,38 +1,44 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h>
-#include <Swift/QtUI/MUCSearch/MUCSearchServiceItem.h>
-#include <QFont>
+#include <memory>
+
#include <QColor>
+#include <QFont>
+
+#include <Swift/QtUI/MUCSearch/MUCSearchServiceItem.h>
namespace Swift {
-MUCSearchEmptyItem::MUCSearchEmptyItem(MUCSearchServiceItem* parent) : parent(parent) {
- parent->addRoom(this);
+MUCSearchEmptyItem::MUCSearchEmptyItem() {
+}
+
+void MUCSearchEmptyItem::setParent(std::weak_ptr<MUCSearchServiceItem> parent) {
+ parent_ = parent;
}
-MUCSearchServiceItem* MUCSearchEmptyItem::getParent() {
- return parent;
+std::shared_ptr<MUCSearchServiceItem> MUCSearchEmptyItem::getParent() {
+ return parent_.lock();
}
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..8a5bb06 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h
@@ -1,25 +1,28 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#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* getParent();
+ void setParent(std::weak_ptr<MUCSearchServiceItem> parent);
+ std::shared_ptr<MUCSearchServiceItem> getParent();
- QVariant data(int role);
+ QVariant data(int role);
- private:
- MUCSearchServiceItem* parent;
- };
+ private:
+ std::weak_ptr<MUCSearchServiceItem> parent_;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchItem.h b/Swift/QtUI/MUCSearch/MUCSearchItem.h
index d2a2c2d..08daa21 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchItem.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchItem.h
@@ -1,17 +1,23 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#include <QVariant>
namespace Swift {
- class MUCSearchItem {
- public:
- virtual ~MUCSearchItem() {}
- virtual QVariant data(int role) = 0;
- };
+
+class MUCSearchServiceItem;
+
+class MUCSearchItem {
+ public:
+ virtual ~MUCSearchItem() {}
+ virtual void setParent(std::weak_ptr<MUCSearchServiceItem>) { }
+ virtual QVariant data(int role) = 0;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchModel.cpp b/Swift/QtUI/MUCSearch/MUCSearchModel.cpp
index adb2a11..cc36f5f 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchModel.cpp
+++ b/Swift/QtUI/MUCSearch/MUCSearchModel.cpp
@@ -1,11 +1,14 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/QtUI/MUCSearch/MUCSearchModel.h"
-#include "Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h"
+#include <Swift/QtUI/MUCSearch/MUCSearchModel.h>
+
+#include <memory>
+
+#include <Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h>
namespace Swift {
@@ -13,78 +16,91 @@ MUCSearchModel::MUCSearchModel() {
}
void MUCSearchModel::clear() {
- emit layoutAboutToBeChanged();
- services_.clear();
- emit layoutChanged();
+ // We need to reset the model, so that model indices containing raw pointers
+ // to MUCSearchServiceItems are invalaidated before we delete the
+ // MUCSearchServiceItems.
+ emit beginResetModel();
+ services_.clear();
+ emit endResetModel();
}
-void MUCSearchModel::addService(MUCSearchServiceItem* service) {
- emit layoutAboutToBeChanged();
- services_.push_back(service);
- emit layoutChanged();
+void MUCSearchModel::addService(std::shared_ptr<MUCSearchServiceItem> service) {
+ emit layoutAboutToBeChanged();
+ if (sortOrder_) {
+ service->setSorting(*sortOrder_);
+ }
+ 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].get()) : 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();
+ }
+
+ std::shared_ptr<MUCSearchServiceItem> parent;
+ 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.get());
+ }
+ 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;
+ }
+}
+
+void MUCSearchModel::sort(int column, Qt::SortOrder order) {
+ sortOrder_ = order;
+ if (column == 0) {
+ for (auto&& serviceItem : services_) {
+ serviceItem->setSorting(*sortOrder_);
+ }
+ }
}
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchModel.h b/Swift/QtUI/MUCSearch/MUCSearchModel.h
index e18a1c0..f36d147 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchModel.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchModel.h
@@ -1,35 +1,37 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/optional.hpp>
#include <QAbstractItemModel>
-#include <QList>
+#include <QVector>
-#include "Swift/QtUI/MUCSearch/MUCSearchServiceItem.h"
+#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(std::shared_ptr<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;
+ virtual void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
+
+ private:
+ QVector<std::shared_ptr<MUCSearchServiceItem>> services_;
+ boost::optional<Qt::SortOrder> sortOrder_;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp
index a8c7bbe..9c3ef2c 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp
+++ b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp
@@ -1,26 +1,34 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/QtUI/MUCSearch/MUCSearchRoomItem.h"
+#include <Swift/QtUI/MUCSearch/MUCSearchRoomItem.h>
-#include "Swift/QtUI/MUCSearch/MUCSearchServiceItem.h"
+#include <memory>
+
+#include <Swift/QtUI/MUCSearch/MUCSearchServiceItem.h>
namespace Swift {
-MUCSearchRoomItem::MUCSearchRoomItem(const QString& node, MUCSearchServiceItem* parent) : parent_(parent), node_(node) {
- parent_->addRoom(this);
+
+MUCSearchRoomItem::MUCSearchRoomItem(const QString& node) : node_(node) {
+
}
-MUCSearchServiceItem* MUCSearchRoomItem::getParent() {
- return parent_;
+void MUCSearchRoomItem::setParent(std::weak_ptr<MUCSearchServiceItem> parent) {
+ parent_ = parent;
}
+
+std::shared_ptr<MUCSearchServiceItem> MUCSearchRoomItem::getParent() {
+ return parent_.lock();
+}
+
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 d0f8daa..5ecb7d7 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.h
@@ -1,23 +1,27 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/QtUI/MUCSearch/MUCSearchItem.h"
+#include <memory>
+
+#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);
+ void setParent(std::weak_ptr<MUCSearchServiceItem> parent);
+ std::shared_ptr<MUCSearchServiceItem> getParent();
+ QVariant data(int role);
+ QString getNode() const {return node_;}
+
+ private:
+ std::weak_ptr<MUCSearchServiceItem> parent_;
+ QString node_;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchServiceItem.cpp b/Swift/QtUI/MUCSearch/MUCSearchServiceItem.cpp
new file mode 100644
index 0000000..57d5aac
--- /dev/null
+++ b/Swift/QtUI/MUCSearch/MUCSearchServiceItem.cpp
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2010-2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/MUCSearch/MUCSearchServiceItem.h>
+
+#include <memory>
+
+#include <QString>
+#include <QVector>
+#include <QtAlgorithms>
+
+namespace Swift {
+
+MUCSearchServiceItem::MUCSearchServiceItem(const QString& jidString) : jidString_(jidString) {
+
+}
+
+void MUCSearchServiceItem::addRoom(std::shared_ptr<MUCSearchItem> room) {
+ room->setParent(shared_from_this());
+ rooms_.push_back(room);
+ if (sortOrder_) {
+ sort();
+ }
+}
+
+void MUCSearchServiceItem::addRooms(const std::vector<std::shared_ptr<MUCSearchItem> >& rooms) {
+ for (auto&& room: rooms) {
+ room->setParent(shared_from_this());
+ rooms_.push_back(room);
+ }
+ if (sortOrder_) {
+ sort();
+ }
+}
+
+int MUCSearchServiceItem::rowCount() {
+ return rooms_.count();
+}
+
+MUCSearchItem* MUCSearchServiceItem::getItem(int i) {
+ return rooms_[i].get();
+}
+
+QVariant MUCSearchServiceItem::data(int role) {
+ switch (role) {
+ case Qt::DisplayRole:
+ return QVariant(jidString_);
+ default:
+ return QVariant();
+ }
+}
+
+QString MUCSearchServiceItem::getHost() const {
+ return jidString_;
+}
+
+void MUCSearchServiceItem::setSorting(Qt::SortOrder sortOrder) {
+ sortOrder_ = sortOrder;
+ sort();
+}
+
+void MUCSearchServiceItem::sort() {
+ if (*sortOrder_ == Qt::AscendingOrder) {
+ qStableSort(rooms_.begin(), rooms_.end(), [](const std::shared_ptr<MUCSearchItem>& item1, const std::shared_ptr<MUCSearchItem>& item2) -> bool {
+ return QString::localeAwareCompare(item1->data(Qt::DisplayRole).toString(), item2->data(Qt::DisplayRole).toString()) < 0;
+ });
+ }
+ else {
+ qStableSort(rooms_.begin(), rooms_.end(), [](const std::shared_ptr<MUCSearchItem>& item1, const std::shared_ptr<MUCSearchItem>& item2) -> bool {
+ return QString::localeAwareCompare(item1->data(Qt::DisplayRole).toString(), item2->data(Qt::DisplayRole).toString()) > 0;
+ });
+ }
+}
+
+}
diff --git a/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h b/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h
index 306e85a..9f5e000 100644
--- a/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h
+++ b/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h
@@ -1,32 +1,39 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QList>
+#include <memory>
+
+#include <boost/optional.hpp>
+
#include <QString>
+#include <QVector>
-#include "Swift/QtUI/MUCSearch/MUCSearchRoomItem.h"
+#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 std::enable_shared_from_this<MUCSearchServiceItem> {
+ public:
+ MUCSearchServiceItem(const QString& jidString);
+
+ void addRoom(std::shared_ptr<MUCSearchItem> room);
+ void addRooms(const std::vector<std::shared_ptr<MUCSearchItem>>& rooms);
+ int rowCount();
+ MUCSearchItem* getItem(int i);
+ QVariant data(int role);
+ QString getHost() const;
+ void setSorting(Qt::SortOrder sortOrder);
+
+ private:
+ void sort();
+
+ private:
+ QVector<std::shared_ptr<MUCSearchItem>> rooms_;
+ QString jidString_;
+ boost::optional<Qt::SortOrder> sortOrder_;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/QtLeafSortFilterProxyModel.cpp b/Swift/QtUI/MUCSearch/QtLeafSortFilterProxyModel.cpp
new file mode 100644
index 0000000..b8cf15a
--- /dev/null
+++ b/Swift/QtUI/MUCSearch/QtLeafSortFilterProxyModel.cpp
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/MUCSearch/QtLeafSortFilterProxyModel.h>
+
+namespace Swift {
+
+QtLeafSortFilterProxyModel::QtLeafSortFilterProxyModel(QObject* parent) : QSortFilterProxyModel(parent) {
+
+}
+
+QtLeafSortFilterProxyModel::~QtLeafSortFilterProxyModel() {
+
+}
+
+bool QtLeafSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const {
+ if (!sourceModel()->hasChildren(sourceModel()->index(source_row, 0, source_parent))) {
+ return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent);
+ }
+ else {
+ return true;
+ }
+}
+
+}
diff --git a/Swift/QtUI/MUCSearch/QtLeafSortFilterProxyModel.h b/Swift/QtUI/MUCSearch/QtLeafSortFilterProxyModel.h
new file mode 100644
index 0000000..b4be622
--- /dev/null
+++ b/Swift/QtUI/MUCSearch/QtLeafSortFilterProxyModel.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#pragma once
+
+#include <QSortFilterProxyModel>
+
+namespace Swift {
+
+/**
+ * @brief The QtLeafSortFilterProxyModel class is similar to the QSortFilterProxyModel
+ * class. While the basic QSortFilterProxyModel class filters all hierarchical items,
+ * the QtLeafSortFilterProxyModel class will only filter on items without children.
+ */
+class QtLeafSortFilterProxyModel : public QSortFilterProxyModel {
+ Q_OBJECT
+
+public:
+ QtLeafSortFilterProxyModel(QObject* parent = nullptr);
+ virtual ~QtLeafSortFilterProxyModel();
+
+protected:
+ virtual bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const;
+};
+
+}
diff --git a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp
index bafb958..f69da41 100644
--- a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp
+++ b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp
@@ -1,58 +1,68 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/QtUI/MUCSearch/QtMUCSearchWindow.h"
+#include <Swift/QtUI/MUCSearch/QtMUCSearchWindow.h>
+
+#include <memory>
+#include <vector>
-#include <qdebug.h>
#include <QMovie>
+#include <QPushButton>
#include <QScrollBar>
+#include <QSortFilterProxyModel>
#include <QTimer>
-#include <QPushButton>
-#include "Swift/Controllers/UIEvents/JoinMUCUIEvent.h"
-#include "Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h"
-#include "Swift/QtUI/MUCSearch/MUCSearchModel.h"
-#include "Swift/QtUI/MUCSearch/MUCSearchDelegate.h"
-#include "Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h"
-#include "Swift/QtUI/QtSwiftUtil.h"
+#include <Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h>
+#include <Swift/Controllers/UIEvents/JoinMUCUIEvent.h>
+
+#include <Swift/QtUI/MUCSearch/MUCSearchDelegate.h>
+#include <Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h>
+#include <Swift/QtUI/MUCSearch/MUCSearchModel.h>
+#include <Swift/QtUI/MUCSearch/QtLeafSortFilterProxyModel.h>
+#include <Swift/QtUI/QtSwiftUtil.h>
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);
+ model_ = new MUCSearchModel();
+ sortFilterProxyModel_ = new QtLeafSortFilterProxyModel(this);
+ sortFilterProxyModel_->setSourceModel(model_);
+ sortFilterProxyModel_->setDynamicSortFilter(true);
+ delegate_ = new MUCSearchDelegate();
+ ui_.results_->setModel(sortFilterProxyModel_);
+ ui_.results_->setItemDelegate(delegate_);
+ ui_.results_->setHeaderHidden(true);
+ ui_.results_->setRootIsDecorated(true);
+ ui_.results_->setAnimated(true);
+ ui_.results_->setAlternatingRowColors(true);
+ ui_.results_->setSortingEnabled(true);
+ ui_.results_->sortByColumn(0, Qt::AscendingOrder);
+ 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()));
+ connect(ui_.filter_, SIGNAL(textChanged(const QString&)), this, SLOT(handleFilterStringChanged(const QString&)));
+
+ 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() {
@@ -60,136 +70,145 @@ 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();
+ for (const auto& 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*>(sortFilterProxyModel_->mapToSource(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::handleFilterStringChanged(const QString& filterString) {
+ sortFilterProxyModel_->setFilterRegExp(filterString);
}
void QtMUCSearchWindow::show() {
- QWidget::show();
- QWidget::activateWindow();
+ ui_.filter_->clear();
+ 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();
+ auto serviceItem = std::make_shared<MUCSearchServiceItem>(P2QSTRING(service.getJID().toString()));
+ if (service.getRooms().size() > 0) {
+ std::vector<std::shared_ptr<MUCSearchItem>> rooms;
+ for (auto&& room : service.getRooms()) {
+ if (!room.getNode().empty()) {
+ rooms.push_back(std::make_shared<MUCSearchRoomItem>(P2QSTRING(room.getNode())));
+ }
+ }
+ serviceItem->addRooms(rooms);
+ }
+ else {
+ serviceItem->addRoom(std::make_shared<MUCSearchEmptyItem>());
+ }
+ 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 nullptr;
+ }
+ else {
+ return dynamic_cast<MUCSearchRoomItem*>(static_cast<MUCSearchItem*>(sortFilterProxyModel_->mapToSource(lstIndex.first()).internalPointer()));
+ }
}
}
diff --git a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h
index bc9fb43..6f38533 100644
--- a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h
+++ b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h
@@ -1,51 +1,55 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/QtUI/MUCSearch/ui_QtMUCSearchWindow.h"
+#include <Swift/Controllers/UIInterfaces/MUCSearchWindow.h>
-#include "Swift/Controllers/UIInterfaces/MUCSearchWindow.h"
+#include <Swift/QtUI/MUCSearch/ui_QtMUCSearchWindow.h>
+
+class QSortFilterProxyModel;
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 handleFilterStringChanged(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_;
+ QSortFilterProxyModel* sortFilterProxyModel_ = nullptr;
+ };
}
diff --git a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.ui b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.ui
index 49460ab..52714c4 100644
--- a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.ui
+++ b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.ui
@@ -6,21 +6,14 @@
<rect>
<x>0</x>
<y>0</y>
- <width>523</width>
- <height>368</height>
+ <width>566</width>
+ <height>264</height>
</rect>
</property>
<property name="windowTitle">
<string>Search Room</string>
</property>
<layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <widget class="QLabel" name="label_2">
- <property name="text">
- <string>Service:</string>
- </property>
- </widget>
- </item>
<item row="0" column="1">
<widget class="QComboBox" name="service_">
<property name="sizePolicy">
@@ -34,26 +27,14 @@
</property>
</widget>
</item>
- <item row="0" column="3">
- <widget class="QLineEdit" name="filter_">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
- <horstretch>1</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
+ <item row="0" column="0">
+ <widget class="QLabel" name="serviceLabel_">
<property name="text">
- <string/>
- </property>
- <property name="frame">
- <bool>true</bool>
+ <string>Service:</string>
</property>
</widget>
</item>
- <item row="1" column="0" colspan="4">
- <widget class="QTreeView" name="results_"/>
- </item>
- <item row="2" column="0" colspan="4">
+ <item row="2" column="0" colspan="5">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<spacer name="horizontalSpacer">
@@ -90,13 +71,42 @@
</item>
</layout>
</item>
+ <item row="0" column="4">
+ <widget class="QLineEdit" name="filter_">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
+ <horstretch>1</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ <property name="frame">
+ <bool>true</bool>
+ </property>
+ <property name="placeholderText">
+ <string/>
+ </property>
+ </widget>
+ </item>
<item row="0" column="2">
- <widget class="QToolButton" name="searchButton">
+ <widget class="QToolButton" name="searchButton_">
<property name="text">
<string>List rooms</string>
</property>
</widget>
</item>
+ <item row="1" column="0" colspan="5">
+ <widget class="QTreeView" name="results_"/>
+ </item>
+ <item row="0" column="3">
+ <widget class="QLabel" name="filterLabel_">
+ <property name="text">
+ <string>Search for</string>
+ </property>
+ </widget>
+ </item>
</layout>
</widget>
<resources/>
diff --git a/Swift/QtUI/MessageSnippet.cpp b/Swift/QtUI/MessageSnippet.cpp
index f76212e..4682365 100644
--- a/Swift/QtUI/MessageSnippet.cpp
+++ b/Swift/QtUI/MessageSnippet.cpp
@@ -1,45 +1,43 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "MessageSnippet.h"
+#include <Swift/QtUI/MessageSnippet.h>
-#include <QtDebug>
#include <QDateTime>
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><span class='swift_ack'></span><span class='swift_receipt'></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_ = QString("<div id='%1'>%2</div>").arg(id).arg(content_);
- content_ = "<span class='date" + time.date().toString(Qt::ISODate) + "'>" + content_ + "</span>";
+ if (appendToPrevious) {
+ setContinuationFallbackSnippet(std::make_shared<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 4e51b1d..302785f 100644
--- a/Swift/QtUI/MessageSnippet.h
+++ b/Swift/QtUI/MessageSnippet.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,24 +8,24 @@
#include <QString>
-#include "ChatSnippet.h"
+#include <Swift/QtUI/ChatSnippet.h>
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 bae670d..8d2e467 100644
--- a/Swift/QtUI/NotifierTest/NotifierTest.cpp
+++ b/Swift/QtUI/NotifierTest/NotifierTest.cpp
@@ -1,26 +1,28 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <iostream>
+#include <string>
+
#include <boost/bind.hpp>
-#include <string>
-#include "Swiften/Base/ByteArray.h"
-#include "Swiften/Notifier/GrowlNotifier.h"
#include <QApplication>
+#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Notifier/GrowlNotifier.h>
+
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..9047525 100644
--- a/Swift/QtUI/QtAboutWidget.cpp
+++ b/Swift/QtUI/QtAboutWidget.cpp
@@ -16,73 +16,148 @@
#include <QVBoxLayout>
#include <QtGlobal>
+#include <Swiften/Base/Log.h>
#include <Swiften/Base/Platform.h>
+#include <Swift/QtUI/QtSwiftUtil.h>
+#include <Swift/QtUI/QtUISettingConstants.h>
+#include <Swift/QtUI/QtUpdateFeedSelectionDialog.h>
+#include <Swift/QtUI/SwiftUpdateFeeds.h>
+
namespace Swift {
-QtAboutWidget::QtAboutWidget() : QDialog() {
+QtAboutWidget::QtAboutWidget(SettingsProvider* settingsProvider) : QDialog(), settingsProvider_(settingsProvider) {
#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"));
-
- 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);
-
- 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'");
+ 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);
+
+ settingsChangedConnection_ = settingsProvider_->onSettingChanged.connect([&](const std::string& path) {
+ if (path == QtUISettingConstants::SOFTWARE_UPDATE_CHANNEL.getKey() || path == QtUISettingConstants::ENABLE_SOFTWARE_UPDATES.getKey()) {
+ updateUpdateInfoLabel();
+ }
+ });
+
+ updateInfoLabel_ = new QLabel("", this);
+ updateInfoLabel_->setTextInteractionFlags(Qt::LinksAccessibleByKeyboard | Qt::LinksAccessibleByMouse);
+ connect(updateInfoLabel_, SIGNAL(linkActivated(const QString &)), this, SLOT(handleChangeUpdateChannelClicked()));
+ mainLayout->addWidget(updateInfoLabel_);
+
+ updateUpdateInfoLabel();
+
+ 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()));
+
+ QPushButton* changelogButton = new QPushButton(tr("View Changes"), this);
+ mainLayout->addWidget(changelogButton);
+ connect(changelogButton, SIGNAL(clicked()), this, SLOT(handleChangelogClicked()));
#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));
+ QPushButton* changelogButton = new QPushButton(tr("View Changes"), this);
+ buttonLayout->addWidget(changelogButton);
+ connect(changelogButton, SIGNAL(clicked()), this, SLOT(handleChangelogClicked()));
- QPushButton* closeButton = new QPushButton(tr("Close"), this);
- buttonLayout->addWidget(closeButton);
- connect(closeButton, SIGNAL(clicked()), this, SLOT(accept()));
+ buttonLayout->addItem(new QSpacerItem(20,20));
+
+ 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();
+ openPlainTextWindow(":/COPYING");
+}
+
+void QtAboutWidget::handleChangelogClicked() {
+ openPlainTextWindow(":/ChangeLog.md");
+}
+
+void QtAboutWidget::handleChangeUpdateChannelClicked() {
+ auto feedSelectionDialog = new QtUpdateFeedSelectionDialog(settingsProvider_);
+ feedSelectionDialog->show();
+}
+
+void QtAboutWidget::openPlainTextWindow(const QString& path) {
+ QTextEdit* text = new QTextEdit();
+ text->setAttribute(Qt::WA_DeleteOnClose);
+ text->setReadOnly(true);
+ QFile file(path);
+ if (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();
+ }
+ else {
+ SWIFT_LOG(error) << "Failed to open " << Q2PSTRING(path) << "." << std::endl;
+ }
+}
+
+void QtAboutWidget::updateUpdateInfoLabel() {
+ if (settingsProvider_->getSetting(QtUISettingConstants::ENABLE_SOFTWARE_UPDATES)) {
+ if (!settingsProvider_->getSetting(QtUISettingConstants::SOFTWARE_UPDATE_CHANNEL).empty()) {
+ QString updateFeedDescription;
+ auto addUpdateFeedDialogLink = false;
+ if (settingsProvider_->getSetting(QtUISettingConstants::SOFTWARE_UPDATE_CHANNEL) == UpdateFeeds::StableChannel) {
+ updateFeedDescription = tr("You are receiving updates from the Stable update channel.");
+ addUpdateFeedDialogLink = true;
+ }
+ else if (settingsProvider_->getSetting(QtUISettingConstants::SOFTWARE_UPDATE_CHANNEL) == UpdateFeeds::DevelopmentChannel) {
+ updateFeedDescription = tr("You are receiving updates from the Development update channel.");
+ addUpdateFeedDialogLink = true;
+ }
+ else if (settingsProvider_->getSetting(QtUISettingConstants::SOFTWARE_UPDATE_CHANNEL) == UpdateFeeds::TestingChannel) {
+ updateFeedDescription = tr("You are receiving updates from the Testing update channel.");
+ addUpdateFeedDialogLink = true;
+ }
+ auto updateFeedDialogLink = QString( addUpdateFeedDialogLink ? "<a href=\"#\">%1</a>" : "" ).arg(tr("Change the update channel."));
+ updateInfoLabel_->setText(QString("<center><font size='-1'>%1<br/>%2</font></center>").arg(updateFeedDescription, updateFeedDialogLink));
+ updateInfoLabel_->show();
+ }
+ else {
+ updateInfoLabel_->hide();
+ }
+ }
+ else {
+ updateInfoLabel_->hide();
+ }
+
}
}
diff --git a/Swift/QtUI/QtAboutWidget.h b/Swift/QtUI/QtAboutWidget.h
index d09010b..fb54c6e 100644
--- a/Swift/QtUI/QtAboutWidget.h
+++ b/Swift/QtUI/QtAboutWidget.h
@@ -1,21 +1,38 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/signals2/connection.hpp>
+
#include <QDialog>
+class QLabel;
+
namespace Swift {
- class QtAboutWidget : public QDialog {
- Q_OBJECT
+ class SettingsProvider;
+
+ class QtAboutWidget : public QDialog {
+ Q_OBJECT
+
+ public:
+ QtAboutWidget(SettingsProvider* settings);
+
+ private slots:
+ void handleLicenseClicked();
+ void handleChangelogClicked();
+ void handleChangeUpdateChannelClicked();
- public:
- QtAboutWidget();
+ private:
+ void openPlainTextWindow(const QString& path);
+ void updateUpdateInfoLabel();
- private slots:
- void handleLicenseClicked();
- };
+ private:
+ SettingsProvider* settingsProvider_;
+ QLabel* updateInfoLabel_ = nullptr;
+ boost::signals2::scoped_connection settingsChangedConnection_;
+ };
}
diff --git a/Swift/QtUI/QtAdHocCommandWindow.cpp b/Swift/QtUI/QtAdHocCommandWindow.cpp
index ef397f4..65dac91 100644
--- a/Swift/QtUI/QtAdHocCommandWindow.cpp
+++ b/Swift/QtUI/QtAdHocCommandWindow.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -19,156 +19,156 @@
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_;
+QtAdHocCommandWindow::QtAdHocCommandWindow(std::shared_ptr<OutgoingAdHocCommandSession> command) : command_(command) {
+ formWidget_ = nullptr;
+
+ 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;
+ for (const auto& note : command->getNotes()) {
+ if (!notes.isEmpty()) {
+ notes += "\n";
+ }
+ QString qNote(P2QSTRING(note.note));
+ switch (note.type) {
+ case Command::Note::Error: notes += tr("Error: %1").arg(qNote); break;
+ case Command::Note::Warn: notes += tr("Warning: %1").arg(qNote); break;
+ case Command::Note::Info: notes += qNote; break;
+ }
+ }
+ label_->setText(notes);
+ if (command->getForm()) {
+ setForm(command->getForm());
+ } else {
+ setNoForm(notes.isEmpty());
+ }
+ setAvailableActions(command);
}
void QtAdHocCommandWindow::handleError(ErrorPayload::ref /*error*/) {
- nextButton_->setEnabled(false);
- backButton_->setEnabled(false);
- completeButton_->setEnabled(false);
- label_->setText(tr("Error executing command"));
+ 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_ = nullptr;
+ resize(minimumSize());
+ setVisible(!andHide);
}
typedef std::pair<Command::Action, QPushButton*> ActionButton;
void QtAdHocCommandWindow::setAvailableActions(Command::ref /*commandResult*/) {
- okButton_->show();
- okButton_->setEnabled(true);
- foreach (ActionButton pair, actions_) {
- 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);
+ for (auto&& pair : actions_) {
+ OutgoingAdHocCommandSession::ActionState state = command_->getActionState(pair.first);
+ if (state & OutgoingAdHocCommandSession::Present) {
+ okButton_->hide();
+ okButton_->setEnabled(false);
+ pair.second->show();
+ }
+ else {
+ pair.second->hide();
+ }
+ if (state & OutgoingAdHocCommandSession::Enabled) {
+ pair.second->setEnabled(true);
+ }
+ else {
+ pair.second->setEnabled(false);
+ }
+ }
}
}
diff --git a/Swift/QtUI/QtAdHocCommandWindow.h b/Swift/QtUI/QtAdHocCommandWindow.h
index c8d493c..1135ef9 100644
--- a/Swift/QtUI/QtAdHocCommandWindow.h
+++ b/Swift/QtUI/QtAdHocCommandWindow.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::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:
+ std::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..1b114d9 100644
--- a/Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp
+++ b/Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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());
+ std::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 3596657..8c5d662 100644
--- a/Swift/QtUI/QtAddBookmarkWindow.cpp
+++ b/Swift/QtUI/QtAddBookmarkWindow.cpp
@@ -1,30 +1,30 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtAddBookmarkWindow.h"
+#include <Swift/QtUI/QtAddBookmarkWindow.h>
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(std::make_shared<AddMUCBookmarkUIEvent>(*bookmark));
+ return true;
+ }
+ else {
+ return false;
+ }
}
}
diff --git a/Swift/QtUI/QtAddBookmarkWindow.h b/Swift/QtUI/QtAddBookmarkWindow.h
index 0152fb3..607f647 100644
--- a/Swift/QtUI/QtAddBookmarkWindow.h
+++ b/Swift/QtUI/QtAddBookmarkWindow.h
@@ -1,24 +1,24 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "QtBookmarkDetailWindow.h"
+#include <Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h>
+#include <Swift/Controllers/UIEvents/UIEventStream.h>
-#include "Swift/Controllers/UIEvents/UIEventStream.h"
-#include "Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h"
+#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 debf024..92b6aff 100644
--- a/Swift/QtUI/QtAffiliationEditor.cpp
+++ b/Swift/QtUI/QtAffiliationEditor.cpp
@@ -1,79 +1,78 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtAffiliationEditor.h"
+#include <Swift/QtUI/QtAffiliationEditor.h>
-#include <QListWidgetItem>
#include <QInputDialog>
+#include <QListWidgetItem>
-#include "QtSwiftUtil.h"
-
+#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
QtAffiliationEditor::QtAffiliationEditor(QWidget* parent) : QDialog(parent){
- ui_.setupUi(this);
- setAttribute(Qt::WA_DeleteOnClose);
- connect(ui_.affiliation, SIGNAL(currentIndexChanged(int)), this, SLOT(handleCurrentIndexChanged(int)));
- connect(ui_.addJID, SIGNAL(clicked()), this, SLOT(handleAddClicked()));
- connect(ui_.removeJID, SIGNAL(clicked()), this, SLOT(handleRemoveClicked()));
+ 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();
+ for (const auto& jid : affiliations_[affiliationFromIndex(index)]) {
+ ui_.list->addItem(P2QSTRING(jid.toString()));
+ }
}
void QtAffiliationEditor::handleAddClicked() {
- bool ok = false;
- JID jid = JID(Q2PSTRING(QInputDialog::getText(this, tr("Add User"), tr("Added User's Address:"), QLineEdit::Normal, "", &ok)));
- if (ok && jid.isValid()) {
- //FIXME: validation
- MUCOccupant::Affiliation affiliation = affiliationFromIndex(ui_.affiliation->currentIndex());
- changes_.push_back(ChangePair(affiliation, jid));
- ui_.list->addItem(P2QSTRING(jid.toString()));
- affiliations_[affiliation].push_back(jid);
- }
+ 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 7064684..58e2497 100644
--- a/Swift/QtUI/QtAffiliationEditor.h
+++ b/Swift/QtUI/QtAffiliationEditor.h
@@ -1,37 +1,38 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <map>
+#include <vector>
#include <QDialog>
-#include <Swift/QtUI/ui_QtAffiliationEditor.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/MUCOccupant.h>
+#include <Swiften/JID/JID.h>
+
+#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 = nullptr);
+ ~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 ca7e22f..7f6e275 100644
--- a/Swift/QtUI/QtAvatarWidget.cpp
+++ b/Swift/QtUI/QtAvatarWidget.cpp
@@ -1,110 +1,111 @@
/*
- * Copyright (c) 2011-2014 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtAvatarWidget.h"
+#include <Swift/QtUI/QtAvatarWidget.h>
-#include <QLabel>
-#include <QVBoxLayout>
-#include <QPixmap>
-#include <QMenu>
#include <QAction>
-#include <QMouseEvent>
+#include <QBuffer>
#include <QFileDialog>
#include <QImageReader>
-#include <QBuffer>
+#include <QLabel>
+#include <QMenu>
#include <QMessageBox>
+#include <QMouseEvent>
#include <QPainter>
+#include <QPixmap>
+#include <QVBoxLayout>
-#include <QtSwiftUtil.h>
#include <Swiften/Base/Path.h>
+#include <Swift/QtUI/QtSwiftUtil.h>
+
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 ed89e37..612c79b 100644
--- a/Swift/QtUI/QtAvatarWidget.h
+++ b/Swift/QtUI/QtAvatarWidget.h
@@ -1,48 +1,49 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QWidget>
#include <QImage>
+#include <QWidget>
+
#include <Swiften/Base/ByteArray.h>
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 48bac26..30c939f 100644
--- a/Swift/QtUI/QtBlockListEditorWindow.cpp
+++ b/Swift/QtUI/QtBlockListEditorWindow.cpp
@@ -5,13 +5,12 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <QtBlockListEditorWindow.h>
-#include <ui_QtBlockListEditorWindow.h>
+#include <Swift/QtUI/QtBlockListEditorWindow.h>
#include <boost/bind.hpp>
@@ -21,206 +20,207 @@
#include <QStyledItemDelegate>
#include <QValidator>
-#include <Swift/QtUI/QtSwiftUtil.h>
-#include <Swift/QtUI/QtUtilities.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/ClientBlockListManager.h>
#include <Swiften/JID/JID.h>
+#include <Swift/QtUI/QtSwiftUtil.h>
+#include <Swift/QtUI/QtUtilities.h>
+#include <Swift/QtUI/ui_QtBlockListEditorWindow.h>
+
namespace Swift {
class QtJIDValidator : public QValidator {
- public:
- QtJIDValidator(QObject* parent) : QValidator(parent) {}
- virtual ~QtJIDValidator() {}
- virtual QValidator::State validate(QString& input, int&) const {
- return JID(Q2PSTRING(input)).isValid() ? Acceptable : Intermediate;
- }
+ 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);
+QtBlockListEditorWindow::QtBlockListEditorWindow() : QWidget(), ui(new Ui::QtBlockListEditorWindow), removeItemDelegate(nullptr), editItemDelegate(nullptr) {
+ 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();
+
+ for (const auto& jid : blockedJIDs) {
+ QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(P2QSTRING(jid.toString())) << "");
+ item->setFlags(item->flags() | Qt::ItemIsEditable);
+ ui->blockListTreeWidget->addTopLevelItem(item);
+ }
+ handleItemChanged(nullptr,0);
}
void QtBlockListEditorWindow::setBusy(bool isBusy) {
- if (isBusy) {
- ui->throbberLabel->movie()->start();
- ui->throbberLabel->show();
- ui->blockListTreeWidget->setEnabled(false);
- ui->savePushButton->setEnabled(false);
- } else {
- ui->throbberLabel->movie()->stop();
- ui->throbberLabel->hide();
- ui->blockListTreeWidget->setEnabled(true);
- ui->savePushButton->setEnabled(true);
- }
+ 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 e5288ca..dc900ab 100644
--- a/Swift/QtUI/QtBlockListEditorWindow.h
+++ b/Swift/QtUI/QtBlockListEditorWindow.h
@@ -5,21 +5,22 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <QTreeWidgetItem>
+#include <QWidget>
+
#include <Swift/Controllers/UIInterfaces/BlockListEditorWidget.h>
-#include <Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h>
-#include <QWidget>
-#include <QTreeWidgetItem>
+#include <Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h>
namespace Ui {
- class QtBlockListEditorWindow;
+ class QtBlockListEditorWindow;
}
namespace Swift {
@@ -27,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 0210305..920e94e 100644
--- a/Swift/QtUI/QtBookmarkDetailWindow.cpp
+++ b/Swift/QtUI/QtBookmarkDetailWindow.cpp
@@ -1,77 +1,79 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtBookmarkDetailWindow.h"
-#include "QtSwiftUtil.h"
+#include <Swift/QtUI/QtBookmarkDetailWindow.h>
+
#include <QMessageBox>
+#include <Swift/QtUI/QtSwiftUtil.h>
+
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 e465007..82e757d 100644
--- a/Swift/QtUI/QtBookmarkDetailWindow.h
+++ b/Swift/QtUI/QtBookmarkDetailWindow.h
@@ -1,32 +1,32 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "ui_QtBookmarkDetailWindow.h"
-
#include <boost/optional.hpp>
#include <QDialog>
-#include "Swiften/MUC/MUCBookmark.h"
+#include <Swiften/MUC/MUCBookmark.h>
+
+#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 = nullptr);
+ 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 8675bb2..e1f540b 100644
--- a/Swift/QtUI/QtCachedImageScaler.cpp
+++ b/Swift/QtUI/QtCachedImageScaler.cpp
@@ -1,14 +1,17 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtCachedImageScaler.h"
+#include <Swift/QtUI/QtCachedImageScaler.h>
-#include <QImage>
#include <boost/lexical_cast.hpp>
+
+#include <QImage>
+
#include <Swiften/Base/Path.h>
+
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
@@ -17,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 8108978..6454d82 100644
--- a/Swift/QtUI/QtCertificateViewerDialog.cpp
+++ b/Swift/QtUI/QtCertificateViewerDialog.cpp
@@ -5,15 +5,12 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtCertificateViewerDialog.h"
-#include "ui_QtCertificateViewerDialog.h"
-
-#include <Swiften/Base/foreach.h>
+#include <Swift/QtUI/QtCertificateViewerDialog.h>
#include <QDateTime>
#include <QLabel>
@@ -21,129 +18,131 @@
#include <QStringList>
#include <QTreeWidgetItem>
+#include <Swift/QtUI/ui_QtCertificateViewerDialog.h>
+
namespace Swift {
QtCertificateViewerDialog::QtCertificateViewerDialog(QWidget* parent) : QDialog(parent), ui(new Ui::QtCertificateViewerDialog) {
- ui->setupUi(this);
- connect(ui->certChainTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), SLOT(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
+ 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();
+ for (auto&& cert : chain) {
+ ByteArray certAsDer = cert->toDER();
+ QByteArray dataArray(reinterpret_cast<const char*>(certAsDer.data()), certAsDer.size());
+ currentChain.push_front(QSslCertificate(dataArray, QSsl::Der));
+ }
+
+ // fill treeWidget
+ QTreeWidgetItem* root = new QTreeWidgetItem(ui->certChainTreeWidget, QStringList(currentChain.at(0).subjectInfo(QSslCertificate::CommonName)));
+ root->setData(0, Qt::UserRole, QVariant(0));
+ root->setExpanded(true);
+ ui->certChainTreeWidget->addTopLevelItem(root);
+ if (currentChain.size() > 1) {
+ QTreeWidgetItem* parent = root;
+ for (int n = 1; n < currentChain.size(); n++) {
+ QTreeWidgetItem* link = new QTreeWidgetItem(parent, QStringList(QString("↳ ") + (QStringList(currentChain.at(n).subjectInfo(QSslCertificate::CommonName)).join(", "))));
+ link->setExpanded(true);
+ link->setData(0, Qt::UserRole, QVariant(n));
+ parent = link;
+ }
+ ui->certChainTreeWidget->setCurrentItem(parent);
+ } else {
+ ui->certChainTreeWidget->setCurrentItem(root);
+ }
}
void QtCertificateViewerDialog::displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain) {
- QtCertificateViewerDialog* dialog = new QtCertificateViewerDialog(parent);
- dialog->setCertificateChain(chain);
- dialog->show();
+ 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"));
+ for (const auto& type : altNames.uniqueKeys()) {
+ for (auto&& name : altNames.values(type)) {
+ if (type == QSsl::EmailEntry) {
+ ADD_FIELD(tr("E-mail Address"), name);
+ } else {
+ ADD_FIELD(tr("DNS Name"), name);
+ }
+ }
+ }
+ }
+
+ ADD_SECTION(tr("Issuer"));
+ ADD_FIELD(tr("Organization"), cert.issuerInfo(QSslCertificate::Organization));
+ ADD_FIELD(tr("Common Name"), cert.issuerInfo(QSslCertificate::CommonName));
+ ADD_FIELD(tr("Locality"), cert.issuerInfo(QSslCertificate::LocalityName));
+ ADD_FIELD(tr("Organizational Unit"), cert.issuerInfo(QSslCertificate::OrganizationalUnitName));
+ ADD_FIELD(tr("Country"), cert.issuerInfo(QSslCertificate::CountryName));
+ ADD_FIELD(tr("State"), cert.issuerInfo(QSslCertificate::StateOrProvinceName));
+
+ ui->certGridLayout->setRowStretch(rowCount + 1, 1);
}
}
diff --git a/Swift/QtUI/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 9ecf093..3241858 100644
--- a/Swift/QtUI/QtChatTabs.cpp
+++ b/Swift/QtUI/QtChatTabs.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,17 +9,6 @@
#include <algorithm>
#include <vector>
-#include <Swiften/Base/Log.h>
-
-#include <Swift/Controllers/ChatMessageSummarizer.h>
-#include <Swift/Controllers/SettingConstants.h>
-#include <Swift/Controllers/Settings/SettingsProvider.h>
-#include <Swift/QtUI/QtSwiftUtil.h>
-#include <Swift/QtUI/QtTabWidget.h>
-#include <Swift/QtUI/QtTabbable.h>
-#include <Swift/QtUI/Trellis/QtDynamicGridLayout.h>
-#include <Swift/QtUI/Trellis/QtGridSelectionDialog.h>
-
#include <QAction>
#include <QApplication>
#include <QCloseEvent>
@@ -31,392 +20,403 @@
#include <QTabWidget>
#include <QtGlobal>
+#include <Swiften/Base/Log.h>
+
+#include <Swift/Controllers/ChatMessageSummarizer.h>
+
+#include <Swift/QtUI/QtSwiftUtil.h>
+#include <Swift/QtUI/QtTabWidget.h>
+#include <Swift/QtUI/QtTabbable.h>
+#include <Swift/QtUI/QtUISettingConstants.h>
+#include <Swift/QtUI/Trellis/QtDynamicGridLayout.h>
+#include <Swift/QtUI/Trellis/QtGridSelectionDialog.h>
+
namespace Swift {
-QtChatTabs::QtChatTabs(bool singleWindow, SettingsProvider* settingsProvider, bool trellisMode) : QWidget(), singleWindow_(singleWindow), settingsProvider_(settingsProvider), trellisMode_(trellisMode), dynamicGrid_(NULL), gridSelectionDialog_(NULL) {
+QtChatTabs::QtChatTabs(bool singleWindow, SettingsProvider* settingsProvider, bool trellisMode) : QWidget(), singleWindow_(singleWindow), settingsProvider_(settingsProvider), trellisMode_(trellisMode), dynamicGrid_(nullptr), gridSelectionDialog_(nullptr) {
#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(QtUISettingConstants::TRELLIS_GRID_SIZE);
+ if (!gridSizeString.empty()) {
+ QByteArray gridSizeData = QByteArray::fromBase64(P2QSTRING(gridSizeString).toUtf8());
+ QDataStream dataStreamGridSize(&gridSizeData, QIODevice::ReadWrite);
+ QSize gridSize(1,1);
+ dataStreamGridSize >> gridSize;
+ dynamicGrid_->setDimensions(gridSize);
+ }
+
+ // restore positions
+ std::string tabPositionsString = settingsProvider->getSetting(QtUISettingConstants::TRELLIS_GRID_POSITIONS);
+ if (!tabPositionsString.empty()) {
+ QByteArray tabPositionsData = QByteArray::fromBase64(P2QSTRING(tabPositionsString).toUtf8());
+ QDataStream inTabPositions(&tabPositionsData, QIODevice::ReadWrite);
+ QHash<QString, QPoint> tabPositions;
+ inTabPositions >> tabPositions;
+ dynamicGrid_->setTabPositions(tabPositions);
+ }
+ }
+
+ gridSelectionDialog_ = new QtGridSelectionDialog();
+
+ // setup shortcuts
+ shortcuts_ << new QShortcut(QKeySequence(tr("CTRL+W", "Close chat tab.")), window(), SLOT(handleCloseTabShortcut()));
+ shortcuts_ << new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageUp), window(), SLOT(handleRequestedPreviousTab()));
+ shortcuts_ << new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageDown), window(), SLOT(handleRequestedNextTab()));
+ shortcuts_ << new QShortcut(QKeySequence(Qt::ALT + Qt::Key_A), window(), SLOT(handleRequestedActiveTab()));
}
QtChatTabs::~QtChatTabs() {
- foreach (QShortcut* shortcut, shortcuts_) {
- delete shortcut;
- }
-
- if (trellisMode_) {
- storeTabPositions();
- }
- delete gridSelectionDialog_;
+ for (auto shortcut : shortcuts_) {
+ delete shortcut;
+ }
+
+ if (trellisMode_) {
+ storeTabPositions();
+ }
+ delete gridSelectionDialog_;
}
void QtChatTabs::closeEvent(QCloseEvent* event) {
- //Hide first to prevent flickering as each tab is removed.
- hide();
- if (trellisMode_) {
- storeTabPositions();
- }
-
- for (int i = dynamicGrid_->count() - 1; i >= 0; i--) {
- dynamicGrid_->widget(i)->close();
- }
- event->accept();
+ //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 (auto& type : types) {
+ 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() == type) {
+ 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(QtUISettingConstants::TRELLIS_GRID_SIZE, Q2PSTRING(QString(gridSizeData.toBase64())));
+
+ // save positions
+ QByteArray tabPositionsData;
+ QDataStream dataStreamTabPositions(&tabPositionsData, QIODevice::ReadWrite);
+ dynamicGrid_->updateTabPositions();
+ dataStreamTabPositions << dynamicGrid_->getTabPositions();
+ settingsProvider_->storeSetting(QtUISettingConstants::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 71d4ddc..0c12d96 100644
--- a/Swift/QtUI/QtChatTabs.h
+++ b/Swift/QtUI/QtChatTabs.h
@@ -1,14 +1,14 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QWidget>
#include <QRect>
#include <QShortcut>
+#include <QWidget>
#include <Swift/QtUI/QtChatTabsBase.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..40ab17f 100644
--- a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp
+++ b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -12,7 +12,6 @@
#include <QShortcut>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swift/QtUI/QtTabbable.h>
@@ -27,82 +26,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 (auto& type : types) {
+ 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() == type) {
+ 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;
+ for (auto 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 069bb0b..b330fe7 100644
--- a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h
+++ b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h
@@ -1,13 +1,13 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QWidget>
#include <QList>
+#include <QWidget>
#include <Swift/QtUI/QtChatTabsBase.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 5a9bc44..e73f8ac 100644
--- a/Swift/QtUI/QtChatTheme.cpp
+++ b/Swift/QtUI/QtChatTheme.cpp
@@ -1,67 +1,71 @@
/*
- * Copyright (c) 2010 Isode Limited..
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtChatTheme.h"
+#include <Swift/QtUI/QtChatTheme.h>
#include <QFile>
-#include <qdebug.h>
namespace Swift {
/**
* Load Adium themes, as http://trac.adium.im/wiki/CreatingMessageStyles
*/
-QtChatTheme::QtChatTheme(const QString& themePath) : qrc_(themePath.isEmpty()), themePath_(qrc_ ? ":/themes/Default/" : 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[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);
- }
+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);
+ }
- /* 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];
}
}
diff --git a/Swift/QtUI/QtChatTheme.h b/Swift/QtUI/QtChatTheme.h
index bc5b0be..8db662f 100644
--- a/Swift/QtUI/QtChatTheme.h
+++ b/Swift/QtUI/QtChatTheme.h
@@ -1,40 +1,41 @@
/*
- * Copyright (c) 2010 Isode Limited..
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QString>
#include <QList>
+#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;
+ 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, 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 9946114..6d9a17d 100644
--- a/Swift/QtUI/QtChatView.cpp
+++ b/Swift/QtUI/QtChatView.cpp
@@ -1,12 +1,11 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtChatView.h>
-
namespace Swift {
QtChatView::QtChatView(QWidget* parent) : QWidget(parent) {
@@ -14,7 +13,7 @@ QtChatView::QtChatView(QWidget* parent) : QWidget(parent) {
}
QtChatView::~QtChatView() {
-
+
}
}
diff --git a/Swift/QtUI/QtChatView.h b/Swift/QtUI/QtChatView.h
index e1d2e1a..fd13cc2 100644
--- a/Swift/QtUI/QtChatView.h
+++ b/Swift/QtUI/QtChatView.h
@@ -1,64 +1,64 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
#include <boost/date_time/posix_time/posix_time.hpp>
-#include <boost/shared_ptr.hpp>
#include <QWidget>
#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, const HighlightAction& highlight) = 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, const HighlightAction& highlight) = 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, std::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, std::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, const HighlightAction& highlight) = 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, const HighlightAction& highlight) = 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 a9bc2b5..d799e19 100644
--- a/Swift/QtUI/QtChatWindow.cpp
+++ b/Swift/QtUI/QtChatWindow.cpp
@@ -6,9 +6,10 @@
#include <Swift/QtUI/QtChatWindow.h>
+#include <memory>
+
#include <boost/cstdint.hpp>
#include <boost/lexical_cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <QApplication>
#include <QBoxLayout>
@@ -62,883 +63,886 @@
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_ = "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_ = nullptr;
+ affiliationEditor_ = nullptr;
+ theme_ = theme;
+ isCorrection_ = false;
+ labelModel_ = nullptr;
+ 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_->setCorrectionHighlight(true);
+ 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_->setCorrectionHighlight(false);
+ 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_);
+ for (const auto& label : labels) {
+ if (label.getIsDefault()) {
+ defaultIndex = i;
+ break;
+ }
+ i++;
+ }
+ labelsWidget_->setCurrentIndex(defaultIndex);
}
void QtChatWindow::handleCurrentLabelChanged(int index) {
- if (static_cast<size_t>(index) >= labelModel_->availableLabels_.size()) {
- SWIFT_LOG(debug) << "User selected a label that doesn't exist";
- return;
- }
- const SecurityLabelsCatalog::Item& label = labelModel_->availableLabels_[index];
- if (label.getLabel()) {
- QPalette palette = labelsWidget_->palette();
- //palette.setColor(QPalette::Base, P2QSTRING(label.getLabel()->getBackgroundColor()));
- palette.setColor(labelsWidget_->backgroundRole(), P2QSTRING(label.getLabel()->getBackgroundColor()));
- palette.setColor(labelsWidget_->foregroundRole(), P2QSTRING(label.getLabel()->getForegroundColor()));
- labelsWidget_->setPalette(palette);
- midBar_->setPalette(palette);
- labelsWidget_->setAutoFillBackground(true);
- }
- else {
- labelsWidget_->setAutoFillBackground(false);
- labelsWidget_->setPalette(defaultLabelsPalette_);
- midBar_->setPalette(defaultLabelsPalette_);
- }
+ 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() == nullptr) {
+ 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(std::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 = nullptr;
+ QAction* configure = nullptr;
+ QAction* affiliations = nullptr;
+ QAction* destroy = nullptr;
+ QAction* invite = nullptr;
+
+ QAction* block = nullptr;
+ QAction* unblock = nullptr;
+
+ if (availableRoomActions_.empty()) {
+ if (blockingState_ == IsBlocked) {
+ unblock = contextMenu.addAction(tr("Unblock"));
+ unblock->setEnabled(isOnline_);
+ }
+ else if (!isMUC_ && blockingState_ == IsUnblocked) {
+ block = contextMenu.addAction(tr("Block"));
+ block->setEnabled(isOnline_);
+ }
+
+ if (supportsImpromptuChat_) {
+ invite = contextMenu.addAction(tr("Invite person to this chat…"));
+ invite->setEnabled(isOnline_ && (blockingState_ != IsBlocked));
+ }
+
+ }
+ else {
+ for (auto&& availableAction : availableRoomActions_) {
+ if (impromptu_) {
+ // hide options we don't need in impromptu chats
+ if (availableAction == ChatWindow::ChangeSubject ||
+ availableAction == ChatWindow::Configure ||
+ availableAction == ChatWindow::Affiliations ||
+ availableAction == ChatWindow::Destroy) {
+ continue;
+ }
+ }
+ switch(availableAction)
+ {
+ case ChatWindow::ChangeSubject:
+ changeSubject = contextMenu.addAction(tr("Change subject…"));
+ changeSubject->setEnabled(isOnline_);
+ break;
+ case ChatWindow::Configure:
+ configure = contextMenu.addAction(tr("Configure room…"));
+ configure->setEnabled(isOnline_);
+ break;
+ case ChatWindow::Affiliations:
+ affiliations = contextMenu.addAction(tr("Edit affiliations…"));
+ affiliations->setEnabled(isOnline_);
+ break;
+ case ChatWindow::Destroy:
+ destroy = contextMenu.addAction(tr("Destroy room"));
+ destroy->setEnabled(isOnline_);
+ break;
+ case ChatWindow::Invite:
+ invite = contextMenu.addAction(tr("Invite person to this room…"));
+ invite->setEnabled(isOnline_);
+ break;
+ }
+ }
+ }
+
+ QAction* bookmark = nullptr;
+ 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 == nullptr) {
+ /* 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::setEmphasiseFocus(bool emphasise) {
+ input_->setEmphasiseFocus(emphasise);
}
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, const HighlightAction& highlight) {
- handleAppendedToLog();
- return messageLog_->addMessage(message, senderName, senderIsSelf, label, avatarPath, time, highlight);
+std::string QtChatWindow::addMessage(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, std::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& 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, const HighlightAction& highlight) {
- handleAppendedToLog();
- return messageLog_->addAction(message, senderName, senderIsSelf, label, avatarPath, time, highlight);
+std::string QtChatWindow::addAction(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, std::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& 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, const HighlightAction& highlight) {
- handleAppendedToLog();
- messageLog_->replaceMessage(message, id, time, highlight);
+void QtChatWindow::replaceMessage(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) {
+ handleAppendedToLog();
+ messageLog_->replaceMessage(message, id, time);
}
-void QtChatWindow::replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time, const HighlightAction& highlight) {
- handleAppendedToLog();
- messageLog_->replaceWithAction(message, id, time, highlight);
+void QtChatWindow::replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& 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 121192a..08ad7ad 100644
--- a/Swift/QtUI/QtChatWindow.h
+++ b/Swift/QtUI/QtChatWindow.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -32,203 +32,204 @@ 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, const HighlightAction& highlight);
- 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, const HighlightAction& highlight);
-
- 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, const HighlightAction& highlight);
- void replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time, const HighlightAction& highlight);
- // 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 = nullptr) : 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();
+ }
+ std::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, std::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, std::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;
+ virtual void setEmphasiseFocus(bool emphasise);
+
+ 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 b9ba89d..9c59e9a 100644
--- a/Swift/QtUI/QtChatWindowFactory.cpp
+++ b/Swift/QtUI/QtChatWindowFactory.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,15 +7,15 @@
#include <Swift/QtUI/QtChatWindowFactory.h>
#include <QDesktopWidget>
+
#include <qdebug.h>
#include <Swift/QtUI/QtChatTabs.h>
#include <Swift/QtUI/QtChatTabsBase.h>
-#include <Swift/QtUI/QtChatWindow.h>
-#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/QtChatTheme.h>
+#include <Swift/QtUI/QtChatWindow.h>
#include <Swift/QtUI/QtSingleWindow.h>
-
+#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
@@ -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_ = nullptr;
+ 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(""); /* 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 db67d79..3030689 100644
--- a/Swift/QtUI/QtChatWindowJSBridge.cpp
+++ b/Swift/QtUI/QtChatWindowJSBridge.cpp
@@ -4,16 +4,22 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "QtChatWindowJSBridge.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/QtChatWindowJSBridge.h>
namespace Swift {
QtChatWindowJSBridge::QtChatWindowJSBridge() {
-
+
}
QtChatWindowJSBridge::~QtChatWindowJSBridge() {
-
+
}
}
diff --git a/Swift/QtUI/QtChatWindowJSBridge.h b/Swift/QtUI/QtChatWindowJSBridge.h
index 5a26302..553e929 100644
--- a/Swift/QtUI/QtChatWindowJSBridge.h
+++ b/Swift/QtUI/QtChatWindowJSBridge.h
@@ -4,23 +4,30 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#pragma once
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
-#include <QObject>
+#pragma once
#include <map>
+#include <QObject>
+
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);
+ void verticalScrollBarPositionChanged(double scrollbarPosition);
};
}
diff --git a/Swift/QtUI/QtClickableLabel.cpp b/Swift/QtUI/QtClickableLabel.cpp
index d944ec8..7ce3325 100644
--- a/Swift/QtUI/QtClickableLabel.cpp
+++ b/Swift/QtUI/QtClickableLabel.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtClickableLabel.h"
+#include <Swift/QtUI/QtClickableLabel.h>
namespace Swift {
@@ -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..0b195dd 100644
--- a/Swift/QtUI/QtClosableLineEdit.h
+++ b/Swift/QtUI/QtClosableLineEdit.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -24,20 +24,20 @@ namespace Swift {
class QtClosableLineEdit : public QLineEdit
{
- Q_OBJECT
- public:
- QtClosableLineEdit(QWidget *parent = 0);
+ Q_OBJECT
+ public:
+ QtClosableLineEdit(QWidget *parent = nullptr);
- 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 1d379a3..b349a47 100644
--- a/Swift/QtUI/QtColorToolButton.cpp
+++ b/Swift/QtUI/QtColorToolButton.cpp
@@ -4,42 +4,48 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include <QColorDialog>
-#include <QPainter>
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
#include <Swift/QtUI/QtColorToolButton.h>
+#include <QColorDialog>
+#include <QPainter>
+
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..babafc5 100644
--- a/Swift/QtUI/QtColorToolButton.h
+++ b/Swift/QtUI/QtColorToolButton.h
@@ -4,29 +4,35 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <QToolButton>
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_; }
+ class QtColorToolButton : public QToolButton {
+ Q_OBJECT
+ Q_PROPERTY(QColor color READ getColor WRITE setColor NOTIFY colorChanged)
+ public:
+ explicit QtColorToolButton(QWidget* parent = nullptr);
+ void setColor(const QColor& color);
+ const QColor& getColor() const { return color_; }
- signals:
- void colorChanged(const QColor&);
+ signals:
+ void colorChanged(const QColor&);
- private slots:
- void onClicked();
+ private slots:
+ void onClicked();
- private:
- void setColorIcon(const QColor& color);
- QColor color_;
- };
+ private:
+ void setColorIcon(const QColor& color);
+ QColor color_;
+ };
}
diff --git a/Swift/QtUI/QtConnectionSettingsWindow.cpp b/Swift/QtUI/QtConnectionSettingsWindow.cpp
index 7b5003a..a58bc5c 100644
--- a/Swift/QtUI/QtConnectionSettingsWindow.cpp
+++ b/Swift/QtUI/QtConnectionSettingsWindow.cpp
@@ -1,23 +1,23 @@
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/QtUI/QtConnectionSettingsWindow.h"
+#include <Swift/QtUI/QtConnectionSettingsWindow.h>
#include <boost/lexical_cast.hpp>
#include <QCoreApplication>
+#include <QFile>
#include <QIcon>
#include <QLabel>
-#include <QVBoxLayout>
-#include <QtGlobal>
+#include <QMessageBox>
#include <QPushButton>
#include <QTextEdit>
-#include <QFile>
#include <QTextStream>
-#include <QMessageBox>
+#include <QVBoxLayout>
+#include <QtGlobal>
#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/QtURLValidator.h>
@@ -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 b86f841..f9fad84 100644
--- a/Swift/QtUI/QtConnectionSettingsWindow.h
+++ b/Swift/QtUI/QtConnectionSettingsWindow.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,30 +8,30 @@
#include <QDialog>
-#include "ui_QtConnectionSettings.h"
-
#include <Swiften/Client/ClientOptions.h>
+#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 478f8ce..17f5ccf 100644
--- a/Swift/QtUI/QtContactEditWidget.cpp
+++ b/Swift/QtUI/QtContactEditWidget.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtContactEditWidget.h"
+#include <Swift/QtUI/QtContactEditWidget.h>
#include <algorithm>
@@ -13,163 +13,163 @@
#include <QLabel>
#include <QLineEdit>
#include <QMovie>
-#include <QScrollArea>
#include <QRadioButton>
+#include <QScrollArea>
-#include "Swift/QtUI/QtSwiftUtil.h"
+#include <Swift/QtUI/QtSwiftUtil.h>
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));
+QtContactEditWidget::QtContactEditWidget(const std::set<std::string>& allGroups, QWidget* parent) : QWidget(parent), nameRadioButton_(nullptr), groups_(nullptr) {
+ 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);
+
+ for (const auto& group : allGroups) {
+ QString groupName = doubleAmpersand(group);
+ QCheckBox* check = new QCheckBox(groups);
+ check->setText(groupName);
+ check->setCheckState(Qt::Unchecked);
+ checkBoxes_[group] = check;
+ scrollLayout->addWidget(check);
+ }
+
+ QHBoxLayout* newGroupLayout = new QHBoxLayout();
+ newGroup_ = new QCheckBox(groups);
+ newGroup_->setText(tr("New Group:"));
+ newGroup_->setCheckState(Qt::Unchecked);
+ newGroupLayout->addWidget(newGroup_);
+ newGroupName_ = new QLineEdit(groups);
+ newGroupLayout->addWidget(newGroupName_);
+ scrollLayout->addLayout(newGroupLayout);
+
+ scrollLayout->addItem(new QSpacerItem(20, 73, QSizePolicy::Minimum, QSizePolicy::Expanding));
}
void QtContactEditWidget::setName(const std::string& name) {
- name_->setText(P2QSTRING(name));
+ 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*>();
+ for (const auto button : buttons) {
+ if (button->isChecked()) {
+ if (button == nameRadioButton_) {
+ name = Q2PSTRING(name_->text());
+ } else {
+ name = singleAmpersand(button->text());
+ }
+ break;
+ }
+ }
+ return name;
}
void QtContactEditWidget::setSelectedGroups(const std::vector<std::string>& groups) {
- foreach (std::string group, groups) {
- checkBoxes_[group]->setCheckState(Qt::Checked);
- }
+ for (auto&& group : groups) {
+ checkBoxes_[group]->setCheckState(Qt::Checked);
+ }
}
std::set<std::string> QtContactEditWidget::getSelectedGroups() const {
- std::set<std::string> groups;
- foreach(const CheckBoxMap::value_type& group, checkBoxes_) {
- 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;
+ for (const auto& group : checkBoxes_) {
+ if (group.second->checkState() == Qt::Checked) {
+ groups.insert(group.first);
+ }
+ }
+ if (newGroup_->checkState() == Qt::Checked && !newGroupName_->text().isEmpty()) {
+ groups.insert(Q2PSTRING(newGroupName_->text()));
+ }
+ return groups;
}
void QtContactEditWidget::setNameSuggestions(const std::vector<std::string>& suggestions) {
- throbberLabel_->movie()->stop();
- throbberLabel_->hide();
-
- // remove old suggestions except for the user input text field
- QLayoutItem* suggestionItem = 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 = nullptr;
+ while ((suggestionItem = suggestionsLayout_->itemAt(0)) && suggestionItem->widget() != name_) {
+ QWidget* suggestionWidget = suggestionItem->widget();
+ suggestionsLayout_->removeWidget(suggestionWidget);
+ delete suggestionWidget;
+ }
+
+ // populate new suggestions
+ for (const auto& name : suggestions) {
+ suggestionsLayout_->insertWidget(nameLayout_->count() - 2, new QRadioButton(doubleAmpersand(name), this));
+ }
+
+ nameRadioButton_ = new QRadioButton(tr("Name:"), this);
+ suggestionsLayout_->insertWidget(nameLayout_->count(), nameRadioButton_);
+
+ QRadioButton* suggestedRadioButton = nullptr;
+ QList<QRadioButton*> radioButtons = findChildren<QRadioButton*>();
+ for (auto candidate : radioButtons) {
+ if (candidate->text() == name_->text()) {
+ suggestedRadioButton = candidate;
+ break;
+ }
+ }
+ if (suggestedRadioButton) {
+ suggestedRadioButton->setChecked(true);
+ } else {
+ nameRadioButton_->setChecked(true);
+ }
}
QString QtContactEditWidget::doubleAmpersand(const std::string& name) const {
- return P2QSTRING(name).replace("&", "&&");
+ 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_ = nullptr;
}
}
diff --git a/Swift/QtUI/QtContactEditWidget.h b/Swift/QtUI/QtContactEditWidget.h
index 4a2d056..0718fee 100644
--- a/Swift/QtUI/QtContactEditWidget.h
+++ b/Swift/QtUI/QtContactEditWidget.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,13 @@
#pragma once
#include <map>
+#include <memory>
#include <set>
-#include <boost/shared_ptr.hpp>
+#include <string>
+#include <vector>
#include <QWidget>
-#include <vector>
-#include <string>
-
class QLabel;
class QLineEdit;
class QCheckBox;
@@ -22,37 +21,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:
+ std::map<std::string, QCheckBox*> checkBoxes_;
+ QHBoxLayout* nameLayout_;
+ QHBoxLayout* suggestionsLayout_;
+ QRadioButton* nameRadioButton_;
+ QLineEdit* name_;
+ QWidget* groups_;
+ QCheckBox* newGroup_;
+ QLineEdit* newGroupName_;
+ QLabel* throbberLabel_;
+ };
}
diff --git a/Swift/QtUI/QtContactEditWindow.cpp b/Swift/QtUI/QtContactEditWindow.cpp
index 5f69b52..138a356 100644
--- a/Swift/QtUI/QtContactEditWindow.cpp
+++ b/Swift/QtUI/QtContactEditWindow.cpp
@@ -1,107 +1,107 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtContactEditWindow.h"
+#include <Swift/QtUI/QtContactEditWindow.h>
#include <algorithm>
#include <boost/bind.hpp>
-#include <QScrollArea>
#include <QBoxLayout>
-#include <QLabel>
#include <QCheckBox>
+#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QPushButton>
+#include <QScrollArea>
-#include "Swift/QtUI/QtSwiftUtil.h"
-#include "QtContactEditWidget.h"
+#include <Swift/QtUI/QtContactEditWidget.h>
+#include <Swift/QtUI/QtSwiftUtil.h>
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);
+QtContactEditWindow::QtContactEditWindow() : contactEditWidget_(nullptr) {
+ 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 1e9b07c..655fbb4 100644
--- a/Swift/QtUI/QtContactEditWindow.h
+++ b/Swift/QtUI/QtContactEditWindow.h
@@ -1,49 +1,51 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <QWidget>
-#include <Swift/Controllers/UIInterfaces/ContactEditWindow.h>
-#include <string>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/VCard.h>
+#include <Swiften/JID/JID.h>
+
+#include <Swift/Controllers/UIInterfaces/ContactEditWindow.h>
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 f71e16e..c873676 100644
--- a/Swift/QtUI/QtDBUSURIHandler.cpp
+++ b/Swift/QtUI/QtDBUSURIHandler.cpp
@@ -1,41 +1,41 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtDBUSURIHandler.h"
+#include <Swift/QtUI/QtDBUSURIHandler.h>
#include <QDBusAbstractAdaptor>
#include <QDBusConnection>
-#include "QtSwiftUtil.h"
+#include <Swift/QtUI/QtSwiftUtil.h>
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 05c1558..3cd12f7 100644
--- a/Swift/QtUI/QtDBUSURIHandler.h
+++ b/Swift/QtUI/QtDBUSURIHandler.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,11 +7,12 @@
#pragma once
#include <QObject>
+
#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 9a7ad64..1d6b467 100644
--- a/Swift/QtUI/QtEditBookmarkWindow.cpp
+++ b/Swift/QtUI/QtEditBookmarkWindow.cpp
@@ -1,29 +1,29 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtEditBookmarkWindow.h"
+#include <Swift/QtUI/QtEditBookmarkWindow.h>
-#include "QtSwiftUtil.h"
+#include <Swift/QtUI/QtSwiftUtil.h>
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(std::make_shared<EditMUCBookmarkUIEvent>(bookmark_, *bookmark));
+ return true;
}
}
diff --git a/Swift/QtUI/QtEditBookmarkWindow.h b/Swift/QtUI/QtEditBookmarkWindow.h
index 63c5f2c..337ba1f 100644
--- a/Swift/QtUI/QtEditBookmarkWindow.h
+++ b/Swift/QtUI/QtEditBookmarkWindow.h
@@ -1,24 +1,25 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "QtBookmarkDetailWindow.h"
-#include "Swift/Controllers/UIEvents/UIEventStream.h"
-#include "Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h"
+#include <Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h>
+#include <Swift/Controllers/UIEvents/UIEventStream.h>
+
+#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..e10c39c 100644
--- a/Swift/QtUI/QtElidingLabel.h
+++ b/Swift/QtUI/QtElidingLabel.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 = nullptr, Qt::WindowFlags f = Qt::Widget);
+ QtElidingLabel(const QString &text, QWidget* parent = nullptr, Qt::WindowFlags f = Qt::Widget);
+ 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 1c1f6ed..fe580aa 100644
--- a/Swift/QtUI/QtEmoticonCell.cpp
+++ b/Swift/QtUI/QtEmoticonCell.cpp
@@ -4,16 +4,22 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "QtEmoticonCell.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/QtEmoticonCell.h>
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() {
@@ -21,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..669d1ed 100644
--- a/Swift/QtUI/QtEmoticonCell.h
+++ b/Swift/QtUI/QtEmoticonCell.h
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <map>
@@ -18,17 +24,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);
+ class QtEmoticonCell : public QLabel {
+ Q_OBJECT
+ public:
+ QtEmoticonCell(const QString emoticonAsText, QString filePath, QWidget* parent = nullptr);
+ ~QtEmoticonCell();
+ virtual void mousePressEvent(QMouseEvent* event);
- signals:
- void emoticonClicked(QString emoticonAsText);
+ signals:
+ void emoticonClicked(QString emoticonAsText);
- private:
- QString emoticonAsText_;
- };
+ private:
+ QString emoticonAsText_;
+ };
}
diff --git a/Swift/QtUI/QtEmoticonsGrid.cpp b/Swift/QtUI/QtEmoticonsGrid.cpp
index 4a599ea..4c8c024 100644
--- a/Swift/QtUI/QtEmoticonsGrid.cpp
+++ b/Swift/QtUI/QtEmoticonsGrid.cpp
@@ -4,38 +4,42 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "QtEmoticonsGrid.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/QtEmoticonsGrid.h>
#include <set>
-#include <QPushButton>
+#include <boost/range/adaptor/reversed.hpp>
-#include <Swiften/Base/foreach.h>
+#include <QPushButton>
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
-typedef std::map<std::string, std::string> EmoticonsMap; // Without this typedef compiler complains when using foreach
-
QtEmoticonsGrid::QtEmoticonsGrid(const std::map<std::string, std::string>& emoticons, QWidget* parent) : QGridLayout(parent) {
- makeUniqueEmoticonsMap(emoticons);
-
- // Create grid: 3 columns, [uniqueEmoticons_.size()/3] rows
- int row = 0;
- int column = 0;
-
- foreach(EmoticonsMap::value_type emoticon, uniqueEmoticons_) {
- 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;
+
+ for (auto&& emoticon : uniqueEmoticons_) {
+ QtEmoticonCell* newCell = new QtEmoticonCell(P2QSTRING(emoticon.first), P2QSTRING(emoticon.second));
+ addWidget(newCell, row, column);
+ connect(newCell, SIGNAL(emoticonClicked(QString)), this, SLOT(emoticonClickedSlot(QString)));
+
+ column++;
+ if (column >= 3) {
+ column = 0;
+ row++;
+ }
+ }
}
QtEmoticonsGrid::~QtEmoticonsGrid() {
@@ -43,17 +47,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;
+ for (auto&& emoticon : boost::adaptors::reverse(emoticons)) {
+ if (paths.find(emoticon.second) == paths.end()) {
+ uniqueEmoticons_.insert(emoticon);
+ paths.insert(emoticon.second);
+ }
+ }
}
void QtEmoticonsGrid::emoticonClickedSlot(QString emoticonAsText) {
- emit emoticonClicked(emoticonAsText);
+ emit emoticonClicked(emoticonAsText);
}
}
diff --git a/Swift/QtUI/QtEmoticonsGrid.h b/Swift/QtUI/QtEmoticonsGrid.h
index b045b26..b3b8ac3 100644
--- a/Swift/QtUI/QtEmoticonsGrid.h
+++ b/Swift/QtUI/QtEmoticonsGrid.h
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <map>
@@ -20,21 +26,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 = nullptr);
+ 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..24d6dd1 100644
--- a/Swift/QtUI/QtFileTransferListItemModel.cpp
+++ b/Swift/QtUI/QtFileTransferListItemModel.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,9 +14,9 @@
#include <boost/bind.hpp>
#include <boost/cstdint.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/FileSize.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swift/Controllers/FileTransfer/FileTransferController.h>
#include <Swift/Controllers/FileTransfer/FileTransferOverview.h>
@@ -25,119 +25,119 @@
namespace Swift {
-QtFileTransferListItemModel::QtFileTransferListItemModel(QObject *parent) : QAbstractItemModel(parent), fileTransferOverview(0) {
+QtFileTransferListItemModel::QtFileTransferListItemModel(QObject *parent) : QAbstractItemModel(parent), fileTransferOverview(nullptr) {
}
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*>(nullptr));
}
}
diff --git a/Swift/QtUI/QtFileTransferListItemModel.h b/Swift/QtUI/QtFileTransferListItemModel.h
index 64cdca4..4d1e48b 100644
--- a/Swift/QtUI/QtFileTransferListItemModel.h
+++ b/Swift/QtUI/QtFileTransferListItemModel.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 = nullptr);
+ 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..8b855b0 100644
--- a/Swift/QtUI/QtFileTransferListWidget.cpp
+++ b/Swift/QtUI/QtFileTransferListWidget.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -25,87 +25,87 @@
namespace Swift {
-QtFileTransferListWidget::QtFileTransferListWidget() : fileTransferOverview(0) {
- QVBoxLayout* layout = new QVBoxLayout(this);
- layout->setSpacing(0);
- layout->setContentsMargins(0,0,0,0);
+QtFileTransferListWidget::QtFileTransferListWidget() : fileTransferOverview(nullptr) {
+ 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 = nullptr;
+ }
+ 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 = nullptr;
+ }
+ 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 b0b0749..b35bb4f 100644
--- a/Swift/QtUI/QtFormResultItemModel.cpp
+++ b/Swift/QtUI/QtFormResultItemModel.cpp
@@ -5,17 +5,16 @@
*/
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtFormResultItemModel.h"
+#include <Swift/QtUI/QtFormResultItemModel.h>
#include <boost/algorithm/string/join.hpp>
#include <Swift/QtUI/QtSwiftUtil.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
@@ -28,67 +27,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();
+
+ for (auto&& field : item) {
+ if (field->getName() == name) {
+ std::string delimiter = "";
+ if (field->getType() == FormField::TextMultiType) {
+ delimiter = "\n";
+ }
+ else if (field->getType() == FormField::JIDMultiType) {
+ delimiter = ", ";
+ }
+ else if (field->getType() == FormField::ListMultiType) {
+ delimiter = ", ";
+ }
+ return boost::algorithm::join(field->getValues(), delimiter);
+ }
+ }
+
+ return "";
}
}
diff --git a/Swift/QtUI/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 58af2cd..96c2da0 100644
--- a/Swift/QtUI/QtFormWidget.cpp
+++ b/Swift/QtUI/QtFormWidget.cpp
@@ -1,68 +1,70 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtFormWidget.h>
+#include <memory>
+
+#include <boost/algorithm/string/join.hpp>
+
+#include <QCheckBox>
#include <QGridLayout>
#include <QLabel>
-#include <QListWidget>
#include <QLineEdit>
-#include <QTextEdit>
-#include <QCheckBox>
+#include <QListWidget>
#include <QScrollArea>
+#include <QTextEdit>
+
#include <qdebug.h>
#include <Swift/QtUI/QtSwiftUtil.h>
-#include <Swiften/Base/foreach.h>
-#include <boost/algorithm/string/join.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
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 */
+ for (auto&& field : form->getFields()) {
+ QWidget* widget = createWidget(field, field->getType(), 0);
+ if (widget) {
+ layout->addWidget(new QLabel(field->getLabel().c_str(), this), row, 0);
+ layout->addWidget(widget, row++, 1);
+ }
+ }
+ } else { /* multi-item forms */
+ const Form::FormItem& headers = form->getFields();
+ for (size_t i = 0; i < items.size(); ++i) {
+ const Form::FormItem& item = items[i];
+ assert(item.size() == headers.size());
+ for (size_t j = 0; j < item.size(); ++j) {
+ QWidget* widget = createWidget(item[j], headers[j]->getType(), i);
+ if (widget) {
+ layout->addWidget(new QLabel(item[j]->getLabel().c_str(), this), row, 0);
+ layout->addWidget(widget, row++, 1);
+ }
+ }
+ }
+ }
+ scrollArea->setWidget(scroll);
+ scrollArea->setWidgetResizable(true);
+ setEditable(form->getType() != Form::CancelType && form->getType() != Form::ResultType);
}
QtFormWidget::~QtFormWidget() {
@@ -70,168 +72,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) {
+ for (const auto& value : field->getValues()) {
+ listWidget->addItem(P2QSTRING(value));
+ selected.push_back(false);
+ }
+ } else {
+ for (auto&& option : field->getOptions()) {
+ listWidget->addItem(option.label.c_str());
+ if (field->getType() == FormField::ListSingleType) {
+ selected.push_back(!field->getValues().empty() && option.value == field->getValues()[0]);
+ }
+ else if (field->getType() == FormField::ListMultiType) {
+ std::string text = option.value;
+ selected.push_back(std::find(field->getValues().begin(), field->getValues().end(), text) != field->getValues().end());
+ }
+ }
+ }
+ for (int i = 0; i < listWidget->count(); i++) {
+ QListWidgetItem* item = listWidget->item(i);
+ item->setSelected(selected[i]);
+ }
+ return listWidget;
}
QWidget* QtFormWidget::createWidget(FormField::ref field, const FormField::Type type, const size_t index) {
- QWidget* widget = 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 = nullptr;
+ if (type == FormField::BooleanType) {
+ QCheckBox* checkWidget = new QCheckBox(this);
+ checkWidget->setCheckState(field->getBoolValue() ? Qt::Checked : Qt::Unchecked);
+ widget = checkWidget;
+ }
+ if (type == FormField::FixedType) {
+ QString value = field->getFixedValue().c_str();
+ widget = new QLabel(value, this);
+ }
+ if (type == FormField::ListSingleType) {
+ widget = createList(field);
+ }
+ 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));
+ for (auto&& field : form_->getFields()) {
+ std::shared_ptr<FormField> resultField = std::make_shared<FormField>(field->getType());
+ if (field->getType() == FormField::BooleanType) {
+ resultField->setBoolValue(qobject_cast<QCheckBox*>(fields_[field->getName()])->checkState() == Qt::Checked);
+ }
+ if (field->getType() == FormField::FixedType || field->getType() == FormField::HiddenType) {
+ resultField->addValue(field->getValues().empty() ? "" : field->getValues()[0]);
+ }
+ if (field->getType() == FormField::ListSingleType) {
+ QListWidget* listWidget = qobject_cast<QListWidget*>(fields_[field->getName()]);
+ if (listWidget->selectedItems().size() > 0) {
+ int i = listWidget->row(listWidget->selectedItems()[0]);
+ resultField->addValue(field->getOptions()[i].value);
+ }
+ }
+ if (field->getType() == FormField::TextMultiType) {
+ QTextEdit* widget = qobject_cast<QTextEdit*>(fields_[field->getName()]);
+ QString string = widget->toPlainText();
+ if (!string.isEmpty()) {
+ resultField->setTextMultiValue(Q2PSTRING(string));
+ }
+ }
+ if (field->getType() == FormField::TextPrivateType || field->getType() == FormField::TextSingleType || field->getType() == FormField::JIDSingleType) {
+ QLineEdit* widget = qobject_cast<QLineEdit*>(fields_[field->getName()]);
+ QString string = widget->text();
+ if (!string.isEmpty()) {
+ resultField->addValue(Q2PSTRING(string));
+ }
+ }
+ if (field->getType() == FormField::JIDMultiType) {
+ QTextEdit* widget = qobject_cast<QTextEdit*>(fields_[field->getName()]);
+ QString string = widget->toPlainText();
+ if (!string.isEmpty()) {
+ QStringList lines = string.split("\n");
+ for (auto&& line : lines) {
+ resultField->addValue(Q2PSTRING(line));
+ }
+ }
+ }
+ if (field->getType() == FormField::ListMultiType) {
+ QListWidget* listWidget = qobject_cast<QListWidget*>(fields_[field->getName()]);
+ for (auto item : listWidget->selectedItems()) {
+ resultField->addValue(field->getOptions()[listWidget->row(item)].value);
+ }
+ }
+ resultField->setName(field->getName());
+ result->addField(resultField);
+ }
+ return result;
}
template<class T> void QtFormWidget::setEnabled(QWidget* rawWidget, bool editable) {
- T* widget = qobject_cast<T*>(rawWidget);
- if (widget) {
- widget->setEnabled(editable);
- }
+ 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;
+ }
+ for (auto&& field : form_->getFields()) {
+ QWidget* widget = nullptr;
+ if (field) {
+ widget = fields_[field->getName()];
+ }
+ setEnabled<QCheckBox>(widget, editable);
+ setEnabled<QListWidget>(widget, editable);
+ setEditable<QTextEdit>(widget, editable);
+ setEditable<QLineEdit>(widget, editable);
+ }
}
}
diff --git a/Swift/QtUI/QtFormWidget.h b/Swift/QtUI/QtFormWidget.h
index 9c01983..f228ccb 100644
--- a/Swift/QtUI/QtFormWidget.h
+++ b/Swift/QtUI/QtFormWidget.h
@@ -1,14 +1,15 @@
/*
- * Copyright (c) 2011-2014 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <map>
+
#include <QWidget>
-#include <map>
#include <Swiften/Elements/Form.h>
class QListWidget;
@@ -16,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 = nullptr);
+ 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..dd95941 100644
--- a/Swift/QtUI/QtHighlightEditor.cpp
+++ b/Swift/QtUI/QtHighlightEditor.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -29,540 +29,540 @@
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()
{
}
-std::string formatShortDescription(const HighlightRule &rule)
+QString QtHighlightEditor::formatShortDescription(const HighlightRule &rule)
{
- const std::string chatOrRoom = (rule.getMatchChat() ? "chat" : "room");
+ const QString chatOrRoom = (rule.getMatchChat() ? tr("chat") : tr("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 tr("All %1 messages.").arg(chatOrRoom);
+ }
- if (rule.getNickIsKeyword()) {
- return std::string("All ") + chatOrRoom + " messages that mention my name.";
- }
+ if (rule.getNickIsKeyword()) {
+ return tr("All %1 messages that mention my name.").arg(chatOrRoom);
+ }
- if (!senders.empty()) {
- return std::string("All ") + chatOrRoom + " messages from " + senders[0] + ".";
- }
+ if (!senders.empty()) {
+ return tr("All %1 messages from %2.").arg(chatOrRoom, P2QSTRING(senders[0]));
+ }
- if (!keywords.empty()) {
- return std::string("All ") + chatOrRoom + " messages mentioning the keyword '" + keywords[0] + "'.";
- }
+ if (!keywords.empty()) {
+ return tr("All %1 messages mentioning the keyword '%2'.").arg(chatOrRoom, P2QSTRING(keywords[0]));
+ }
- return "Unknown Rule";
+ return tr("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(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(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(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(), tr("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(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 eb6a52b..c4a12e2 100644
--- a/Swift/QtUI/QtHighlightEditor.h
+++ b/Swift/QtUI/QtHighlightEditor.h
@@ -5,70 +5,72 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swift/QtUI/ui_QtHighlightEditor.h>
-
#include <Swift/Controllers/HighlightRule.h>
#include <Swift/Controllers/UIInterfaces/HighlightEditorWindow.h>
+#include <Swift/QtUI/ui_QtHighlightEditor.h>
+
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 = nullptr);
+ 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:
+ QString formatShortDescription(const HighlightRule &rule);
+ 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_;
- };
+ private:
+ Ui::QtHighlightEditor ui_;
+ QtSettingsProvider* settings_;
+ HighlightManager* highlightManager_ = nullptr;
+ QtSuggestingJIDInput* jid_;
+ int previousRow_;
+ };
}
diff --git a/Swift/QtUI/QtHighlightEditorWidget.cpp b/Swift/QtUI/QtHighlightEditorWidget.cpp
deleted file mode 100644
index 7ff094e..0000000
--- a/Swift/QtUI/QtHighlightEditorWidget.cpp
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (c) 2012 Maciej Niedzielski
- * Licensed under the simplified BSD license.
- * See Documentation/Licenses/BSD-simplified.txt for more information.
- */
-
-#include <cassert>
-
-#include <Swift/QtUI/QtHighlightEditorWidget.h>
-#include <Swift/QtUI/QtHighlightRulesItemModel.h>
-
-namespace Swift {
-
-QtHighlightEditorWidget::QtHighlightEditorWidget(QWidget* parent)
- : QWidget(parent)
-{
- ui_.setupUi(this);
-
- itemModel_ = new QtHighlightRulesItemModel(this);
- ui_.treeView->setModel(itemModel_);
- ui_.ruleWidget->setModel(itemModel_);
-
- for (int i = 0; i < QtHighlightRulesItemModel::NumberOfColumns; ++i) {
- switch (i) {
- case QtHighlightRulesItemModel::ApplyTo:
- case QtHighlightRulesItemModel::Sender:
- case QtHighlightRulesItemModel::Keyword:
- case QtHighlightRulesItemModel::Action:
- ui_.treeView->showColumn(i);
- break;
- default:
- ui_.treeView->hideColumn(i);
- break;
- }
- }
-
- setHighlightManager(NULL); // setup buttons for empty rules list
-
- connect(ui_.treeView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), SLOT(onCurrentRowChanged(QModelIndex)));
-
- connect(ui_.newButton, SIGNAL(clicked()), SLOT(onNewButtonClicked()));
- connect(ui_.deleteButton, SIGNAL(clicked()), SLOT(onDeleteButtonClicked()));
-
- connect(ui_.moveUpButton, SIGNAL(clicked()), SLOT(onMoveUpButtonClicked()));
- connect(ui_.moveDownButton, SIGNAL(clicked()), SLOT(onMoveDownButtonClicked()));
-
- connect(ui_.closeButton, SIGNAL(clicked()), SLOT(close()));
-
- setWindowTitle(tr("Highlight Rules"));
-}
-
-QtHighlightEditorWidget::~QtHighlightEditorWidget()
-{
-}
-
-void QtHighlightEditorWidget::show()
-{
- if (itemModel_->rowCount(QModelIndex())) {
- selectRow(0);
- }
- QWidget::show();
- QWidget::activateWindow();
-}
-
-void QtHighlightEditorWidget::setHighlightManager(HighlightManager* highlightManager)
-{
- itemModel_->setHighlightManager(highlightManager);
- ui_.newButton->setEnabled(highlightManager != NULL);
-
- ui_.ruleWidget->setEnabled(false);
- ui_.deleteButton->setEnabled(false);
- ui_.moveUpButton->setEnabled(false);
- ui_.moveDownButton->setEnabled(false);
-}
-
-void QtHighlightEditorWidget::closeEvent(QCloseEvent* event) {
- ui_.ruleWidget->save();
- event->accept();
-}
-
-void QtHighlightEditorWidget::onNewButtonClicked()
-{
- int row = getSelectedRow() + 1;
- itemModel_->insertRow(row, QModelIndex());
- selectRow(row);
-}
-
-void QtHighlightEditorWidget::onDeleteButtonClicked()
-{
- int row = getSelectedRow();
- assert(row >= 0);
-
- itemModel_->removeRow(row, QModelIndex());
- if (row == itemModel_->rowCount(QModelIndex())) {
- --row;
- }
- selectRow(row);
-}
-
-void QtHighlightEditorWidget::onMoveUpButtonClicked()
-{
- int row = getSelectedRow();
- assert(row > 0);
-
- ui_.ruleWidget->save();
- ui_.ruleWidget->setActiveIndex(QModelIndex());
- itemModel_->swapRows(row, row - 1);
- selectRow(row - 1);
-}
-
-void QtHighlightEditorWidget::onMoveDownButtonClicked()
-{
- int row = getSelectedRow();
- assert(row < itemModel_->rowCount(QModelIndex()) - 1);
-
- ui_.ruleWidget->save();
- ui_.ruleWidget->setActiveIndex(QModelIndex());
- if (itemModel_->swapRows(row, row + 1)) {
- selectRow(row + 1);
- }
-}
-
-void QtHighlightEditorWidget::onCurrentRowChanged(const QModelIndex& index)
-{
- ui_.ruleWidget->save();
- ui_.ruleWidget->setActiveIndex(index);
-
- ui_.ruleWidget->setEnabled(index.isValid());
-
- ui_.deleteButton->setEnabled(index.isValid());
-
- ui_.moveUpButton->setEnabled(index.isValid() && index.row() != 0);
- ui_.moveDownButton->setEnabled(index.isValid() && index.row() != itemModel_->rowCount(QModelIndex()) - 1);
-}
-
-void QtHighlightEditorWidget::selectRow(int row)
-{
- QModelIndex index = itemModel_->index(row, 0, QModelIndex());
- ui_.treeView->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
-}
-
-/** Return index of selected row or -1 if none is selected */
-int QtHighlightEditorWidget::getSelectedRow() const
-{
- QModelIndexList rows = ui_.treeView->selectionModel()->selectedRows();
- return rows.isEmpty() ? -1 : rows[0].row();
-}
-
-}
diff --git a/Swift/QtUI/QtHighlightEditorWidget.h b/Swift/QtUI/QtHighlightEditorWidget.h
deleted file mode 100644
index 1293c87..0000000
--- a/Swift/QtUI/QtHighlightEditorWidget.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2012 Maciej Niedzielski
- * Licensed under the simplified BSD license.
- * See Documentation/Licenses/BSD-simplified.txt for more information.
- */
-
-#pragma once
-
-#include <Swift/Controllers/UIInterfaces/HighlightEditorWidget.h>
-#include <Swift/QtUI/ui_QtHighlightEditorWidget.h>
-
-namespace Swift {
-
- class QtHighlightRulesItemModel;
-
- class QtHighlightEditorWidget : public QWidget, public HighlightEditorWidget {
- Q_OBJECT
-
- public:
- QtHighlightEditorWidget(QWidget* parent = NULL);
- virtual ~QtHighlightEditorWidget();
-
- void show();
-
- void setHighlightManager(HighlightManager* highlightManager);
-
- private slots:
- void onNewButtonClicked();
- void onDeleteButtonClicked();
- void onMoveUpButtonClicked();
- void onMoveDownButtonClicked();
- void onCurrentRowChanged(const QModelIndex&);
-
- private:
- virtual void closeEvent(QCloseEvent* event);
-
- void selectRow(int row);
- int getSelectedRow() const;
-
- Ui::QtHighlightEditorWidget ui_;
- QtHighlightRulesItemModel* itemModel_;
- };
-
-}
diff --git a/Swift/QtUI/QtHighlightEditorWidget.ui b/Swift/QtUI/QtHighlightEditorWidget.ui
deleted file mode 100644
index 0f39168..0000000
--- a/Swift/QtUI/QtHighlightEditorWidget.ui
+++ /dev/null
@@ -1,124 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>QtHighlightEditorWidget</class>
- <widget class="QWidget" name="QtHighlightEditorWidget">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>419</width>
- <height>373</height>
- </rect>
- </property>
- <property name="windowTitle">
- <string>Form</string>
- </property>
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <layout class="QVBoxLayout" name="verticalLayout_2">
- <item>
- <widget class="QLabel" name="label">
- <property name="text">
- <string>Incoming messages are checked against the following rules. First rule that matches will be executed.</string>
- </property>
- <property name="wordWrap">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QTreeView" name="treeView">
- <property name="rootIsDecorated">
- <bool>false</bool>
- </property>
- <property name="itemsExpandable">
- <bool>false</bool>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
- <widget class="Swift::QtHighlightRuleWidget" name="ruleWidget" native="true"/>
- </item>
- <item>
- <layout class="QVBoxLayout" name="verticalLayout">
- <item>
- <widget class="QPushButton" name="newButton">
- <property name="text">
- <string>New</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="deleteButton">
- <property name="text">
- <string>Delete</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="verticalSpacer_2">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::Fixed</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QPushButton" name="moveUpButton">
- <property name="text">
- <string>Move up</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="moveDownButton">
- <property name="text">
- <string>Move down</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="verticalSpacer_3">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>40</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QPushButton" name="closeButton">
- <property name="text">
- <string>Close</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>Swift::QtHighlightRuleWidget</class>
- <extends>QWidget</extends>
- <header>QtHighlightRuleWidget.h</header>
- <container>1</container>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections/>
-</ui>
diff --git a/Swift/QtUI/QtHighlightRulesItemModel.cpp b/Swift/QtUI/QtHighlightRulesItemModel.cpp
deleted file mode 100644
index fcbaddc..0000000
--- a/Swift/QtUI/QtHighlightRulesItemModel.cpp
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright (c) 2012 Maciej Niedzielski
- * Licensed under the simplified BSD license.
- * See Documentation/Licenses/BSD-simplified.txt for more information.
- */
-
-#include <boost/algorithm/string.hpp>
-#include <boost/lambda/lambda.hpp>
-#include <boost/numeric/conversion/cast.hpp>
-
-#include <QStringList>
-#include <QColor>
-
-#include <Swift/Controllers/HighlightManager.h>
-#include <Swift/QtUI/QtHighlightRulesItemModel.h>
-#include <Swift/QtUI/QtSwiftUtil.h>
-
-namespace Swift {
-
-QtHighlightRulesItemModel::QtHighlightRulesItemModel(QObject* parent) : QAbstractItemModel(parent), highlightManager_(NULL)
-{
-}
-
-void QtHighlightRulesItemModel::setHighlightManager(HighlightManager* highlightManager)
-{
- emit layoutAboutToBeChanged();
- highlightManager_ = highlightManager;
- emit layoutChanged();
-}
-
-QVariant QtHighlightRulesItemModel::headerData(int section, Qt::Orientation /* orientation */, int role) const
-{
- if (role == Qt::DisplayRole) {
- switch (section) {
- case ApplyTo: return QVariant(tr("Apply to"));
- case Sender: return QVariant(tr("Sender"));
- case Keyword: return QVariant(tr("Keyword"));
- case Action: return QVariant(tr("Action"));
- case NickIsKeyword: return QVariant(tr("Nick Is Keyword"));
- case MatchCase: return QVariant(tr("Match Case"));
- case MatchWholeWords: return QVariant(tr("Match Whole Words"));
- case HighlightText: return QVariant(tr("Highlight Text"));
- case TextColor: return QVariant(tr("Text Color"));
- case TextBackground: return QVariant(tr("Text Background"));
- case PlaySound: return QVariant(tr("Play Sounds"));
- case SoundFile: return QVariant(tr("Sound File"));
- }
- }
-
- return QVariant();
-}
-
-int QtHighlightRulesItemModel::columnCount(const QModelIndex& /* parent */) const
-{
- return NumberOfColumns;
-}
-
-QVariant QtHighlightRulesItemModel::data(const QModelIndex &index, int role) const
-{
- if (index.isValid() && highlightManager_ && (role == Qt::DisplayRole || role == Qt::EditRole)) {
-
- const char* separator = (role == Qt::DisplayRole) ? " ; " : "\n";
-
- if (boost::numeric_cast<std::vector<std::string>::size_type>(index.row()) < highlightManager_->getRules().size()) {
- const HighlightRule& r = highlightManager_->getRules()[index.row()];
- switch (index.column()) {
- case ApplyTo: {
- int applyTo = 0;
- if (r.getMatchChat() && r.getMatchMUC()) {
- applyTo = 1;
- } else if (r.getMatchChat()) {
- applyTo = 2;
- } else if (r.getMatchMUC()) {
- applyTo = 3;
- }
-
- if (role == Qt::DisplayRole) {
- return QVariant(getApplyToString(applyTo));
- } else {
- return QVariant(applyTo);
- }
- }
- case Sender: {
- std::string s = boost::join(r.getSenders(), separator);
- return QVariant(P2QSTRING(s));
- }
- case Keyword: {
- std::string s = boost::join(r.getKeywords(), separator);
- QString qs(P2QSTRING(s));
- if (role == Qt::DisplayRole && r.getNickIsKeyword()) {
- qs = tr("<nick>") + (qs.isEmpty() ? "" : separator + qs);
- }
- return QVariant(qs);
- }
- case Action: {
- std::vector<std::string> v;
- const HighlightAction & action = r.getAction();
- if (action.highlightText()) {
- v.push_back(Q2PSTRING(tr("Highlight text")));
- }
- if (action.playSound()) {
- v.push_back(Q2PSTRING(tr("Play sound")));
- }
- std::string s = boost::join(v, separator);
- return QVariant(P2QSTRING(s));
- }
- case NickIsKeyword: {
- return QVariant(r.getNickIsKeyword());
- }
- case MatchCase: {
- return QVariant(r.getMatchCase());
- }
- case MatchWholeWords: {
- return QVariant(r.getMatchWholeWords());
- }
- case HighlightText: {
- return QVariant(r.getAction().highlightText());
- }
- case TextColor: {
- return QVariant(QColor(P2QSTRING(r.getAction().getTextColor())));
- }
- case TextBackground: {
- return QVariant(QColor(P2QSTRING(r.getAction().getTextBackground())));
- }
- case PlaySound: {
- return QVariant(r.getAction().playSound());
- }
- case SoundFile: {
- return QVariant(P2QSTRING(r.getAction().getSoundFile()));
- }
- }
- }
- }
- return QVariant();
-}
-
-bool QtHighlightRulesItemModel::setData(const QModelIndex &index, const QVariant &value, int role)
-{
- if (index.isValid() && highlightManager_ && role == Qt::EditRole) {
- if (boost::numeric_cast<std::vector<std::string>::size_type>(index.row()) < highlightManager_->getRules().size()) {
- HighlightRule r = highlightManager_->getRule(index.row());
- std::vector<int> changedColumns;
- switch (index.column()) {
- case ApplyTo: {
- bool ok = false;
- int applyTo = value.toInt(&ok);
- if (!ok) {
- return false;
- }
- r.setMatchChat(applyTo == ApplyToAll || applyTo == ApplyToChat);
- r.setMatchMUC(applyTo == ApplyToAll || applyTo == ApplyToMUC);
- break;
- }
- case Sender:
- case Keyword: {
- std::string s = Q2PSTRING(value.toString());
- std::vector<std::string> v;
- boost::split(v, s, boost::is_any_of("\n"));
- v.erase(std::remove_if(v.begin(), v.end(), boost::lambda::_1 == ""), v.end());
- if (index.column() == Sender) {
- r.setSenders(v);
- } else {
- r.setKeywords(v);
- }
- break;
- }
- case NickIsKeyword: {
- r.setNickIsKeyword(value.toBool());
- changedColumns.push_back(Keyword); // "<nick>"
- break;
- }
- case MatchCase: {
- r.setMatchCase(value.toBool());
- break;
- }
- case MatchWholeWords: {
- r.setMatchWholeWords(value.toBool());
- break;
- }
- case HighlightText: {
- r.getAction().setHighlightText(value.toBool());
- changedColumns.push_back(Action);
- break;
- }
- case TextColor: {
- QColor c = value.value<QColor>();
- r.getAction().setTextColor(c.isValid() ? Q2PSTRING(c.name()) : "");
- break;
- }
- case TextBackground: {
- QColor c = value.value<QColor>();
- r.getAction().setTextBackground(c.isValid() ? Q2PSTRING(c.name()) : "");
- break;
- }
- case PlaySound: {
- r.getAction().setPlaySound(value.toBool());
- changedColumns.push_back(Action);
- break;
- }
- case SoundFile: {
- r.getAction().setSoundFile(Q2PSTRING(value.toString()));
- break;
- }
- }
-
- highlightManager_->setRule(index.row(), r);
- emit dataChanged(index, index);
- foreach (int column, changedColumns) {
- QModelIndex i = createIndex(index.row(), column, static_cast<void*>(0));
- emit dataChanged(i, i);
- }
- }
- }
-
- return false;
-}
-
-QModelIndex QtHighlightRulesItemModel::parent(const QModelIndex& /* child */) const
-{
- return QModelIndex();
-}
-
-int QtHighlightRulesItemModel::rowCount(const QModelIndex& /* parent */) const
-{
- return highlightManager_ ? highlightManager_->getRules().size() : 0;
-}
-
-QModelIndex QtHighlightRulesItemModel::index(int row, int column, const QModelIndex& /* parent */) const
-{
- return createIndex(row, column, static_cast<void*>(0));
-}
-
-bool QtHighlightRulesItemModel::insertRows(int row, int count, const QModelIndex& /* parent */)
-{
- if (highlightManager_) {
- beginInsertRows(QModelIndex(), row, row + count);
- while (count--) {
- highlightManager_->insertRule(row, HighlightRule());
- }
- endInsertRows();
- return true;
- }
- return false;
-}
-
-bool QtHighlightRulesItemModel::removeRows(int row, int count, const QModelIndex& /* parent */)
-{
- if (highlightManager_) {
- beginRemoveRows(QModelIndex(), row, row + count);
- while (count--) {
- highlightManager_->removeRule(row);
- }
- endRemoveRows();
- return true;
- }
- return false;
-}
-
-bool QtHighlightRulesItemModel::swapRows(int row1, int row2)
-{
- if (highlightManager_) {
- assert(row1 >= 0 && row2 >= 0 && boost::numeric_cast<std::vector<std::string>::size_type>(row1) < highlightManager_->getRules().size() && boost::numeric_cast<std::vector<std::string>::size_type>(row2) < highlightManager_->getRules().size());
- HighlightRule r = highlightManager_->getRule(row1);
- highlightManager_->setRule(row1, highlightManager_->getRule(row2));
- highlightManager_->setRule(row2, r);
- emit dataChanged(index(row1, 0, QModelIndex()), index(row1, 0, QModelIndex()));
- emit dataChanged(index(row2, 0, QModelIndex()), index(row2, 0, QModelIndex()));
- return true;
- }
- return false;
-}
-
-QString QtHighlightRulesItemModel::getApplyToString(int applyTo)
-{
- switch (applyTo) {
- case ApplyToNone: return tr("None");
- case ApplyToAll: return tr("Chat or MUC");
- case ApplyToChat: return tr("Chat");
- case ApplyToMUC: return tr("MUC");
- default: return "";
- }
-}
-
-}
diff --git a/Swift/QtUI/QtHighlightRulesItemModel.h b/Swift/QtUI/QtHighlightRulesItemModel.h
deleted file mode 100644
index ac85628..0000000
--- a/Swift/QtUI/QtHighlightRulesItemModel.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (c) 2012 Maciej Niedzielski
- * Licensed under the simplified BSD license.
- * See Documentation/Licenses/BSD-simplified.txt for more information.
- */
-
-#pragma once
-
-#include <QAbstractItemModel>
-
-namespace Swift {
-
- class HighlightManager;
-
- class QtHighlightRulesItemModel : public QAbstractItemModel {
- Q_OBJECT
-
- public:
- QtHighlightRulesItemModel(QObject* parent = NULL);
-
- void setHighlightManager(HighlightManager* highlightManager);
-
- QVariant headerData(int section, Qt::Orientation orientation, int role) const;
- int columnCount(const QModelIndex& parent) const;
- QVariant data(const QModelIndex& index, int role) const;
- bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole);
- QModelIndex parent(const QModelIndex& child) const;
- int rowCount(const QModelIndex& parent) const;
- QModelIndex index(int row, int column, const QModelIndex& parent) const;
- bool insertRows(int row, int count, const QModelIndex& parent = QModelIndex());
- bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex());
- bool swapRows(int row1, int row2);
-
- static QString getApplyToString(int);
-
- enum Columns {
- ApplyTo = 0,
- Sender,
- Keyword,
- Action,
- NickIsKeyword,
- MatchCase,
- MatchWholeWords,
- HighlightText,
- TextColor,
- TextBackground,
- PlaySound,
- SoundFile,
- NumberOfColumns // end of list marker
- };
-
- enum ApplyToValues {
- ApplyToNone = 0,
- ApplyToAll,
- ApplyToChat,
- ApplyToMUC,
- ApplyToEOL // end of list marker
- };
-
- private:
- HighlightManager* highlightManager_;
- };
-
-}
diff --git a/Swift/QtUI/QtHistoryWindow.cpp b/Swift/QtUI/QtHistoryWindow.cpp
index f07c9b2..77a7f12 100644
--- a/Swift/QtUI/QtHistoryWindow.cpp
+++ b/Swift/QtUI/QtHistoryWindow.cpp
@@ -5,264 +5,263 @@
*/
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <QtHistoryWindow.h>
+#include <Swift/QtUI/QtHistoryWindow.h>
+#include <memory>
#include <string>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/numeric/conversion/cast.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <QTime>
-#include <QUrl>
-#include <QMenu>
-#include <QTextDocument>
#include <QDateTime>
#include <QLineEdit>
+#include <QMenu>
+#include <QTextDocument>
+#include <QTime>
+#include <QUrl>
#include <Swiften/History/HistoryMessage.h>
#include <Swift/Controllers/Settings/SettingsProvider.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
-#include <Swift/QtUI/QtSwiftUtil.h>
+#include <Swift/QtUI/ChatSnippet.h>
#include <Swift/QtUI/MessageSnippet.h>
#include <Swift/QtUI/QtScaledAvatarCache.h>
-#include <Swift/QtUI/ChatSnippet.h>
+#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/QtUtilities.h>
-#include <Swift/QtUI/Roster/QtTreeWidget.h>
#include <Swift/QtUI/QtWebKitChatView.h>
+#include <Swift/QtUI/Roster/QtTreeWidget.h>
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(nullptr, nullptr, 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(std::make_shared<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(std::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;
+ for (const auto& date : dates_) {
+ int snippetPosition = conversation_->getSnippetPositionByDate(date);
+ if (snippetPosition <= pos) {
+ currentDate = date;
+ }
+ }
+
+ if (ui_.calendarWidget_->selectedDate() != currentDate) {
+ ui_.calendarWidget_->setSelectedDate(currentDate);
+ }
}
void QtHistoryWindow::handleScrollReachedTop() {
- if (dates_.empty()) {
- return;
- }
-
- int year, month, day;
- QDate firstDate = *dates_.begin();
- firstDate.getDate(&year, &month, &day);
- onScrollReachedTop(boost::gregorian::date(boost::numeric_cast<unsigned short>(year), boost::numeric_cast<unsigned short>(month), boost::numeric_cast<unsigned short>(day)));
+ 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 e17d29f..02d7fb8 100644
--- a/Swift/QtUI/QtHistoryWindow.h
+++ b/Swift/QtUI/QtHistoryWindow.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -19,65 +19,64 @@
#include <Swift/Controllers/UIInterfaces/HistoryWindow.h>
#include <Swift/QtUI/QtTabbable.h>
-
#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..400d1bf 100644
--- a/Swift/QtUI/QtJoinMUCWindow.cpp
+++ b/Swift/QtUI/QtJoinMUCWindow.cpp
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtJoinMUCWindow.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <QToolTip>
@@ -17,59 +17,60 @@ 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(std::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();
+ QWidget::raise();
+ ui.password->setText("");
}
}
diff --git a/Swift/QtUI/QtJoinMUCWindow.h b/Swift/QtUI/QtJoinMUCWindow.h
index 92580ff..c2e8068 100644
--- a/Swift/QtUI/QtJoinMUCWindow.h
+++ b/Swift/QtUI/QtJoinMUCWindow.h
@@ -1,13 +1,11 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swift/QtUI/ui_QtJoinMUCWindow.h>
-
#include <string>
#include <QValidator>
@@ -15,62 +13,63 @@
#include <Swift/Controllers/UIInterfaces/JoinMUCWindow.h>
#include <Swift/QtUI/QtSwiftUtil.h>
+#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 75deafe..d3ec4c4 100644
--- a/Swift/QtUI/QtLineEdit.cpp
+++ b/Swift/QtUI/QtLineEdit.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/QtUI/QtLineEdit.h"
+#include <Swift/QtUI/QtLineEdit.h>
#include <QKeyEvent>
@@ -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..851a2ff 100644
--- a/Swift/QtUI/QtLineEdit.h
+++ b/Swift/QtUI/QtLineEdit.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 = nullptr);
+ signals:
+ void escapePressed();
+ protected:
+ virtual void keyPressEvent(QKeyEvent* event);
+ };
}
diff --git a/Swift/QtUI/QtLoginWindow.cpp b/Swift/QtUI/QtLoginWindow.cpp
index 229df7f..865d8b5 100644
--- a/Swift/QtUI/QtLoginWindow.cpp
+++ b/Swift/QtUI/QtLoginWindow.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -10,7 +10,7 @@
#include <cassert>
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <QApplication>
#include <QBoxLayout>
@@ -54,524 +54,523 @@
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);
+ QIcon swiftWithTextLogo = QIcon(":/logo-shaded-text.png");
+ logo->setPixmap(swiftWithTextLogo.pixmap(QSize(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(nullptr);
#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 (auto& widget : widgets) {
+ widget->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 = std::make_shared<CAPICertificate>(certificateString, timerFactory_);
+ } else {
+ certificate = std::make_shared<PKCS12Certificate>(certificateString, createSafeByteArray(Q2PSTRING(password_->text())));
+ }
#else
- certificate = boost::make_shared<PKCS12Certificate>(certificateString, createSafeByteArray(Q2PSTRING(password_->text())));
+ certificate = std::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(settings_);
+ aboutDialog_->show();
+ }
+ else {
+ aboutDialog_->show();
+ aboutDialog_->raise();
+ aboutDialog_->activateWindow();
+ }
}
void QtLoginWindow::handleShowXMLConsole() {
- uiEventStream_->send(boost::make_shared<RequestXMLConsoleUIEvent>());
+ uiEventStream_->send(std::make_shared<RequestXMLConsoleUIEvent>());
}
void QtLoginWindow::handleShowFileTransferOverview() {
- uiEventStream_->send(boost::make_shared<RequestFileTransferListUIEvent>());
+ uiEventStream_->send(std::make_shared<RequestFileTransferListUIEvent>());
}
void QtLoginWindow::handleShowHighlightEditor() {
- uiEventStream_->send(boost::make_shared<RequestHighlightEditorUIEvent>());
+ uiEventStream_->send(std::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];
+ for (auto menu : mainWindowMenus) {
+ menuBar_->addMenu(menu);
+ }
+ setFocus();
}
void QtLoginWindow::setMessage(const std::string& message) {
- if (!message.empty()) {
- message_->setText("<center><font color=\"red\">" + P2QSTRING(message) + "</font></center>");
- }
- else {
- message_->setText("");
- }
+ 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 66730fd..c42d65d 100644
--- a/Swift/QtUI/QtLoginWindow.h
+++ b/Swift/QtUI/QtLoginWindow.h
@@ -1,112 +1,113 @@
/*
- * Copyright (c) 2010-2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <QCheckBox>
+#include <QLineEdit>
#include <QMainWindow>
+#include <QMenuBar>
#include <QPointer>
-#include <QLineEdit>
#include <QPushButton>
-#include <QCheckBox>
#include <QStackedWidget>
-#include <QMenuBar>
-#include <Swift/Controllers/UIInterfaces/LoginWindow.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
+#include <Swift/Controllers/UIInterfaces/LoginWindow.h>
#include <Swift/Controllers/UIInterfaces/MainWindow.h>
-#include <QtAboutWidget.h>
+
+#include <Swift/QtUI/QtAboutWidget.h>
class QLabel;
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_ = nullptr;
+ 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 8e8cc0b..e07b8c6 100644
--- a/Swift/QtUI/QtMUCConfigurationWindow.cpp
+++ b/Swift/QtUI/QtMUCConfigurationWindow.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,37 +7,39 @@
#include <Swift/QtUI/QtMUCConfigurationWindow.h>
#include <boost/bind.hpp>
+
#include <QBoxLayout>
#include <QCloseEvent>
+
#include <Swift/QtUI/QtFormWidget.h>
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_ = nullptr;
+ 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() {
@@ -45,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 dcf941f..da3e12a 100644
--- a/Swift/QtUI/QtMUCConfigurationWindow.h
+++ b/Swift/QtUI/QtMUCConfigurationWindow.h
@@ -1,39 +1,40 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QWidget>
-#include <QPushButton>
+#include <boost/signals2.hpp>
+
#include <QLabel>
+#include <QPushButton>
+#include <QWidget>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Elements/Form.h>
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::signals2::signal<void (Form::ref)> onFormComplete;
+ boost::signals2::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..0c1dd97 100644
--- a/Swift/QtUI/QtMainWindow.cpp
+++ b/Swift/QtUI/QtMainWindow.cpp
@@ -1,14 +1,15 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtMainWindow.h>
+#include <memory>
+
#include <boost/bind.hpp>
#include <boost/optional.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <QAction>
#include <QBoxLayout>
@@ -52,373 +53,374 @@
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_ = nullptr;
+ 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(std::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(std::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);
+ std::shared_ptr<UIEvent> event(new RequestAddUserDialogUIEvent());
+ uiEventStream_->send(event);
}
void QtMainWindow::handleChatUserActionTriggered(bool /*checked*/) {
- boost::shared_ptr<UIEvent> event(new RequestChatWithUserDialogUIEvent());
- uiEventStream_->send(event);
+ std::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(std::make_shared<RequestProfileEditorUIEvent>());
}
void QtMainWindow::handleJoinMUCAction() {
- uiEventStream_->send(boost::make_shared<RequestJoinMUCUIEvent>());
+ uiEventStream_->send(std::make_shared<RequestJoinMUCUIEvent>());
}
void QtMainWindow::handleViewLogsAction() {
- uiEventStream_->send(boost::make_shared<RequestHistoryUIEvent>());
+ uiEventStream_->send(std::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);
+ for (auto action : onlineOnlyActions_) {
+ action->setEnabled(online);
+ }
+ serverAdHocMenu_->setEnabled(online);
}
-void QtMainWindow::setMyContactRosterItem(boost::shared_ptr<ContactRosterItem> contact) {
- meView_->setContactRosterItem(contact);
+void QtMainWindow::setMyContactRosterItem(std::shared_ptr<ContactRosterItem> 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);
+ assert(serverAdHocCommandActions_.indexOf(action) >= 0);
+ DiscoItems::Item command = serverAdHocCommands_[serverAdHocCommandActions_.indexOf(action)];
+ uiEventStream_->send(std::make_shared<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;
+ for (auto action : serverAdHocCommandActions_) {
+ delete action;
+ }
+ serverAdHocMenu_->clear();
+ serverAdHocCommandActions_.clear();
+ for (const auto& 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 2e314f7..c46fdfc 100644
--- a/Swift/QtUI/QtMainWindow.h
+++ b/Swift/QtUI/QtMainWindow.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,16 +8,16 @@
#include <vector>
-#include <QWidget>
-#include <QMenu>
#include <QList>
+#include <QMenu>
+#include <QWidget>
#include <Swift/Controllers/UIInterfaces/MainWindow.h>
-#include <Swift/QtUI/QtRosterHeader.h>
-#include <Swift/QtUI/EventViewer/QtEventWindow.h>
#include <Swift/QtUI/ChatList/QtChatListWindow.h>
+#include <Swift/QtUI/EventViewer/QtEventWindow.h>
#include <Swift/QtUI/QtLoginWindow.h>
+#include <Swift/QtUI/QtRosterHeader.h>
class QComboBox;
class QLineEdit;
@@ -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(std::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 428b243..0610a00 100644
--- a/Swift/QtUI/QtNameWidget.cpp
+++ b/Swift/QtUI/QtNameWidget.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtNameWidget.h"
+#include <Swift/QtUI/QtNameWidget.h>
#include <QHBoxLayout>
#include <QMenu>
@@ -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 a794167..05a2eb0 100644
--- a/Swift/QtUI/QtPlainChatView.cpp
+++ b/Swift/QtUI/QtPlainChatView.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -18,7 +18,6 @@
#include <QVBoxLayout>
#include <Swiften/Base/FileSize.h>
-#include <Swiften/Base/foreach.h>
#include <Swift/Controllers/UIEvents/JoinMUCUIEvent.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
@@ -31,402 +30,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;
+ for (auto&& part : message.getParts()) {
+ std::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
+ std::shared_ptr<ChatWindow::ChatURIMessagePart> uriPart;
+ std::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart;
+ std::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart;
+
+ if ((textPart = std::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
+ QString text = QtUtilities::htmlEscape(P2QSTRING(textPart->text));
+ text.replace("\n","<br/>");
+ result += text;
+ continue;
+ }
+ if ((uriPart = std::dynamic_pointer_cast<ChatWindow::ChatURIMessagePart>(part))) {
+ QString uri = QtUtilities::htmlEscape(P2QSTRING(uriPart->target));
+ result += "<a href='" + uri + "' >" + uri + "</a>";
+ continue;
+ }
+ if ((emoticonPart = std::dynamic_pointer_cast<ChatWindow::ChatEmoticonMessagePart>(part))) {
+ result += P2QSTRING(emoticonPart->alternativeText);
+ continue;
+ }
+ if ((highlightPart = std::dynamic_pointer_cast<ChatWindow::ChatHighlightingMessagePart>(part))) {
+ //FIXME: Maybe do something here. Anything, really.
+ continue;
+ }
+ }
+ return result;
}
-std::string QtPlainChatView::addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr<SecurityLabel> label, const std::string& /*avatarPath*/, const boost::posix_time::ptime& time, const HighlightAction& /*highlight*/) {
- 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::addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, std::shared_ptr<SecurityLabel> label, const std::string& /*avatarPath*/, const boost::posix_time::ptime& time) {
+ QString text = "<p>";
+ 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, const HighlightAction& /*highlight*/) {
- 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::addAction(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, std::shared_ptr<SecurityLabel> label, const std::string& /*avatarPath*/, const boost::posix_time::ptime& time) {
+ QString text = "<p>";
+ 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, const HighlightAction& /*highlight*/)
+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, const HighlightAction& /*highlight*/)
+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(std::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)
+: PopupDialog(parent), bar_(nullptr), 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 aeb50b6..d65672c 100644
--- a/Swift/QtUI/QtPlainChatView.h
+++ b/Swift/QtUI/QtPlainChatView.h
@@ -1,15 +1,15 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
#include <boost/date_time/posix_time/posix_time.hpp>
-#include <boost/shared_ptr.hpp>
#include <QTextEdit>
#include <QWidget>
@@ -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*/, const HighlightAction& /*highlight*/);
- /** 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*/, const HighlightAction& /*highlight*/);
-
- 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*/, const HighlightAction& /*highlight*/);
- virtual void replaceWithAction(const ChatWindow::ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/, const HighlightAction& /*highlight*/);
- 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*/, std::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*/, std::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, std::shared_ptr<SecurityLabel> > lastMessageLabel_;
+ int idGenerator_;
+
+ };
}
diff --git a/Swift/QtUI/QtProfileWindow.cpp b/Swift/QtUI/QtProfileWindow.cpp
index 06d602a..80e275b 100644
--- a/Swift/QtUI/QtProfileWindow.cpp
+++ b/Swift/QtUI/QtProfileWindow.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -11,7 +11,6 @@
*/
#include <Swift/QtUI/QtProfileWindow.h>
-#include <Swift/QtUI/ui_QtProfileWindow.h>
#include <QCloseEvent>
#include <QMovie>
@@ -21,147 +20,148 @@
#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/QtUtilities.h>
+#include <Swift/QtUI/ui_QtProfileWindow.h>
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*>();
+ for (auto 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 1a973c0..b405d10 100644
--- a/Swift/QtUI/QtRosterHeader.cpp
+++ b/Swift/QtUI/QtRosterHeader.cpp
@@ -1,13 +1,12 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtRosterHeader.h"
+#include <Swift/QtUI/QtRosterHeader.h>
#include <QBitmap>
-#include <qdebug.h>
#include <QFileInfo>
#include <QHBoxLayout>
#include <QHelpEvent>
@@ -18,121 +17,123 @@
#include <QToolTip>
#include <QVBoxLayout>
-#include "QtStatusWidget.h"
-#include <Swift/QtUI/QtElidingLabel.h>
+#include <qdebug.h>
+
#include <Swift/QtUI/QtClickableLabel.h>
+#include <Swift/QtUI/QtElidingLabel.h>
#include <Swift/QtUI/QtNameWidget.h>
+#include <Swift/QtUI/QtScaledAvatarCache.h>
+#include <Swift/QtUI/QtStatusWidget.h>
#include <Swift/QtUI/Roster/RosterTooltip.h>
-#include "QtScaledAvatarCache.h"
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();
+QtRosterHeader::QtRosterHeader(SettingsProvider* settings, StatusCache* statusCache, QWidget* parent) : QWidget(parent), statusEdit_(nullptr) {
+ 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.svg").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;
+void QtRosterHeader::setContactRosterItem(std::shared_ptr<ContactRosterItem> 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 f9983a2..8370eb5 100644
--- a/Swift/QtUI/QtRosterHeader.h
+++ b/Swift/QtUI/QtRosterHeader.h
@@ -1,64 +1,66 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QWidget>
+#include <string>
+
#include <QLabel>
#include <QPixmap>
#include <QSize>
#include <QToolButton>
+#include <QWidget>
-#include <string>
#include <Swiften/Elements/StatusShow.h>
#include <Swiften/Elements/VCard.h>
+
#include <Swift/Controllers/Roster/ContactRosterItem.h>
-#include "QtTextEdit.h"
+#include <Swift/QtUI/QtTextEdit.h>
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;
+
+ class QtRosterHeader : public QWidget {
+ Q_OBJECT
+ public:
+ QtRosterHeader(SettingsProvider* settings, StatusCache* statusCache, QWidget* parent = nullptr);
+ void setAvatar(const QString& path);
- void setJID(const QString& jid);
- void setNick(const QString& nick);
- void setContactRosterItem(boost::shared_ptr<ContactRosterItem> contact);
+ void setJID(const QString& jid);
+ void setNick(const QString& nick);
+ void setContactRosterItem(std::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();
+ 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_;
- };
+ 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_;
+ std::shared_ptr<ContactRosterItem> contact_;
+ };
}
diff --git a/Swift/QtUI/QtScaledAvatarCache.cpp b/Swift/QtUI/QtScaledAvatarCache.cpp
index ec826dc..37ea6a9 100644
--- a/Swift/QtUI/QtScaledAvatarCache.cpp
+++ b/Swift/QtUI/QtScaledAvatarCache.cpp
@@ -1,61 +1,88 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtScaledAvatarCache.h"
+#include <Swift/QtUI/QtScaledAvatarCache.h>
-#include <QFileInfo>
+#include <QByteArray>
#include <QDir>
-#include <QPixmap>
+#include <QFileInfo>
#include <QImage>
#include <QImageReader>
#include <QPainter>
-#include <QByteArray>
+#include <QPixmap>
#include <Swiften/Base/Log.h>
+
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
+namespace {
+ // This number needs to be incremented whenever the avatar scaling procedure changes.
+ const int QT_SCALED_AVATAR_CACHE_VERSION = 1;
+}
+
QtScaledAvatarCache::QtScaledAvatarCache(int size) : size(size) {
}
+static QPixmap cropToBiggestCenteredSquare(const QPixmap& input) {
+ QPixmap squareCropped;
+ if (input.width() != input.height()) {
+ QRect centeredSquare;
+ if (input.width() > input.height()) {
+ int x = (input.width() - input.height()) / 2;
+ centeredSquare = QRect(x, 0, input.height(), input.height());
+ }
+ else {
+ int y = (input.height() - input.width()) / 2;
+ centeredSquare = QRect(0, y, input.width(), input.width());
+ }
+ squareCropped = input.copy(centeredSquare);
+ }
+ else {
+ squareCropped = input;
+ }
+ return squareCropped;
+}
+
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() && !avatarFile.absolutePath().startsWith(":/")) {
+ QString cacheSubPath = QString("ScaledAvatarCacheV%1/%2").arg(QString::number(QT_SCALED_AVATAR_CACHE_VERSION), QString::number(size));
+ if (!avatarFile.dir().mkpath(cacheSubPath)) {
+ SWIFT_LOG(error) << "avatarFile.dir(): " << Q2PSTRING(avatarFile.dir().absolutePath()) << std::endl;
+ SWIFT_LOG(error) << "Failed creating cache folder: " << Q2PSTRING(cacheSubPath) << std::endl;
+ return path;
+ }
+ QDir targetDir(avatarFile.dir().absoluteFilePath(cacheSubPath));
+ QString targetFile = targetDir.absoluteFilePath(avatarFile.baseName());
+ if (!QFileInfo(targetFile).exists()) {
+ QPixmap avatarPixmap;
+ if (avatarPixmap.load(path)) {
+ QPixmap squaredAvatarPixmap = cropToBiggestCenteredSquare(avatarPixmap);
+ QPixmap maskedAvatar(squaredAvatarPixmap.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, squaredAvatarPixmap);
+ maskPainter.end();
+ if (!maskedAvatar.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation).save(targetFile, "PNG")) {
+ return path;
+ }
+ } else {
+ SWIFT_LOG(warning) << "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 535c5e1..748fb40 100644
--- a/Swift/QtUI/QtScaledAvatarCache.h
+++ b/Swift/QtUI/QtScaledAvatarCache.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,16 +7,17 @@
#pragma once
#include <string>
+
#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 b76a6d5..42ac22d 100644
--- a/Swift/QtUI/QtSettingsProvider.cpp
+++ b/Swift/QtUI/QtSettingsProvider.cpp
@@ -1,13 +1,13 @@
/*
- * Copyright (c) 2010-2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <QtSettingsProvider.h>
+#include <Swift/QtUI/QtSettingsProvider.h>
-#include <QStringList>
#include <QFile>
+#include <QStringList>
namespace Swift {
@@ -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");
+ for (const auto& profileQString : profilesVariant.toStringList()) {
+ profiles.push_back(std::string(profileQString.toUtf8()));
+ }
+ return profiles;
}
void QtSettingsProvider::createProfile(const std::string& profile) {
- QStringList stringList = settings_.value("profileList").toStringList();
- stringList.append(profile.c_str());
- settings_.setValue("profileList", stringList);
- updatePermissions();
+ 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()) + ":");
+ for (auto&& key : settings_.allKeys()) {
+ if (key.startsWith(profileStart)) {
+ settings_.remove(key);
+ }
+ }
+ QStringList stringList = settings_.value("profileList").toStringList();
+ stringList.removeAll(profile.c_str());
+ settings_.setValue("profileList", stringList);
+ updatePermissions();
}
QSettings* QtSettingsProvider::getQSettings() {
- return &settings_;
+ 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 128eefb..21e9211 100644
--- a/Swift/QtUI/QtSettingsProvider.h
+++ b/Swift/QtUI/QtSettingsProvider.h
@@ -1,40 +1,40 @@
/*
- * Copyright (c) 2010-2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swift/Controllers/Settings/SettingsProvider.h>
-
#include <QSettings>
+#include <Swift/Controllers/Settings/SettingsProvider.h>
+
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 0acd081..1fba497 100644
--- a/Swift/QtUI/QtSingleWindow.cpp
+++ b/Swift/QtUI/QtSingleWindow.cpp
@@ -1,15 +1,13 @@
/*
- * Copyright (c) 2010-2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtSingleWindow.h>
-
-#include <Swiften/Base/foreach.h>
-#include <Swift/QtUI/QtSettingsProvider.h>
#include <Swift/QtUI/QtChatTabs.h>
+#include <Swift/QtUI/QtSettingsProvider.h>
namespace Swift {
@@ -17,13 +15,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 +29,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();
+ for (const auto& value : intValues) {
+ variantValues.append(QVariant(value));
+ }
+ settings_->getQSettings()->setValue(SINGLE_WINDOW_SPLITS, QVariant(variantValues));
}
void QtSingleWindow::restoreSplitters() {
- QList<QVariant> variantValues = settings_->getQSettings()->value(SINGLE_WINDOW_SPLITS).toList();
- QList<int> intValues;
- foreach (QVariant value, variantValues) {
- intValues.append(value.toInt());
- }
- setSizes(intValues);
+ QList<QVariant> variantValues = settings_->getQSettings()->value(SINGLE_WINDOW_SPLITS).toList();
+ QList<int> intValues;
+ for (auto&& 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();
+void QtSingleWindow::resizeEvent(QResizeEvent* event) {
+ handleGeometryChanged();
+ QSplitter::resizeEvent(event);
}
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 e9c500a..22f544d 100644
--- a/Swift/QtUI/QtSoundPlayer.cpp
+++ b/Swift/QtUI/QtSoundPlayer.cpp
@@ -1,43 +1,46 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtSoundPlayer.h"
+#include <Swift/QtUI/QtSoundPlayer.h>
-#include <QSound>
#include <iostream>
-#include <SwifTools/Application/ApplicationPathProvider.h>
-#include <QtSwiftUtil.h>
+#include <QSound>
+
#include <Swiften/Base/Path.h>
+#include <SwifTools/Application/ApplicationPathProvider.h>
+
+#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 208af09..8a0b8fe 100644
--- a/Swift/QtUI/QtSoundPlayer.h
+++ b/Swift/QtUI/QtSoundPlayer.h
@@ -1,30 +1,30 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/SoundPlayer.h"
-
#include <QObject>
+#include <Swift/Controllers/SoundPlayer.h>
+
namespace Swift {
- class ApplicationPathProvider;
-
+ class ApplicationPathProvider;
+
- class QtSoundPlayer : public QObject, public SoundPlayer {
- Q_OBJECT
- public:
- QtSoundPlayer(ApplicationPathProvider* applicationPathProvider);
+ class QtSoundPlayer : public QObject, public SoundPlayer {
+ Q_OBJECT
+ public:
+ QtSoundPlayer(ApplicationPathProvider* applicationPathProvider);
- void playSound(SoundEffect sound, const std::string& soundResource);
+ void playSound(SoundEffect sound, const std::string& soundResource);
- private:
- void playSound(const std::string& soundResource);
+ private:
+ void playSound(const std::string& soundResource);
- private:
- ApplicationPathProvider* applicationPathProvider;
- };
+ private:
+ ApplicationPathProvider* applicationPathProvider;
+ };
}
diff --git a/Swift/QtUI/QtSpellCheckHighlighter.cpp b/Swift/QtUI/QtSpellCheckHighlighter.cpp
index 0112d7a..cb467e2 100644
--- a/Swift/QtUI/QtSpellCheckHighlighter.cpp
+++ b/Swift/QtUI/QtSpellCheckHighlighter.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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);
- };
+ for (auto&& 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 f4a43b8..5519a1d 100644
--- a/Swift/QtUI/QtSpellCheckHighlighter.h
+++ b/Swift/QtUI/QtSpellCheckHighlighter.h
@@ -1,15 +1,15 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <SwifTools/SpellParser.h>
-
#include <QSyntaxHighlighter>
+#include <SwifTools/SpellParser.h>
+
class QString;
class QTextDocument;
@@ -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 db2b1e7..a8178c4 100644
--- a/Swift/QtUI/QtSpellCheckerWindow.cpp
+++ b/Swift/QtUI/QtSpellCheckerWindow.cpp
@@ -4,112 +4,95 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "Swift/QtUI/QtSpellCheckerWindow.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
-#include <Swift/Controllers/Settings/SettingsProvider.h>
-#include <Swift/Controllers/SettingConstants.h>
-#include <Swift/QtUI/QtUISettingConstants.h>
-#include <Swift/QtUI/QtSwiftUtil.h>
+#include <Swift/QtUI/QtSpellCheckerWindow.h>
#include <QCoreApplication>
-#include <QFileDialog>
#include <QDir>
+#include <QFileDialog>
#include <QStringList>
#include <QTimer>
+#include <Swiften/Base/Log.h>
+
+#include <Swift/QtUI/QtSwiftUtil.h>
+#include <Swift/QtUI/QtUISettingConstants.h>
+
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()));
+ 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(QtUISettingConstants::SPELL_CHECKER));
+ setEnabled(settings_->getSetting(QtUISettingConstants::SPELL_CHECKER));
}
-void QtSpellCheckerWindow::handleChecker(bool state) {
- setEnabled(state);
+void QtSpellCheckerWindow::setSupportedLanguages(const std::vector<std::string>& languages) {
+ languageItems_.clear();
+ ui_.languageView->clear();
+ for (const auto& shortLang : languages) {
+ auto locale = QLocale(P2QSTRING(shortLang));
+ auto label = QString("%1 ( %2 )").arg(locale.nativeLanguageName(), locale.nativeCountryName());
+
+ QListWidgetItem* item = new QListWidgetItem(label);
+ item->setData(Qt::UserRole, P2QSTRING(shortLang));
+ languageItems_[shortLang] = item;
+ ui_.languageView->addItem(item);
+ }
}
-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);
+void QtSpellCheckerWindow::setActiveLanguage(const std::string& language) {
+ SWIFT_LOG_ASSERT(languageItems_.find(language) != languageItems_.end(), warning) << "Language '" << language << "' is not available." << std::endl;
+ if (languageItems_.find(language) != languageItems_.end()) {
+ languageItems_[language]->setSelected(true);
+ }
}
-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);
+void QtSpellCheckerWindow::setAutomaticallyIdentifiesLanguage(bool isAutomaticallyIdentifying) {
+ ui_.languageView->setHidden(isAutomaticallyIdentifying);
}
-void QtSpellCheckerWindow::handleCancel() {
- this->done(0);
+void QtSpellCheckerWindow::handleChecker(bool state) {
+ setEnabled(state);
}
-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);
- }
+void QtSpellCheckerWindow::setEnabled(bool state) {
+ ui_.language->setEnabled(state);
}
-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));
+void QtSpellCheckerWindow::handleApply() {
+ settings_->storeSetting(QtUISettingConstants::SPELL_CHECKER, ui_.spellChecker->isChecked());
+ QList<QListWidgetItem* > selectedLanguage = ui_.languageView->selectedItems();
+ if (!selectedLanguage.empty()) {
+ settings_->storeSetting(QtUISettingConstants::SPELL_CHECKER_LANGUAGE, Q2PSTRING(selectedLanguage.first()->data(Qt::UserRole).toString()));
+ }
+ this->done(0);
}
-void QtSpellCheckerWindow::showFiles(const QStringList& files) {
- ui_.languageView->clear();
- for (int i = 0; i < files.size(); ++i) {
- ui_.languageView->insertItem(i, files[i]);
- }
+void QtSpellCheckerWindow::handleCancel() {
+ this->done(0);
}
}
diff --git a/Swift/QtUI/QtSpellCheckerWindow.h b/Swift/QtUI/QtSpellCheckerWindow.h
index 7b63318..86ebd40 100644
--- a/Swift/QtUI/QtSpellCheckerWindow.h
+++ b/Swift/QtUI/QtSpellCheckerWindow.h
@@ -4,31 +4,49 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include "ui_QtSpellCheckerWindow.h"
+#include <string>
+#include <unordered_map>
+#include <vector>
#include <QDialog>
+#include <Swift/QtUI/ui_QtSpellCheckerWindow.h>
+
+class QListWidgetItem;
+
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 = nullptr);
+
+ void setSupportedLanguages(const std::vector<std::string>& languages);
+ void setActiveLanguage(const std::string& language);
+ void setAutomaticallyIdentifiesLanguage(bool isAutomaticallyIdentifying);
+
+ public slots:
+ void handleChecker(bool state);
+ void handleCancel();
+ void handleApply();
+
+ private slots:
+ void shrinkWindow();
+
+ private:
+ void setEnabled(bool state);
+ void setFromSettings();
+
+ SettingsProvider* settings_;
+ Ui::QtSpellCheckerWindow ui_;
+ std::unordered_map<std::string, QListWidgetItem*> languageItems_;
+ };
}
diff --git a/Swift/QtUI/QtSpellCheckerWindow.ui b/Swift/QtUI/QtSpellCheckerWindow.ui
index b7f5161..dcb70fa 100644
--- a/Swift/QtUI/QtSpellCheckerWindow.ui
+++ b/Swift/QtUI/QtSpellCheckerWindow.ui
@@ -25,45 +25,6 @@
<widget class="QWidget" name="hunspellOptions" native="true">
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
- <layout class="QHBoxLayout" name="horizontalLayout_2">
- <item>
- <widget class="QLabel" name="pathLabel">
- <property name="text">
- <string>Dictionary Path:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLineEdit" name="pathContent"/>
- </item>
- <item>
- <widget class="QPushButton" name="pathButton">
- <property name="text">
- <string>Change</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout_3">
- <item>
- <widget class="QLabel" name="currentLanguage">
- <property name="text">
- <string>Current Language:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QLabel" name="currentLanguageValue">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QLabel" name="language">
@@ -73,7 +34,11 @@
</widget>
</item>
<item>
- <widget class="QListWidget" name="languageView"/>
+ <widget class="QListWidget" name="languageView">
+ <property name="alternatingRowColors">
+ <bool>true</bool>
+ </property>
+ </widget>
</item>
</layout>
</item>
diff --git a/Swift/QtUI/QtStatusWidget.cpp b/Swift/QtUI/QtStatusWidget.cpp
index bf1b0c9..b175e5c 100644
--- a/Swift/QtUI/QtStatusWidget.cpp
+++ b/Swift/QtUI/QtStatusWidget.cpp
@@ -1,299 +1,302 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtStatusWidget.h"
+#include <Swift/QtUI/QtStatusWidget.h>
#include <algorithm>
-#include <boost/lambda/lambda.hpp>
+
#include <boost/lambda/bind.hpp>
+#include <boost/lambda/lambda.hpp>
+#include <QApplication>
#include <QBoxLayout>
#include <QComboBox>
-#include <QLabel>
-#include <QFrame>
-#include <QPoint>
-#include <QStackedWidget>
-#include <QApplication>
#include <QDesktopWidget>
-#include <qdebug.h>
+#include <QFrame>
+#include <QLabel>
#include <QListWidget>
#include <QListWidgetItem>
#include <QMovie>
+#include <QPoint>
+#include <QStackedWidget>
+
+#include <qdebug.h>
-#include "Swift/QtUI/QtElidingLabel.h"
-#include "Swift/QtUI/QtLineEdit.h"
-#include "Swift/QtUI/QtSwiftUtil.h"
-#include <Swift/Controllers/StatusUtil.h>
#include <Swift/Controllers/StatusCache.h>
+#include <Swift/Controllers/StatusUtil.h>
+
+#include <Swift/QtUI/QtElidingLabel.h>
+#include <Swift/QtUI/QtLineEdit.h>
+#include <Swift/QtUI/QtSwiftUtil.h>
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();
+ for (const auto& type : icons_.keys()) {
+ QListWidgetItem* item = new QListWidgetItem(text == "" ? getNoMessage() : text, menu_);
+ item->setIcon(icons_[type]);
+ item->setToolTip(P2QSTRING(statusShowTypeToFriendlyName(type)) + ": " + item->text());
+ item->setStatusTip(item->toolTip());
+ item->setData(Qt::UserRole, QVariant(type));
+ }
+ std::vector<StatusCache::PreviousStatus> previousStatuses = statusCache_->getMatches(Q2PSTRING(text), 8);
+ for (const auto& savedStatus : previousStatuses) {
+ if (savedStatus.first.empty() || std::find_if(allTypes_.begin(), allTypes_.end(),
+ savedStatus.second == lambda::_1 && savedStatus.first == lambda::bind(&statusShowTypeToFriendlyName, lambda::_1)) != allTypes_.end()) {
+ continue;
+ }
+ QListWidgetItem* item = new QListWidgetItem(P2QSTRING(savedStatus.first), menu_);
+ item->setIcon(icons_[savedStatus.second]);
+ item->setToolTip(item->text());
+ item->setStatusTip(item->toolTip());
+ item->setData(Qt::UserRole, QVariant(savedStatus.second));
+ }
+ for (const auto& type : icons_.keys()) {
+ if (Q2PSTRING(text) == statusShowTypeToFriendlyName(type)) {
+ continue;
+ }
+ QListWidgetItem* item = new QListWidgetItem(P2QSTRING(statusShowTypeToFriendlyName(type)), menu_);
+ item->setIcon(icons_[type]);
+ item->setToolTip(item->text());
+ item->setStatusTip(item->toolTip());
+ item->setData(Qt::UserRole, QVariant(type));
+ }
+ resizeMenu();
}
void QtStatusWidget::resizeMenu() {
- int height = menu_->sizeHintForRow(0) * menu_->count();
- int marginLeft;
- int marginTop;
- int marginRight;
- int marginBottom;
- menu_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom);
- height += marginTop + marginBottom;
-
- menu_->setGeometry(menu_->x(), menu_->y(), menu_->width(), height);
+ 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;
+ }
+ //for (StatusShow::Type type : allTypes_) {
+ // if (statusEdit_->text() == P2QSTRING(statusShowTypeToFriendlyName(type))) {
+ statusEdit_->setText("");
+ // }
+ //}
+ generateList();
+
+ height = menu_->sizeHintForRow(0) * menu_->count();
+ int marginLeft;
+ int marginTop;
+ int marginRight;
+ int marginBottom;
+ menu_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom);
+ height += marginTop + marginBottom;
+ width += marginLeft + marginRight;
+
+ menu_->setGeometry(x, y, width, height);
+ menu_->move(x, y);
+ menu_->setMaximumWidth(width);
+ menu_->show();
+ activateWindow();
+ statusEdit_->selectAll();
+ stack_->setCurrentIndex(1);
+ statusEdit_->setFocus();
+ connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)), Qt::QueuedConnection);
}
void QtStatusWidget::viewMode() {
- disconnect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)));
- editing_ = false;
- menu_->hide();
- 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 edee711..f346868 100644
--- a/Swift/QtUI/QtStatusWidget.h
+++ b/Swift/QtUI/QtStatusWidget.h
@@ -1,16 +1,16 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swiften/Elements/StatusShow.h"
-
-#include <QWidget>
-#include <QMap>
#include <QIcon>
+#include <QMap>
+#include <QWidget>
+
+#include <Swiften/Elements/StatusShow.h>
class QComboBox;
class QLabel;
@@ -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/QtStrings.h b/Swift/QtUI/QtStrings.h
index 586e775..d0cd421 100644
--- a/Swift/QtUI/QtStrings.h
+++ b/Swift/QtUI/QtStrings.h
@@ -16,7 +16,7 @@
QT_TRANSLATE_NOOP("CloseButton", "Close Tab");
-QT_TRANSLATE_NOOP3("QApplication", "QT_LAYOUT_DIRECTION", "Translate this to LTR for left-to-right or RTL for right-to-left languages");
+QT_TRANSLATE_NOOP3("QGuiApplication", "QT_LAYOUT_DIRECTION", "Translate this to LTR for left-to-right or RTL for right-to-left languages");
QT_TRANSLATE_NOOP("QLineEdit", "Select All");
QT_TRANSLATE_NOOP("QLineEdit", "&Undo");
diff --git a/Swift/QtUI/QtSubscriptionRequestWindow.cpp b/Swift/QtUI/QtSubscriptionRequestWindow.cpp
index 2ea7305..c8c4178 100644
--- a/Swift/QtUI/QtSubscriptionRequestWindow.cpp
+++ b/Swift/QtUI/QtSubscriptionRequestWindow.cpp
@@ -1,90 +1,90 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/QtUI/QtSubscriptionRequestWindow.h"
+#include <Swift/QtUI/QtSubscriptionRequestWindow.h>
-#include <QPushButton>
#include <QHBoxLayout>
-#include <QVBoxLayout>
#include <QLabel>
+#include <QPushButton>
+#include <QVBoxLayout>
#include <Swift/QtUI/QtSwiftUtil.h>
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);
+QtSubscriptionRequestWindow::QtSubscriptionRequestWindow(std::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);
- 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;
+QtSubscriptionRequestWindow* QtSubscriptionRequestWindow::getWindow(std::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent) {
+ for (auto 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_;
+std::shared_ptr<SubscriptionRequestEvent> QtSubscriptionRequestWindow::getEvent() {
+ return event_;
}
QList<QtSubscriptionRequestWindow*> QtSubscriptionRequestWindow::windows_;
diff --git a/Swift/QtUI/QtSubscriptionRequestWindow.h b/Swift/QtUI/QtSubscriptionRequestWindow.h
index 5b02991..3f1e816 100644
--- a/Swift/QtUI/QtSubscriptionRequestWindow.h
+++ b/Swift/QtUI/QtSubscriptionRequestWindow.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QDialog>
+#include <memory>
-#include <boost/shared_ptr.hpp>
+#include <QDialog>
-#include "Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h"
+#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(std::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent = nullptr);
+ ~QtSubscriptionRequestWindow();
+ std::shared_ptr<SubscriptionRequestEvent> getEvent();
+ private slots:
+ void handleYes();
+ void handleNo();
+ void handleDefer();
+ private:
+ QtSubscriptionRequestWindow(std::shared_ptr<SubscriptionRequestEvent> event, QWidget* parent = nullptr);
+ static QList<QtSubscriptionRequestWindow*> windows_;
+ std::shared_ptr<SubscriptionRequestEvent> event_;
+ /*QPushButton* yesButton_;
+ QPushButton* noButton_;
+ QPushButton* deferButton_;*/
+ };
}
diff --git a/Swift/QtUI/QtSwift.cpp b/Swift/QtUI/QtSwift.cpp
index 756f530..3f6ce8e 100644
--- a/Swift/QtUI/QtSwift.cpp
+++ b/Swift/QtUI/QtSwift.cpp
@@ -1,54 +1,57 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtSwift.h>
-#include <string>
#include <map>
+#include <string>
#include <boost/bind.hpp>
-#include <QFile>
-#include <QMessageBox>
#include <QApplication>
+#include <QFile>
+#include <QFontDatabase>
#include <QMap>
+#include <QMessageBox>
#include <qdebug.h>
#include <Swiften/Base/Log.h>
#include <Swiften/Base/Path.h>
+#include <Swiften/Base/Paths.h>
#include <Swiften/Base/Platform.h>
-#include <Swiften/Elements/Presence.h>
#include <Swiften/Client/Client.h>
-#include <Swiften/Base/Paths.h>
+#include <Swiften/Elements/Presence.h>
#include <Swiften/TLS/TLSContextFactory.h>
#include <SwifTools/Application/PlatformApplicationPathProvider.h>
#include <SwifTools/AutoUpdater/AutoUpdater.h>
#include <SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.h>
-#include <Swift/Controllers/Storages/CertificateFileStorageFactory.h>
-#include <Swift/Controllers/Storages/FileStoragesFactory.h>
-#include <Swift/Controllers/Settings/XMLSettingsProvider.h>
-#include <Swift/Controllers/Settings/SettingsProviderHierachy.h>
-#include <Swift/Controllers/SettingConstants.h>
-#include <Swift/Controllers/MainController.h>
#include <Swift/Controllers/ApplicationInfo.h>
#include <Swift/Controllers/BuildVersion.h>
+#include <Swift/Controllers/MainController.h>
+#include <Swift/Controllers/SettingConstants.h>
+#include <Swift/Controllers/Settings/SettingsProviderHierachy.h>
+#include <Swift/Controllers/Settings/XMLSettingsProvider.h>
#include <Swift/Controllers/StatusCache.h>
+#include <Swift/Controllers/Storages/CertificateFileStorageFactory.h>
+#include <Swift/Controllers/Storages/FileStoragesFactory.h>
-#include <Swift/QtUI/QtLoginWindow.h>
-#include <Swift/QtUI/QtChatTabsBase.h>
#include <Swift/QtUI/QtChatTabs.h>
+#include <Swift/QtUI/QtChatTabsBase.h>
#include <Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h>
-#include <Swift/QtUI/QtSystemTray.h>
+#include <Swift/QtUI/QtChatWindowFactory.h>
+#include <Swift/QtUI/QtLoginWindow.h>
+#include <Swift/QtUI/QtSingleWindow.h>
#include <Swift/QtUI/QtSoundPlayer.h>
#include <Swift/QtUI/QtSwiftUtil.h>
+#include <Swift/QtUI/QtSystemTray.h>
#include <Swift/QtUI/QtUIFactory.h>
-#include <Swift/QtUI/QtChatWindowFactory.h>
-#include <Swift/QtUI/QtSingleWindow.h>
+#include <Swift/QtUI/QtUISettingConstants.h>
+#include <Swift/QtUI/SwiftUpdateFeeds.h>
#if defined(SWIFTEN_PLATFORM_WINDOWS)
#include <Swift/QtUI/WindowsNotifier.h>
@@ -76,212 +79,275 @@
#include <Swift/QtUI/QtDBUSURIHandler.h>
#endif
-namespace Swift{
-
#if defined(SWIFTEN_PLATFORM_MACOSX)
-//#define SWIFT_APPCAST_URL "http://swift.im/appcast/swift-mac-dev.xml"
-#else
-//#define SWIFT_APPCAST_URL ""
+#include <Swift/QtUI/CocoaUIHelpers.h>
#endif
+namespace Swift{
+
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.")
#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_, "", 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);
+const std::string& QtSwift::updateChannelToFeed(const std::string& channel) {
+ static const std::string invalidChannel;
+ if (channel == UpdateFeeds::StableChannel) {
+ return UpdateFeeds::StableAppcastFeed;
+ }
+ else if (channel == UpdateFeeds::TestingChannel) {
+ return UpdateFeeds::TestingAppcastFeed;
+ }
+ else if (channel == UpdateFeeds::DevelopmentChannel) {
+ return UpdateFeeds::DevelopmentAppcastFeed;
+ }
+ else {
+ return invalidChannel;
+ }
+}
+
+QtSwift::QtSwift(const po::variables_map& options) : networkFactories_(&clientMainThreadCaller_), autoUpdater_(nullptr), 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_ = nullptr;
+ }
+
+ 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);
+ }
+
+ // Load fonts
+ std::vector<std::string> fontNames = {
+ "themes/Default/Lato2OFL/Lato-Black.ttf",
+ "themes/Default/Lato2OFL/Lato-BlackItalic.ttf",
+ "themes/Default/Lato2OFL/Lato-Bold.ttf",
+ "themes/Default/Lato2OFL/Lato-BoldItalic.ttf",
+ "themes/Default/Lato2OFL/Lato-Hairline.ttf",
+ "themes/Default/Lato2OFL/Lato-HairlineItalic.ttf",
+ "themes/Default/Lato2OFL/Lato-Heavy.ttf",
+ "themes/Default/Lato2OFL/Lato-HeavyItalic.ttf",
+ "themes/Default/Lato2OFL/Lato-Italic.ttf",
+ "themes/Default/Lato2OFL/Lato-Light.ttf",
+ "themes/Default/Lato2OFL/Lato-LightItalic.ttf",
+ "themes/Default/Lato2OFL/Lato-Medium.ttf",
+ "themes/Default/Lato2OFL/Lato-MediumItalic.ttf",
+ "themes/Default/Lato2OFL/Lato-Regular.ttf",
+ "themes/Default/Lato2OFL/Lato-Semibold.ttf",
+ "themes/Default/Lato2OFL/Lato-SemiboldItalic.ttf",
+ "themes/Default/Lato2OFL/Lato-Thin.ttf",
+ "themes/Default/Lato2OFL/Lato-ThinItalic.ttf"
+ };
+
+ for (auto&& fontName : fontNames) {
+ std::string fontPath = std::string(":/") + fontName;
+ int error = QFontDatabase::addApplicationFont(P2QSTRING(fontPath));
+ assert((error != -1) && "Failed to load font.");
+ }
+
+ bool enableAdHocCommandOnJID = options.count("enable-jid-adhocs") > 0;
+ tabs_ = nullptr;
+ if (options.count("no-tabs") && !splitter_) {
+ tabs_ = new QtChatTabsShortcutOnlySubstitute();
+ }
+ else {
+ tabs_ = new QtChatTabs(splitter_ != nullptr, settingsHierachy_, true);
+ }
+ 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);
+ }
+
+ connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(handleAboutToQuit()));
+
+ PlatformAutoUpdaterFactory autoUpdaterFactory;
+ if (autoUpdaterFactory.isSupported() && settingsHierachy_->getSetting(QtUISettingConstants::ENABLE_SOFTWARE_UPDATES)
+ && !settingsHierachy_->getSetting(QtUISettingConstants::SOFTWARE_UPDATE_CHANNEL).empty()) {
+ autoUpdater_ = autoUpdaterFactory.createAutoUpdater(updateChannelToFeed(settingsHierachy_->getSetting(QtUISettingConstants::SOFTWARE_UPDATE_CHANNEL)));
+ autoUpdater_->checkForUpdates();
+ autoUpdater_->onSuggestRestartToUserToUpdate.connect(boost::bind(&QtSwift::handleRecommendRestartToInstallUpdate, this));
+
+ settingsHierachy_->onSettingChanged.connect([&](const std::string& path) {
+ if (path == QtUISettingConstants::SOFTWARE_UPDATE_CHANNEL.getKey()) {
+ autoUpdater_->setAppcastFeed(updateChannelToFeed(settingsHierachy_->getSetting(QtUISettingConstants::SOFTWARE_UPDATE_CHANNEL)));
+ 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_;
+ for (auto* factory : uiFactories_) {
+ delete factory;
+ }
+ for (auto* controller : mainControllers_) {
+ delete controller;
+ }
+ delete notifier_;
+ for (auto* 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_;
+}
+
+void QtSwift::handleAboutToQuit() {
+#if defined(SWIFTEN_PLATFORM_MACOSX)
+ // This is required so Sparkle knows about the application shutting down
+ // and can update the application in background.
+ CocoaUIHelpers::sendCocoaApplicationWillTerminateNotification();
+#endif
+}
+
+void QtSwift::handleRecommendRestartToInstallUpdate() {
+ notifier_->showMessage(Notifier::SystemMessage, Q2PSTRING(tr("Swift Update Available")), Q2PSTRING(tr("Restart Swift to update to the new Swift version.")), "", [](){});
}
}
diff --git a/Swift/QtUI/QtSwift.h b/Swift/QtUI/QtSwift.h
index a971324..3ad5714 100644
--- a/Swift/QtUI/QtSwift.h
+++ b/Swift/QtUI/QtSwift.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -30,65 +30,72 @@ 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 slots:
+ void handleAboutToQuit();
+ void handleRecommendRestartToInstallUpdate();
+
+ private:
+ XMLSettingsProvider* loadSettingsFile(const QString& fileName);
+ void loadEmoticonsFile(const QString& fileName, std::map<std::string, std::string>& emoticons);
+ static const std::string& updateChannelToFeed(const std::string& channel);
+
+ 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 f000e6f..d9bfbc3 100644
--- a/Swift/QtUI/QtSystemTray.cpp
+++ b/Swift/QtUI/QtSystemTray.cpp
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma GCC diagnostic ignored "-Wredundant-decls"
-#include "Swift/QtUI/QtSystemTray.h"
+#include <Swift/QtUI/QtSystemTray.h>
#include <QtDebug>
#if defined (Q_OS_UNIX) && !defined(Q_OS_MAC)
@@ -19,72 +19,72 @@
#include <QAction>
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)));
+QtSystemTray::QtSystemTray() : QObject(), statusType_(StatusShow::None), trayMenu_(nullptr), 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)));
#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 df460b2..ba2c5cb 100644
--- a/Swift/QtUI/QtSystemTray.h
+++ b/Swift/QtUI/QtSystemTray.h
@@ -1,50 +1,50 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/SystemTray.h"
-
-#include <QSystemTrayIcon>
#include <QMovie>
+#include <QSystemTrayIcon>
+
+#include <Swift/Controllers/SystemTray.h>
class QIcon;
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 1be3777..67e3ae9 100644
--- a/Swift/QtUI/QtTabWidget.cpp
+++ b/Swift/QtUI/QtTabWidget.cpp
@@ -1,10 +1,16 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtTabWidget.h"
+#include <Swift/QtUI/QtTabWidget.h>
+
+#include <QLabel>
+#include <QPainter>
+#include <QPoint>
+
+#include <Swift/QtUI/Trellis/QtDNDTabBar.h>
namespace Swift {
@@ -17,10 +23,44 @@ QtTabWidget::~QtTabWidget() {
}
QTabBar* QtTabWidget::tabBar() {
- return QTabWidget::tabBar();
+ return QTabWidget::tabBar();
}
void QtTabWidget::setTabBar(QTabBar* tabBar) {
- QTabWidget::setTabBar(tabBar);
+ QTabWidget::setTabBar(tabBar);
+ if (dynamic_cast<QtDNDTabBar*>(tabBar)) {
+ setAcceptDrops(true);
+ }
+ else {
+ setAcceptDrops(false);
+ }
}
+
+void QtTabWidget::dragEnterEvent(QDragEnterEvent* event) {
+ QtDNDTabBar* dndTabBar = dynamic_cast<QtDNDTabBar*>(tabBar());
+ if (dndTabBar) {
+ dndTabBar->dragEnterEvent(event);
+ }
+}
+
+void QtTabWidget::dropEvent(QDropEvent* event) {
+ QtDNDTabBar* dndTabBar = dynamic_cast<QtDNDTabBar*>(tabBar());
+ if (dndTabBar) {
+ dndTabBar->dropEvent(event);
+ }
+}
+
+void QtTabWidget::paintEvent(QPaintEvent * event) {
+ QTabWidget::paintEvent(event);
+ if (count() == 0) {
+ QLabel label;
+ label.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
+ label.setGeometry(QRect(QPoint(0,0), size()) - QMargins(10,10,10,10));
+ label.setWordWrap(true);
+ label.setText(tr("This empty cell is a placeholder for chat windows. You can move existing chats to this cell by dragging the tab over here. You can change the number of cells via the 'Change layout' dialog under the 'View' menu or by using the %1 shortcut.").arg(QKeySequence(tr("Ctrl+Alt+L")).toString(QKeySequence::NativeText)));
+ QPainter painter(this);
+ painter.drawPixmap(label.geometry().topLeft(), label.grab());
+ }
+}
+
}
diff --git a/Swift/QtUI/QtTabWidget.h b/Swift/QtUI/QtTabWidget.h
index 0a723e2..f19721d 100644
--- a/Swift/QtUI/QtTabWidget.h
+++ b/Swift/QtUI/QtTabWidget.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,13 +9,18 @@
#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);
+
+ protected:
+ virtual void dragEnterEvent(QDragEnterEvent* event);
+ virtual void dropEvent(QDropEvent* event);
+ virtual void paintEvent(QPaintEvent* event);
+ };
}
diff --git a/Swift/QtUI/QtTabbable.cpp b/Swift/QtUI/QtTabbable.cpp
index 2a0bbc2..df2cbfe 100644
--- a/Swift/QtUI/QtTabbable.cpp
+++ b/Swift/QtUI/QtTabbable.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -10,7 +10,6 @@
#include <QKeyEvent>
#include <QShortcut>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/Platform.h>
#include <Swift/QtUI/QtChatTabs.h>
@@ -23,47 +22,52 @@ QtTabbable::QtTabbable() : QWidget() {
}
QtTabbable::~QtTabbable() {
- emit windowClosing();
+
}
bool QtTabbable::isWidgetSelected() {
- /*isActiveWindow() shouldn't be necessary, but I don't trust it as far as I can throw it*/
- if (!isActiveWindow()) {
- return false;
- }
- QtChatTabs* parent = qobject_cast<QtChatTabs*>(window());
- return parent ? parent->getCurrentTab() == this : isAncestorOf(QApplication::focusWidget());
+ /*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);
+}
+
+void QtTabbable::closeEvent(QCloseEvent* event) {
+ emit windowClosing();
+ event->accept();
}
}
diff --git a/Swift/QtUI/QtTabbable.h b/Swift/QtUI/QtTabbable.h
index db83ba9..5837702 100644
--- a/Swift/QtUI/QtTabbable.h
+++ b/Swift/QtUI/QtTabbable.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -11,29 +11,32 @@
#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();
- protected:
- QtTabbable();
- bool event(QEvent* event);
+ bool isWidgetSelected();
+ virtual AlertType getWidgetAlertState() {return NoActivity;}
+ virtual int getCount() {return 0;}
+ virtual std::string getID() const = 0;
+ virtual void setEmphasiseFocus(bool /*emphasise*/) {}
- signals:
- void titleUpdated();
- void countUpdated();
- void windowClosing();
- void windowOpening();
- void wantsToActivate();
- void requestPreviousTab();
- void requestNextTab();
- void requestActiveTab();
- void requestFlash();
- };
+ protected:
+ QtTabbable();
+ virtual bool event(QEvent* event);
+ virtual void closeEvent(QCloseEvent* event);
+
+ 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 a0188d9..e9708bf 100644
--- a/Swift/QtUI/QtTextEdit.cpp
+++ b/Swift/QtUI/QtTextEdit.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -12,210 +12,256 @@
#include <QApplication>
#include <QKeyEvent>
+#include <QKeySequence>
#include <QMenu>
-#include <QTime>
#include <QTextDocument>
-#include <Swiften/Base/foreach.h>
-
-#include <Swift/Controllers/SettingConstants.h>
+#include <Swiften/Base/Log.h>
#include <SwifTools/SpellChecker.h>
#include <SwifTools/SpellCheckerFactory.h>
#include <Swift/QtUI/QtSpellCheckerWindow.h>
#include <Swift/QtUI/QtSwiftUtil.h>
+#include <Swift/QtUI/QtUISettingConstants.h>
#include <Swift/QtUI/QtUtilities.h>
namespace Swift {
-QtTextEdit::QtTextEdit(SettingsProvider* settings, QWidget* parent) : QTextEdit(parent), checker_(NULL), highlighter_(NULL) {
- connect(this, SIGNAL(textChanged()), this, SLOT(handleTextChanged()));
- settings_ = settings;
+QtTextEdit::QtTextEdit(SettingsProvider* settings, QWidget* parent) : QTextEdit(parent), checker_(nullptr), highlighter_(nullptr) {
+ 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)
+ || (event->matches(QKeySequence::ZoomIn))
+ || (event->matches(QKeySequence::ZoomOut))
+ ) {
+ 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::setEmphasiseFocus(bool emphasise) {
+ emphasiseFocus_ = emphasise;
+ updateStyleSheet();
+}
+
+void QtTextEdit::setCorrectionHighlight(bool correctionHighlight) {
+ correctionHighlight_ = correctionHighlight;
+ updateStyleSheet();
+}
+
+void QtTextEdit::updateStyleSheet() {
+ QString newStyleSheet;
+
+ if (correctionHighlight_) {
+ newStyleSheet += "background: rgb(255, 255, 153); color: black;";
+ }
+
+ if (emphasiseFocus_) {
+ if (hasFocus()) {
+ newStyleSheet += "border: 2px solid palette(highlight);";
+ }
+ }
+
+ setStyleSheet(newStyleSheet);
+ handleTextChanged();
}
void QtTextEdit::focusInEvent(QFocusEvent* event) {
- receivedFocus();
- QTextEdit::focusInEvent(event);
+ receivedFocus();
+ QTextEdit::focusInEvent(event);
+ updateStyleSheet();
}
void QtTextEdit::focusOutEvent(QFocusEvent* event) {
- lostFocus();
- QTextEdit::focusOutEvent(event);
+ lostFocus();
+ QTextEdit::focusOutEvent(event);
+ updateStyleSheet();
}
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 (auto& misspelledPosition : misspelledPositions) {
+ if (cursorPosition >= boost::get<0>(misspelledPosition) && cursorPosition <= boost::get<1>(misspelledPosition)) {
+ return misspelledPosition;
+ }
+ }
+ 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 (auto& replaceWordAction : replaceWordActions_) {
+ if (replaceWordAction == result) {
+ replaceMisspelledWord(replaceWordAction->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 (auto& word : wordList) {
+ QAction* wordAction = new QAction(word.c_str(), menu);
+ menu->insertAction(insertPoint, wordAction);
+ replaceWordActions_.push_back(wordAction);
+ }
+ }
+ menu->insertAction(insertPoint, menu->addSeparator());
+ }
}
#ifdef HAVE_SPELLCHECKER
-void QtTextEdit::setUpSpellChecker()
-{
- 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);
- delete highlighter_;
- highlighter_ = NULL;
- highlighter_ = new QtSpellCheckHighlighter(document(), checker_);
- }
+void QtTextEdit::setUpSpellChecker() {
+ delete highlighter_;
+ highlighter_ = nullptr;
+ delete checker_;
+ checker_ = nullptr;
+ if (settings_->getSetting(QtUISettingConstants::SPELL_CHECKER)) {
+ checker_ = SpellCheckerFactory().createSpellChecker();
+ if (checker_) {
+ if (!checker_->isAutomaticallyDetectingLanguage()) {
+ checker_->setActiveLanguage(settings_->getSetting(QtUISettingConstants::SPELL_CHECKER_LANGUAGE));
+ }
+ 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(QtUISettingConstants::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();
+ }
+ if (checker_) {
+ spellCheckerWindow_->setAutomaticallyIdentifiesLanguage(checker_->isAutomaticallyDetectingLanguage());
+ if (!checker_->isAutomaticallyDetectingLanguage()) {
+ spellCheckerWindow_->setSupportedLanguages(checker_->supportedLanguages());
+ spellCheckerWindow_->setActiveLanguage(checker_->activeLanguage());
+ }
+ }
}
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 == QtUISettingConstants::SPELL_CHECKER.getKey() ||
+ settings == QtUISettingConstants::SPELL_CHECKER_LANGUAGE.getKey()) {
#ifdef HAVE_SPELLCHECKER
- setUpSpellChecker();
- highlighter_->rehighlight();
+ setUpSpellChecker();
+ if (highlighter_) {
+ highlighter_->rehighlight();
+ }
#endif
- }
+ }
}
}
diff --git a/Swift/QtUI/QtTextEdit.h b/Swift/QtUI/QtTextEdit.h
index 67826ba..228aa9e 100644
--- a/Swift/QtUI/QtTextEdit.h
+++ b/Swift/QtUI/QtTextEdit.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,7 +9,6 @@
#include <QPointer>
#include <QTextEdit>
-#include <Swift/Controllers/SettingConstants.h>
#include <Swift/Controllers/Settings/SettingsProvider.h>
#include <SwifTools/SpellParser.h>
@@ -17,47 +16,53 @@
#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 = nullptr);
+ virtual ~QtTextEdit();
+ virtual QSize sizeHint() const;
+
+ void setEmphasiseFocus(bool emphasise);
+ void setCorrectionHighlight(bool coorectionHighlight);
+
+ 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);
+ void updateStyleSheet();
+
+ private:
+ SpellChecker* checker_;
+ QtSpellCheckHighlighter* highlighter_;
+ std::vector<QAction*> replaceWordActions_;
+ SettingsProvider* settings_;
+ QPointer<QtSpellCheckerWindow> spellCheckerWindow_;
+ bool emphasiseFocus_ = false;
+ bool correctionHighlight_ = false;
+ };
}
diff --git a/Swift/QtUI/QtTranslator.h b/Swift/QtUI/QtTranslator.h
index b74ea3e..92abf77 100644
--- a/Swift/QtUI/QtTranslator.h
+++ b/Swift/QtUI/QtTranslator.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,19 +7,31 @@
#pragma once
#include <QCoreApplication>
+#include <QDateTime>
#include <Swift/Controllers/Translator.h>
+#include <Swift/QtUI/QtSwiftUtil.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(), nullptr).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
- }
+ }
+
+ virtual std::string ptimeToHumanReadableString(const boost::posix_time::ptime& time) {
+ return Q2PSTRING(QDateTime::fromTime_t(posixTimeToTimeT(time)).toString(Qt::SystemLocaleLongDate));
+ }
+
+ private:
+ static std::time_t posixTimeToTimeT(boost::posix_time::ptime pt) {
+ return std::time_t((pt - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_seconds());
+ }
};
diff --git a/Swift/QtUI/QtUIFactory.cpp b/Swift/QtUI/QtUIFactory.cpp
index 8dece86..9eed822 100644
--- a/Swift/QtUI/QtUIFactory.cpp
+++ b/Swift/QtUI/QtUIFactory.cpp
@@ -1,185 +1,191 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtUIFactory.h>
+#include <algorithm>
+
#include <QSplitter>
-#include <Swift/QtUI/QtXMLConsoleWidget.h>
+#include <Swiften/Whiteboard/WhiteboardSession.h>
+
+#include <Swift/Controllers/Settings/SettingsProviderHierachy.h>
+
+#include <Swift/QtUI/MUCSearch/QtMUCSearchWindow.h>
+#include <Swift/QtUI/QtAdHocCommandWindow.h>
+#include <Swift/QtUI/QtBlockListEditorWindow.h>
#include <Swift/QtUI/QtChatTabs.h>
#include <Swift/QtUI/QtChatTabsBase.h>
-#include <Swift/QtUI/QtMainWindow.h>
-#include <Swift/QtUI/QtLoginWindow.h>
-#include <Swift/QtUI/QtSystemTray.h>
-#include <Swift/QtUI/QtSettingsProvider.h>
-#include <Swift/QtUI/QtMainWindow.h>
#include <Swift/QtUI/QtChatWindow.h>
-#include <Swift/QtUI/QtJoinMUCWindow.h>
#include <Swift/QtUI/QtChatWindowFactory.h>
-#include <Swift/QtUI/QtSwiftUtil.h>
-#include <Swift/QtUI/MUCSearch/QtMUCSearchWindow.h>
-#include <Swift/QtUI/UserSearch/QtUserSearchWindow.h>
-#include <Swift/QtUI/QtProfileWindow.h>
#include <Swift/QtUI/QtContactEditWindow.h>
-#include <Swift/QtUI/QtAdHocCommandWindow.h>
#include <Swift/QtUI/QtFileTransferListWidget.h>
#include <Swift/QtUI/QtHighlightEditor.h>
-#include <Swift/QtUI/Whiteboard/QtWhiteboardWindow.h>
-#include <Swift/Controllers/Settings/SettingsProviderHierachy.h>
-#include <Swift/QtUI/QtUISettingConstants.h>
#include <Swift/QtUI/QtHistoryWindow.h>
-#include <Swiften/Whiteboard/WhiteboardSession.h>
+#include <Swift/QtUI/QtJoinMUCWindow.h>
+#include <Swift/QtUI/QtLoginWindow.h>
+#include <Swift/QtUI/QtMainWindow.h>
+#include <Swift/QtUI/QtProfileWindow.h>
+#include <Swift/QtUI/QtSettingsProvider.h>
#include <Swift/QtUI/QtSingleWindow.h>
-#include <Swift/QtUI/QtBlockListEditorWindow.h>
+#include <Swift/QtUI/QtSwiftUtil.h>
+#include <Swift/QtUI/QtSystemTray.h>
+#include <Swift/QtUI/QtUISettingConstants.h>
+#include <Swift/QtUI/QtXMLConsoleWidget.h>
+#include <Swift/QtUI/UserSearch/QtUserSearchWindow.h>
+#include <Swift/QtUI/Whiteboard/QtWhiteboardWindow.h>
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);
+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(nullptr), loginWindow(nullptr), 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);
}
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));
+
+ // remove already closed and thereby deleted chat windows
+ chatWindows.erase(std::remove_if(chatWindows.begin(), chatWindows.end(),
+ [](QPointer<QtChatWindow>& window) {
+ return window.isNull();
+ }), chatWindows.end());
+
+ chatWindows.push_back(window);
+
+ 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);
+
+ // resize font in other chat windows
+ for (auto&& existingWindow : chatWindows) {
+ if (!existingWindow.isNull()) {
+ existingWindow->handleFontResized(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);
+WhiteboardWindow* QtUIFactory::createWhiteboardWindow(std::shared_ptr<WhiteboardSession> 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);
+AdHocCommandWindow* QtUIFactory::createAdHocCommandWindow(std::shared_ptr<OutgoingAdHocCommandSession> 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..ce3b533 100644
--- a/Swift/QtUI/QtUIFactory.h
+++ b/Swift/QtUI/QtUIFactory.h
@@ -1,11 +1,13 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <vector>
+
#include <QObject>
#include <QPointer>
@@ -14,70 +16,69 @@
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 QtChatTabs;
+ class QtChatTabsBase;
+ class QtChatTheme;
+ class QtChatWindow;
+ class QtChatWindowFactory;
+ class QtLoginWindow;
+ class QtMainWindow;
+ class QtSettingsProvider;
+ class QtSingleWindow;
+ class QtSystemTray;
+ class SettingsProviderHierachy;
+ class StatusCache;
+ class TimerFactory;
+ class WhiteboardSession;
- 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(std::shared_ptr<WhiteboardSession> whiteboardSession);
+ virtual HighlightEditorWindow* createHighlightEditorWindow();
+ virtual BlockListEditorWidget* createBlockListEditorWidget();
+ virtual AdHocCommandWindow* createAdHocCommandWindow(std::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.cpp b/Swift/QtUI/QtUISettingConstants.cpp
index 812e3eb..24cc6dc 100644
--- a/Swift/QtUI/QtUISettingConstants.cpp
+++ b/Swift/QtUI/QtUISettingConstants.cpp
@@ -1,11 +1,13 @@
/*
- * Copyright (c) 2012-2013 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtUISettingConstants.h>
+#include <Swift/QtUI/SwiftUpdateFeeds.h>
+
namespace Swift {
const SettingsProvider::Setting<bool> QtUISettingConstants::COMPACT_ROSTER("compactRoster", false);
@@ -17,4 +19,11 @@ const SettingsProvider::Setting<int> QtUISettingConstants::HISTORYWINDOW_FONT_SI
const SettingsProvider::Setting<bool> QtUISettingConstants::SHOW_EMOTICONS("showEmoticons", true);
const SettingsProvider::Setting<bool> QtUISettingConstants::USE_PLAIN_CHATS("plainChats", false);
const SettingsProvider::Setting<bool> QtUISettingConstants::USE_SCREENREADER("screenreader", false);
+const SettingsProvider::Setting<bool> QtUISettingConstants::SPELL_CHECKER("spellChecker", false);
+const SettingsProvider::Setting<std::string> QtUISettingConstants::SPELL_CHECKER_LANGUAGE("spellCheckerLanguage", "en_US");
+const SettingsProvider::Setting<std::string> QtUISettingConstants::TRELLIS_GRID_SIZE("trellisGridSize", "");
+const SettingsProvider::Setting<std::string> QtUISettingConstants::TRELLIS_GRID_POSITIONS("trellisGridPositions", "");
+const SettingsProvider::Setting<bool> QtUISettingConstants::ENABLE_SOFTWARE_UPDATES("enableSoftwareUpdates", true);
+const SettingsProvider::Setting<std::string> QtUISettingConstants::SOFTWARE_UPDATE_CHANNEL("softwareUpdateChannel", UpdateFeeds::StableChannel);
+
}
diff --git a/Swift/QtUI/QtUISettingConstants.h b/Swift/QtUI/QtUISettingConstants.h
index 4c17c0d..a569587 100644
--- a/Swift/QtUI/QtUISettingConstants.h
+++ b/Swift/QtUI/QtUISettingConstants.h
@@ -1,24 +1,53 @@
/*
- * Copyright (c) 2012-2013 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#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;
+ static const SettingsProvider::Setting<bool> SPELL_CHECKER;
+ static const SettingsProvider::Setting<std::string> SPELL_CHECKER_LANGUAGE;
+ /**
+ * 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 #ENABLE_SOFTWARE_UPDATES setting specifies, whether Swift
+ * should automatically check for software updates in regular
+ * intervals and install them automatically.
+ */
+ static const SettingsProvider::Setting<bool> ENABLE_SOFTWARE_UPDATES;
+ /**
+ * The #SOFTWARE_UPDATE_CHANNEL setting defines what update channel
+ * Swift uses to check for, and receive, updates.
+ */
+ static const SettingsProvider::Setting<std::string> SOFTWARE_UPDATE_CHANNEL;
+ };
}
diff --git a/Swift/QtUI/QtURIHandler.cpp b/Swift/QtUI/QtURIHandler.cpp
index 5ab2aa9..24bd328 100644
--- a/Swift/QtUI/QtURIHandler.cpp
+++ b/Swift/QtUI/QtURIHandler.cpp
@@ -1,30 +1,30 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtURIHandler.h"
+#include <Swift/QtUI/QtURIHandler.h>
#include <QCoreApplication>
#include <QFileOpenEvent>
#include <QUrl>
-#include "QtSwiftUtil.h"
+#include <Swift/QtUI/QtSwiftUtil.h>
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 43aa737..309e55b 100644
--- a/Swift/QtUI/QtURIHandler.h
+++ b/Swift/QtUI/QtURIHandler.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,16 +7,17 @@
#pragma once
#include <QObject>
+
#include <SwifTools/URIHandler/URIHandler.h>
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 4b8e555..8017710 100644
--- a/Swift/QtUI/QtURLValidator.cpp
+++ b/Swift/QtUI/QtURLValidator.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,6 +7,7 @@
#include <Swift/QtUI/QtURLValidator.h>
#include <Swiften/Base/URL.h>
+
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
@@ -15,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/QtUpdateFeedSelectionDialog.cpp b/Swift/QtUI/QtUpdateFeedSelectionDialog.cpp
new file mode 100644
index 0000000..1f4058a
--- /dev/null
+++ b/Swift/QtUI/QtUpdateFeedSelectionDialog.cpp
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/QtUpdateFeedSelectionDialog.h>
+
+#include <QComboBox>
+
+#include <Swift/Controllers/Settings/SettingsProvider.h>
+
+#include <Swift/QtUI/QtUISettingConstants.h>
+#include <Swift/QtUI/SwiftUpdateFeeds.h>
+
+namespace Swift {
+
+QtUpdateFeedSelectionDialog::QtUpdateFeedSelectionDialog(SettingsProvider* settingsProvider) : QDialog(), settings_(settingsProvider) {
+ ui.setupUi(this);
+
+ connect(ui.currentChannelComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), [&] (int newIndex) {
+ setDescriptionForIndex(newIndex);
+ });
+
+ auto updateChannel = settings_->getSetting(QtUISettingConstants::SOFTWARE_UPDATE_CHANNEL);
+ if (updateChannel == UpdateFeeds::StableChannel) {
+ ui.currentChannelComboBox->setCurrentIndex(0);
+ }
+ else if (updateChannel == UpdateFeeds::TestingChannel) {
+ ui.currentChannelComboBox->setCurrentIndex(1);
+ }
+ else if (updateChannel == UpdateFeeds::DevelopmentChannel) {
+ ui.currentChannelComboBox->setCurrentIndex(2);
+ }
+
+ connect(this, &QDialog::accepted, [&]() {
+ auto newUpdateChannel = std::string("");
+ switch (ui.currentChannelComboBox->currentIndex()) {
+ case 0:
+ newUpdateChannel = UpdateFeeds::StableChannel;
+ break;
+ case 1:
+ newUpdateChannel = UpdateFeeds::TestingChannel;
+ break;
+ case 2:
+ newUpdateChannel = UpdateFeeds::DevelopmentChannel;
+ break;
+ }
+ settings_->storeSetting(QtUISettingConstants::SOFTWARE_UPDATE_CHANNEL, newUpdateChannel);
+ });
+
+ setAttribute(Qt::WA_DeleteOnClose);
+}
+
+void QtUpdateFeedSelectionDialog::setDescriptionForIndex(int index) {
+ switch (index) {
+ case 0:
+ ui.stableDescriptionLabel->show();
+ ui.testingDescriptionLabel->hide();
+ ui.developmentDescriptionLabel->hide();
+ break;
+ case 1:
+ ui.stableDescriptionLabel->hide();
+ ui.testingDescriptionLabel->show();
+ ui.developmentDescriptionLabel->hide();
+ break;
+ case 2:
+ ui.stableDescriptionLabel->hide();
+ ui.testingDescriptionLabel->hide();
+ ui.developmentDescriptionLabel->show();
+ break;
+ default:
+ ui.stableDescriptionLabel->hide();
+ ui.testingDescriptionLabel->hide();
+ ui.developmentDescriptionLabel->hide();
+ break;
+ }
+ setFixedSize(sizeHint());
+}
+
+
+
+}
diff --git a/Swift/QtUI/QtUpdateFeedSelectionDialog.h b/Swift/QtUI/QtUpdateFeedSelectionDialog.h
new file mode 100644
index 0000000..80b986f
--- /dev/null
+++ b/Swift/QtUI/QtUpdateFeedSelectionDialog.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#pragma once
+
+#include <QDialog>
+
+#include <Swift/QtUI/ui_QtUpdateFeedSelectionDialog.h>
+
+namespace Swift {
+
+class SettingsProvider;
+
+class QtUpdateFeedSelectionDialog : public QDialog {
+ Q_OBJECT
+ public:
+ QtUpdateFeedSelectionDialog(SettingsProvider* settingsProvider);
+
+ private:
+ void setDescriptionForIndex(int index);
+
+ private:
+ Ui::QtUpdateFeedSelectionDialog ui;
+ SettingsProvider* settings_ = nullptr;
+};
+
+}
diff --git a/Swift/QtUI/QtUpdateFeedSelectionDialog.ui b/Swift/QtUI/QtUpdateFeedSelectionDialog.ui
new file mode 100644
index 0000000..2eac1f1
--- /dev/null
+++ b/Swift/QtUI/QtUpdateFeedSelectionDialog.ui
@@ -0,0 +1,146 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>QtUpdateFeedSelectionDialog</class>
+ <widget class="QDialog" name="QtUpdateFeedSelectionDialog">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>335</width>
+ <height>158</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Select Update Channel</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QComboBox" name="currentChannelComboBox">
+ <property name="currentText">
+ <string/>
+ </property>
+ <property name="currentIndex">
+ <number>-1</number>
+ </property>
+ <item>
+ <property name="text">
+ <string>Stable Channel</string>
+ </property>
+ <property name="icon">
+ <iconset theme=":/icons/delivery-success.svg"/>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>Testing Channel</string>
+ </property>
+ <property name="icon">
+ <iconset theme=":/icons/delivery-warning.svg"/>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>Development Channel</string>
+ </property>
+ <property name="icon">
+ <iconset theme=":/icons/delivery-warning.svg"/>
+ </property>
+ </item>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="stableDescriptionLabel">
+ <property name="text">
+ <string>This release channel includes our stable releases. They went throught internal QA testing and had previous RC releases to find critical bugs.</string>
+ </property>
+ <property name="textFormat">
+ <enum>Qt::PlainText</enum>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignJustify|Qt::AlignTop</set>
+ </property>
+ <property name="wordWrap">
+ <bool>true</bool>
+ </property>
+ <property name="textInteractionFlags">
+ <set>Qt::NoTextInteraction</set>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="testingDescriptionLabel">
+ <property name="enabled">
+ <bool>true</bool>
+ </property>
+ <property name="text">
+ <string>This release channel includes our stable releases, beta releases and release candidates. They should be free from obvious bugs and are released for wider testing to find more obscure bugs.</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignJustify|Qt::AlignTop</set>
+ </property>
+ <property name="wordWrap">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="developmentDescriptionLabel">
+ <property name="text">
+ <string>This release channel includes our stable releases, beta releases, release candidates and development releases. The development releases are not thoroughly tested and might contain bugs.</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignJustify|Qt::AlignTop</set>
+ </property>
+ <property name="wordWrap">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="standardButtons">
+ <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>QtUpdateFeedSelectionDialog</receiver>
+ <slot>accept()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>248</x>
+ <y>254</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>157</x>
+ <y>274</y>
+ </hint>
+ </hints>
+ </connection>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>rejected()</signal>
+ <receiver>QtUpdateFeedSelectionDialog</receiver>
+ <slot>reject()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>316</x>
+ <y>260</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>286</x>
+ <y>274</y>
+ </hint>
+ </hints>
+ </connection>
+ </connections>
+</ui>
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 ebd62bc..da4f22f 100644
--- a/Swift/QtUI/QtVCardWidget/QtCloseButton.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtCloseButton.cpp
@@ -4,7 +4,13 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "QtCloseButton.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/QtVCardWidget/QtCloseButton.h>
#include <QMouseEvent>
#include <QPainter>
@@ -18,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, nullptr, nullptr), style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, nullptr, nullptr));
}
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..0c6e192 100644
--- a/Swift/QtUI/QtVCardWidget/QtCloseButton.h
+++ b/Swift/QtUI/QtVCardWidget/QtCloseButton.h
@@ -4,21 +4,27 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <QAbstractButton>
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 = nullptr);
+ 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 10237ce..079f77d 100644
--- a/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp
@@ -5,16 +5,18 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtRemovableItemDelegate.h"
-#include <Swiften/Base/Platform.h>
+#include <Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h>
+
#include <QEvent>
#include <QPainter>
+#include <Swiften/Base/Platform.h>
+
namespace Swift {
QtRemovableItemDelegate::QtRemovableItemDelegate(const QStyle* style) : style(style) {
@@ -22,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, nullptr, nullptr);
+ 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 nullptr;
}
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, nullptr, nullptr) + 2, style->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, nullptr, nullptr) + 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 f60f9a8..9eef970 100644
--- a/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp
@@ -5,54 +5,54 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtResizableLineEdit.h"
+#include <Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h>
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..eab5b2b 100644
--- a/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h
+++ b/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h
@@ -4,30 +4,36 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <QLineEdit>
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 = nullptr);
+ ~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 33863b2..02ceb0a 100644
--- a/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp
@@ -5,12 +5,12 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtTagComboBox.h"
+#include <Swift/QtUI/QtVCardWidget/QtTagComboBox.h>
#include <QAbstractItemView>
#include <QtGui>
@@ -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();
+ for (auto action : tagActions) {
+ if (action->data() == id) {
+ action->setChecked(value);
+ updateDisplayItem();
+ return;
+ }
+ }
}
bool QtTagComboBox::isTagSet(const QString &id) const {
- QList<QAction*> tagActions = editMenu->actions();
- foreach(QAction* action, tagActions) {
- if (action->data() == id) {
- return action->isChecked();
- }
- }
- return false;
+ QList<QAction*> tagActions = editMenu->actions();
+ for (auto 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 = "";
+ for (auto 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..e9dbbdd 100644
--- a/Swift/QtUI/QtVCardWidget/QtTagComboBox.h
+++ b/Swift/QtUI/QtVCardWidget/QtTagComboBox.h
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <QComboBox>
@@ -14,33 +20,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 = nullptr);
+ ~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..596006a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(nullptr), poboxLineEdit(nullptr), addressextLineEdit(nullptr), cityLineEdit(nullptr), pocodeLineEdit(nullptr), regionLineEdit(nullptr), countryLineEdit(nullptr), textFieldGridLayout(nullptr), textFieldGridLayoutItem(nullptr), deliveryTypeLabel(nullptr), domesticRadioButton(nullptr), internationalRadioButton(nullptr), buttonGroup(nullptr) {
+ 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);
+ for (auto widget : textFields) {
+ widget->hide();
+ textFieldGridLayout->removeWidget(widget);
+ }
+ getGridLayout()->removeItem(textFieldGridLayoutItem);
}
bool QtVCardAddressField::isEmpty() const {
- return streetLineEdit->text().isEmpty() &&
- poboxLineEdit->text().isEmpty() &&
- addressextLineEdit->text().isEmpty() &&
- cityLineEdit->text().isEmpty() &&
- pocodeLineEdit->text().isEmpty() &&
- regionLineEdit->text().isEmpty() &&
- countryLineEdit->text().isEmpty();
+ 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() == nullptr ? "" : buttonGroup->checkedButton()->text());
+ deliveryTypeLabel->setVisible(!isEditable);
+
+ domesticRadioButton->setVisible(isEditable);
+ internationalRadioButton->setVisible(isEditable);
+
+ for (auto widget : textFields) {
+ QtResizableLineEdit* lineEdit;
+ if ((lineEdit = dynamic_cast<QtResizableLineEdit*>(widget))) {
+ lineEdit->setVisible(isEditable ? true : !lineEdit->text().isEmpty());
+ lineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }");
+ }
+ }
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h
index 8cbee18..aeebbff 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -27,42 +27,42 @@ namespace Swift {
class QtElidingLabel;
class QtVCardAddressField : public QtVCardGeneralField, public QtVCardHomeWork {
- Q_OBJECT
-
- public:
- GENERIC_QT_VCARD_FIELD_INFO("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 = nullptr, QGridLayout* layout = nullptr, 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..e4a75cd 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(nullptr), deliveryTypeLabel(nullptr), domesticRadioButton(nullptr), internationalRadioButton(nullptr), buttonGroup(nullptr) {
+ 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() == nullptr ? "" : 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 7d9893b..ceca88a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -27,32 +27,32 @@ namespace Swift {
class QtElidingLabel;
class QtVCardAddressLabelField : public QtVCardGeneralField, public QtVCardHomeWork {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO("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 = nullptr, QGridLayout* layout = nullptr, 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 7b0d02e..1111295 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp
@@ -4,58 +4,65 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "QtVCardBirthdayField.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h>
+
+#include <boost/algorithm/string.hpp>
#include <QGridLayout>
#include <QHBoxLayout>
-#include <boost/algorithm/string.hpp>
#include <Swift/QtUI/QtSwiftUtil.h>
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(nullptr), birthdayDateEdit(nullptr) {
+ 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 4be6e27..0383b6c 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h
@@ -4,40 +4,47 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <QDateEdit>
+
#include <Swiften/Elements/VCard.h>
-#include "QtCloseButton.h"
-#include "QtVCardFieldInfo.h"
-#include "QtVCardGeneralField.h"
+#include <Swift/QtUI/QtVCardWidget/QtCloseButton.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h>
namespace Swift {
class QtVCardBirthdayField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO("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 = nullptr, QGridLayout* layout = nullptr, 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 183e64d..2a8e1c9 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp
@@ -4,9 +4,16 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "QtVCardDescriptionField.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h>
#include <boost/algorithm/string.hpp>
+
#include <QFontMetrics>
#include <QGridLayout>
@@ -15,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(nullptr) {
+ 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 3b1b3d9..c06dd97 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h
@@ -4,39 +4,45 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#pragma once
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
-#include <Swiften/Elements/VCard.h>
+#pragma once
#include <QPlainTextEdit>
-#include "QtVCardFieldInfo.h"
-#include "QtVCardGeneralField.h"
+#include <Swiften/Elements/VCard.h>
+
+#include <Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h>
namespace Swift {
class QtVCardDescriptionField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO("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 = nullptr, QGridLayout* layout = nullptr, 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 168c01b..093357a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h
@@ -4,49 +4,55 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
+#include <typeinfo>
+
#include <QGridLayout>
#include <QObject>
#include <QString>
-#include <typeinfo>
-
#define GENERIC_QT_VCARD_FIELD_INFO(MENU_NAME, ALLOWED_INSTANCES, FIELD_CLASS) \
- class FieldInfo : public QtVCardFieldInfo { \
- public: \
- virtual ~FieldInfo() { \
- } \
- \
- virtual QString getMenuName() const { \
- return QObject::tr(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..9bb6a35 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(nullptr), label(nullptr), labelText(label),
+ tagComboBox(nullptr), tagLabel(nullptr), closeButton(nullptr) {
}
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();
+ for (auto widget : childWidgets) {
+ widget->hide();
+ layout->removeWidget(widget);
+ }
+ deleteField(this);
}
void QtVCardGeneralField::handlePreferredStarStateChanged(int state) {
- if (state == Qt::Checked) {
- QToolTip::showText(QCursor::pos(), tr("Marked as your preferred %1. Click again to undo.").arg(labelText));
- }
+ 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..48ecf9f 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 = nullptr, QGridLayout* layout = nullptr, 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 3119a80..7f204ca 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp
@@ -4,36 +4,42 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "QtVCardHomeWork.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h>
namespace Swift {
-QtVCardHomeWork::QtVCardHomeWork() : tagComboBox(0) {
+QtVCardHomeWork::QtVCardHomeWork() : tagComboBox(nullptr) {
}
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 768d984..dd1452a 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h
@@ -4,28 +4,34 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <QObject>
-#include "QtTagComboBox.h"
+#include <Swift/QtUI/QtVCardWidget/QtTagComboBox.h>
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 bae9771..9deb7ba 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp
@@ -4,11 +4,18 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "QtVCardInternetEMailField.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QTextDocument>
+
#include <Swiften/Base/Log.h>
#include <Swift/QtUI/QtSwiftUtil.h>
@@ -17,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(nullptr), emailLabel(nullptr) {
+ 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 3f8a27f..07f4f8d 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h
@@ -4,40 +4,46 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Elements/VCard.h>
-#include "QtResizableLineEdit.h"
-#include "QtVCardFieldInfo.h"
-#include "QtVCardGeneralField.h"
-#include "QtVCardHomeWork.h"
+#include <Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h>
namespace Swift {
class QtVCardInternetEMailField : public QtVCardGeneralField, public QtVCardHomeWork {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO("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 = nullptr, QGridLayout* layout = nullptr, 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 28a4438..f93ea06 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp
@@ -4,11 +4,18 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "QtVCardJIDField.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/QtVCardWidget/QtVCardJIDField.h>
+
+#include <boost/algorithm/string.hpp>
#include <QGridLayout>
#include <QTextDocument>
-#include <boost/algorithm/string.hpp>
#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/QtUtilities.h>
@@ -16,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(nullptr), jidLineEdit(nullptr) {
+ 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 016bcf8..f2df9f9 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardJIDField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardJIDField.h
@@ -4,39 +4,45 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Elements/VCard.h>
-#include "QtResizableLineEdit.h"
-#include "QtVCardFieldInfo.h"
-#include "QtVCardGeneralField.h"
+#include <Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h>
namespace Swift {
class QtVCardJIDField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO("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 = nullptr, QGridLayout* layout = nullptr, 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..5162c73 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h>
#include <boost/algorithm/string.hpp>
@@ -17,129 +23,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(nullptr), organizationLineEdit(nullptr), unitsTreeWidget(nullptr), itemDelegate(nullptr) {
+ 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();
+ for (const auto& unit : organization.units) {
+ QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(P2QSTRING(unit)) << "");
+ item->setFlags(item->flags() | Qt::ItemIsEditable);
+ unitsTreeWidget->addTopLevelItem(item);
+ }
+
+ QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << "");
+ item->setFlags(item->flags() | Qt::ItemIsEditable);
+ unitsTreeWidget->addTopLevelItem(item);
}
VCard::Organization QtVCardOrganizationField::getOrganization() const {
- VCard::Organization organization;
- organization.name = Q2PSTRING(organizationLineEdit->text());
- for(int i=0; i < unitsTreeWidget->topLevelItemCount(); ++i) {
- QTreeWidgetItem* row = unitsTreeWidget->topLevelItem(i);
- if (!row->text(0).isEmpty()) {
- organization.units.push_back(Q2PSTRING(row->text(0)));
- }
- }
-
- return organization;
+ 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);
+ for (auto row : rows) {
+ if (row->text(0).isEmpty()) {
+ hasEmptyRow = true;
+ }
+ }
+
+ if (!hasEmptyRow) {
+ QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << "");
+ item->setFlags(item->flags() | Qt::ItemIsEditable);
+ unitsTreeWidget->addTopLevelItem(item);
+ unitsTreeWidget->setCurrentItem(item);
+ }
}
}
diff --git a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h
index 47868a7..23e89c0 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <QTreeWidget>
@@ -18,37 +24,37 @@
namespace Swift {
class QtVCardOrganizationField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO("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 = nullptr, QGridLayout* layout = nullptr, 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 75b1f07..eef6728 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp
@@ -5,148 +5,148 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h>
-#include <Swift/QtUI/QtVCardWidget/ui_QtVCardPhotoAndNameFields.h>
-
#include <QMenu>
+#include <Swift/QtUI/QtVCardWidget/ui_QtVCardPhotoAndNameFields.h>
+
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 (auto& i : fullname) {
+ 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..ca6a1f3 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <QMenu>
@@ -12,51 +18,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 = nullptr);
+ ~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 af28d28..e9e29ad 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp
@@ -4,47 +4,54 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "QtVCardRoleField.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/QtVCardWidget/QtVCardRoleField.h>
-#include <QGridLayout>
#include <boost/algorithm/string.hpp>
+#include <QGridLayout>
+
#include <Swift/QtUI/QtSwiftUtil.h>
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(nullptr) {
+ 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 3c819ed..a507fef 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardRoleField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardRoleField.h
@@ -4,38 +4,44 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Elements/VCard.h>
-#include "QtResizableLineEdit.h"
-#include "QtVCardFieldInfo.h"
-#include "QtVCardGeneralField.h"
+#include <Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h>
namespace Swift {
class QtVCardRoleField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO("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 = nullptr, QGridLayout* layout = nullptr, 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 401d0a0..9421016 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp
@@ -4,7 +4,13 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "QtVCardTelephoneField.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h>
#include <QGridLayout>
@@ -13,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(nullptr) {
+ 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 b433e3c..13bb232 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h
@@ -4,39 +4,45 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Elements/VCard.h>
-#include "QtResizableLineEdit.h"
-#include "QtVCardFieldInfo.h"
-#include "QtVCardGeneralField.h"
-#include "QtVCardHomeWork.h"
+#include <Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h>
namespace Swift {
class QtVCardTelephoneField : public QtVCardGeneralField, public QtVCardHomeWork {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO("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 = nullptr, QGridLayout* layout = nullptr, 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 64b05c0..14c3813 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp
@@ -4,48 +4,55 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "QtVCardTitleField.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/QtVCardWidget/QtVCardTitleField.h>
-#include <QGridLayout>
#include <boost/algorithm/string.hpp>
+#include <QGridLayout>
+
#include <Swift/QtUI/QtSwiftUtil.h>
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(nullptr) {
+ 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 28dc603..0ea3772 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardTitleField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardTitleField.h
@@ -4,38 +4,44 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Elements/VCard.h>
-#include "QtResizableLineEdit.h"
-#include "QtVCardFieldInfo.h"
-#include "QtVCardGeneralField.h"
+#include <Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h>
namespace Swift {
class QtVCardTitleField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO("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 = nullptr, QGridLayout* layout = nullptr, 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 18241b4..153b897 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp
@@ -4,68 +4,74 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "QtVCardURLField.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/QtVCardWidget/QtVCardURLField.h>
+
+#include <boost/algorithm/string.hpp>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QTextDocument>
-#include <boost/algorithm/string.hpp>
#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/QtUtilities.h>
-
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(nullptr), urlLineEdit(nullptr) {
+ 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 2c011d8..3830a7b 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardURLField.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardURLField.h
@@ -4,39 +4,45 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Elements/VCard.h>
-#include "QtResizableLineEdit.h"
-#include "QtVCardFieldInfo.h"
-#include "QtVCardGeneralField.h"
+#include <Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h>
+#include <Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h>
namespace Swift {
class QtVCardURLField : public QtVCardGeneralField {
- Q_OBJECT
+ Q_OBJECT
- public:
- GENERIC_QT_VCARD_FIELD_INFO("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 = nullptr, QGridLayout* layout = nullptr, 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 9092e08..290feca 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp
+++ b/Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp
@@ -5,13 +5,12 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/QtVCardWidget/QtVCardWidget.h>
-#include <Swift/QtUI/QtVCardWidget/ui_QtVCardWidget.h>
#include <QLineEdit>
#include <QMenu>
@@ -29,398 +28,399 @@
#include <Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h>
#include <Swift/QtUI/QtVCardWidget/QtVCardTitleField.h>
#include <Swift/QtUI/QtVCardWidget/QtVCardURLField.h>
+#include <Swift/QtUI/QtVCardWidget/ui_QtVCardWidget.h>
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, std::make_shared<QtVCardInternetEMailField::FieldInfo>());
+ addFieldType(menu, std::make_shared<QtVCardTelephoneField::FieldInfo>());
+ addFieldType(menu, std::make_shared<QtVCardAddressField::FieldInfo>());
+ addFieldType(menu, std::make_shared<QtVCardAddressLabelField::FieldInfo>());
+ addFieldType(menu, std::make_shared<QtVCardBirthdayField::FieldInfo>());
+ addFieldType(menu, std::make_shared<QtVCardJIDField::FieldInfo>());
+ addFieldType(menu, std::make_shared<QtVCardDescriptionField::FieldInfo>());
+ addFieldType(menu, std::make_shared<QtVCardRoleField::FieldInfo>());
+ addFieldType(menu, std::make_shared<QtVCardTitleField::FieldInfo>());
+ addFieldType(menu, std::make_shared<QtVCardOrganizationField::FieldInfo>());
+ addFieldType(menu, std::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);
+ for (auto 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 = std::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());
+
+ for (const auto& address : vcard->getEMailAddresses()) {
+ if (address.isInternet) {
+ QtVCardInternetEMailField* internetEmailField = new QtVCardInternetEMailField(this, ui->cardFields);
+ internetEmailField->initialize();
+ internetEmailField->setInternetEMailAddress(address);
+ appendField(internetEmailField);
+ }
+ }
+
+ for (const auto& telephone : vcard->getTelephones()) {
+ QtVCardTelephoneField* telField = new QtVCardTelephoneField(this, ui->cardFields);
+ telField->initialize();
+ telField->setTelephone(telephone);
+ appendField(telField);
+ }
+
+ for (const auto& address : vcard->getAddresses()) {
+ QtVCardAddressField* addressField = new QtVCardAddressField(this, ui->cardFields);
+ addressField->initialize();
+ addressField->setAddress(address);
+ appendField(addressField);
+ }
+
+ for (const auto& 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);
+ }
+
+ for (const auto& 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);
+ }
+
+ for (const auto& org : vcard->getOrganizations()) {
+ QtVCardOrganizationField* orgField = new QtVCardOrganizationField(this, ui->cardFields);
+ orgField->initialize();
+ orgField->setOrganization(org);
+ appendField(orgField);
+ }
+
+ for (const auto& role : vcard->getRoles()) {
+ QtVCardRoleField* roleField = new QtVCardRoleField(this, ui->cardFields);
+ roleField->initialize();
+ roleField->setRole(role);
+ appendField(roleField);
+ }
+
+ for (const auto& title : vcard->getTitles()) {
+ QtVCardTitleField* titleField = new QtVCardTitleField(this, ui->cardFields);
+ titleField->initialize();
+ titleField->setTitle(title);
+ appendField(titleField);
+ }
+
+ for (const auto& 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 = nullptr;
+ QtVCardDescriptionField* descriptionField = nullptr;
+
+ for (auto 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 = nullptr;
+ if ((action = dynamic_cast<QAction*>(sender()))) {
+ std::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 = nullptr;
+ for (auto 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);
- }
+void QtVCardWidget::addFieldType(QMenu* menu, std::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);
+ }
}
-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 QtVCardWidget::fieldTypeInstances(std::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;
}
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)) != nullptr) {
+ 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();
+ for (auto 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;
+ for (auto field : fields) {
+ if (field->property("empty").isValid() && field->property("empty").toBool()) {
+ ui->cardFields->removeWidget(field);
+ items_to_remove.push_back(field);
+ delete field;
+ }
+ }
+
+ for (auto 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 = nullptr;
+ for (auto 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..9aae158 100644
--- a/Swift/QtUI/QtVCardWidget/QtVCardWidget.h
+++ b/Swift/QtUI/QtVCardWidget/QtVCardWidget.h
@@ -5,14 +5,15 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/smart_ptr/make_shared.hpp>
+#include <list>
+#include <memory>
#include <QToolButton>
#include <QWidget>
@@ -24,50 +25,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 = nullptr);
+ ~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*, std::shared_ptr<QtVCardFieldInfo>);
+ int fieldTypeInstances(std::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*, std::shared_ptr<QtVCardFieldInfo> > actionFieldInfo;
+ };
}
diff --git a/Swift/QtUI/QtWebKitChatView.cpp b/Swift/QtUI/QtWebKitChatView.cpp
index b543e34..6fe9397 100644
--- a/Swift/QtUI/QtWebKitChatView.cpp
+++ b/Swift/QtUI/QtWebKitChatView.cpp
@@ -8,6 +8,7 @@
#include <QApplication>
#include <QDesktopServices>
+#include <QDesktopWidget>
#include <QEventLoop>
#include <QFile>
#include <QFileDialog>
@@ -19,6 +20,7 @@
#include <QTimer>
#include <QVBoxLayout>
#include <QWebFrame>
+#include <QWebSettings>
#include <QtDebug>
#include <Swiften/Base/FileSize.h>
@@ -49,1004 +51,941 @@ const QString QtWebKitChatView::ButtonFileTransferAcceptRequest = QString("filet
const QString QtWebKitChatView::ButtonFileTransferOpenFile = QString("filetransfer-openfile");
const QString QtWebKitChatView::ButtonMUCInvite = QString("mucinvite");
+namespace {
+ const double minimalFontScaling = 0.8;
+}
+
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&)));
-
- viewReady_ = false;
- isAtBottom_ = true;
- resetView();
+ 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()));
- 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)));
+ 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)));
+ connect(jsBridge, SIGNAL(verticalScrollBarPositionChanged(double)), this, SLOT(handleVerticalScrollBarPositionChanged(double)));
}
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);
-}
-
-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);
- }
-}
-
-void QtWebKitChatView::addMessageTop(boost::shared_ptr<ChatSnippet> snippet) {
- // save scrollbar maximum value
- if (!topMessageAdded_) {
- scrollBarMaximum_ = webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical);
- }
- topMessageAdded_ = true;
-
- QWebElement continuationElement = firstElement_.findFirst("#insert");
-
- bool insert = snippet->getAppendToPrevious();
- bool fallback = continuationElement.isNull();
-
- boost::shared_ptr<ChatSnippet> newSnippet = (insert && fallback) ? snippet->getContinuationFallbackSnippet() : snippet;
- QWebElement newElement = snippetToDOM(newSnippet);
-
- if (insert && !fallback) {
- Q_ASSERT(!continuationElement.isNull());
- continuationElement.replace(newElement);
- } else {
- continuationElement.removeFromDocument();
- topInsertPoint_.prependOutside(newElement);
- }
-
- firstElement_ = newElement;
-
- if (lastElement_.isNull()) {
- lastElement_ = firstElement_;
- }
-
- if (fontSizeSteps_ != 0) {
- double size = 1.0 + 0.2 * fontSizeSteps_;
- QString sizeString(QString().setNum(size, 'g', 3) + "em");
- const QWebElementCollection spans = firstElement_.findAll("span.swift_resizable");
- Q_FOREACH (QWebElement span, spans) {
- span.setStyleProperty("font-size", sizeString);
- }
- }
-}
-
-QWebElement QtWebKitChatView::snippetToDOM(boost::shared_ptr<ChatSnippet> snippet) {
- QWebElement newElement = newInsertPoint_.clone();
- newElement.setInnerXml(snippet->getContent());
- Q_ASSERT(!newElement.isNull());
- return newElement;
-}
-
-void QtWebKitChatView::addToDOM(boost::shared_ptr<ChatSnippet> snippet) {
- //qDebug() << snippet->getContent();
- rememberScrolledToBottom();
- bool insert = snippet->getAppendToPrevious();
- QWebElement continuationElement = lastElement_.findFirst("#insert");
- bool fallback = insert && continuationElement.isNull();
- boost::shared_ptr<ChatSnippet> newSnippet = (insert && fallback) ? snippet->getContinuationFallbackSnippet() : snippet;
- QWebElement newElement = snippetToDOM(newSnippet);
- if (insert && !fallback) {
- Q_ASSERT(!continuationElement.isNull());
- continuationElement.replace(newElement);
- } else {
- continuationElement.removeFromDocument();
- newInsertPoint_.prependOutside(newElement);
- }
- lastElement_ = newElement;
- if (fontSizeSteps_ != 0) {
- double size = 1.0 + 0.2 * fontSizeSteps_;
- QString sizeString(QString().setNum(size, 'g', 3) + "em");
- const QWebElementCollection spans = lastElement_.findAll("span.swift_resizable");
- Q_FOREACH (QWebElement span, spans) {
- span.setStyleProperty("font-size", sizeString);
- }
- }
- //qDebug() << "-----------------";
- //qDebug() << webPage_->mainFrame()->toHtml();
+ webView_->keyPressEvent(event);
+}
+
+void QtWebKitChatView::addMessageBottom(std::shared_ptr<ChatSnippet> snippet) {
+ if (viewReady_) {
+ addToDOM(snippet);
+ } else {
+ /* If this asserts, the previous queuing code was necessary and should be reinstated */
+ assert(false);
+ }
+}
+
+void QtWebKitChatView::addMessageTop(std::shared_ptr<ChatSnippet> /* snippet */) {
+ // TODO: Implement this in a sensible manner later.
+ SWIFT_LOG(error) << "Not yet implemented!" << std::endl;
+}
+
+void QtWebKitChatView::addToDOM(std::shared_ptr<ChatSnippet> snippet) {
+ //qDebug() << snippet->getContent();
+ rememberScrolledToBottom();
+
+ QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert");
+ assert(!insertElement.isNull());
+ insertElement.prependOutside(snippet->getContent());
+
+ //qDebug() << "-----------------";
+ //qDebug() << webPage_->mainFrame()->toHtml();
}
void QtWebKitChatView::addLastSeenLine() {
- /* if the line is added we should break the snippet */
- insertingLastLine_ = true;
- if (lineSeparator_.isNull()) {
- lineSeparator_ = newInsertPoint_.clone();
- lineSeparator_.setInnerXml(QString("<hr/>"));
- newInsertPoint_.prependOutside(lineSeparator_);
- }
- else {
- QWebElement lineSeparatorC = lineSeparator_.clone();
- lineSeparatorC.removeFromDocument();
- }
- newInsertPoint_.prependOutside(lineSeparator_);
+ // 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());
}
void QtWebKitChatView::replaceLastMessage(const QString& newMessage, const ChatWindow::TimestampBehaviour timestampBehaviour) {
- assert(viewReady_);
- rememberScrolledToBottom();
- assert(!lastElement_.isNull());
- QWebElement replace = lastElement_.findFirst("span.swift_message");
- assert(!replace.isNull());
- QString old = lastElement_.toOuterXml();
- replace.setInnerXml(ChatSnippet::escape(newMessage));
- if (timestampBehaviour == ChatWindow::UpdateTimestamp) {
- replace = lastElement_.findFirst("span.swift_time");
- assert(!replace.isNull());
- replace.setInnerXml(ChatSnippet::timeToEscapedString(QDateTime::currentDateTime()));
- }
+ 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()));
+ }
}
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);
+ if (webPage_) {
+ 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");
- //qDebug() << "Setting to " << sizeString;
- const QWebElementCollection spans = document_.findAll("span.swift_resizable");
- Q_FOREACH (QWebElement span, spans) {
- span.setStyleProperty("font-size", sizeString);
- }
- webView_->setFontSizeIsMinimal(size == 1.0);
+ fontSizeSteps_ = fontSizeSteps;
+ double size = minimalFontScaling + 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 == minimalFontScaling);
}
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();
-
- resetTopInsertPoint();
- QWebElement chatElement = document_.findFirst("#Chat");
- newInsertPoint_ = chatElement.clone();
- newInsertPoint_.setOuterXml("<div id='swift_insert'/>");
- chatElement.appendInside(newInsertPoint_);
- Q_ASSERT(!newInsertPoint_.isNull());
-
- 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_) {
+ syncLoop.processEvents(QEventLoop::AllEvents, 50);
+ }
+ document_ = webPage_->mainFrame()->documentElement();
+
+ scrollToBottom();
+
+ connect(webPage_->mainFrame(), SIGNAL(contentsSizeChanged(const QSize&)), this, SLOT(handleFrameSizeChanged()), Qt::UniqueConnection);
+
+ // Hooking up to scroll bar update, because Qt does not provide a way to retrieve accurate scroll bar updates from C++ directly.
+ QWebElement body = document_.findFirst("body");
+ assert(!body.isNull());
+ body.setAttribute("onscroll", "chatwindow.verticalScrollBarPositionChanged(document.body.scrollTop / (document.body.scrollHeight - window.innerHeight))");
+
+ // Adjust web view default 96 DPI setting to screen DPI.
+ // For more information see https://webkit.org/blog/57/css-units/
+ webView_->setZoomFactor(QApplication::desktop()->screen()->logicalDpiX() / 96.0);
+
+ body.setStyleProperty("font-size", QString("%1pt").arg(QApplication::font().pointSize()));
}
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));
- }
-}
-
-void QtWebKitChatView::handleScrollRequested(int, int dy, const QRect&) {
- rememberScrolledToBottom();
-
- 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();
- }
+ QFileInfo fileInfo(filename);
+ if (fileInfo.exists() && fileInfo.isFile()) {
+ QDesktopServices::openUrl(QUrl::fromLocalFile(filename));
+ }
}
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() {
- QWebElement continuationElement = firstElement_.findFirst("#insert");
- continuationElement.removeFromDocument();
- firstElement_ = QWebElement();
-
- topInsertPoint_.removeFromDocument();
- QWebElement chatElement = document_.findFirst("#Chat");
- topInsertPoint_ = chatElement.clone();
- topInsertPoint_.setOuterXml("<div id='swift_insert'/>");
- chatElement.prependInside(topInsertPoint_);
+ // TODO: Implement or refactor later.
+ SWIFT_LOG(error) << "Not yet implemented!" << std::endl;
}
-
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,
- const HighlightAction& highlight) {
- return addMessage(chatMessageToHTML(message), senderName, senderIsSelf, label, avatarPath, "", time, highlight, ChatSnippet::getDirection(message));
+ const ChatWindow::ChatMessage& message,
+ const std::string& senderName,
+ bool senderIsSelf,
+ std::shared_ptr<SecurityLabel> label,
+ const std::string& avatarPath,
+ const boost::posix_time::ptime& time) {
+ return addMessage(chatMessageToHTML(message), senderName, senderIsSelf, label, avatarPath, "", time, message.getFullMessageHighlightAction(), ChatSnippet::getDirection(message));
}
QString QtWebKitChatView::getHighlightSpanStart(const std::string& text, const std::string& background) {
- QString ecsapeColor = QtUtilities::htmlEscape(P2QSTRING(text));
- QString escapeBackground = QtUtilities::htmlEscape(P2QSTRING(background));
- if (ecsapeColor.isEmpty()) {
- ecsapeColor = "black";
- }
- if (escapeBackground.isEmpty()) {
- escapeBackground = "yellow";
- }
- return QString("<span style=\"color: %1; background: %2\">").arg(ecsapeColor).arg(escapeBackground);
+ QString 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->foregroundColor, highlightPart->backgroundColor);
- result += spanStart + QtUtilities::htmlEscape(P2QSTRING(highlightPart->text)) + "</span>";
- continue;
- }
-
- }
- return result;
+ QString result;
+ for (const auto& part : message.getParts()) {
+ std::shared_ptr<ChatWindow::ChatTextMessagePart> textPart;
+ std::shared_ptr<ChatWindow::ChatURIMessagePart> uriPart;
+ std::shared_ptr<ChatWindow::ChatEmoticonMessagePart> emoticonPart;
+ std::shared_ptr<ChatWindow::ChatHighlightingMessagePart> highlightPart;
+
+ if ((textPart = std::dynamic_pointer_cast<ChatWindow::ChatTextMessagePart>(part))) {
+ QString text = QtUtilities::htmlEscape(P2QSTRING(textPart->text));
+ text.replace("\n","<br/>");
+ result += text;
+ continue;
+ }
+ if ((uriPart = std::dynamic_pointer_cast<ChatWindow::ChatURIMessagePart>(part))) {
+ QString uri = QtUtilities::htmlEscape(P2QSTRING(uriPart->target));
+ result += "<a href='" + uri + "' >" + uri + "</a>";
+ continue;
+ }
+ if ((emoticonPart = std::dynamic_pointer_cast<ChatWindow::ChatEmoticonMessagePart>(part))) {
+ QString textStyle = showEmoticons_ ? "style='display:none'" : "";
+ QString imageStyle = showEmoticons_ ? "" : "style='display:none'";
+ result += "<span class='swift_emoticon_image' " + imageStyle + "><img src='" + P2QSTRING(emoticonPart->imagePath) + "'/></span><span class='swift_emoticon_text' " + textStyle + ">" + QtUtilities::htmlEscape(P2QSTRING(emoticonPart->alternativeText)) + "</span>";
+ continue;
+ }
+ if ((highlightPart = std::dynamic_pointer_cast<ChatWindow::ChatHighlightingMessagePart>(part))) {
+ QString spanStart = getHighlightSpanStart(highlightPart->action.getTextColor(), highlightPart->action.getTextBackground());
+ result += spanStart + QtUtilities::htmlEscape(P2QSTRING(highlightPart->text)) + "</span>";
+ continue;
+ }
+
+ }
+ return result;
}
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,
+ std::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.svg" : QUrl::fromLocalFile(scaledAvatarPath).toEncoded();
+ std::string id = "id" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(std::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, const HighlightAction& highlight) {
- return addMessage(" *" + chatMessageToHTML(message) + "*", senderName, senderIsSelf, label, avatarPath, "font-style:italic ", time, highlight, ChatSnippet::getDirection(message));
+std::string QtWebKitChatView::addAction(const ChatWindow::ChatMessage& message, const std::string &senderName, bool senderIsSelf, std::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) {
+ return addMessage(" *" + chatMessageToHTML(message) + "*", senderName, senderIsSelf, label, avatarPath, "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;
+}
+
+void QtWebKitChatView::resizeEvent(QResizeEvent* event) {
+ // This code ensures that if the user is scrolled all to the bottom of a chat view,
+ // the view stays scrolled to the bottom if the view is resized or if the message
+ // input widget becomes multi line.
+ if (isAtBottom_) {
+ scrollToBottom();
+ }
+ QWidget::resizeEvent(event);
}
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, std::shared_ptr<SecurityLabel>(), "", boost::posix_time::second_clock::local_time());
+
+ bool appendToPrevious = appendToPreviousCheck(PreviousMessageWasFileTransfer, senderName, senderIsSelf);
+
+ QString qAvatarPath = "qrc:/icons/avatar.svg";
+ std::string id = "ftmessage" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(std::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.svg";
+ std::string id = "wbmessage" + boost::lexical_cast<std::string>(idCounter_++);
+ addMessageBottom(std::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(std::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::handleVerticalScrollBarPositionChanged(double position) {
+ rememberScrolledToBottom();
+ if (position == 0) {
+ emit scrollReachedTop();
+ }
+ else if (position == 1) {
+ emit scrollReachedBottom();
+ }
}
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(std::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(std::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, const HighlightAction& highlight) {
- replaceMessage(" *" + chatMessageToHTML(message) + "*", id, time, "font-style:italic ", highlight);
+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());
}
-void QtWebKitChatView::replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time, const HighlightAction& highlight) {
- replaceMessage(chatMessageToHTML(message), id, time, "", highlight);
+void QtWebKitChatView::replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) {
+ 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(std::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.svg";
- 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(std::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/check.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/error.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-success.svg' title='" + tr("The receipt for this message has been received.") + "'/>";
+ break;
+ case ChatWindow::ReceiptRequested:
+ xml = "<img src='qrc:/icons/delivery-warning.svg' 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.svg' 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;
-// }
-
-
}
diff --git a/Swift/QtUI/QtWebKitChatView.h b/Swift/QtUI/QtWebKitChatView.h
index 173a05b..098c1ac 100644
--- a/Swift/QtUI/QtWebKitChatView.h
+++ b/Swift/QtUI/QtWebKitChatView.h
@@ -6,7 +6,7 @@
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <QList>
#include <QString>
@@ -25,171 +25,171 @@ 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, const HighlightAction& highlight) 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, const HighlightAction& highlight) 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, const HighlightAction& highlight) 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, const HighlightAction& highlight) 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);
- QWebElement snippetToDOM(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 newInsertPoint_;
- QWebElement topInsertPoint_;
- 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, std::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, std::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(std::shared_ptr<ChatSnippet> snippet);
+ void addMessageBottom(std::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 handleHTMLButtonClicked(QString id, QString arg1, QString arg2, QString arg3, QString arg4, QString arg5);
+ void handleVerticalScrollBarPositionChanged(double position);
+
+ private:
+ enum PreviousMessageKind {
+ PreviosuMessageWasNone,
+ PreviousMessageWasMessage,
+ PreviousMessageWasSystem,
+ PreviousMessageWasPresence,
+ PreviousMessageWasFileTransfer,
+ PreviousMessageWasMUCInvite
+ };
+ std::string addMessage(
+ const QString& message,
+ const std::string& senderName,
+ bool senderIsSelf,
+ std::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());
+
+ protected:
+ void resizeEvent(QResizeEvent* event) SWIFTEN_OVERRIDE;
+
+ private:
+ void headerEncode();
+ void messageEncode();
+ void addToDOM(std::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 f9894e6..abdc17a 100644
--- a/Swift/QtUI/QtWebView.cpp
+++ b/Swift/QtUI/QtWebView.cpp
@@ -1,43 +1,56 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtWebView.h"
+#include <Swift/QtUI/QtWebView.h>
-#include <QKeyEvent>
-#include <QFocusEvent>
#include <boost/numeric/conversion/cast.hpp>
+
+#include <QFocusEvent>
+#include <QKeyEvent>
+#include <QKeySequence>
#include <QMenu>
+
#include <Swiften/Base/Log.h>
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 (event->matches(QKeySequence::ZoomIn)) {
+ event->accept();
+ emit fontGrowRequested();
+ return;
+ }
+ if (event->matches(QKeySequence::ZoomOut)) {
+ event->accept();
+ emit fontShrinkRequested();
+ return;
+ }
+ 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*) {
@@ -45,43 +58,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 (auto action : actions) {
+ bool removeAction = true;
+ for(auto& filteredAction : filteredActions) {
+ if (action == pageAction(filteredAction)) {
+ 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()), QKeySequence(QKeySequence::ZoomIn));
+ QAction* shrink = new QAction(tr("Decrease font size"), this);
+ shrink->setShortcut(QKeySequence(QKeySequence::ZoomOut));
+ 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 792f5f7..985a0db 100644
--- a/Swift/QtUI/QtWebView.h
+++ b/Swift/QtUI/QtWebView.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,30 +7,31 @@
#pragma once
-#include <QWebView>
#include <vector>
+#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 a586591..bf55706 100644
--- a/Swift/QtUI/QtWin32NotifierWindow.h
+++ b/Swift/QtUI/QtWin32NotifierWindow.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,22 +8,22 @@
#include <QWidget>
-#include "SwifTools/Notifier/Win32NotifierWindow.h"
+#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 ddb8661..a7f9702 100644
--- a/Swift/QtUI/QtXMLConsoleWidget.cpp
+++ b/Swift/QtUI/QtXMLConsoleWidget.cpp
@@ -1,19 +1,19 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtXMLConsoleWidget.h"
+#include <Swift/QtUI/QtXMLConsoleWidget.h>
#include <string>
+#include <QCheckBox>
#include <QCloseEvent>
-#include <QTextEdit>
-#include <QVBoxLayout>
#include <QPushButton>
#include <QScrollBar>
-#include <QCheckBox>
+#include <QTextEdit>
+#include <QVBoxLayout>
#include <Swiften/Base/format.h>
@@ -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 ace9bd5..ef10e63 100644
--- a/Swift/QtUI/QtXMLConsoleWidget.h
+++ b/Swift/QtUI/QtXMLConsoleWidget.h
@@ -1,42 +1,43 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/Controllers/UIInterfaces/XMLConsoleWidget.h"
-#include "QtTabbable.h"
+#include <Swift/Controllers/UIInterfaces/XMLConsoleWidget.h>
+
+#include <Swift/QtUI/QtTabbable.h>
class QTextEdit;
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 73cfbb5..e4a2f46 100644
--- a/Swift/QtUI/Roster/DelegateCommons.cpp
+++ b/Swift/QtUI/Roster/DelegateCommons.cpp
@@ -1,108 +1,111 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "DelegateCommons.h"
+#include <Swift/QtUI/Roster/DelegateCommons.h>
-#include <QtScaledAvatarCache.h>
+#include <QColor>
#include <QFileInfo>
-namespace Swift {
+#include <Swift/QtUI/QtScaledAvatarCache.h>
+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));
+ }
+ auto secondLineColor = painter->pen().color();
+ secondLineColor.setAlphaF(0.7);
+
+ 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.svg").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(secondLineColor));
+
+ 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 084d41f..74b08f2 100644
--- a/Swift/QtUI/Roster/DelegateCommons.h
+++ b/Swift/QtUI/Roster/DelegateCommons.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,36 +8,36 @@
#include <QApplication>
#include <QFont>
+#include <QIcon>
#include <QPainter>
#include <QRect>
#include <QString>
-#include <QIcon>
#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 a9942f8..0356aa0 100644
--- a/Swift/QtUI/Roster/GroupItemDelegate.cpp
+++ b/Swift/QtUI/Roster/GroupItemDelegate.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "GroupItemDelegate.h"
+#include <Swift/QtUI/Roster/GroupItemDelegate.h>
#include <QPainter>
#include <QPen>
@@ -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 859f3ec..f989ed0 100644
--- a/Swift/QtUI/Roster/GroupItemDelegate.h
+++ b/Swift/QtUI/Roster/GroupItemDelegate.h
@@ -1,29 +1,29 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QStyledItemDelegate>
#include <QColor>
#include <QFont>
+#include <QStyledItemDelegate>
-#include "DelegateCommons.h"
+#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 acfd50f..2e1ead9 100644
--- a/Swift/QtUI/Roster/QtFilterWidget.cpp
+++ b/Swift/QtUI/Roster/QtFilterWidget.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -10,6 +10,8 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+#include <Swift/QtUI/Roster/QtFilterWidget.h>
+
#include <QEvent>
#include <QKeyEvent>
#include <QLayout>
@@ -18,31 +20,31 @@
#include <Swift/Controllers/UIEvents/RequestChatUIEvent.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
+
#include <Swift/QtUI/QtClosableLineEdit.h>
#include <Swift/QtUI/QtSwiftUtil.h>
-#include <Swift/QtUI/Roster/QtFilterWidget.h>
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);
+QtFilterWidget::QtFilterWidget(QWidget* parent, QtTreeWidget* treeView, UIEventStream* eventStream, QBoxLayout* layout) : QWidget(parent), treeView_(treeView), eventStream_(eventStream), fuzzyRosterFilter_(nullptr), isModifierSinglePressed_(false) {
+ 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() {
@@ -50,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(std::make_shared<RequestChatUIEvent>(target));
+ }
+ filterLineEdit_->setText("");
+ updateRosterFilters();
+ } else if (keyEvent->key() == Qt::Key_Escape) {
+ filterLineEdit_->setText("");
+ } else {
+ isModifierSinglePressed_ = false;
+ }
+ }
+
+ filterLineEdit_->event(event);
+
+ if (event->type() == QEvent::KeyRelease) {
+ updateRosterFilters();
+ }
+ return true;
+ }
+ return false;
}
void QtFilterWidget::popAllFilters() {
- std::vector<RosterFilter*> filters = treeView_->getRoster()->getFilters();
- foreach(RosterFilter* filter, filters) {
- 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();
+ for (auto filter : filters) {
+ filters_.push_back(filter);
+ treeView_->getRoster()->removeFilter(filter);
+ }
+ treeView_->getRoster()->onFilterAdded.connect(boost::bind(&QtFilterWidget::handleFilterAdded, this, _1));
+ treeView_->getRoster()->onFilterRemoved.connect(boost::bind(&QtFilterWidget::handleFilterRemoved, this, _1));
}
void QtFilterWidget::pushAllFilters() {
- treeView_->getRoster()->onFilterAdded.disconnect(boost::bind(&QtFilterWidget::handleFilterAdded, this, _1));
- treeView_->getRoster()->onFilterRemoved.disconnect(boost::bind(&QtFilterWidget::handleFilterRemoved, this, _1));
- foreach(RosterFilter* filter, filters_) {
- 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));
+ for (auto filter : filters_) {
+ treeView_->getRoster()->addFilter(filter);
+ }
+ filters_.clear();
}
void QtFilterWidget::updateRosterFilters() {
- if (fuzzyRosterFilter_) {
- if (filterLineEdit_->text().isEmpty()) {
- // remove currently installed search filter and put old filters back
- treeView_->getRoster()->removeFilter(fuzzyRosterFilter_);
- delete fuzzyRosterFilter_;
- fuzzyRosterFilter_ = 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_ = nullptr;
+ pushAllFilters();
+ } else {
+ // remove currently intsalled search filter and put new search filter in place
+ updateSearchFilter();
+ }
+ } else {
+ if (!filterLineEdit_->text().isEmpty()) {
+ // remove currently installed filters and put a search filter in place
+ popAllFilters();
+ updateSearchFilter();
+ }
+ }
+ filterLineEdit_->setVisible(!filterLineEdit_->text().isEmpty());
}
void QtFilterWidget::updateSearchFilter() {
- if (fuzzyRosterFilter_) {
- treeView_->getRoster()->removeFilter(fuzzyRosterFilter_);
- 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_ = nullptr;
+ }
+ 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 d0307ea..ea3c325 100644
--- a/Swift/QtUI/Roster/QtFilterWidget.h
+++ b/Swift/QtUI/Roster/QtFilterWidget.h
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <vector>
@@ -11,8 +17,8 @@
#include <QBoxLayout>
#include <QWidget>
-#include <Swift/Controllers/Roster/RosterFilter.h>
#include <Swift/Controllers/Roster/FuzzyRosterFilter.h>
+#include <Swift/Controllers/Roster/RosterFilter.h>
#include <Swift/QtUI/Roster/QtTreeWidget.h>
@@ -20,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 = nullptr);
+ 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 4d7a543..a12863d 100644
--- a/Swift/QtUI/Roster/QtOccupantListWidget.cpp
+++ b/Swift/QtUI/Roster/QtOccupantListWidget.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2014 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,10 +7,10 @@
#include <Swift/QtUI/Roster/QtOccupantListWidget.h>
-#include <QContextMenuEvent>
-#include <QMenu>
#include <QAction>
+#include <QContextMenuEvent>
#include <QInputDialog>
+#include <QMenu>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
#include <Swift/Controllers/Roster/GroupRosterItem.h>
@@ -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;
+ for (const auto& availableAction : availableOccupantActions_) {
+ QString text = "Error: missing string";
+ switch (availableAction) {
+ case ChatWindow::Kick: text = tr("Kick user"); break;
+ case ChatWindow::Ban: text = tr("Kick and ban user"); break;
+ case ChatWindow::MakeModerator: text = tr("Make moderator"); break;
+ case ChatWindow::MakeParticipant: text = tr("Make participant"); break;
+ case ChatWindow::MakeVisitor: text = tr("Remove voice"); break;
+ case ChatWindow::AddContact: text = tr("Add to contacts"); break;
+ case ChatWindow::ShowProfile: text = tr("Show profile"); break;
+ }
+ QAction* action = contextMenu.addAction(text);
+ actions[action] = availableAction;
+ }
+ QAction* result = contextMenu.exec(event->globalPos());
+ if (result) {
+ onOccupantActionSelected(actions[result], contact);
+ }
+ }
+ }
}
}
diff --git a/Swift/QtUI/Roster/QtOccupantListWidget.h b/Swift/QtUI/Roster/QtOccupantListWidget.h
index 645c21a..0f80943 100644
--- a/Swift/QtUI/Roster/QtOccupantListWidget.h
+++ b/Swift/QtUI/Roster/QtOccupantListWidget.h
@@ -1,31 +1,31 @@
/*
- * Copyright (c) 2011-2014 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swift/QtUI/Roster/QtTreeWidget.h>
-
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
#include <Swift/Controllers/UIInterfaces/ChatWindow.h>
+#include <Swift/QtUI/Roster/QtTreeWidget.h>
+
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 = nullptr);
+ virtual ~QtOccupantListWidget();
+ void setAvailableOccupantActions(const std::vector<ChatWindow::OccupantAction>& actions);
+ boost::signals2::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 bef8635..935d6f6 100644
--- a/Swift/QtUI/Roster/QtRosterWidget.cpp
+++ b/Swift/QtUI/Roster/QtRosterWidget.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2014 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,24 @@
#include <Swift/QtUI/Roster/QtRosterWidget.h>
#include <QContextMenuEvent>
+#include <QFileDialog>
+#include <QInputDialog>
#include <QMenu>
#include <QMessageBox>
-#include <QInputDialog>
-#include <QFileDialog>
#include <QPushButton>
-#include <Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h>
+#include <Swift/Controllers/Roster/ContactRosterItem.h>
+#include <Swift/Controllers/Roster/GroupRosterItem.h>
#include <Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h>
#include <Swift/Controllers/UIEvents/RenameGroupUIEvent.h>
-#include <Swift/Controllers/UIEvents/SendFileUIEvent.h>
+#include <Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h>
+#include <Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h>
+#include <Swift/Controllers/UIEvents/SendFileUIEvent.h>
#include <Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h>
-#include <Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h>
-#include <Swift/QtUI/QtContactEditWindow.h>
-#include <Swift/Controllers/Roster/ContactRosterItem.h>
-#include <Swift/Controllers/Roster/GroupRosterItem.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
+
+#include <Swift/QtUI/QtContactEditWindow.h>
#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
@@ -37,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(std::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 = nullptr;
+ if (contact->blockState() == ContactRosterItem::IsBlocked ||
+ contact->blockState() == ContactRosterItem::IsDomainBlocked) {
+ unblockContact = contextMenu.addAction(tr("Unblock"));
+ unblockContact->setEnabled(isOnline());
+ }
+
+ QAction* blockContact = nullptr;
+ 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 = nullptr;
+ 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 = nullptr;
+ 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(std::make_shared<RequestContactEditorUIEvent>(contact->getJID()));
+ }
+ else if (result == removeContact) {
+ if (QtContactEditWindow::confirmContactDeletion(contact->getJID())) {
+ eventStream_->send(std::make_shared<RemoveRosterItemUIEvent>(contact->getJID()));
+ }
+ }
+ else if (result == showProfileForContact) {
+ eventStream_->send(std::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(std::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, contact->getJID().getDomain()));
+ }
+ } else {
+ eventStream_->send(std::make_shared<RequestChangeBlockStateUIEvent>(RequestChangeBlockStateUIEvent::Unblocked, contact->getJID()));
+ }
+ }
+ else if (blockContact && result == blockContact) {
+ eventStream_->send(std::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(std::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(std::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(nullptr, 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(std::make_shared<RenameGroupUIEvent>(group->getDisplayName(), Q2PSTRING(newName)));
+ }
}
}
diff --git a/Swift/QtUI/Roster/QtRosterWidget.h b/Swift/QtUI/Roster/QtRosterWidget.h
index d785af2..2cf8315 100644
--- a/Swift/QtUI/Roster/QtRosterWidget.h
+++ b/Swift/QtUI/Roster/QtRosterWidget.h
@@ -1,27 +1,27 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include "Swift/QtUI/Roster/QtTreeWidget.h"
+#include <Swift/QtUI/Roster/QtTreeWidget.h>
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 = nullptr);
+ 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 06a76c3..1264a09 100644
--- a/Swift/QtUI/Roster/QtTreeWidget.cpp
+++ b/Swift/QtUI/Roster/QtTreeWidget.cpp
@@ -1,263 +1,267 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/Roster/QtTreeWidget.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <QUrl>
+#include <QFont>
+#include <QLabel>
#include <QMimeData>
#include <QObject>
-#include <QLabel>
#include <QTimer>
#include <QToolTip>
+#include <QUrl>
#include <Swiften/Base/Platform.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
#include <Swift/Controllers/Roster/GroupRosterItem.h>
-#include <Swift/Controllers/UIEvents/UIEventStream.h>
+#include <Swift/Controllers/Settings/SettingsProvider.h>
#include <Swift/Controllers/UIEvents/RequestChatUIEvent.h>
#include <Swift/Controllers/UIEvents/SendFileUIEvent.h>
-#include <Swift/Controllers/Settings/SettingsProvider.h>
-
+#include <Swift/Controllers/UIEvents/UIEventStream.h>
+
+#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/QtUISettingConstants.h>
#include <Swift/QtUI/Roster/RosterModel.h>
-#include <QtSwiftUtil.h>
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);
+QtTreeWidget::QtTreeWidget(UIEventStream* eventStream, SettingsProvider* settings, MessageTarget messageTarget, QWidget* parent) : QTreeView(parent), eventStream_(eventStream), settings_(settings), messageTarget_(messageTarget) {
+ 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));
+
+ QFont lato = font();
+ lato.setFamily("Lato");
+ setFont(lato);
}
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 = nullptr;
+ 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(std::make_shared<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(std::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 = nullptr;
+ 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 ff45547..331458a 100644
--- a/Swift/QtUI/Roster/QtTreeWidget.h
+++ b/Swift/QtUI/Roster/QtTreeWidget.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,74 +7,74 @@
#pragma once
#include <QDragEnterEvent>
-#include <QDropEvent>
#include <QDragMoveEvent>
+#include <QDropEvent>
#include <QModelIndex>
#include <QTreeView>
-
-#include <Swift/QtUI/Roster/RosterDelegate.h>
-#include <Swift/QtUI/Roster/RosterModel.h>
#include <Swift/Controllers/UIInterfaces/ChatWindow.h>
+#include <Swift/QtUI/Roster/RosterDelegate.h>
+#include <Swift/QtUI/Roster/RosterModel.h>
+
namespace Swift {
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 = nullptr);
+ ~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::signals2::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_ = nullptr;
+ RosterDelegate* delegate_;
+ QtTreeWidgetItem* treeRoot_ = nullptr;
+ SettingsProvider* settings_;
+ bool tooltipShown_ = false;
+ MessageTarget messageTarget_;
+ bool isOnline_ = false;
};
}
diff --git a/Swift/QtUI/Roster/RosterDelegate.cpp b/Swift/QtUI/Roster/RosterDelegate.cpp
index c5bb290..061982e 100644
--- a/Swift/QtUI/Roster/RosterDelegate.cpp
+++ b/Swift/QtUI/Roster/RosterDelegate.cpp
@@ -1,83 +1,83 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "RosterDelegate.h"
+#include <Swift/QtUI/Roster/RosterDelegate.h>
#include <QApplication>
-#include <QPainter>
-#include <QColor>
+#include <QBitmap>
#include <QBrush>
+#include <QColor>
+#include <QDebug>
#include <QFontMetrics>
+#include <QPainter>
#include <QPainterPath>
#include <QPolygon>
-#include <qdebug.h>
-#include <QBitmap>
-#include "Swift/Controllers/Roster/ContactRosterItem.h"
-#include "Swift/Controllers/Roster/GroupRosterItem.h"
+#include <Swift/Controllers/Roster/ContactRosterItem.h>
+#include <Swift/Controllers/Roster/GroupRosterItem.h>
-#include "QtTreeWidget.h"
-#include "RosterModel.h"
+#include <Swift/QtUI/Roster/QtTreeWidget.h>
+#include <Swift/QtUI/Roster/RosterModel.h>
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 aedb6d6..34c1569 100644
--- a/Swift/QtUI/Roster/RosterDelegate.h
+++ b/Swift/QtUI/Roster/RosterDelegate.h
@@ -1,35 +1,35 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QStyledItemDelegate>
#include <QColor>
#include <QFont>
+#include <QStyledItemDelegate>
-#include "GroupItemDelegate.h"
-#include "DelegateCommons.h"
+#include <Swift/QtUI/Roster/DelegateCommons.h>
+#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 b7a1d0a..ef4d778 100644
--- a/Swift/QtUI/Roster/RosterModel.cpp
+++ b/Swift/QtUI/Roster/RosterModel.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -11,268 +11,269 @@
#include <QColor>
#include <QIcon>
#include <QMimeData>
+
#include <qdebug.h>
-#include <Swiften/Elements/StatusShow.h>
#include <Swiften/Base/Path.h>
+#include <Swiften/Elements/StatusShow.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
#include <Swift/Controllers/Roster/GroupRosterItem.h>
#include <Swift/Controllers/StatusUtil.h>
-#include <Swift/QtUI/Roster/QtTreeWidget.h>
-#include <Swift/QtUI/Roster/RosterTooltip.h>
#include <Swift/QtUI/QtResourceHelper.h>
#include <Swift/QtUI/QtSwiftUtil.h>
+#include <Swift/QtUI/Roster/QtTreeWidget.h>
+#include <Swift/QtUI/Roster/RosterTooltip.h>
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);
+RosterModel::RosterModel(QtTreeWidget* view, bool screenReaderMode) : roster_(nullptr), view_(view), screenReader_(screenReaderMode) {
+ const int tooltipAvatarSize = 96; // maximal suggested size according to XEP-0153
+ cachedImageScaler_ = new QtScaledAvatarCache(tooltipAvatarSize);
}
RosterModel::~RosterModel() {
- delete cachedImageScaler_;
+ 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;
+ }
+ for (auto item : roster_->getRoot()->getDisplayedChildren()) {
+ GroupRosterItem* child = dynamic_cast<GroupRosterItem*>(item);
+ if (!child) continue;
+ emit itemExpanded(index(child), child->isExpanded());
+ }
}
void RosterModel::handleChildrenChanged(GroupRosterItem* /*group*/) {
- reLayout();
+ 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)) == nullptr) {
+ 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()) : nullptr;
}
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 = 0x595959; break;
+ case StatusShow::Away: color = 0x336699; break;
+ case StatusShow::XA: color = 0x336699; break;
+ case StatusShow::FFC: color = 0x595959; 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 == nullptr || roster_ == nullptr || (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 == nullptr) {
+ 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 86f175d..ea4c9cd 100644
--- a/Swift/QtUI/Roster/RosterTooltip.cpp
+++ b/Swift/QtUI/Roster/RosterTooltip.cpp
@@ -4,163 +4,172 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swift/QtUI/Roster/RosterTooltip.h>
+#include <QApplication>
#include <QObject>
#include <QString>
-#include <QApplication>
#include <Swiften/Base/Path.h>
#include <Swift/Controllers/Roster/ContactRosterItem.h>
#include <Swift/Controllers/StatusUtil.h>
+#include <Swift/Controllers/Translator.h>
-#include <Swift/QtUI/QtSwiftUtil.h>
+#include <Swift/QtUI/QtResourceHelper.h>
#include <Swift/QtUI/QtScaledAvatarCache.h>
+#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/QtUtilities.h>
-#include <Swift/QtUI/QtResourceHelper.h>
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.svg" : 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());
+
+ boost::posix_time::ptime idleTime = contact->getIdle();
+ QString idleString;
+ if (!idleTime.is_not_a_date_time()) {
+ idleString = QObject::tr("Idle since %1").arg(P2QSTRING(Swift::Translator::getInstance()->ptimeToHumanReadableString(idleTime)));
+ idleString = htmlEscape(idleString) + "<br/>";
+ }
+
+ boost::posix_time::ptime lastSeenTime = contact->getOfflineSince();
+ QString lastSeen;
+ if (!lastSeenTime.is_not_a_date_time()) {
+ lastSeen = QObject::tr("Last seen %1").arg(P2QSTRING(Swift::Translator::getInstance()->ptimeToHumanReadableString(lastSeenTime)));
+ lastSeen = htmlEscape(lastSeen) + "<br/>";
+ }
+
+ QString mucOccupant= P2QSTRING(contact->getMUCAffiliationText());
+ if (!mucOccupant.isEmpty()) {
+ mucOccupant = htmlEscape(mucOccupant) + "<br/>";
+ }
+
+ return tooltipTemplate.arg(scaledAvatarPath, htmlEscape(fullName), htmlEscape(bareJID), presenceIconTag, htmlEscape(statusMessage), mucOccupant, idleString, lastSeen, vCardSummary);
}
QString RosterTooltip::buildVCardSummary(VCard::ref vcard) {
- QString summary;
- summary = "<table>";
-
- // star | name | content
- QString currentBlock;
- foreach (const VCard::Telephone& tel, vcard->getTelephones()) {
- 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;
+ for (const auto& tel : vcard->getTelephones()) {
+ QString type = tel.isFax ? QObject::tr("Fax") : QObject::tr("Telephone");
+ QString field = buildVCardField(tel.isPreferred, type, htmlEscape(P2QSTRING(tel.number)));
+ if (tel.isPreferred) {
+ currentBlock = field;
+ break;
+ }
+ currentBlock += field;
+ }
+ summary += currentBlock;
+
+ currentBlock = "";
+ for (const auto& mail : vcard->getEMailAddresses()) {
+ QString field = buildVCardField(mail.isPreferred, QObject::tr("E-Mail"), htmlEscape(P2QSTRING(mail.address)));
+ if (mail.isPreferred) {
+ currentBlock = field;
+ break;
+ }
+ currentBlock += field;
+ }
+ summary += currentBlock;
+
+ currentBlock = "";
+ for (const auto& org : vcard->getOrganizations()) {
+ QString field = buildVCardField(false, QObject::tr("Organization"), htmlEscape(P2QSTRING(org.name)));
+ currentBlock += field;
+ }
+ summary += currentBlock;
+
+ currentBlock = "";
+ for (const auto& title : vcard->getTitles()) {
+ QString field = buildVCardField(false, QObject::tr("Title"), htmlEscape(P2QSTRING(title)));
+ currentBlock += field;
+ }
+ summary += currentBlock;
+
+ summary += "</table>";
+ return summary;
}
QString RosterTooltip::buildVCardField(bool preferred, const QString& name, const QString& content) {
- QString rowTemplate;
- if (QApplication::layoutDirection() == Qt::RightToLeft) {
- rowTemplate = QString("<tr><td>%3</td><td valign='middle'><strong>%2</strong></td><td valign='middle'>%1</td></tr>");
- } else {
- rowTemplate = QString("<tr><td>%1</td><td valign='middle'><strong>%2</strong></td><td valign='middle'>%3</td></tr>");
- }
- return rowTemplate.arg(preferred ? "<img src=':/icons/star-checked.png' />" : "", name, content);
+ 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 c2fecb5..c0402e8 100644
--- a/Swift/QtUI/Roster/main.cpp
+++ b/Swift/QtUI/Roster/main.cpp
@@ -1,66 +1,67 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <QtGui>
-#include "QtTreeWidget.h"
-#include "QtTreeWidgetFactory.h"
-#include "Swiften/Elements/StatusShow.h"
+#include <Swiften/Elements/StatusShow.h>
+
+#include <Swift/QtUI/Roster/QtTreeWidget.h>
+#include <Swift/QtUI/Roster/QtTreeWidgetFactory.h>
int main(int argc, char *argv[])
{
- QApplication app(argc, argv);
+ QApplication app(argc, argv);
+
+ //Swift::RosterModel model;
+
+ //QTreeView view;
+ //view.setModel(&model);
+ //view.setWindowTitle("A roster");
+ //view.show();
- //Swift::RosterModel model;
+ 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);
+ }
- //QTreeView view;
- //view.setModel(&model);
- //view.setWindowTitle("A roster");
- //view.show();
+ Swift::QtTreeWidgetItem* group = dynamic_cast<Swift::QtTreeWidgetItem*>(treeWidgetFactory.createTreeWidgetItem(tree));
+ group->setText("Many People");
- 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::QtTreeWidgetItem* person350;
+ Swift::QtTreeWidgetItem* person1200;
- 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;
- }
+ 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;
+ }
- for (int i = 0; i < item3s.size(); i++) {
- item3s[i]->setStatusShow(Swift::StatusShow::XA);
- }
+ for (int i = 0; i < item3s.size(); i++) {
+ item3s[i]->setStatusShow(Swift::StatusShow::XA);
+ }
- person350->setStatusShow(Swift::StatusShow::DND);
- person1200->setStatusShow(Swift::StatusShow::Online);
+ person350->setStatusShow(Swift::StatusShow::DND);
+ person1200->setStatusShow(Swift::StatusShow::Online);
- return app.exec();
+ return app.exec();
}
diff --git a/Swift/QtUI/SConscript b/Swift/QtUI/SConscript
index c8313c2..88cb1ac 100644
--- a/Swift/QtUI/SConscript
+++ b/Swift/QtUI/SConscript
@@ -1,21 +1,21 @@
import os, datetime, re, time
import Version
-def generateDefaultTheme(dir) :
- sourceDir = dir.abspath
- result = "<!-- WARNING: This file is automatically generated. Any changes will be overwritten. -->\n"
- result += "<RCC version =\"1.0\">"
- result += "<qresource prefix=\"/themes/Default\">"
- for (path, dirs, files) in os.walk(sourceDir) :
- for file in files :
- filePath = os.path.join(path,file)
- result += "<file alias=\"%(alias)s\">%(path)s</file>" % {
- "alias": filePath[len(sourceDir)+1:],
- "path": filePath
- }
- result += "</qresource>"
- result += "</RCC>"
- return result
+def generateQRCTheme(dir, prefix) :
+ sourceDir = dir.abspath
+ result = "<!-- WARNING: This file is automatically generated. Any changes will be overwritten. -->\n"
+ result += "<RCC version =\"1.0\">"
+ result += "<qresource prefix=\"/themes/" + prefix + "\">"
+ for (path, dirs, files) in os.walk(sourceDir) :
+ for file in files :
+ filePath = os.path.join(path,file)
+ result += "<file alias=\"%(alias)s\">%(path)s</file>" % {
+ "alias": filePath[len(sourceDir)+1:],
+ "path": filePath
+ }
+ result += "</qresource>"
+ result += "</RCC>"
+ return result
Import("env")
@@ -24,33 +24,30 @@ myenv = env.Clone()
# Disable warnings that affect Qt
myenv["CXXFLAGS"] = filter(lambda x : x != "-Wfloat-equal", myenv["CXXFLAGS"])
if "clang" in env["CC"] :
- myenv.Append(CXXFLAGS = ["-Wno-float-equal", "-Wno-shorten-64-to-32", "-Wno-missing-prototypes", "-Wno-unreachable-code", "-Wno-disabled-macro-expansion", "-Wno-unused-private-field", "-Wno-extra-semi", "-Wno-duplicate-enum", "-Wno-missing-variable-declarations", "-Wno-conversion", "-Wno-undefined-reinterpret-cast"])
+ myenv.Append(CXXFLAGS = ["-Wno-float-equal", "-Wno-shorten-64-to-32", "-Wno-missing-prototypes", "-Wno-unreachable-code", "-Wno-disabled-macro-expansion", "-Wno-unused-private-field", "-Wno-extra-semi", "-Wno-duplicate-enum", "-Wno-missing-variable-declarations", "-Wno-conversion", "-Wno-undefined-reinterpret-cast"])
myenv.UseFlags(env["SWIFT_CONTROLLERS_FLAGS"])
myenv.UseFlags(env["SWIFTOOLS_FLAGS"])
if myenv["HAVE_XSS"] :
- myenv.UseFlags(env["XSS_FLAGS"])
+ myenv.UseFlags(env["XSS_FLAGS"])
if env["PLATFORM"] == "posix" :
- myenv.Append(LIBS = ["X11"])
+ myenv.Append(LIBS = ["X11"])
if myenv["HAVE_SPARKLE"] :
- myenv.UseFlags(env["SPARKLE_FLAGS"])
+ myenv.UseFlags(env["SPARKLE_FLAGS"])
myenv.UseFlags(env["SWIFTEN_FLAGS"])
myenv.UseFlags(env["SWIFTEN_DEP_FLAGS"])
if myenv.get("HAVE_BREAKPAD") :
- myenv.UseFlags(env["BREAKPAD_FLAGS"])
+ myenv.UseFlags(env["BREAKPAD_FLAGS"])
if myenv.get("HAVE_GROWL", False) :
- myenv.UseFlags(myenv["GROWL_FLAGS"])
- myenv.Append(CPPDEFINES = ["HAVE_GROWL"])
+ myenv.UseFlags(myenv["GROWL_FLAGS"])
+ myenv.Append(CPPDEFINES = ["HAVE_GROWL"])
if myenv["swift_mobile"] :
- myenv.Append(CPPDEFINES = ["SWIFT_MOBILE"])
-if myenv.get("HAVE_SNARL", False) :
- myenv.UseFlags(myenv["SNARL_FLAGS"])
- myenv.Append(CPPDEFINES = ["HAVE_SNARL"])
+ myenv.Append(CPPDEFINES = ["SWIFT_MOBILE"])
if myenv.get("HAVE_HUNSPELL", True):
- myenv.Append(CPPDEFINES = ["HAVE_HUNSPELL"])
- myenv.UseFlags(myenv["HUNSPELL_FLAGS"])
+ myenv.Append(CPPDEFINES = ["HAVE_HUNSPELL"])
+ myenv.UseFlags(myenv["HUNSPELL_FLAGS"])
if env["PLATFORM"] == "win32" :
- myenv.Append(LIBS = ["cryptui"])
+ myenv.Append(LIBS = ["cryptui"])
myenv.UseFlags(myenv["PLATFORM_FLAGS"])
myenv.Tool("qt4", toolpath = ["#/BuildTools/SCons/Tools"])
@@ -59,16 +56,18 @@ myenv.Tool("wix", toolpath = ["#/BuildTools/SCons/Tools"])
myenv.Tool("textfile", toolpath = ["#/BuildTools/SCons/Tools"])
qt4modules = ['QtCore', 'QtWebKit', 'QtGui']
if myenv["qt5"] :
- qt_version = '5'
- qt4modules += ['QtWidgets', 'QtWebKitWidgets', 'QtMultimedia']
- if env["PLATFORM"] != "win32" and env["PLATFORM"] != "darwin" :
- qt4modules += ['QtX11Extras']
+ qt_version = '5'
+ # QtSvg is required so the image format plugin for SVG images is installed
+ # correctly by Qt's deployment tools.
+ qt4modules += ['QtWidgets', 'QtWebKitWidgets', 'QtMultimedia', 'QtSvg']
+ if env["PLATFORM"] != "win32" and env["PLATFORM"] != "darwin" :
+ qt4modules += ['QtX11Extras']
else :
- qt_version = '4'
+ qt_version = '4'
if env["PLATFORM"] == "posix" :
- qt4modules += ["QtDBus"]
+ qt4modules += ["QtDBus"]
if env["PLATFORM"] != "win32" and env["PLATFORM"] != "darwin" :
- qt4modules += ["QtNetwork"]
+ qt4modules += ["QtNetwork"]
myenv.EnableQt4Modules(qt4modules, debug = False, version = qt_version)
@@ -76,167 +75,170 @@ myenv.Append(CPPPATH = ["."])
# Qt requires applications to be build with the -fPIC flag on some 32-bit Linux distributions.
if env["PLATFORM"] == "posix" :
- testEnv = myenv.Clone()
- conf = Configure(testEnv)
- if conf.CheckDeclaration("QT_REDUCE_RELOCATIONS", "#include <QtCore/qconfig.h>") and conf.CheckDeclaration("__i386__"):
- myenv.AppendUnique(CXXFLAGS = "-fPIC")
- testEnv = conf.Finish()
+ testEnv = myenv.Clone()
+ conf = Configure(testEnv)
+ if conf.CheckDeclaration("QT_REDUCE_RELOCATIONS", "#include <QtCore/qconfig.h>") and conf.CheckDeclaration("__i386__"):
+ myenv.AppendUnique(CXXFLAGS = "-fPIC")
+ testEnv = conf.Finish()
if env["PLATFORM"] == "win32" :
- #myenv.Append(LINKFLAGS = ["/SUBSYSTEM:CONSOLE"])
- myenv.Append(LINKFLAGS = ["/SUBSYSTEM:WINDOWS"])
- myenv.Append(LIBS = "qtmain")
- if myenv.get("HAVE_SCHANNEL", 0) :
- myenv.Append(LIBS = "Cryptui")
- myenv.Append(CPPDEFINES = "HAVE_SCHANNEL")
- if env["debug"] and not env["optimize"]:
- myenv.Append(LINKFLAGS = ["/NODEFAULTLIB:msvcrt"])
+ #myenv.Append(LINKFLAGS = ["/SUBSYSTEM:CONSOLE"])
+ myenv.Append(LINKFLAGS = ["/SUBSYSTEM:WINDOWS"])
+ myenv.Append(LIBS = "qtmain")
+ if myenv.get("HAVE_SCHANNEL", 0) :
+ myenv.Append(LIBS = "Cryptui")
+ myenv.Append(CPPDEFINES = "HAVE_SCHANNEL")
-myenv.WriteVal("DefaultTheme.qrc", myenv.Value(generateDefaultTheme(myenv.Dir("#/Swift/resources/themes/Default"))))
+if env["PLATFORM"] == "darwin" and env["HAVE_SPARKLE"] :
+ myenv.Append(LINKFLAGS = ["-Wl,-rpath,@loader_path/../Frameworks"])
+
+myenv.WriteVal("DefaultTheme.qrc", myenv.Value(generateQRCTheme(myenv.Dir("#/Swift/resources/themes/Default"), "Default")))
sources = [
- "main.cpp",
- "QtAboutWidget.cpp",
- "QtSpellCheckerWindow.cpp",
- "QtAvatarWidget.cpp",
- "QtUIFactory.cpp",
- "QtChatWindowFactory.cpp",
- "QtClickableLabel.cpp",
- "QtLoginWindow.cpp",
- "QtMainWindow.cpp",
- "QtProfileWindow.cpp",
- "QtBlockListEditorWindow.cpp",
- "QtNameWidget.cpp",
- "QtSettingsProvider.cpp",
- "QtStatusWidget.cpp",
- "QtScaledAvatarCache.cpp",
- "QtSwift.cpp",
- "QtURIHandler.cpp",
- "QtChatWindow.cpp",
- "QtChatView.cpp",
- "QtWebKitChatView.cpp",
- "QtPlainChatView.cpp",
- "QtChatTheme.cpp",
- "QtChatTabs.cpp",
- "QtChatTabsBase.cpp",
- "QtChatTabsShortcutOnlySubstitute.cpp",
- "QtSoundPlayer.cpp",
- "QtSystemTray.cpp",
- "QtCachedImageScaler.cpp",
- "QtTabbable.cpp",
- "QtTabWidget.cpp",
- "QtTextEdit.cpp",
- "QtXMLConsoleWidget.cpp",
- "QtHistoryWindow.cpp",
- "QtFileTransferListWidget.cpp",
- "QtFileTransferListItemModel.cpp",
- "QtAdHocCommandWindow.cpp",
- "QtAdHocCommandWithJIDWindow.cpp",
- "QtUtilities.cpp",
- "QtBookmarkDetailWindow.cpp",
- "QtAddBookmarkWindow.cpp",
- "QtEditBookmarkWindow.cpp",
- "QtEmoticonsGrid.cpp",
- "QtEmoticonCell.cpp",
- "QtContactEditWindow.cpp",
- "QtContactEditWidget.cpp",
- "QtSingleWindow.cpp",
- "QtHighlightEditor.cpp",
- "QtColorToolButton.cpp",
- "QtClosableLineEdit.cpp",
- "ChatSnippet.cpp",
- "MessageSnippet.cpp",
- "SystemMessageSnippet.cpp",
- "QtElidingLabel.cpp",
- "QtFormWidget.cpp",
- "QtFormResultItemModel.cpp",
- "QtLineEdit.cpp",
- "QtJoinMUCWindow.cpp",
- "QtConnectionSettingsWindow.cpp",
- "Roster/RosterModel.cpp",
- "Roster/QtTreeWidget.cpp",
-# "Roster/QtTreeWidgetItem.cpp",
- "Roster/RosterDelegate.cpp",
- "Roster/GroupItemDelegate.cpp",
- "Roster/DelegateCommons.cpp",
- "Roster/QtFilterWidget.cpp",
- "Roster/QtRosterWidget.cpp",
- "Roster/QtOccupantListWidget.cpp",
- "Roster/RosterTooltip.cpp",
- "EventViewer/EventModel.cpp",
- "EventViewer/EventDelegate.cpp",
- "EventViewer/TwoLineDelegate.cpp",
- "EventViewer/QtEventWindow.cpp",
- "EventViewer/QtEvent.cpp",
- "ChatList/QtChatListWindow.cpp",
- "ChatList/ChatListModel.cpp",
- "ChatList/ChatListDelegate.cpp",
- "ChatList/ChatListMUCItem.cpp",
- "ChatList/ChatListRecentItem.cpp",
- "ChatList/ChatListWhiteboardItem.cpp",
- "MUCSearch/QtMUCSearchWindow.cpp",
- "MUCSearch/MUCSearchModel.cpp",
- "MUCSearch/MUCSearchRoomItem.cpp",
- "MUCSearch/MUCSearchEmptyItem.cpp",
- "MUCSearch/MUCSearchDelegate.cpp",
- "UserSearch/ContactListDelegate.cpp",
- "UserSearch/ContactListModel.cpp",
- "UserSearch/QtContactListWidget.cpp",
- "UserSearch/QtSuggestingJIDInput.cpp",
- "UserSearch/QtUserSearchFirstPage.cpp",
- "UserSearch/QtUserSearchFirstMultiJIDPage.cpp",
- "UserSearch/QtUserSearchFieldsPage.cpp",
- "UserSearch/QtUserSearchResultsPage.cpp",
- "UserSearch/QtUserSearchDetailsPage.cpp",
- "UserSearch/QtUserSearchWindow.cpp",
- "UserSearch/UserSearchModel.cpp",
- "UserSearch/UserSearchDelegate.cpp",
- "Whiteboard/FreehandLineItem.cpp",
- "Whiteboard/GView.cpp",
- "Whiteboard/TextDialog.cpp",
- "Whiteboard/QtWhiteboardWindow.cpp",
- "Whiteboard/ColorWidget.cpp",
- "QtSubscriptionRequestWindow.cpp",
- "QtRosterHeader.cpp",
- "QtWebView.cpp",
- "qrc_DefaultTheme.cc",
- "qrc_Swift.cc",
- "QtChatWindowJSBridge.cpp",
- "QtMUCConfigurationWindow.cpp",
- "QtAffiliationEditor.cpp",
- "QtUISettingConstants.cpp",
- "QtURLValidator.cpp",
- "QtResourceHelper.cpp",
- "QtSpellCheckHighlighter.cpp",
- "Trellis/QtDynamicGridLayout.cpp",
- "Trellis/QtDNDTabBar.cpp",
- "Trellis/QtGridSelectionDialog.cpp"
+ "main.cpp",
+ "QtAboutWidget.cpp",
+ "QtSpellCheckerWindow.cpp",
+ "QtAvatarWidget.cpp",
+ "QtUIFactory.cpp",
+ "QtChatWindowFactory.cpp",
+ "QtClickableLabel.cpp",
+ "QtLoginWindow.cpp",
+ "QtMainWindow.cpp",
+ "QtProfileWindow.cpp",
+ "QtBlockListEditorWindow.cpp",
+ "QtNameWidget.cpp",
+ "QtSettingsProvider.cpp",
+ "QtStatusWidget.cpp",
+ "QtScaledAvatarCache.cpp",
+ "QtSwift.cpp",
+ "QtURIHandler.cpp",
+ "QtChatWindow.cpp",
+ "QtChatView.cpp",
+ "QtWebKitChatView.cpp",
+ "QtPlainChatView.cpp",
+ "QtChatTheme.cpp",
+ "QtChatTabs.cpp",
+ "QtChatTabsBase.cpp",
+ "QtChatTabsShortcutOnlySubstitute.cpp",
+ "QtSoundPlayer.cpp",
+ "QtSystemTray.cpp",
+ "QtCachedImageScaler.cpp",
+ "QtTabbable.cpp",
+ "QtTabWidget.cpp",
+ "QtTextEdit.cpp",
+ "QtXMLConsoleWidget.cpp",
+ "QtHistoryWindow.cpp",
+ "QtFileTransferListWidget.cpp",
+ "QtFileTransferListItemModel.cpp",
+ "QtAdHocCommandWindow.cpp",
+ "QtAdHocCommandWithJIDWindow.cpp",
+ "QtUtilities.cpp",
+ "QtBookmarkDetailWindow.cpp",
+ "QtAddBookmarkWindow.cpp",
+ "QtEditBookmarkWindow.cpp",
+ "QtEmoticonsGrid.cpp",
+ "QtEmoticonCell.cpp",
+ "QtContactEditWindow.cpp",
+ "QtContactEditWidget.cpp",
+ "QtSingleWindow.cpp",
+ "QtHighlightEditor.cpp",
+ "QtColorToolButton.cpp",
+ "QtClosableLineEdit.cpp",
+ "ChatSnippet.cpp",
+ "MessageSnippet.cpp",
+ "SystemMessageSnippet.cpp",
+ "QtElidingLabel.cpp",
+ "QtFormWidget.cpp",
+ "QtFormResultItemModel.cpp",
+ "QtLineEdit.cpp",
+ "QtJoinMUCWindow.cpp",
+ "QtConnectionSettingsWindow.cpp",
+ "Roster/RosterModel.cpp",
+ "Roster/QtTreeWidget.cpp",
+ "Roster/RosterDelegate.cpp",
+ "Roster/GroupItemDelegate.cpp",
+ "Roster/DelegateCommons.cpp",
+ "Roster/QtFilterWidget.cpp",
+ "Roster/QtRosterWidget.cpp",
+ "Roster/QtOccupantListWidget.cpp",
+ "Roster/RosterTooltip.cpp",
+ "EventViewer/EventModel.cpp",
+ "EventViewer/EventDelegate.cpp",
+ "EventViewer/TwoLineDelegate.cpp",
+ "EventViewer/QtEventWindow.cpp",
+ "EventViewer/QtEvent.cpp",
+ "ChatList/QtChatListWindow.cpp",
+ "ChatList/ChatListModel.cpp",
+ "ChatList/ChatListDelegate.cpp",
+ "ChatList/ChatListMUCItem.cpp",
+ "ChatList/ChatListRecentItem.cpp",
+ "ChatList/ChatListWhiteboardItem.cpp",
+ "MUCSearch/MUCSearchDelegate.cpp",
+ "MUCSearch/MUCSearchEmptyItem.cpp",
+ "MUCSearch/MUCSearchModel.cpp",
+ "MUCSearch/MUCSearchRoomItem.cpp",
+ "MUCSearch/MUCSearchServiceItem.cpp",
+ "MUCSearch/QtLeafSortFilterProxyModel.cpp",
+ "MUCSearch/QtMUCSearchWindow.cpp",
+ "UserSearch/ContactListDelegate.cpp",
+ "UserSearch/ContactListModel.cpp",
+ "UserSearch/QtContactListWidget.cpp",
+ "UserSearch/QtSuggestingJIDInput.cpp",
+ "UserSearch/QtUserSearchFirstPage.cpp",
+ "UserSearch/QtUserSearchFirstMultiJIDPage.cpp",
+ "UserSearch/QtUserSearchFieldsPage.cpp",
+ "UserSearch/QtUserSearchResultsPage.cpp",
+ "UserSearch/QtUserSearchDetailsPage.cpp",
+ "UserSearch/QtUserSearchWindow.cpp",
+ "UserSearch/UserSearchModel.cpp",
+ "UserSearch/UserSearchDelegate.cpp",
+ "Whiteboard/FreehandLineItem.cpp",
+ "Whiteboard/GView.cpp",
+ "Whiteboard/TextDialog.cpp",
+ "Whiteboard/QtWhiteboardWindow.cpp",
+ "Whiteboard/ColorWidget.cpp",
+ "QtSubscriptionRequestWindow.cpp",
+ "QtRosterHeader.cpp",
+ "QtWebView.cpp",
+ "qrc_DefaultTheme.cc",
+ "qrc_Swift.cc",
+ "QtChatWindowJSBridge.cpp",
+ "QtMUCConfigurationWindow.cpp",
+ "QtAffiliationEditor.cpp",
+ "QtUISettingConstants.cpp",
+ "QtURLValidator.cpp",
+ "QtResourceHelper.cpp",
+ "QtSpellCheckHighlighter.cpp",
+ "QtUpdateFeedSelectionDialog.cpp",
+ "Trellis/QtDynamicGridLayout.cpp",
+ "Trellis/QtDNDTabBar.cpp",
+ "Trellis/QtGridSelectionDialog.cpp"
]
if env["PLATFORM"] == "win32" :
- sources.extend(["qrc_SwiftWindows.cc"])
+ sources.extend(["qrc_SwiftWindows.cc"])
# QtVCardWidget
sources.extend([
- "QtVCardWidget/QtCloseButton.cpp",
- "QtVCardWidget/QtRemovableItemDelegate.cpp",
- "QtVCardWidget/QtResizableLineEdit.cpp",
- "QtVCardWidget/QtTagComboBox.cpp",
- "QtVCardWidget/QtVCardHomeWork.cpp",
- "QtVCardWidget/QtVCardAddressField.cpp",
- "QtVCardWidget/QtVCardAddressLabelField.cpp",
- "QtVCardWidget/QtVCardBirthdayField.cpp",
- "QtVCardWidget/QtVCardDescriptionField.cpp",
- "QtVCardWidget/QtVCardInternetEMailField.cpp",
- "QtVCardWidget/QtVCardJIDField.cpp",
- "QtVCardWidget/QtVCardOrganizationField.cpp",
- "QtVCardWidget/QtVCardPhotoAndNameFields.cpp",
- "QtVCardWidget/QtVCardRoleField.cpp",
- "QtVCardWidget/QtVCardTelephoneField.cpp",
- "QtVCardWidget/QtVCardTitleField.cpp",
- "QtVCardWidget/QtVCardURLField.cpp",
- "QtVCardWidget/QtVCardGeneralField.cpp",
- "QtVCardWidget/QtVCardWidget.cpp"
+ "QtVCardWidget/QtCloseButton.cpp",
+ "QtVCardWidget/QtRemovableItemDelegate.cpp",
+ "QtVCardWidget/QtResizableLineEdit.cpp",
+ "QtVCardWidget/QtTagComboBox.cpp",
+ "QtVCardWidget/QtVCardHomeWork.cpp",
+ "QtVCardWidget/QtVCardAddressField.cpp",
+ "QtVCardWidget/QtVCardAddressLabelField.cpp",
+ "QtVCardWidget/QtVCardBirthdayField.cpp",
+ "QtVCardWidget/QtVCardDescriptionField.cpp",
+ "QtVCardWidget/QtVCardInternetEMailField.cpp",
+ "QtVCardWidget/QtVCardJIDField.cpp",
+ "QtVCardWidget/QtVCardOrganizationField.cpp",
+ "QtVCardWidget/QtVCardPhotoAndNameFields.cpp",
+ "QtVCardWidget/QtVCardRoleField.cpp",
+ "QtVCardWidget/QtVCardTelephoneField.cpp",
+ "QtVCardWidget/QtVCardTitleField.cpp",
+ "QtVCardWidget/QtVCardURLField.cpp",
+ "QtVCardWidget/QtVCardGeneralField.cpp",
+ "QtVCardWidget/QtVCardWidget.cpp"
])
myenv.Uic4("QtVCardWidget/QtVCardPhotoAndNameFields.ui")
@@ -247,52 +249,52 @@ myenv.Uic4("QtProfileWindow.ui")
# Determine the version
myenv["SWIFT_VERSION"] = Version.getBuildVersion(env.Dir("#").abspath, "swift")
if env["PLATFORM"] == "win32" :
- swift_windows_version = Version.convertToWindowsVersion(myenv["SWIFT_VERSION"])
- myenv["SWIFT_VERSION_MAJOR"] = swift_windows_version[0]
- myenv["SWIFT_VERSION_MINOR"] = swift_windows_version[1]
- myenv["SWIFT_VERSION_PATCH"] = swift_windows_version[2]
+ swift_windows_version = Version.convertToWindowsVersion(myenv["SWIFT_VERSION"])
+ myenv["SWIFT_VERSION_MAJOR"] = swift_windows_version[0]
+ myenv["SWIFT_VERSION_MINOR"] = swift_windows_version[1]
+ myenv["SWIFT_VERSION_PATCH"] = swift_windows_version[2]
if env["PLATFORM"] == "win32" :
- res_env = myenv.Clone()
- res_env.Append(CPPDEFINES = [
- ("SWIFT_COPYRIGHT_YEAR", "\"\\\"2010-%s\\\"\"" % str(time.localtime()[0])),
- ("SWIFT_VERSION_MAJOR", "${SWIFT_VERSION_MAJOR}"),
- ("SWIFT_VERSION_MINOR", "${SWIFT_VERSION_MINOR}"),
- ("SWIFT_VERSION_PATCH", "${SWIFT_VERSION_PATCH}"),
- ])
- res = res_env.RES("#/Swift/resources/Windows/Swift.rc")
- # For some reason, SCons isn't picking up the dependency correctly
- # Adding it explicitly until i figure out why
- myenv.Depends(res, "../Controllers/BuildVersion.h")
- sources += [
- "WinUIHelpers.cpp",
- "CAPICertificateSelector.cpp",
- "WindowsNotifier.cpp",
- "#/Swift/resources/Windows/Swift.res"
- ]
+ res_env = myenv.Clone()
+ res_env.Append(CPPDEFINES = [
+ ("SWIFT_COPYRIGHT_YEAR", "\"\\\"2010-%s\\\"\"" % str(time.localtime()[0])),
+ ("SWIFT_VERSION_MAJOR", "${SWIFT_VERSION_MAJOR}"),
+ ("SWIFT_VERSION_MINOR", "${SWIFT_VERSION_MINOR}"),
+ ("SWIFT_VERSION_PATCH", "${SWIFT_VERSION_PATCH}"),
+ ])
+ res = res_env.RES("#/Swift/resources/Windows/Swift.rc")
+ # For some reason, SCons isn't picking up the dependency correctly
+ # Adding it explicitly until i figure out why
+ myenv.Depends(res, "../Controllers/BuildVersion.h")
+ sources += [
+ "WinUIHelpers.cpp",
+ "CAPICertificateSelector.cpp",
+ "WindowsNotifier.cpp",
+ "#/Swift/resources/Windows/Swift.res"
+ ]
if env["PLATFORM"] == "posix" :
- sources += [
- "FreeDesktopNotifier.cpp",
- "QtDBUSURIHandler.cpp",
- ]
+ sources += [
+ "FreeDesktopNotifier.cpp",
+ "QtDBUSURIHandler.cpp",
+ ]
if env["PLATFORM"] == "darwin" :
- sources += ["CocoaApplicationActivateHelper.mm"]
- sources += ["CocoaUIHelpers.mm"]
+ sources += ["CocoaApplicationActivateHelper.mm"]
+ sources += ["CocoaUIHelpers.mm"]
if env["PLATFORM"] == "darwin" or env["PLATFORM"] == "win32" :
- swiftProgram = myenv.Program("Swift", sources)
+ swiftProgram = myenv.Program("Swift", sources)
else :
- sources += ["QtCertificateViewerDialog.cpp"];
- myenv.Uic4("QtCertificateViewerDialog.ui");
- swiftProgram = myenv.Program("swift-im", sources)
+ sources += ["QtCertificateViewerDialog.cpp"];
+ myenv.Uic4("QtCertificateViewerDialog.ui");
+ swiftProgram = myenv.Program("swift-im", sources)
if env["PLATFORM"] != "darwin" and env["PLATFORM"] != "win32" :
- openURIProgram = myenv.Program("swift-open-uri", "swift-open-uri.cpp")
+ openURIProgram = myenv.Program("swift-open-uri", "swift-open-uri.cpp")
else :
- openURIProgram = []
+ openURIProgram = []
myenv.Uic4("MUCSearch/QtMUCSearchWindow.ui")
myenv.Uic4("UserSearch/QtUserSearchWizard.ui")
@@ -308,15 +310,16 @@ myenv.Uic4("QtConnectionSettings.ui")
myenv.Uic4("QtHighlightEditor.ui")
myenv.Uic4("QtBlockListEditorWindow.ui")
myenv.Uic4("QtSpellCheckerWindow.ui")
+myenv.Uic4("QtUpdateFeedSelectionDialog.ui")
myenv.Qrc("DefaultTheme.qrc")
myenv.Qrc("Swift.qrc")
if env["PLATFORM"] == "win32" :
- myenv.Qrc("SwiftWindows.qrc")
+ myenv.Qrc("SwiftWindows.qrc")
# Resources
commonResources = {
- "": ["#/Swift/resources/sounds"]
+ "": ["#/Swift/resources/sounds"]
}
myenv["TEXTFILESUFFIX"] = ""
@@ -329,138 +332,143 @@ myenv.MyTextfile(target = "COPYING", source = [myenv.File("../../COPYING.gpl"),
# Collect available languages
translation_languages = []
for file in os.listdir(Dir("#/Swift/Translations").abspath) :
- if file.startswith("swift_") and file.endswith(".ts") :
- translation_languages.append(file[6:-3])
+ if file.startswith("swift_") and file.endswith(".ts") :
+ translation_languages.append(file[6:-3])
# Generate translation modules
translation_sources = [env.File("#/Swift/Translations/swift.ts").abspath]
translation_modules = []
for lang in translation_languages :
- translation_resource = "#/Swift/resources/translations/swift_" + lang + ".qm"
- translation_source = "#/Swift/Translations/swift_" + lang + ".ts"
- translation_sources.append(env.File(translation_source).abspath)
- translation_modules.append(env.File(translation_resource).abspath)
- myenv.Qm(translation_resource, translation_source)
- commonResources["translations"] = commonResources.get("translations", []) + [translation_resource]
+ translation_resource = "#/Swift/resources/translations/swift_" + lang + ".qm"
+ translation_source = "#/Swift/Translations/swift_" + lang + ".ts"
+ translation_sources.append(env.File(translation_source).abspath)
+ translation_modules.append(env.File(translation_resource).abspath)
+ myenv.Qm(translation_resource, translation_source)
+ commonResources["translations"] = commonResources.get("translations", []) + [translation_resource]
# LUpdate translation (if requested)
if ARGUMENTS.get("update_translations", False) :
- myenv.Precious(translation_sources)
- remove_obsolete_option = ""
- codecfortr = ""
- if ARGUMENTS.get("remove_obsolete_translations", False) :
- remove_obsolete_option = " -no-obsolete"
- if qt_version == '4':
- codecfortr = "-codecfortr UTF-8"
- for translation_source in filter(lambda x: not x.endswith("_en.ts"), translation_sources) :
- t = myenv.Command([translation_source], [], [myenv.Action("$QT4_LUPDATE -I " + env.Dir("#").abspath + remove_obsolete_option + " -silent " + codecfortr + " -recursive Swift -ts " + translation_source, cmdstr = "$QT4_LUPDATECOMSTR")])
- myenv.AlwaysBuild(t)
+ myenv.Precious(translation_sources)
+ remove_obsolete_option = ""
+ codecfortr = ""
+ if ARGUMENTS.get("remove_obsolete_translations", False) :
+ remove_obsolete_option = " -no-obsolete"
+ if qt_version == '4':
+ codecfortr = "-codecfortr UTF-8"
+ for translation_source in filter(lambda x: not x.endswith("_en.ts"), translation_sources) :
+ t = myenv.Command([translation_source], [], [myenv.Action("$QT4_LUPDATE -I " + env.Dir("#").abspath + remove_obsolete_option + " -silent " + codecfortr + " -recursive Swift -ts " + translation_source, cmdstr = "$QT4_LUPDATECOMSTR")])
+ myenv.AlwaysBuild(t)
# NSIS installation script
if env["PLATFORM"] == "win32" :
- nsis_translation_install_script = ""
- nsis_translation_uninstall_script = ""
- for lang in translation_languages :
- nsis_translation_install_script += "File \"..\\..\\QtUI\\Swift\\translations\\swift_" + lang + ".qm\"\n"
- nsis_translation_uninstall_script += "delete $INSTDIR\\translations\\swift_" + lang + ".qm\n"
- myenv.WriteVal("../Packaging/nsis/translations-install.nsh", myenv.Value(nsis_translation_install_script))
- myenv.WriteVal("../Packaging/nsis/translations-uninstall.nsh", myenv.Value(nsis_translation_uninstall_script))
-
+ nsis_translation_install_script = ""
+ nsis_translation_uninstall_script = ""
+ for lang in translation_languages :
+ nsis_translation_install_script += "File \"..\\..\\QtUI\\Swift\\translations\\swift_" + lang + ".qm\"\n"
+ nsis_translation_uninstall_script += "delete $INSTDIR\\translations\\swift_" + lang + ".qm\n"
+ myenv.WriteVal("../Packaging/nsis/translations-install.nsh", myenv.Value(nsis_translation_install_script))
+ myenv.WriteVal("../Packaging/nsis/translations-uninstall.nsh", myenv.Value(nsis_translation_uninstall_script))
+
################################################################################
if env["PLATFORM"] == "darwin" :
- frameworks = []
- if env["HAVE_SPARKLE"] :
- frameworks.append(env["SPARKLE_FRAMEWORK"])
- if env["HAVE_GROWL"] :
- frameworks.append(env["GROWL_FRAMEWORK"])
- commonResources[""] = commonResources.get("", []) + ["#/Swift/resources/MacOSX/Swift.icns"]
- app = myenv.AppBundle("Swift", version = myenv["SWIFT_VERSION"], resources = commonResources, frameworks = frameworks, handlesXMPPURIs = True)
- if env["DIST"] :
- myenv.Command(["#/Packages/Swift/Swift-${SWIFT_VERSION}.dmg"], [app], ["Swift/Packaging/MacOSX/package.sh " + app.path + " Swift/Packaging/MacOSX/Swift.dmg.gz $TARGET $QTDIR"])
- dsym = myenv.Command(["Swift-${SWIFT_VERSION}.dSYM"], ["Swift"], ["dsymutil -o ${TARGET} ${SOURCE}"])
- myenv.Command(["#/Packages/Swift/Swift-${SWIFT_VERSION}.dSYM.zip"], dsym, ["cd ${SOURCE.dir} && zip -r ${TARGET.abspath} ${SOURCE.name}"])
+ frameworks = []
+ if env["HAVE_SPARKLE"] :
+ frameworks.append(env["SPARKLE_FRAMEWORK"])
+ if env["HAVE_GROWL"] :
+ frameworks.append(env["GROWL_FRAMEWORK"])
+ commonResources[""] = commonResources.get("", []) + ["#/Swift/resources/MacOSX/Swift.icns"]
+ app = myenv.AppBundle("Swift", version = myenv["SWIFT_VERSION"], resources = commonResources, frameworks = frameworks, handlesXMPPURIs = True, sparklePublicDSAKey = myenv["SWIFT_SPARKLE_PUBLIC_DSA_KEY"])
+ if env["DIST"] :
+ myenv.Command(["#/Packages/Swift/Swift-${SWIFT_VERSION}.dmg"], [app], ["Swift/Packaging/MacOSX/package.sh " + app.path + " Swift/Packaging/MacOSX/Swift.dmg.gz $TARGET $QTDIR " + "\"$CODE_SIGN_IDENTITY\""])
+ dsym = myenv.Command(["Swift-${SWIFT_VERSION}.dSYM"], ["Swift"], ["dsymutil -o ${TARGET} ${SOURCE}"])
+ myenv.Command(["#/Packages/Swift/Swift-${SWIFT_VERSION}.dSYM.zip"], dsym, ["cd ${SOURCE.dir} && zip -r ${TARGET.abspath} ${SOURCE.name}"])
if env.get("SWIFT_INSTALLDIR", "") :
- env.Install(os.path.join(env["SWIFT_INSTALLDIR"], "bin"), swiftProgram + openURIProgram)
- env.InstallAs(os.path.join(env["SWIFT_INSTALLDIR"], "share", "pixmaps", "swift.xpm"), "#/Swift/resources/logo/logo-icon-32.xpm")
- icons_path = os.path.join(env["SWIFT_INSTALLDIR"], "share", "icons", "hicolor")
- env.InstallAs(os.path.join(icons_path, "32x32", "apps", "swift.xpm"), "#/Swift/resources/logo/logo-icon-32.xpm")
- env.InstallAs(os.path.join(icons_path, "scalable", "apps", "swift.svg"), "#/Swift/resources/logo/logo-icon.svg")
- for i in ["16", "22", "24", "64", "128"] :
- env.InstallAs(os.path.join(icons_path, i + "x" + i, "apps", "swift.png"), "#/Swift/resources/logo/logo-icon-" + i + ".png")
- env.Install(os.path.join(env["SWIFT_INSTALLDIR"], "share", "applications"), "#/Swift/resources/swift.desktop")
- for dir, resource in commonResources.items() :
- env.Install(os.path.join(env["SWIFT_INSTALLDIR"], "share", "swift", dir), resource)
+ env.Install(os.path.join(env["SWIFT_INSTALLDIR"], "bin"), swiftProgram + openURIProgram)
+ env.InstallAs(os.path.join(env["SWIFT_INSTALLDIR"], "share", "pixmaps", "swift.xpm"), "#/Swift/resources/logo/logo-icon-32.xpm")
+ icons_path = os.path.join(env["SWIFT_INSTALLDIR"], "share", "icons", "hicolor")
+ env.InstallAs(os.path.join(icons_path, "32x32", "apps", "swift.xpm"), "#/Swift/resources/logo/logo-icon-32.xpm")
+ env.InstallAs(os.path.join(icons_path, "scalable", "apps", "swift.svg"), "#/Swift/resources/logo/logo-icon.svg")
+ for i in ["16", "22", "24", "64", "128"] :
+ env.InstallAs(os.path.join(icons_path, i + "x" + i, "apps", "swift.png"), "#/Swift/resources/logo/logo-icon-" + i + ".png")
+ env.Install(os.path.join(env["SWIFT_INSTALLDIR"], "share", "applications"), "#/Swift/resources/swift.desktop")
+ for dir, resource in commonResources.items() :
+ env.Install(os.path.join(env["SWIFT_INSTALLDIR"], "share", "swift", dir), resource)
if env["PLATFORM"] == "win32" :
- if env["DIST"] or ARGUMENTS.get("dump_trace") :
- commonResources[""] = commonResources.get("", []) + [
- #os.path.join(env["OPENSSL_DIR"], "bin", "ssleay32.dll"),
- #os.path.join(env["OPENSSL_DIR"], "bin", "libeay32.dll"),
- "#/Swift/resources/images",
- ]
- if env["SWIFTEN_DLL"] :
- commonResources[""] = commonResources.get("", []) + ["#/Swiften/${SWIFTEN_LIBRARY_FILE}"]
- qtplugins = {}
- qtplugins["imageformats"] = ["gif", "ico", "jpeg", "mng", "svg", "tiff"]
- qtlibs = ["QtCore", "QtGui", "QtNetwork", "QtWebKit", "QtXMLPatterns"]
- if qt_version == '4' :
- qtlibs.append("phonon")
- qtlibs = [lib + '4' for lib in qtlibs]
- else :
- qtlibs += ['QtQuick', 'QtQml', 'QtPositioning', 'QtMultimedia', 'QtSql', 'QtSensors', 'QtWidgets', 'QtWebChannel', 'QtWebKitWidgets', 'QtMultimediaWidgets', 'QtOpenGL', 'QtPrintSupport']
- qtlibs = [lib.replace('Qt', 'Qt5') for lib in qtlibs]
- qtlibs += ['icuin51', 'icuuc51', 'icudt51', 'libGLESv2', 'libEGL']
- qtplugins["platforms"] = ['windows']
- qtplugins["accessible"] = ["taccessiblewidgets"]
-
- windowsBundleFiles = myenv.WindowsBundle("Swift",
- resources = commonResources,
- qtplugins = qtplugins,
- qtlibs = qtlibs,
- qtversion = qt_version)
-
- if env["DIST"] :
- #myenv.Append(NSIS_OPTIONS = [
- # "/DmsvccRedistributableDir=\"" + env["vcredist"] + "\"",
- # "/DbuildVersion=" + myenv["SWIFT_VERSION"]
- # ])
- #myenv.Nsis("../Packaging/nsis/swift.nsi")
- if env["SCONS_STAGE"] == "build" and env.get("wix_bindir", None):
- def convertToRTF(env, target, source) :
- infile = open(source[0].abspath, 'r')
- outfile = open(target[0].abspath, 'w')
- outfile.write('{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\fs16\\f0\\pard\n')
- for line in infile:
- for char in line.decode("utf-8") :
- if ord(char) > 127 :
- # FIXME: This is incorrect, because it only works for latin1.
- # The correct way is \u<decimal utf16 point>? , but this is more
- # work
- outfile.write("\\'%X" % ord(char))
- else :
- outfile.write(char)
- outfile.write('\\par ')
- outfile.write('}')
- outfile.close()
- infile.close()
- copying = env.Command(["Swift/COPYING.rtf"], ["COPYING"], convertToRTF)
- wixvariables = {
- 'VCCRTFile': env["vcredist"],
- 'Version': str(myenv["SWIFT_VERSION_MAJOR"]) + "." + str(myenv["SWIFT_VERSION_MINOR"]) + "." + str(myenv["SWIFT_VERSION_PATCH"])
- }
- wixincludecontent = "<Include>"
- for key in wixvariables:
- wixincludecontent += "<?define %s = \"%s\" ?>" % (key, wixvariables[key])
- wixincludecontent += "</Include>"
- myenv.WriteVal("..\\Packaging\\Wix\\variables.wxs", env.Value(wixincludecontent))
- myenv["WIX_SOURCE_OBJECT_DIR"] = "Swift\\QtUI\\Swift"
- myenv.WiX_Heat('..\\Packaging\\WiX\\gen_files.wxs', windowsBundleFiles + copying)
- myenv.WiX_Candle('..\\Packaging\\WiX\\Swift.wixobj', '..\\Packaging\\WiX\\Swift.wxs')
- myenv.WiX_Candle('..\\Packaging\\WiX\\gen_files.wixobj', '..\\Packaging\\WiX\\gen_files.wxs')
- myenv.WiX_Light('#/Packages/Swift/Swift-' + myenv["SWIFT_VERSION"] + '.msi', ['..\\Packaging\\WiX\\gen_files.wixobj','..\\Packaging\\WiX\\Swift.wixobj'])
-
- if myenv["debug"] :
- myenv.InstallAs('#/Packages/Swift/Swift-' + myenv["SWIFT_VERSION"] + '.pdb', "Swift.pdb")
+ if env["DIST"] or ARGUMENTS.get("dump_trace") :
+ commonResources[""] = commonResources.get("", []) + [
+ #os.path.join(env["OPENSSL_DIR"], "bin", "ssleay32.dll"),
+ #os.path.join(env["OPENSSL_DIR"], "bin", "libeay32.dll"),
+ "#/Swift/resources/images",
+ ]
+ if env["SWIFTEN_DLL"] :
+ commonResources[""] = commonResources.get("", []) + ["#/Swiften/${SWIFTEN_LIBRARY_FILE}"]
+ qtplugins = {}
+ qtplugins["imageformats"] = ["gif", "ico", "jpeg", "mng", "svg", "tiff"]
+ qtlibs = ["QtCore", "QtGui", "QtNetwork", "QtWebKit", "QtXMLPatterns"]
+ if qt_version == '4' :
+ qtlibs.append("phonon")
+ qtlibs = [lib + '4' for lib in qtlibs]
+ else :
+ qtlibs += ['QtQuick', 'QtQml', 'QtPositioning', 'QtMultimedia', 'QtSql', 'QtSensors', 'QtWidgets', 'QtWebChannel', 'QtWebKitWidgets', 'QtMultimediaWidgets', 'QtOpenGL', 'QtPrintSupport']
+ qtlibs = [lib.replace('Qt', 'Qt5') for lib in qtlibs]
+ qtlibs += ['icuin51', 'icuuc51', 'icudt51', 'libGLESv2', 'libEGL']
+ qtplugins["platforms"] = ['windows']
+ qtplugins["accessible"] = ["taccessiblewidgets"]
+
+ windowsBundleFiles = myenv.WindowsBundle("Swift",
+ resources = commonResources,
+ qtplugins = qtplugins,
+ qtlibs = qtlibs,
+ qtversion = qt_version)
+
+ if env["DIST"] :
+ #myenv.Append(NSIS_OPTIONS = [
+ # "/DmsvccRedistributableDir=\"" + env["vcredist"] + "\"",
+ # "/DbuildVersion=" + myenv["SWIFT_VERSION"]
+ # ])
+ #myenv.Nsis("../Packaging/nsis/swift.nsi")
+ if env["SCONS_STAGE"] == "build" and env.get("wix_bindir", None):
+ def convertToRTF(env, target, source) :
+ infile = open(source[0].abspath, 'r')
+ outfile = open(target[0].abspath, 'w')
+ outfile.write('{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\fs16\\f0\\pard\n')
+ for line in infile:
+ for char in line.decode("utf-8") :
+ if ord(char) > 127 :
+ # FIXME: This is incorrect, because it only works for latin1.
+ # The correct way is \u<decimal utf16 point>? , but this is more
+ # work
+ outfile.write("\\'%X" % ord(char))
+ else :
+ outfile.write(char)
+ outfile.write('\\par ')
+ outfile.write('}')
+ outfile.close()
+ infile.close()
+ copying = env.Command(["Swift/COPYING.rtf"], ["COPYING"], convertToRTF)
+ wixvariables = {
+ 'VCCRTFile': env["vcredist"],
+ 'Version': str(myenv["SWIFT_VERSION_MAJOR"]) + "." + str(myenv["SWIFT_VERSION_MINOR"]) + "." + str(myenv["SWIFT_VERSION_PATCH"])
+ }
+ wixincludecontent = "<Include>"
+ for key in wixvariables:
+ wixincludecontent += "<?define %s = \"%s\" ?>" % (key, wixvariables[key])
+ wixincludecontent += "</Include>"
+ myenv.WriteVal("..\\Packaging\\Wix\\variables.wxs", env.Value(wixincludecontent))
+ myenv["WIX_SOURCE_OBJECT_DIR"] = "Swift\\QtUI\\Swift"
+ myenv.WiX_Heat('..\\Packaging\\WiX\\gen_files.wxs', windowsBundleFiles + copying)
+ myenv.WiX_Candle('..\\Packaging\\WiX\\Swift.wixobj', '..\\Packaging\\WiX\\Swift.wxs')
+ myenv.WiX_Candle('..\\Packaging\\WiX\\gen_files.wixobj', '..\\Packaging\\WiX\\gen_files.wxs')
+ lightTask = myenv.WiX_Light('#/Packages/Swift/Swift-' + myenv["SWIFT_VERSION"] + '.msi', ['..\\Packaging\\WiX\\gen_files.wixobj','..\\Packaging\\WiX\\Swift.wixobj'])
+ if myenv.get("SIGNTOOL_KEY_PFX", None) and myenv.get("SIGNTOOL_TIMESTAMP_URL", None) :
+ def signToolAction(target = None, source = None, env = None):
+ env.Execute('signtool.exe sign /fd SHA256 /f "${SIGNTOOL_KEY_PFX}" /t "${SIGNTOOL_TIMESTAMP_URL}" ' + str(target[0]))
+
+ myenv.AddPostAction(lightTask, signToolAction)
+
+ if myenv["debug"] :
+ myenv.InstallAs('#/Packages/Swift/Swift-' + myenv["SWIFT_VERSION"] + '.pdb', "Swift.pdb")
diff --git a/Swift/QtUI/Swift.qrc b/Swift/QtUI/Swift.qrc
index 0478d76..cfb0fec 100644
--- a/Swift/QtUI/Swift.qrc
+++ b/Swift/QtUI/Swift.qrc
@@ -4,7 +4,7 @@
<file alias="logo-icon-16.png">../resources/logo/logo-icon-16.png</file>
<file alias="logo-icon-16-win.png">../resources/logo/logo-icon-16-win.png</file>
<file alias="logo-chat-16.png">../resources/logo/logo-chat-16.png</file>
- <file alias="logo-shaded-text.256.png">../resources/logo/logo-shaded-text.256.png</file>
+ <file alias="logo-shaded-text.png">../resources/logo/logo-shaded-text.png</file>
<file alias="icons/online.png">../resources/icons/online.png</file>
<file alias="icons/connecting.mng">../resources/icons/connecting.mng</file>
<file alias="icons/away.png">../resources/icons/away.png</file>
@@ -16,12 +16,13 @@
<file alias="icons/warn.png">../resources/icons/warn.png</file>
<file alias="icons/check.png">../resources/icons/check.png</file>
<file alias="icons/throbber.gif">../resources/icons/throbber.gif</file>
- <file alias="icons/avatar.png">../resources/icons/avatar.png</file>
+ <file alias="icons/avatar.svg">../resources/icons/avatar.svg</file>
<file alias="icons/no-avatar.png">../resources/icons/no-avatar.png</file>
<file alias="icons/tray-standard.png">../resources/icons/tray-standard.png</file>
<file alias="icons/new-chat.png">../resources/icons/new-chat.png</file>
<file alias="icons/actions.png">../resources/icons/actions.png</file>
<file alias="COPYING">COPYING</file>
+ <file alias="ChangeLog.md">../ChangeLog.md</file>
<file alias="icons/line.png">../resources/icons/line.png</file>
<file alias="icons/rect.png">../resources/icons/rect.png</file>
<file alias="icons/circle.png">../resources/icons/circle.png</file>
@@ -43,5 +44,8 @@
<file alias="icons/star-unchecked.png">../resources/icons/star-unchecked2.png</file>
<file alias="icons/zzz.png">../resources/icons/zzz.png</file>
<file alias="icons/stop.png">../resources/icons/stop.png</file>
+ <file alias="icons/delivery-success.svg">../resources/icons/delivery-success.svg</file>
+ <file alias="icons/delivery-failure.svg">../resources/icons/delivery-failure.svg</file>
+ <file alias="icons/delivery-warning.svg">../resources/icons/delivery-warning.svg</file>
</qresource>
</RCC>
diff --git a/Swift/QtUI/SwiftUpdateFeeds.h b/Swift/QtUI/SwiftUpdateFeeds.h
new file mode 100644
index 0000000..a6476f5
--- /dev/null
+++ b/Swift/QtUI/SwiftUpdateFeeds.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2010-2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Base/Platform.h>
+
+namespace Swift {
+
+namespace UpdateFeeds {
+ const std::string StableChannel = "stable";
+ const std::string TestingChannel = "testing";
+ const std::string DevelopmentChannel = "development";
+
+#if defined(SWIFTEN_PLATFORM_MACOSX)
+ const std::string StableAppcastFeed = "https://swift.im/downloads/swift-stable-appcast-mac.xml";
+ const std::string TestingAppcastFeed = "https://swift.im/downloads/swift-testing-appcast-mac.xml";
+ const std::string DevelopmentAppcastFeed = "https://swift.im/downloads/swift-development-appcast-mac.xml";
+#else
+ const std::string StableAppcastFeed = "";
+ const std::string TestingAppcastFeed = "";
+ const std::string DevelopmentAppcastFeed = "";
+#endif
+}
+
+}
diff --git a/Swift/QtUI/SystemMessageSnippet.cpp b/Swift/QtUI/SystemMessageSnippet.cpp
index e752e32..eeb6b9a 100644
--- a/Swift/QtUI/SystemMessageSnippet.cpp
+++ b/Swift/QtUI/SystemMessageSnippet.cpp
@@ -1,26 +1,26 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "SystemMessageSnippet.h"
+#include <Swift/QtUI/SystemMessageSnippet.h>
#include <QDateTime>
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_ = QString("<div id='%1'>%2</div>").arg(id).arg(content_);
+ if (appendToPrevious) {
+ setContinuationFallbackSnippet(std::make_shared<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 8cd68c2..c0d4d2f 100644
--- a/Swift/QtUI/SystemMessageSnippet.h
+++ b/Swift/QtUI/SystemMessageSnippet.h
@@ -8,23 +8,23 @@
#include <QString>
-#include "ChatSnippet.h"
+#include <Swift/QtUI/ChatSnippet.h>
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..9a6c436 100644
--- a/Swift/QtUI/Trellis/QtDNDTabBar.cpp
+++ b/Swift/QtUI/Trellis/QtDNDTabBar.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 = nullptr;
+
+ // 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..6de04d5 100644
--- a/Swift/QtUI/Trellis/QtDNDTabBar.h
+++ b/Swift/QtUI/Trellis/QtDNDTabBar.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,34 +8,37 @@
#include <QTabBar>
+#include <Swift/QtUI/QtTabWidget.h>
+
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 = nullptr);
+ virtual ~QtDNDTabBar();
+
+ int getDragIndex() const;
+ QString getDragText() const;
+ QWidget* getDragWidget() const;
+
+ virtual QSize sizeHint() const;
+
+ friend class QtTabWidget;
+ 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 = -1;
+ QString dragText;
+ QWidget* dragWidget = nullptr;
};
}
diff --git a/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp b/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp
index 3b8adf8..5600cc8 100644
--- a/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp
+++ b/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -23,128 +23,129 @@
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*)));
+QtDynamicGridLayout::QtDynamicGridLayout(QWidget* parent, bool enableDND) : QWidget(parent), dndEnabled_(enableDND), movingTab_(nullptr) {
+ 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);
-
- 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));
-
- 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;
+ assert(gridLayout_->rowCount() > 0 && gridLayout_->columnCount() > 0);
+
+ 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));
+
+ QLayoutItem* item = gridLayout_->itemAtPosition(lastPos.y(), lastPos.x());
+ QtTabWidget* tabWidget = dynamic_cast<QtTabWidget*>(item ? item->widget() : nullptr);
+ if (tabWidget) {
+ tabWidget->addTab(tab, title);
+ }
+ tab->setEmphasiseFocus(getDimension().width() > 1 || getDimension().height() > 1);
+ 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 = nullptr;
+ 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 ? layoutItem->widget() : nullptr);
+ 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_ || resizing_) {
+ 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 +159,375 @@ 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 = nullptr;
+ current = focusWidget();
+ while (current && !dynamic_cast<QtTabbable*>(current)) {
+ if (current->parentWidget()) {
+ current = current->parentWidget();
+ } else {
+ current = nullptr;
+ 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);
- }
- }
- }
- }
- }
+ 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++) {
+ 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 nullptr;
+ }
+ }
+ }
+ }
+ }
+ tabIndex = -1;
+ return nullptr;
}
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;
+ resizing_ = true;
+ assert(dim.width() > 0 && dim.height() > 0);
+ setUpdatesEnabled(false);
+
+ QWidget* restoredWidget = currentWidget();
+
+ QGridLayout* oldLayout = dynamic_cast<QGridLayout*>(layout());
+ QGridLayout* newLayout = new QGridLayout(this);
+ 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;
+
+ resizing_ = false;
+ setCurrentWidget(restoredWidget);
+
+ updateEmphasiseFocusOnTabs();
+}
+
+void QtDynamicGridLayout::updateEmphasiseFocusOnTabs() {
+ const auto currentDimensions = getDimension();
+
+ 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);
+ tab->setEmphasiseFocus(currentDimensions.height() > 1 || currentDimensions.width() > 1);
+ }
+ }
+ }
}
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_ == nullptr, error) << std::endl;
+ movingTab_ = qobject_cast<QtTabbable*>(tabWidget->widget(oldIndex));
+ SWIFT_LOG_ASSERT(movingTab_ != nullptr, 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_ = nullptr;
+ 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..682ae41 100644
--- a/Swift/QtUI/Trellis/QtDynamicGridLayout.h
+++ b/Swift/QtUI/Trellis/QtDynamicGridLayout.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,67 +14,69 @@
#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 = nullptr, 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);
+ void updateEmphasiseFocusOnTabs();
- private:
- QGridLayout *gridLayout_;
- bool dndEnabled_;
- QHash<QString, QPoint> tabPositions_;
- QtTabbable* movingTab_;
- };
+ private:
+ QGridLayout *gridLayout_;
+ bool dndEnabled_;
+ QHash<QString, QPoint> tabPositions_;
+ QtTabbable* movingTab_;
+ bool resizing_ = false;
+ };
}
diff --git a/Swift/QtUI/Trellis/QtGridSelectionDialog.cpp b/Swift/QtUI/Trellis/QtGridSelectionDialog.cpp
index a3a1bf8..f03d0ec 100644
--- a/Swift/QtUI/Trellis/QtGridSelectionDialog.cpp
+++ b/Swift/QtUI/Trellis/QtGridSelectionDialog.cpp
@@ -1,157 +1,181 @@
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/Trellis/QtGridSelectionDialog.h>
+#include <QApplication>
+#include <QCursor>
#include <QPaintEvent>
#include <QPainter>
#include <QStyle>
-#include <QStyleOptionFrame>
-#include <QStyleOptionMenuItem>
-#include <QStyleOptionSizeGrip>
+#include <QStyleOption>
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;
+QtGridSelectionDialog::QtGridSelectionDialog(QWidget* parent) : QWidget(parent), descriptionText(tr("Select the number of rows and columns for your layout. You can change the size by moving the mouse or cursor keys.")) {
+ frameSize = QSize(28,28) * 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_LayoutLeftMargin);
+ verticalMargin = style()->pixelMetric(QStyle::PM_LayoutBottomMargin);
}
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;
+
+ // Add space for descriptive centered text below.
+ auto fontMetrics = QFontMetrics(QApplication::font());
+ auto descriptionBB = fontMetrics.boundingRect(QRect(0,0,width - 2*horizontalMargin,1000), Qt::TextWordWrap, descriptionText, 0, 0);
+
+ height += descriptionBB.height() + descriptionBB.y();
+
+ 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);
+
+ QSize newSizeHint = sizeHint();
+ resize(newSizeHint);
+ QCursor::setPos(mapToGlobal(QPoint(newSizeHint.width(), newSizeHint.height()) - QPoint(frameSize.width() / 2, frameSize.height() / 2)));
+ }
+ }
}
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);
+ // draw grid
+ QRect gridCell = QRect(QPoint(0,0), frameSize);
+ painter.setBrush(palette().highlight());
+ painter.setPen(Qt::NoPen);
+ 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));
+ gridCell.moveTo(QPoint(xPos, yPos));
+ painter.drawRect(gridCell);
+ }
+ }
+
+ // draw description text
+ auto fontMetrics = QFontMetrics(QApplication::font());
+ auto descriptionBB = fontMetrics.boundingRect(QRect(0,0, width() - 2 * horizontalMargin,0), Qt::AlignHCenter | Qt::AlignTop | Qt::TextWordWrap, descriptionText, 0, 0);
+
+ QStyleOption opt;
+ opt.initFrom(this);
+ int textY = verticalMargin + (currentGridSize.height() * (frameSize.height() + padding));
+ int textX = (size().width() - descriptionBB.width()) / 2;
+ style()->drawItemText(&painter, QRect(textX, textY, descriptionBB.width(), descriptionBB.height()), Qt::AlignHCenter | Qt::AlignTop | Qt::TextWordWrap, opt.palette, true, descriptionText, foregroundRole());
}
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());
+ }
+}
+
+bool QtGridSelectionDialog::event(QEvent* event) {
+ // Hide the window when it becomes a non-top-level window.
+ if (event->type() == QEvent::WindowDeactivate) {
+ hide();
+ return true;
+ }
+ return QWidget::event(event);
}
}
diff --git a/Swift/QtUI/Trellis/QtGridSelectionDialog.h b/Swift/QtUI/Trellis/QtGridSelectionDialog.h
index abcc8b1..557963d 100644
--- a/Swift/QtUI/Trellis/QtGridSelectionDialog.h
+++ b/Swift/QtUI/Trellis/QtGridSelectionDialog.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -11,47 +11,50 @@
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 = nullptr);
+
+ 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);
+ bool event(QEvent* event);
+
+ private:
+ int padding;
+ int horizontalMargin;
+ int verticalMargin;
+
+ QSize frameSize;
+
+ QSize currentGridSize;
+ QSize minGridSize;
+ QSize maxGridSize;
+
+ const QString descriptionText;
+ };
}
diff --git a/Swift/QtUI/UserSearch/ContactListDelegate.cpp b/Swift/QtUI/UserSearch/ContactListDelegate.cpp
index 19290aa..75e25a1 100644
--- a/Swift/QtUI/UserSearch/ContactListDelegate.cpp
+++ b/Swift/QtUI/UserSearch/ContactListDelegate.cpp
@@ -5,15 +5,17 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/UserSearch/ContactListDelegate.h>
-#include <Swift/QtUI/UserSearch/ContactListModel.h>
+
#include <Swift/Controllers/Contact.h>
+
#include <Swift/QtUI/QtSwiftUtil.h>
+#include <Swift/QtUI/UserSearch/ContactListModel.h>
namespace Swift {
@@ -24,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 db13fbc..6ef85d7 100644
--- a/Swift/QtUI/UserSearch/ContactListModel.cpp
+++ b/Swift/QtUI/UserSearch/ContactListModel.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -15,125 +15,124 @@
#include <QMimeData>
#include <Swiften/Base/Path.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/StatusShow.h>
-#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/QtResourceHelper.h>
+#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
QDataStream& operator >>(QDataStream& in, StatusShow::Type& e){
- quint32 buffer;
- in >> buffer;
- switch(buffer) {
- case StatusShow::Online:
- e = StatusShow::Online;
- break;
- case StatusShow::Away:
- e = StatusShow::Away;
- break;
- case StatusShow::FFC:
- e = StatusShow::FFC;
- break;
- case StatusShow::XA:
- e = StatusShow::XA;
- break;
- case StatusShow::DND:
- e = StatusShow::DND;
- break;
- default:
- e = StatusShow::None;
- break;
- }
- 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 51a4bd1..026b01b 100644
--- a/Swift/QtUI/UserSearch/ContactListModel.h
+++ b/Swift/QtUI/UserSearch/ContactListModel.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,52 +13,54 @@
#pragma once
#include <vector>
+
#include <boost/bind.hpp>
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
#include <QAbstractItemModel>
#include <Swift/Controllers/Contact.h>
-#include <Swift/QtUI/ChatList/ChatListItem.h>
+
#include <Swift/QtUI/ChatList/ChatListGroupItem.h>
+#include <Swift/QtUI/ChatList/ChatListItem.h>
#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
- };
+ class ContactListModel : public QAbstractItemModel {
+ Q_OBJECT
+ public:
+ enum ContactRoles {
+ DetailTextRole = Qt::UserRole,
+ AvatarRole = Qt::UserRole + 1,
+ PresenceIconRole = Qt::UserRole + 2
+ };
- public:
- ContactListModel(bool editable);
+ 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;
+ 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());
+ 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;
+ 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);
+ signals:
+ void onListChanged(std::vector<Contact::ref> list);
+ void onJIDsDropped(const std::vector<JID>& contact);
- private:
- bool editable_;
- std::vector<Contact::ref> contacts_;
- };
+ private:
+ bool editable_;
+ std::vector<Contact::ref> contacts_;
+ };
}
diff --git a/Swift/QtUI/UserSearch/QtContactListWidget.cpp b/Swift/QtUI/UserSearch/QtContactListWidget.cpp
index 9b76aba..73a8482 100644
--- a/Swift/QtUI/UserSearch/QtContactListWidget.cpp
+++ b/Swift/QtUI/UserSearch/QtContactListWidget.cpp
@@ -5,98 +5,99 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/UserSearch/QtContactListWidget.h>
-#include <Swift/QtUI/UserSearch/ContactListModel.h>
-#include <Swift/QtUI/UserSearch/ContactListDelegate.h>
-#include <Swift/QtUI/QtUISettingConstants.h>
+#include <QHeaderView>
+
#include <Swift/Controllers/Settings/SettingsProvider.h>
-#include <Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h>
-#include <QHeaderView>
+#include <Swift/QtUI/QtUISettingConstants.h>
+#include <Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h>
+#include <Swift/QtUI/UserSearch/ContactListDelegate.h>
+#include <Swift/QtUI/UserSearch/ContactListModel.h>
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();
+ for (const auto& contactUpdate : contactUpdates) {
+ for (auto&& contact : contacts) {
+ if (contactUpdate->jid == contact->jid) {
+ contact = contactUpdate;
+ break;
+ }
+ }
+ }
+ contactListModel_->setList(contacts);
}
void QtContactListWidget::handleSettingsChanged(const std::string&) {
- contactListDelegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
+ contactListDelegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER));
}
}
diff --git a/Swift/QtUI/UserSearch/QtContactListWidget.h b/Swift/QtUI/UserSearch/QtContactListWidget.h
index 43da011..f2483c3 100644
--- a/Swift/QtUI/UserSearch/QtContactListWidget.h
+++ b/Swift/QtUI/UserSearch/QtContactListWidget.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,14 +14,14 @@
#include <vector>
+#include <QDragEnterEvent>
+#include <QDragMoveEvent>
+#include <QDropEvent>
#include <QTreeView>
-#include <Swift/Controllers/Contact.h>
#include <Swiften/Base/Log.h>
-#include <QDragEnterEvent>
-#include <QDragMoveEvent>
-#include <QDropEvent>
+#include <Swift/Controllers/Contact.h>
namespace Swift {
@@ -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 8ed6efb..8c46e38 100644
--- a/Swift/QtUI/UserSearch/QtSuggestingJIDInput.cpp
+++ b/Swift/QtUI/UserSearch/QtSuggestingJIDInput.cpp
@@ -5,205 +5,211 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/UserSearch/QtSuggestingJIDInput.h>
-#include <Swift/QtUI/UserSearch/ContactListDelegate.h>
-#include <Swift/Controllers/Settings/SettingsProvider.h>
-#include <Swift/QtUI/QtUISettingConstants.h>
-#include <Swift/QtUI/UserSearch/ContactListModel.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <boost/bind.hpp>
-
-#include <Swift/QtUI/QtSwiftUtil.h>
+#include <boost/signals2.hpp>
#include <QAbstractItemView>
#include <QApplication>
#include <QDesktopWidget>
#include <QKeyEvent>
+#include <QtGlobal>
+#include <Swift/Controllers/Settings/SettingsProvider.h>
+
+#include <Swift/QtUI/QtSwiftUtil.h>
+#include <Swift/QtUI/QtUISettingConstants.h>
+#include <Swift/QtUI/UserSearch/ContactListDelegate.h>
+#include <Swift/QtUI/UserSearch/ContactListModel.h>
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 = std::make_shared<Contact>();
+ manualContact->name = jid.toString();
+ manualContact->jid = jid;
+ return manualContact;
+ }
+ }
+ return std::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();
-
- // Give focus back to input widget because the hide() call passes the focus to the wrong widget.
- setFocus();
+ 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();
+#if defined(Q_WS_MAC)
+ // This workaround is needed on OS X, to bring the dialog containing this widget back to the front after
+ // the popup is hidden. Ubuntu 16.04 and Windows 8 do not have this issue.
+ window()->raise();
+#endif
}
}
diff --git a/Swift/QtUI/UserSearch/QtSuggestingJIDInput.h b/Swift/QtUI/UserSearch/QtSuggestingJIDInput.h
index d5ec45d..402667d 100644
--- a/Swift/QtUI/UserSearch/QtSuggestingJIDInput.h
+++ b/Swift/QtUI/UserSearch/QtSuggestingJIDInput.h
@@ -5,16 +5,18 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/signals2.hpp>
+
#include <QLineEdit>
#include <QTreeView>
-#include <Swiften/Base/boost_bsignals.h>
+
#include <Swift/Controllers/Contact.h>
namespace Swift {
@@ -24,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::signals2::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 a6c1e24..96b6031 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.cpp
@@ -1,17 +1,17 @@
/*
- * Copyright (c) 2011-2014 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h"
-
-#include <QVBoxLayout>
-#include <QLabel>
+#include <Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h>
#include <boost/bind.hpp>
+#include <boost/signals2.hpp>
+
+#include <QLabel>
+#include <QVBoxLayout>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/JID/JID.h>
#include <Swift/QtUI/QtContactEditWidget.h>
@@ -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 eefa630..7185bce 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchDetailsPage.h
@@ -1,44 +1,45 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QWizardPage>
-
#include <set>
#include <string>
#include <vector>
+#include <QWizardPage>
+
#include <Swiften/Elements/VCard.h>
#include <Swiften/JID/JID.h>
+
#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 13b61a7..3a6028d 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.cpp
@@ -1,42 +1,42 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h"
+#include <Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h>
namespace Swift {
-QtUserSearchFieldsPage::QtUserSearchFieldsPage() : formWidget_(0) {
- setupUi(this);
+QtUserSearchFieldsPage::QtUserSearchFieldsPage() : formWidget_(nullptr) {
+ 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_ = nullptr;
+ }
+ 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 70618f9..4089d05 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchFieldsPage.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,23 +9,22 @@
#include <QWizardPage>
#include <Swift/QtUI/QtFormWidget.h>
-
#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 9abdcf0..1327a8f 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.cpp
@@ -5,97 +5,98 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h"
+#include <Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h>
#include <QMessageBox>
#include <QMimeData>
#include <QUrl>
-#include "Swift/QtUI/QtSwiftUtil.h"
#include <Swift/Controllers/Settings/SettingsProvider.h>
+
+#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/UserSearch/QtContactListWidget.h>
#include <Swift/QtUI/UserSearch/QtSuggestingJIDInput.h>
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 8cc6616..d9147db 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchFirstMultiJIDPage.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,39 +14,40 @@
#include <QWizardPage>
-#include <Swift/QtUI/UserSearch/ui_QtUserSearchFirstMultiJIDPage.h>
#include <Swift/Controllers/UIInterfaces/UserSearchWindow.h>
+#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 6e8744f..5d0c9fa 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFirstPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchFirstPage.cpp
@@ -1,49 +1,49 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/QtUI/UserSearch/QtUserSearchFirstPage.h"
-
-#include "Swift/QtUI/QtSwiftUtil.h"
+#include <Swift/QtUI/UserSearch/QtUserSearchFirstPage.h>
#include <Swiften/Base/Log.h>
+#include <Swift/QtUI/QtSwiftUtil.h>
+
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 4bc3923..2e73e9e 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchFirstPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchFirstPage.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,26 +8,26 @@
#include <QWizardPage>
-#include <Swift/QtUI/UserSearch/ui_QtUserSearchFirstPage.h>
#include <Swift/Controllers/UIInterfaces/UserSearchWindow.h>
#include <Swift/QtUI/UserSearch/QtSuggestingJIDInput.h>
+#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 39ef3e7..c8a9ad8 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchResultsPage.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchResultsPage.cpp
@@ -1,39 +1,39 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/QtUI/UserSearch/QtUserSearchResultsPage.h"
+#include <Swift/QtUI/UserSearch/QtUserSearchResultsPage.h>
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 60be555..33227e6 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchResultsPage.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchResultsPage.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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..cf62540 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchWindow.cpp
+++ b/Swift/QtUI/UserSearch/QtUserSearchWindow.cpp
@@ -1,22 +1,20 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swift/QtUI/UserSearch/QtUserSearchWindow.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <QItemDelegate>
#include <QModelIndex>
#include <QMovie>
#include <QWizardPage>
-#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
-
#include <Swift/Controllers/UIEvents/AddContactUIEvent.h>
#include <Swift/Controllers/UIEvents/CreateImpromptuMUCUIEvent.h>
#include <Swift/Controllers/UIEvents/InviteToMUCUIEvent.h>
@@ -36,593 +34,606 @@
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);
+QtUserSearchWindow::QtUserSearchWindow(UIEventStream* eventStream, UserSearchWindow::Type type, const std::set<std::string>& groups, SettingsProvider* settingsProvider) : eventStream_(eventStream), type_(type), model_(nullptr), firstMultiJIDPage_(nullptr), settings_(settingsProvider), searchNext_(false), supportsImpromptu_(false) {
+ 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);
+ if (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(std::make_shared<AddContactUIEvent>(jid, detailsPage_->getName(), detailsPage_->getSelectedGroups()));
+ break;
+ case ChatToContact:
+ if (contactVector_.size() == 1) {
+ std::shared_ptr<UIEvent> event(new RequestChatUIEvent(contactVector_[0]->jid));
+ eventStream_->send(event);
+ break;
+ }
+
+ for (Contact::ref contact : contactVector_) {
+ jids.push_back(contact->jid);
+ }
+
+ eventStream_->send(std::make_shared<CreateImpromptuMUCUIEvent>(jids, Q2PSTRING(firstMultiJIDPage_->reason_->text())));
+ break;
+ case InviteToChat:
+ for (Contact::ref contact : contactVector_) {
+ jids.push_back(contact->jid);
+ }
+ eventStream_->send(std::make_shared<InviteToMUCUIEvent>(originatorJID_, 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));
- }
+ auto contactToAdd = firstMultiJIDPage_->jid_->getContact();
+ if (!!contactToAdd) {
+ contactVector_.push_back(contactToAdd);
+ firstMultiJIDPage_->jid_->clear();
+ }
+
+ firstMultiJIDPage_->contactList_->setList(contactVector_);
+ firstMultiJIDPage_->emitCompletenessCheck();
+ if (type_ == ChatToContact) {
+ firstMultiJIDPage_->groupBox->setEnabled(supportsImpromptu_ ? 1 : (contactVector_.size() < 1));
+ }
+
+ if (!!contactToAdd && contactToAdd->jid.isValid() && contactToAdd->statusType == StatusShow::None) {
+ onJIDUpdateRequested({contactToAdd->jid});
+ }
}
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());
+ std::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;
+ for (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 std::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();
+ raise();
}
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();
- }
-}
-
-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();
+ if (type_ == AddContact) {
+ firstPage_->service_->clear();
+ for (auto&& jid : services) {
+ firstPage_->service_->addItem(P2QSTRING(jid.toString()));
+ }
+ firstPage_->service_->clearEditText();
+ } else {
+ firstMultiJIDPage_->service_->clear();
+ for (auto&& jid : services) {
+ firstMultiJIDPage_->service_->addItem(P2QSTRING(jid.toString()));
+ }
+ firstMultiJIDPage_->service_->clearEditText();
+ }
+}
+
+void QtUserSearchWindow::setSearchFields(std::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(nullptr);
+ 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);
+ for (auto&& jid : jids) {
+ addSearchedJIDToList(std::make_shared<Contact>("", jid, StatusShow::None, ""));
+ }
+ onJIDUpdateRequested(jids);
+}
+
+void QtUserSearchWindow::setOriginator(const JID& originator) {
+ originatorJID_ = originator;
}
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;
+ for (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 */
+ for (Contact::ref newContact : contacts) {
+ bool found = false;
+ for (Contact::ref oldContact : contactVector_) {
+ if (newContact->jid == oldContact->jid) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ contactVector_.push_back(newContact);
+ }
+ }
+ if (type_ != InviteToChat && !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) != nullptr) {
+ 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) != nullptr) {
+ 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) != nullptr) {
+ 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 (auto&& legacySearchWidget : legacySearchWidgets) {
+ legacySearchWidget->hide();
+ if (QLineEdit* edit = qobject_cast<QLineEdit*>(legacySearchWidget)) {
+ 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(nullptr);
+ delete model_;
+ model_ = nullptr;
+ 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 15e68bf..0714ac1 100644
--- a/Swift/QtUI/UserSearch/QtUserSearchWindow.h
+++ b/Swift/QtUI/UserSearch/QtUserSearchWindow.h
@@ -1,104 +1,110 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <QWizard>
#include <set>
-#include <Swift/QtUI/UserSearch/ui_QtUserSearchWizard.h>
+#include <QWizard>
+
+#include <Swiften/Base/Override.h>
+
#include <Swift/Controllers/UIInterfaces/UserSearchWindow.h>
+#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) SWIFTEN_OVERRIDE;
- 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() SWIFTEN_OVERRIDE;
+ virtual void show() SWIFTEN_OVERRIDE;
+ virtual void setResults(const std::vector<UserSearchResult>& results) SWIFTEN_OVERRIDE;
+ virtual void setResultsForm(Form::ref results) SWIFTEN_OVERRIDE;
+ virtual void setSelectedService(const JID& jid) SWIFTEN_OVERRIDE;
+ virtual void setServerSupportsSearch(bool error) SWIFTEN_OVERRIDE;
+ virtual void setSearchError(bool error) SWIFTEN_OVERRIDE;
+ virtual void setSearchFields(std::shared_ptr<SearchPayload> fields) SWIFTEN_OVERRIDE;
+ virtual void setNameSuggestions(const std::vector<std::string>& suggestions) SWIFTEN_OVERRIDE;
+ virtual void prepopulateJIDAndName(const JID& jid, const std::string& name) SWIFTEN_OVERRIDE;
+ virtual void setContactSuggestions(const std::vector<Contact::ref>& suggestions) SWIFTEN_OVERRIDE;
+ virtual void setJIDs(const std::vector<JID> &jids) SWIFTEN_OVERRIDE;
+ virtual void setOriginator(const JID& originator) SWIFTEN_OVERRIDE;
+ virtual void setRoomJID(const JID &roomJID) SWIFTEN_OVERRIDE;
+ virtual std::string getReason() const SWIFTEN_OVERRIDE;
+ virtual std::vector<JID> getJIDs() const SWIFTEN_OVERRIDE;
+ virtual void setCanStartImpromptuChats(bool supportsImpromptu) SWIFTEN_OVERRIDE;
+ virtual void updateContacts(const std::vector<Contact::ref> &contacts) SWIFTEN_OVERRIDE;
+ virtual void addContacts(const std::vector<Contact::ref>& contacts) SWIFTEN_OVERRIDE;
+ virtual void setCanSupplyDescription(bool allowed) SWIFTEN_OVERRIDE;
+ virtual void setWarning(const boost::optional<std::string>& message) SWIFTEN_OVERRIDE;
- protected:
- virtual int nextId() const;
+ protected:
+ virtual int nextId() const SWIFTEN_OVERRIDE;
- 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();
+ void handleCurrentChanged(int);
+ 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_;
+ JID originatorJID_;
+ 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..a5639ec 100644
--- a/Swift/QtUI/UserSearch/UserSearchDelegate.h
+++ b/Swift/QtUI/UserSearch/UserSearchDelegate.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 = nullptr);
+ 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 c758492..b6ac3cf 100644
--- a/Swift/QtUI/UserSearch/UserSearchModel.cpp
+++ b/Swift/QtUI/UserSearch/UserSearchModel.cpp
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swift/QtUI/UserSearch/UserSearchModel.h"
+#include <Swift/QtUI/UserSearch/UserSearchModel.h>
-#include "Swift/QtUI/QtSwiftUtil.h"
+#include <Swift/QtUI/QtSwiftUtil.h>
namespace Swift {
@@ -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 5048100..a3940da 100644
--- a/Swift/QtUI/UserSearch/UserSearchModel.h
+++ b/Swift/QtUI/UserSearch/UserSearchModel.h
@@ -1,41 +1,41 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <QAbstractItemModel>
#include <QList>
-#include "Swift/Controllers/Chat/UserSearchController.h"
+#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 e96b760..7669ecc 100644
--- a/Swift/QtUI/Whiteboard/ColorWidget.cpp
+++ b/Swift/QtUI/Whiteboard/ColorWidget.cpp
@@ -4,34 +4,41 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+
+#include <Swift/QtUI/Whiteboard/ColorWidget.h>
-#include "ColorWidget.h"
-#include <QPainter>
#include <QMouseEvent>
+#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..56ada0c 100644
--- a/Swift/QtUI/Whiteboard/ColorWidget.h
+++ b/Swift/QtUI/Whiteboard/ColorWidget.h
@@ -4,30 +4,36 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#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 = nullptr);
+ 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 8821062..4ac93b8 100644
--- a/Swift/QtUI/Whiteboard/FreehandLineItem.cpp
+++ b/Swift/QtUI/Whiteboard/FreehandLineItem.cpp
@@ -4,94 +4,99 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "FreehandLineItem.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+#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 b1af3d1..5b83d95 100644
--- a/Swift/QtUI/Whiteboard/FreehandLineItem.h
+++ b/Swift/QtUI/Whiteboard/FreehandLineItem.h
@@ -4,30 +4,37 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
+#include <iostream>
+
#include <QGraphicsItem>
#include <QPainter>
-#include <iostream>
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 = nullptr);
+ QRectF boundingRect() const;
+ void paint(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, QWidget* /*widget*/ = nullptr);
+ 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 f92322a..80061fd 100644
--- a/Swift/QtUI/Whiteboard/GView.cpp
+++ b/Swift/QtUI/Whiteboard/GView.cpp
@@ -4,493 +4,500 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "GView.h"
-#include <QtSwiftUtil.h>
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/Whiteboard/GView.h>
+
+#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(nullptr), selectionRect(nullptr), textDialog(nullptr) {
+ }
+
+ 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 = nullptr;
+ 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 = nullptr;
+ selectionRect = nullptr;
+ 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 != nullptr) {
+ 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 != nullptr) {
+ 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 != nullptr) {
+ 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 != nullptr) {
+ 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 == nullptr) {
+ 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 = nullptr;
+ 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 != nullptr) {
+ pen = defaultPen;
+ brush = defaultBrush;
+ scene()->removeItem(selectionRect);
+ delete selectionRect;
+ selectionRect = nullptr;
+ lineWidthChanged(pen.width());
+ lineColorChanged(pen.color());
+ brushColorChanged(brush.color());
+ }
+ }
+
+ void GView::deselect(QString id) {
+ if (selectionRect != nullptr) {
+ QGraphicsItem* item = getItem(id);
+ if (item && selectionRect->data(1).value<QGraphicsItem*>() == item) {
+ pen = defaultPen;
+ brush = defaultBrush;
+ scene()->removeItem(selectionRect);
+ delete selectionRect;
+ selectionRect = nullptr;
+ lineWidthChanged(pen.width());
+ lineColorChanged(pen.color());
+ brushColorChanged(brush.color());
+ }
+ }
+ }
}
diff --git a/Swift/QtUI/Whiteboard/GView.h b/Swift/QtUI/Whiteboard/GView.h
index bc64589..4af5a53 100644
--- a/Swift/QtUI/Whiteboard/GView.h
+++ b/Swift/QtUI/Whiteboard/GView.h
@@ -4,73 +4,81 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <QGraphicsView>
+#include <iostream>
+
#include <QGraphicsLineItem>
+#include <QGraphicsView>
#include <QMouseEvent>
#include <QPen>
-#include <iostream>
+
#include <Swiften/Base/IDGenerator.h>
-#include "TextDialog.h"
-#include "FreehandLineItem.h"
+#include <Swift/QtUI/Whiteboard/FreehandLineItem.h>
+#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 = nullptr);
+ 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 916246c..62f5b89 100644
--- a/Swift/QtUI/Whiteboard/QtWhiteboardWindow.cpp
+++ b/Swift/QtUI/Whiteboard/QtWhiteboardWindow.cpp
@@ -5,18 +5,18 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "QtWhiteboardWindow.h"
+#include <Swift/QtUI/Whiteboard/QtWhiteboardWindow.h>
#include <iostream>
+#include <memory>
#include <boost/bind.hpp>
#include <boost/numeric/conversion/cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <QLabel>
#include <QMessageBox>
@@ -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 = std::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
+ if (insertOp) {
+ WhiteboardElementDrawingVisitor visitor(graphicsView, operation->getPos(), GView::New);
+ insertOp->getElement()->accept(visitor);
+ }
+
+ WhiteboardUpdateOperation::ref updateOp = std::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 = std::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(), nullptr, "Select pen color", QColorDialog::ShowAlphaChannel);
+ if(color.isValid())
+ graphicsView->setLineColor(color);
+ }
+
+ void QtWhiteboardWindow::showBrushColorDialog()
+ {
+ QColor color = QColorDialog::getColor(graphicsView->getBrushColor(), nullptr, "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 != nullptr) {
+ QLine line = lineItem->line().toLine();
+ QColor color = lineItem->pen().color();
+ WhiteboardLineElement::ref element = std::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 != nullptr) {
+ WhiteboardFreehandPathElement::ref element = std::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 != nullptr) {
+ QRectF rect = rectItem->rect();
+ WhiteboardRectElement::ref element = std::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 != nullptr) {
+ QPointF point = textItem->pos();
+ WhiteboardTextElement::ref element = std::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 = std::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 = std::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 = std::make_shared<WhiteboardInsertOperation>();
+ insertOp->setPos(pos);
+ insertOp->setElement(el);
+ whiteboardSession_->sendOperation(insertOp);
+ } else {
+ WhiteboardUpdateOperation::ref updateOp = std::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 = std::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 3957bb7..21aa7ca 100644
--- a/Swift/QtUI/Whiteboard/QtWhiteboardWindow.h
+++ b/Swift/QtUI/Whiteboard/QtWhiteboardWindow.h
@@ -4,85 +4,91 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#pragma once
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
-#include <Swift/Controllers/UIInterfaces/WhiteboardWindow.h>
-#include <Swiften/Elements/Message.h>
-#include <Swiften/Whiteboard/WhiteboardSession.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
+#pragma once
-#include <QWidget>
-#include <QGraphicsView>
+#include <QCloseEvent>
+#include <QColorDialog>
#include <QGraphicsScene>
-#include <QVBoxLayout>
-#include <QHBoxLayout>
+#include <QGraphicsView>
#include <QGridLayout>
+#include <QHBoxLayout>
#include <QPainter>
#include <QPushButton>
#include <QSpinBox>
-#include <QColorDialog>
#include <QToolButton>
-#include <QCloseEvent>
+#include <QVBoxLayout>
+#include <QWidget>
+
+#include <Swiften/Elements/Message.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
+#include <Swiften/Whiteboard/WhiteboardSession.h>
+
+#include <Swift/Controllers/UIInterfaces/WhiteboardWindow.h>
-#include "GView.h"
-#include "ColorWidget.h"
+#include <Swift/QtUI/Whiteboard/ColorWidget.h>
+#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;
+ 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 021895a..c15e7b4 100644
--- a/Swift/QtUI/Whiteboard/TextDialog.cpp
+++ b/Swift/QtUI/Whiteboard/TextDialog.cpp
@@ -4,49 +4,55 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "TextDialog.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#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 64a0fe2..513d381 100644
--- a/Swift/QtUI/Whiteboard/TextDialog.h
+++ b/Swift/QtUI/Whiteboard/TextDialog.h
@@ -4,40 +4,46 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
+#include <iostream>
+
#include <QDialog>
-#include <QVBoxLayout>
-#include <QHBoxLayout>
#include <QDialogButtonBox>
-#include <QLineEdit>
#include <QGraphicsTextItem>
+#include <QHBoxLayout>
+#include <QLineEdit>
#include <QSpinBox>
-
-#include <iostream>
+#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 = nullptr);
+
+ 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 74c6c1d..5a5aefa 100644
--- a/Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h
+++ b/Swift/QtUI/Whiteboard/WhiteboardElementDrawingVisitor.h
@@ -4,184 +4,192 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardLineElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardRectElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardTextElement.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h>
+
+#include <Swift/QtUI/QtSwiftUtil.h>
#include <Swift/QtUI/Whiteboard/GView.h>
-#include <QtSwiftUtil.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 == nullptr && 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 161ff1d..ec39c38 100644
--- a/Swift/QtUI/WinUIHelpers.cpp
+++ b/Swift/QtUI/WinUIHelpers.cpp
@@ -4,58 +4,62 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "WinUIHelpers.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swift/QtUI/WinUIHelpers.h>
#include <windows.h>
#include <Wincrypt.h>
#include <cryptuiapi.h>
#pragma comment(lib, "cryptui.lib")
-#include <boost/shared_ptr.hpp>
-
-#include <Swiften/Base/foreach.h>
+#include <memory>
namespace Swift {
void WinUIHelpers::displayCertificateChainAsSheet(QWidget* parent, const std::vector<Certificate::ref>& chain) {
- if (chain.empty()) {
- return;
- }
-
- // create certificate store to store the certificate chain in
- HCERTSTORE chainStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, NULL);
- if (!chainStore) {
- return;
- }
-
- ByteArray certAsDER = chain[0]->toDER();
- 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);
- }
-
- 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);
+ if (chain.empty()) {
+ return;
+ }
+
+ // create certificate store to store the certificate chain in
+ HCERTSTORE chainStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, NULL, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, NULL);
+ if (!chainStore) {
+ return;
+ }
+
+ ByteArray certAsDER = chain[0]->toDER();
+ std::shared_ptr<const CERT_CONTEXT> certificate_chain;
+ {
+ PCCERT_CONTEXT certChain;
+ BOOL ok = CertAddCertificateContextToStore(chainStore, CertCreateCertificateContext(X509_ASN_ENCODING, vecptr(certAsDER), certAsDER.size()), CERT_STORE_ADD_ALWAYS, &certChain);
+ // maybe free the cert contex we created
+ if (!ok || !certChain) {
+ return;
+ }
+ certificate_chain.reset(certChain, CertFreeCertificateContext);
+ }
+
+ for (size_t i = 1; i < chain.size(); ++i) {
+ ByteArray certAsDER = chain[i]->toDER();
+ CertAddCertificateContextToStore(chainStore, CertCreateCertificateContext(X509_ASN_ENCODING, vecptr(certAsDER), certAsDER.size()), CERT_STORE_ADD_ALWAYS, NULL);
+ }
+
+ 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);
}
}
diff --git a/Swift/QtUI/WinUIHelpers.h b/Swift/QtUI/WinUIHelpers.h
index d34d236..36f5c9e 100644
--- a/Swift/QtUI/WinUIHelpers.h
+++ b/Swift/QtUI/WinUIHelpers.h
@@ -4,16 +4,23 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <Swiften/TLS/Certificate.h>
#include <QWidget>
+#include <Swiften/TLS/Certificate.h>
+
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 1352dfa..d6e8ba9 100644
--- a/Swift/QtUI/WindowsNotifier.cpp
+++ b/Swift/QtUI/WindowsNotifier.cpp
@@ -1,54 +1,50 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "WindowsNotifier.h"
+#include <Swift/QtUI/WindowsNotifier.h>
-#include <QSystemTrayIcon>
#include <cassert>
#include <iostream>
+
#include <boost/bind.hpp>
-#include "QtWin32NotifierWindow.h"
-#include "QtSwiftUtil.h"
+#include <QSystemTrayIcon>
+
+#include <Swift/QtUI/QtSwiftUtil.h>
+#include <Swift/QtUI/QtWin32NotifierWindow.h>
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();
+ connect(tray, SIGNAL(messageClicked()), SLOT(handleMessageClicked()));
}
WindowsNotifier::~WindowsNotifier() {
- delete snarlNotifier;
- delete notifierWindow;
+ 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);
+ 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 fe6bf18..945ef6b 100644
--- a/Swift/QtUI/WindowsNotifier.h
+++ b/Swift/QtUI/WindowsNotifier.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,29 +9,30 @@
#include <map>
#include <QObject>
+
#include <SwifTools/Notifier/Notifier.h>
-#include <SwifTools/Notifier/SnarlNotifier.h>
class QSystemTrayIcon;
namespace Swift {
- class WindowsNotifier : public QObject, public Notifier {
- Q_OBJECT
+ class Win32NotifierWindow;
+
+ 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;
+ boost::function<void()> lastCallback;
+ };
}
diff --git a/Swift/QtUI/main.cpp b/Swift/QtUI/main.cpp
index 2b8716c..472c99a 100644
--- a/Swift/QtUI/main.cpp
+++ b/Swift/QtUI/main.cpp
@@ -1,99 +1,125 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <cstdlib>
+#include <iostream>
+#include <locale>
+#include <memory>
+#include <sstream>
+
+#include <boost/date_time/gregorian/gregorian.hpp>
+#include <boost/program_options.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
-#include <boost/program_options.hpp>
#include <boost/version.hpp>
-#include <iostream>
+
#include <QApplication>
-#include <QTextCodec>
-#include <QTranslator>
#include <QLocale>
#include <QStringList>
+#include <QTextCodec>
+#include <QTranslator>
+
+#include <Swiften/Base/Path.h>
-#include <Swift/Controllers/Translator.h>
#include <Swift/Controllers/ApplicationInfo.h>
#include <Swift/Controllers/BuildVersion.h>
+#include <Swift/Controllers/Translator.h>
+
#include <SwifTools/Application/PlatformApplicationPathProvider.h>
#include <SwifTools/CrashReporter.h>
-#include <stdlib.h>
-#include <Swiften/Base/Path.h>
-#include "QtSwift.h"
-#include "QtTranslator.h"
-#include "QtSwiftUtil.h"
+#include <Swift/QtUI/QtSwift.h>
+#include <Swift/QtUI/QtSwiftUtil.h>
+#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");
+ // Set crash report prefix to include date and version.
+ std::stringstream prefix;
+
+ // This date_facet will be cleaned up by the stringstream.
+ auto outputFacet = new boost::gregorian::date_facet();
+ outputFacet->format("%Y-%m-%d");
+ prefix.imbue(std::locale(std::locale::classic(), outputFacet));
+
+ prefix << buildVersion << "_" << boost::gregorian::date(boost::gregorian::day_clock::local_day()) << "_";
+
+ Swift::CrashReporter crashReporter(applicationPathProvider.getDataDir() / "crashes", prefix.str());
#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);
+#if QT_VERSION < 0x050501
+ /* According to Qt documenation, Qt is suppsoed to set the applications layout
+ * direction based on the translatable QT_LAYOUT_DIRECTION string. There is a
+ * bug in Qt prior version 5.5.1, i.e. QTBUG-43447, thus we set the layout
+ * direction manually based on the tranlsated QT_LAYOUT_DIRECTION string.
+ */
+ app.setLayoutDirection(QGuiApplication::tr("QT_LAYOUT_DIRECTION") == QLatin1String("RTL") ? Qt::RightToLeft : Qt::LeftToRight);
+#endif
- Swift::QtSwift swift(vm);
- int result = app.exec();
+ Swift::QtSwift swift(vm);
+ int result = app.exec();
- Swift::Translator::setInstance(NULL);
+ Swift::Translator::setInstance(nullptr);
- return result;
+ return result;
}
diff --git a/Swift/QtUI/swift-open-uri.cpp b/Swift/QtUI/swift-open-uri.cpp
index a8ae0a4..23a8851 100644
--- a/Swift/QtUI/swift-open-uri.cpp
+++ b/Swift/QtUI/swift-open-uri.cpp
@@ -1,30 +1,31 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <iostream>
+
#include <QCoreApplication>
#include <QDBusConnection>
#include <QDBusMessage>
-#include <iostream>
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/Swift/SConscript b/Swift/SConscript
index bf19873..daff755 100644
--- a/Swift/SConscript
+++ b/Swift/SConscript
@@ -5,17 +5,13 @@ Import("env")
SConscript("Controllers/SConscript")
if env["SCONS_STAGE"] == "build" :
- if not GetOption("help") and not env.get("HAVE_OPENSSL", 0) and not env.get("HAVE_SCHANNEL", 0) and not env.get("HAVE_SECURETRANSPORT", 0):
- print "Error: Swift requires OpenSSL support, and OpenSSL was not found."
- if "Swift" in env["PROJECTS"] :
- env["PROJECTS"].remove("Swift")
- elif not GetOption("help") and not env.get("HAVE_QT", 0) :
- if "Swift" in env["PROJECTS"] :
- print "Warning: Swift requires Qt. Not building the Swift Qt application."
- env["PROJECTS"].remove("Swift")
- elif not GetOption("help") and env["target"] == "native" and "Swift" in env["PROJECTS"] :
- try :
- SConscript("QtUI/SConscript")
- except Exception as e:
- print "Warning: %s" % str(e)
- env["PROJECTS"].remove("Swift")
+ if not GetOption("help") and not env.get("HAVE_QT", 0) :
+ if "Swift" in env["PROJECTS"] :
+ print "Warning: Swift requires Qt. Not building the Swift Qt application."
+ env["PROJECTS"].remove("Swift")
+ elif not GetOption("help") and env["target"] == "native" and "Swift" in env["PROJECTS"] :
+ try :
+ SConscript("QtUI/SConscript")
+ except Exception as e:
+ print "Warning: %s" % str(e)
+ env["PROJECTS"].remove("Swift")
diff --git a/Swift/Translations/swift_ca.ts b/Swift/Translations/swift_ca.ts
index a512f1f..8fa72b2 100644
--- a/Swift/Translations/swift_ca.ts
+++ b/Swift/Translations/swift_ca.ts
@@ -704,7 +704,7 @@
</message>
</context>
<context>
- <name>QApplication</name>
+ <name>QGuiApplication</name>
<message>
<location filename="../QtUI/QtStrings.h" line="19"/>
<source>QT_LAYOUT_DIRECTION</source>
diff --git a/Swift/Translations/swift_cs.ts b/Swift/Translations/swift_cs.ts
index 314cd60..3621733 100644
--- a/Swift/Translations/swift_cs.ts
+++ b/Swift/Translations/swift_cs.ts
@@ -697,7 +697,7 @@
</message>
</context>
<context>
- <name>QApplication</name>
+ <name>QGuiApplication</name>
<message>
<location filename="../QtUI/QtStrings.h" line="19"/>
<source>QT_LAYOUT_DIRECTION</source>
diff --git a/Swift/Translations/swift_de.ts b/Swift/Translations/swift_de.ts
index 3f86218..6eaa2ca 100644
--- a/Swift/Translations/swift_de.ts
+++ b/Swift/Translations/swift_de.ts
@@ -879,7 +879,7 @@
</message>
</context>
<context>
- <name>QApplication</name>
+ <name>QGuiApplication</name>
<message>
<location filename="../QtUI/QtStrings.h" line="19"/>
<source>QT_LAYOUT_DIRECTION</source>
diff --git a/Swift/Translations/swift_es.ts b/Swift/Translations/swift_es.ts
index 384c411..e6d414d 100644
--- a/Swift/Translations/swift_es.ts
+++ b/Swift/Translations/swift_es.ts
@@ -704,7 +704,7 @@
</message>
</context>
<context>
- <name>QApplication</name>
+ <name>QGuiApplication</name>
<message>
<location filename="../QtUI/QtStrings.h" line="19"/>
<source>QT_LAYOUT_DIRECTION</source>
diff --git a/Swift/Translations/swift_fr.ts b/Swift/Translations/swift_fr.ts
index b95c0d1..f344a83 100644
--- a/Swift/Translations/swift_fr.ts
+++ b/Swift/Translations/swift_fr.ts
@@ -573,7 +573,7 @@
</message>
</context>
<context>
- <name>QApplication</name>
+ <name>QGuiApplication</name>
<message>
<location filename="../QtUI/QtStrings.h" line="19"/>
<source>QT_LAYOUT_DIRECTION</source>
diff --git a/Swift/Translations/swift_gl.ts b/Swift/Translations/swift_gl.ts
index c189a1d..46acb93 100644
--- a/Swift/Translations/swift_gl.ts
+++ b/Swift/Translations/swift_gl.ts
@@ -575,7 +575,7 @@
</message>
</context>
<context>
- <name>QApplication</name>
+ <name>QGuiApplication</name>
<message>
<location filename="../QtUI/QtStrings.h" line="19"/>
<source>QT_LAYOUT_DIRECTION</source>
diff --git a/Swift/Translations/swift_he.ts b/Swift/Translations/swift_he.ts
index 4a810f8..3a8f400 100644
--- a/Swift/Translations/swift_he.ts
+++ b/Swift/Translations/swift_he.ts
@@ -697,7 +697,7 @@
</message>
</context>
<context>
- <name>QApplication</name>
+ <name>QGuiApplication</name>
<message>
<location filename="../QtUI/QtStrings.h" line="19"/>
<source>QT_LAYOUT_DIRECTION</source>
@@ -2704,7 +2704,7 @@ If you choose to defer this choice, you will be asked again when you next login.
<location filename="../QtUI/QtAboutWidget.cpp" line="49"/>
<location filename="../QtUI/QtAboutWidget.cpp" line="50"/>
<source>TRANSLATION_AUTHOR</source>
- <translation>Isratine Citizen</translation>
+ <translation>Hebrew Translation Team</translation>
</message>
<message>
<location filename="../QtUI/QtAboutWidget.cpp" line="52"/>
diff --git a/Swift/Translations/swift_hu.ts b/Swift/Translations/swift_hu.ts
index 54167e2..d8601aa 100644
--- a/Swift/Translations/swift_hu.ts
+++ b/Swift/Translations/swift_hu.ts
@@ -454,7 +454,7 @@
</message>
</context>
<context>
- <name>QApplication</name>
+ <name>QGuiApplication</name>
<message>
<source>QT_LAYOUT_DIRECTION</source>
<comment>Translate this to LTR for left-to-right or RTL for right-to-left languages</comment>
diff --git a/Swift/Translations/swift_nl.ts b/Swift/Translations/swift_nl.ts
index 3134e65..2686e5e 100644
--- a/Swift/Translations/swift_nl.ts
+++ b/Swift/Translations/swift_nl.ts
@@ -695,7 +695,7 @@
</message>
</context>
<context>
- <name>QApplication</name>
+ <name>QGuiApplication</name>
<message>
<source>QT_LAYOUT_DIRECTION</source>
<comment>Translate this to LTR for left-to-right or RTL for right-to-left languages</comment>
diff --git a/Swift/Translations/swift_pl.ts b/Swift/Translations/swift_pl.ts
index cc461a1..838725e 100644
--- a/Swift/Translations/swift_pl.ts
+++ b/Swift/Translations/swift_pl.ts
@@ -573,7 +573,7 @@
</message>
</context>
<context>
- <name>QApplication</name>
+ <name>QGuiApplication</name>
<message>
<location filename="../QtUI/QtStrings.h" line="19"/>
<source>QT_LAYOUT_DIRECTION</source>
diff --git a/Swift/Translations/swift_ru.ts b/Swift/Translations/swift_ru.ts
index 56069a5..08492f7 100644
--- a/Swift/Translations/swift_ru.ts
+++ b/Swift/Translations/swift_ru.ts
@@ -695,7 +695,7 @@
</message>
</context>
<context>
- <name>QApplication</name>
+ <name>QGuiApplication</name>
<message>
<location filename="../QtUI/QtStrings.h" line="19"/>
<source>QT_LAYOUT_DIRECTION</source>
diff --git a/Swift/Translations/swift_sk.ts b/Swift/Translations/swift_sk.ts
index e99a638..77db4f8 100644
--- a/Swift/Translations/swift_sk.ts
+++ b/Swift/Translations/swift_sk.ts
@@ -698,7 +698,7 @@
</message>
</context>
<context>
- <name>QApplication</name>
+ <name>QGuiApplication</name>
<message>
<location filename="../QtUI/QtStrings.h" line="19"/>
<source>QT_LAYOUT_DIRECTION</source>
diff --git a/Swift/Translations/swift_sv.ts b/Swift/Translations/swift_sv.ts
index b979dab..6aedfb8 100644
--- a/Swift/Translations/swift_sv.ts
+++ b/Swift/Translations/swift_sv.ts
@@ -580,7 +580,7 @@
</message>
</context>
<context>
- <name>QApplication</name>
+ <name>QGuiApplication</name>
<message>
<location filename="../QtUI/QtStrings.h" line="19"/>
<source>QT_LAYOUT_DIRECTION</source>
diff --git a/Swift/resources/icons/avatar.png b/Swift/resources/icons/avatar.png
deleted file mode 100644
index 4b73b44..0000000
--- a/Swift/resources/icons/avatar.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/icons/avatar.svg b/Swift/resources/icons/avatar.svg
index e9f3a89..54e2aae 100644
--- a/Swift/resources/icons/avatar.svg
+++ b/Swift/resources/icons/avatar.svg
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
+
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
@@ -13,96 +14,4747 @@
height="128"
id="svg2459"
sodipodi:version="0.32"
- inkscape:version="0.46"
+ inkscape:version="0.91+devel+osxmenu r12922"
sodipodi:docname="avatar.svg"
- inkscape:output_extension="org.inkscape.output.svg.inkscape"
- version="1.0"
- inkscape:export-filename="/Users/remko/src/swift/Swift/resources/icons/avatar.png"
- inkscape:export-xdpi="33.75"
- inkscape:export-ydpi="33.75">
+ viewBox="0 0 89 89"
+ version="1.1">
+ <metadata
+ id="metadata8">
+ <rdf:RDF>
+ <cc:Work
+ rdf:about="">
+ <dc:format>image/svg+xml</dc:format>
+ <dc:type
+ rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+ <dc:title />
+ </cc:Work>
+ </rdf:RDF>
+ </metadata>
<defs
- id="defs2461">
+ id="defs6">
+ <linearGradient
+ id="linearGradient4748"
+ spreadMethod="pad"
+ gradientTransform="matrix(1e-8,132.483,132.483,-1e-8,100,38.223)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop4750"
+ offset="0"
+ style="stop-opacity:1;stop-color:#191716" />
+ <stop
+ id="stop4752"
+ offset="1"
+ style="stop-opacity:1;stop-color:#6e6c6f" />
+ </linearGradient>
+ <clipPath
+ id="clipPath4744"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4746"
+ d="m 832.219,1466.16 c -75.211,-74.1 -87.246,-182.97 -48.348,-242.43 4.039,147.22 143.539,286.73 290.739,290.74 -59.43,38.96 -168.247,26.93 -242.391,-48.31 z m 266.441,-914.762 -197.316,0 c -31.125,0 -56.375,-25.226 -56.375,-56.347 0,-31.141 25.25,-56.391 56.375,-56.391 l 9.851,0 c 15.836,-33.269 49.496,-56.43 88.805,-56.43 39.31,0 72.97,23.161 88.81,56.43 l 9.85,0 c 31.12,0 56.37,25.25 56.37,56.391 0,31.121 -25.25,56.347 -56.37,56.347 z m 28.17,140.954 -253.662,0 c -31.148,0 -56.375,-25.243 -56.375,-56.372 0,-31.14 25.227,-56.371 56.375,-56.371 l 253.662,0 c 31.12,0 56.38,25.231 56.38,56.371 0,31.129 -25.26,56.372 -56.38,56.372 z m -23.99,112.757 -205.703,0 c -14.852,129.922 -73.711,203.561 -125.934,268.971 -53.258,66.65 -95.355,119.35 -95.355,238.34 0,173.87 142.394,310.06 324.152,310.06 178.73,0 324.15,-145.41 324.15,-324.14 0,-108.68 -38.54,-155.55 -91.94,-220.48 -51.08,-62.12 -114.03,-138.649 -129.37,-272.751 z M 1000,1707.05 c -225.77,0 -408.727,-168.87 -408.727,-394.63 0,-281.87 205.59,-286.54 223.61,-535.549 2.211,-31.051 27.137,-56.332 58.285,-56.332 l 253.662,0 c 31.12,0 56.11,25.281 58.29,56.332 17.96,251.809 223.61,253.679 223.61,521.469 0,225.74 -182.99,408.71 -408.73,408.71 z"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4730"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4732"
+ d="m 300.047,1685.95 c 0.398,27.09 19.152,49.74 44.312,56.1 -18.988,-13.76 -33.398,-33.44 -44.312,-56.1 m 1399.743,3.16 c -10.51,21.05 -24.24,39.32 -42.19,52.41 23.18,-6.73 40.49,-27.43 42.19,-52.41"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4718"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4720"
+ d="m 292.504,1668.47 0,15.42 c 0,37.22 30.211,67.46 67.344,67.52 -5.477,-2.7 -10.633,-5.84 -15.489,-9.36 -25.16,-6.36 -43.914,-29.01 -44.312,-56.1 -2.727,-5.66 -5.235,-11.5 -7.543,-17.48 m 1414.956,3.42 c -2.34,5.91 -4.89,11.66 -7.67,17.22 -1.7,24.98 -19.01,45.68 -42.19,52.41 -5.12,3.73 -10.59,7.05 -16.41,9.88 36.65,-0.61 66.27,-30.63 66.27,-67.51 l 0,-12"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4706"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4708"
+ d="m 284.973,1646.18 0,36.54 c 0,42.07 34.191,76.27 76.203,76.27 l 19.051,0 c -7.243,-1.89 -14.024,-4.44 -20.379,-7.58 -37.133,-0.06 -67.344,-30.3 -67.344,-67.52 l 0,-15.42 c -2.793,-7.26 -5.293,-14.7 -7.531,-22.29 M 1715,1650.2 c -2.24,7.4 -4.74,14.64 -7.54,21.69 l 0,12 c 0,36.88 -29.62,66.9 -66.27,67.51 -6.46,3.14 -13.37,5.7 -20.75,7.59 l 18.4,0 c 41.99,0 76.16,-34.2 76.16,-76.27 l 0,-32.52"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4694"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4696"
+ d="m 277.438,1615.76 0,65.79 c 0,46.88 38.121,85.02 84.96,85.02 l 1275.232,0 c 46.81,0 84.91,-38.14 84.91,-85.02 l 0,-61.09 c -2.1,10.03 -4.59,20.01 -7.54,29.74 l 0,32.52 c 0,42.07 -34.17,76.27 -76.16,76.27 l -18.4,0 c -9.8,2.51 -20.45,3.85 -32.01,3.85 l -1176.856,0 c -11.301,0 -21.726,-1.34 -31.347,-3.85 l -19.051,0 c -42.012,0 -76.203,-34.2 -76.203,-76.27 l 0,-36.54 c -2.942,-9.98 -5.434,-20.18 -7.535,-30.42"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4682"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4684"
+ d="m 269.906,1565.73 0,114.65 c 0,5.91 0.551,11.69 1.602,17.3 3.906,14.17 9.91,27.48 17.656,39.57 17.145,22.41 44.145,36.89 74.453,36.89 l 1272.793,0 c 30.68,0 57.96,-14.84 75.06,-37.74 7.24,-11.48 12.92,-24.04 16.74,-37.38 1.22,-6.03 1.86,-12.26 1.86,-18.64 l 0,-109.22 c -1.67,16.1 -4.08,32.78 -7.53,49.3 l 0,61.09 c 0,46.88 -38.1,85.02 -84.91,85.02 l -1275.232,0 c -46.839,0 -84.96,-38.14 -84.96,-85.02 l 0,-65.79 c -3.458,-16.85 -5.864,-33.79 -7.532,-50.03"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4670"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4672"
+ d="m 1733.79,1489.91 c 0,21.11 -0.48,50.07 -3.72,81.25 l 0,109.22 c 0,6.38 -0.64,12.61 -1.86,18.64 3.63,-12.69 5.58,-26.09 5.58,-39.92 l 0,-169.19 m -1467.485,0 0,169.19 c 0,13.35 1.812,26.29 5.203,38.58 -1.051,-5.61 -1.602,-11.39 -1.602,-17.3 l 0,-114.65 c -2.988,-29.11 -3.601,-55.94 -3.601,-75.82 M 1711.47,1736.4 c -17.1,22.9 -44.38,37.74 -75.06,37.74 l -1272.793,0 c -30.308,0 -57.308,-14.48 -74.453,-36.89 8.082,12.62 18.059,23.91 29.524,33.46 13.878,7.04 29.558,11.01 46.152,11.01 l 1270.36,0 c 16.65,0 32.38,-4 46.3,-11.09 11.68,-9.76 21.81,-21.31 29.97,-34.23"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4658"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4660"
+ d="m 1681.5,1770.63 c -13.92,7.09 -29.65,11.09 -46.3,11.09 l -1270.36,0 c -16.594,0 -32.274,-3.97 -46.152,-11.01 7.277,6.08 15.144,11.44 23.519,16.01 7.688,1.69 15.672,2.58 23.855,2.58 l 1267.928,0 c 8.2,0 16.19,-0.9 23.89,-2.59 8.41,-4.59 16.32,-9.98 23.62,-16.08"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4646"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4648"
+ d="m 1657.88,1786.71 c -7.7,1.69 -15.69,2.59 -23.89,2.59 l -1267.928,0 c -8.183,0 -16.167,-0.89 -23.855,-2.58 7.367,4.02 15.133,7.43 23.203,10.14 0.621,0.01 1.25,0.02 1.875,0.02 l 1265.485,0 c 0.62,0 1.25,-0.01 1.87,-0.02 8.08,-2.71 15.86,-6.12 23.24,-10.15"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4634"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4636"
+ d="m 365.41,1796.86 c 14.512,4.88 30.031,7.52 46.164,7.52 l 1176.856,0 c 16.15,0 31.68,-2.64 46.21,-7.52 -0.62,0.01 -1.25,0.02 -1.87,0.02 l -1265.485,0 c -0.625,0 -1.254,-0.01 -1.875,-0.02"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4622"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4624"
+ d="m 300.039,1666.88 0,18.18 c 0,0.3 0,0.6 0.008,0.89 10.914,22.66 25.324,42.34 44.312,56.1 4.602,1.16 9.418,1.78 14.371,1.78 l 14.618,0 c -2.598,-0.9 -5.047,-1.89 -7.313,-2.96 -30.355,-13.17 -51.543,-40.91 -65.996,-73.99 m 1399.891,2.86 c -14.26,31.74 -35.08,58.22 -64.87,71.04 -2.36,1.11 -4.93,2.12 -7.64,3.05 l 13.84,0 c 5.67,0 11.15,-0.8 16.34,-2.31 17.95,-13.09 31.68,-31.36 42.19,-52.41 0.09,-1.33 0.14,-2.69 0.14,-4.05 l 0,-15.32"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4610"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4612"
+ d="m 292.504,1647.49 0,20.98 c 2.308,5.98 4.816,11.82 7.543,17.48 -0.008,-0.29 -0.008,-0.59 -0.008,-0.89 l 0,-18.18 c -2.75,-6.29 -5.258,-12.77 -7.535,-19.39 m 1414.956,3.36 c -2.28,6.45 -4.78,12.77 -7.53,18.89 l 0,15.32 c 0,1.36 -0.05,2.72 -0.14,4.05 2.78,-5.56 5.33,-11.31 7.67,-17.22 l 0,-21.04 m -49.86,90.67 c -5.19,1.51 -10.67,2.31 -16.34,2.31 l -13.84,0 c -12.66,4.33 -28.7,6.72 -43.38,6.72 l -1168.177,0 c -14.347,0 -30.086,-2.39 -42.515,-6.72 l -14.618,0 c -4.953,0 -9.769,-0.62 -14.371,-1.78 4.856,3.52 10.012,6.66 15.489,9.36 0.035,0 0.07,0 0.105,0 l 1280.097,0 c 0.38,0 0.76,0 1.14,-0.01 5.82,-2.83 11.29,-6.15 16.41,-9.88"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4598"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4600"
+ d="m 284.973,1622.14 0,24.04 c 2.238,7.59 4.738,15.03 7.531,22.29 l 0,-20.98 c -2.856,-8.29 -5.356,-16.78 -7.531,-25.35 M 1715,1626.08 c -2.18,8.39 -4.68,16.69 -7.54,24.77 l 0,21.04 c 2.8,-7.05 5.3,-14.29 7.54,-21.69 l 0,-24.12 m -73.81,125.32 c -0.38,0.01 -0.76,0.01 -1.14,0.01 l -1280.097,0 c -0.035,0 -0.07,0 -0.105,0 6.355,3.14 13.136,5.69 20.379,7.58 l 1240.213,0 c 7.38,-1.89 14.29,-4.45 20.75,-7.59"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4586"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4588"
+ d="m 277.438,1584.72 0,31.04 c 2.101,10.24 4.593,20.44 7.535,30.42 l 0,-24.04 c -3.157,-12.43 -5.637,-25.03 -7.535,-37.42 m 1445.102,4.76 c -1.91,12.16 -4.39,24.48 -7.54,36.6 l 0,24.12 c 2.95,-9.73 5.44,-19.71 7.54,-29.74 l 0,-30.98 m -102.1,169.51 -1240.213,0 c 9.621,2.51 20.046,3.85 31.347,3.85 l 1176.856,0 c 11.56,0 22.21,-1.34 32.01,-3.85"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4574"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4576"
+ d="m 269.906,1516.99 0,48.74 c 1.668,16.24 4.074,33.18 7.532,50.03 l 0,-31.04 c -1.008,-6.58 -1.852,-13.09 -2.547,-19.49 -1.856,-17.17 -3.489,-33.62 -4.985,-48.24 m 1460.164,2.4 c -1.34,13.97 -2.78,29.53 -4.4,45.73 -0.81,7.97 -1.84,16.13 -3.13,24.36 l 0,30.98 c 3.45,-16.52 5.86,-33.2 7.53,-49.3 l 0,-51.77 M 271.508,1697.68 c 2.746,14.67 8.922,28.16 17.656,39.57 -7.746,-12.09 -13.75,-25.4 -17.656,-39.57 m 1456.702,1.34 c -3.82,13.34 -9.5,25.9 -16.74,37.38 8.13,-10.88 13.95,-23.59 16.74,-37.38"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4562"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4564"
+ d="m 1733.79,1484.29 c -1.22,9.68 -2.42,21.66 -3.72,35.1 l 0,51.77 c 3.24,-31.18 3.72,-60.14 3.72,-81.25 l 0,169.19 c 0,13.83 -1.95,27.23 -5.58,39.92 -2.79,13.79 -8.61,26.5 -16.74,37.38 -8.16,12.92 -18.29,24.47 -29.97,34.23 5.69,-2.9 11.08,-6.32 16.1,-10.2 22.2,-23.62 36.84,-54.42 40.01,-88.5 l 0,-150.54 c -0.78,-15.53 -2.2,-37.1 -3.82,-37.1 m -1467.485,0 c -1.696,0 -3.172,23.66 -3.93,39.27 l 0,147.2 c 2.945,34.65 17.738,65.97 40.301,89.88 4.996,3.83 10.355,7.21 16.012,10.07 -11.465,-9.55 -21.442,-20.84 -29.524,-33.46 -8.734,-11.41 -14.91,-24.9 -17.656,-39.57 -3.391,-12.29 -5.203,-25.23 -5.203,-38.58 l 0,-169.19 c 0,19.88 0.613,46.71 3.601,75.82 l 0,-48.74 c -1.277,-12.47 -2.461,-23.6 -3.601,-32.7"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4550"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4552"
+ d="m 1737.61,1521.39 0,150.54 c 0.43,-4.61 0.64,-9.27 0.64,-13.98 l 0,-121.07 c 0,-0.85 -0.23,-7.34 -0.64,-15.49 m -1475.235,2.17 c -0.348,7.13 -0.543,12.58 -0.543,13.35 l 0,121.04 c 0,4.32 0.184,8.59 0.543,12.81 l 0,-147.2 M 1697.6,1760.43 c -5.02,3.88 -10.41,7.3 -16.1,10.2 -7.3,6.1 -15.21,11.49 -23.62,16.08 4.39,-0.97 8.68,-2.19 12.86,-3.67 9.82,-6.47 18.83,-14.07 26.86,-22.61 m -1394.924,0.21 c 7.988,8.47 16.945,16 26.695,22.43 4.172,1.47 8.453,2.69 12.836,3.65 -8.375,-4.57 -16.242,-9.93 -23.519,-16.01 -5.657,-2.86 -11.016,-6.24 -16.012,-10.07"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4538"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4540"
+ d="m 1670.74,1783.04 c -4.18,1.48 -8.47,2.7 -12.86,3.67 -7.38,4.03 -15.16,7.44 -23.24,10.15 3.91,-0.06 7.77,-0.31 11.59,-0.74 8.6,-3.6 16.81,-8 24.51,-13.08 m -1341.369,0.03 c 7.688,5.07 15.871,9.45 24.453,13.05 3.813,0.43 7.672,0.68 11.586,0.74 -8.07,-2.71 -15.836,-6.12 -23.203,-10.14 -4.383,-0.96 -8.664,-2.18 -12.836,-3.65"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4526"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4528"
+ d="m 1646.23,1796.12 c -3.82,0.43 -7.68,0.68 -11.59,0.74 -14.53,4.88 -30.06,7.52 -46.21,7.52 l -1176.856,0 c -16.133,0 -31.652,-2.64 -46.164,-7.52 -3.914,-0.06 -7.773,-0.31 -11.586,-0.74 8.504,3.58 17.395,6.38 26.61,8.33 l 1239.166,0 c 9.22,-1.95 18.12,-4.75 26.63,-8.33"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4514"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4516"
+ d="m 1619.6,1804.45 -1239.166,0 c 10.046,2.14 20.468,3.26 31.14,3.26 l 1176.856,0 c 10.68,0 21.11,-1.12 31.17,-3.26"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4502"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4504"
+ d="m 300.039,1647.09 0,19.79 c 14.453,33.08 35.641,60.82 65.996,73.99 2.266,1.07 4.715,2.06 7.313,2.96 l 1254.072,0 c 2.71,-0.93 5.28,-1.94 7.64,-3.05 29.79,-12.82 50.61,-39.3 64.87,-71.04 l 0,-19.86 c -14.6,36.12 -36.98,66.82 -69.54,79.58 -12.02,5.62 -34.69,8.79 -50.74,8.79 l -1159.494,0 c -15.613,0 -37.769,-3.14 -49.566,-8.71 -33.051,-13.05 -55.789,-45.06 -70.551,-82.45"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4490"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4492"
+ d="m 292.504,1625.41 0,22.08 c 2.277,6.62 4.785,13.1 7.535,19.39 l 0,-19.79 c -2.793,-7.06 -5.301,-14.33 -7.535,-21.68 m 1414.956,3.26 c -2.23,7.21 -4.74,14.31 -7.53,21.21 l 0,19.86 c 2.75,-6.12 5.25,-12.44 7.53,-18.89 l 0,-22.18 m -80.04,115.16 -1254.072,0 c 12.429,4.33 28.168,6.72 42.515,6.72 l 1168.177,0 c 14.68,0 30.72,-2.39 43.38,-6.72"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4478"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4480"
+ d="m 284.973,1595.72 0,26.42 c 2.175,8.57 4.675,17.06 7.531,25.35 l 0,-22.08 c -2.977,-9.79 -5.473,-19.76 -7.531,-29.69 m 1430.027,3.9 c -2.07,9.74 -4.57,19.49 -7.54,29.05 l 0,22.18 c 2.86,-8.08 5.36,-16.38 7.54,-24.77 l 0,-26.46"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4466"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4468"
+ d="m 277.438,1542.25 0,42.47 c 1.898,12.39 4.378,24.99 7.535,37.42 l 0,-26.42 c -2.77,-13.34 -4.739,-26.61 -6.008,-39.28 -0.477,-4.81 -0.985,-9.55 -1.527,-14.19 m 1445.102,4.06 c -0.35,3.3 -0.68,6.65 -0.98,10.03 -1.3,13.94 -3.44,28.6 -6.56,43.28 l 0,26.46 c 3.15,-12.12 5.63,-24.44 7.54,-36.6 l 0,-43.17"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4454"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4456"
+ d="m 269.906,1493.76 0,23.23 c 1.496,14.62 3.129,31.07 4.985,48.24 0.695,6.4 1.539,12.91 2.547,19.49 l 0,-42.47 c -2.114,-18.17 -4.708,-34.91 -7.532,-48.49 m 1460.164,0.72 c -2.92,14.47 -5.51,32.43 -7.53,51.83 l 0,43.17 c 1.29,-8.23 2.32,-16.39 3.13,-24.36 1.62,-16.2 3.06,-31.76 4.4,-45.73 l 0,-24.91"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4442"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4444"
+ d="m 1733.79,1478.66 c -1.28,4.6 -2.53,9.92 -3.72,15.82 l 0,24.91 c 1.3,-13.44 2.5,-25.42 3.72,-35.1 1.62,0 3.04,21.57 3.82,37.1 l 0,-33.75 c -1.16,-5.35 -2.45,-8.98 -3.82,-8.98 m -1467.485,0 c -1.41,0 -2.743,3.87 -3.93,9.5 l 0,35.4 c 0.758,-15.61 2.234,-39.27 3.93,-39.27 1.14,9.1 2.324,20.23 3.601,32.7 l 0,-23.23 c -1.168,-5.61 -2.375,-10.69 -3.601,-15.1 m -3.93,192.1 0,8.44 c 0,13.42 2.59,26.24 7.297,38 1.82,4.26 3.832,8.44 6.016,12.49 6.843,12.04 16.05,22.58 26.988,30.95 -22.563,-23.91 -37.356,-55.23 -40.301,-89.88 m 1475.235,1.17 c -3.17,34.08 -17.81,64.88 -40.01,88.5 24.31,-18.76 40.01,-48.2 40.01,-81.23 l 0,-7.27"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4430"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4432"
+ d="m 1737.61,1487.64 0,33.75 c 0.41,8.15 0.64,14.64 0.64,15.49 l 0,121.07 c 0,4.71 -0.21,9.37 -0.64,13.98 l 0,7.27 c 0,33.03 -15.7,62.47 -40.01,81.23 -8.03,8.54 -17.04,16.14 -26.86,22.61 5.12,-1.8 10.07,-3.97 14.81,-6.47 34.86,-28.3 57.17,-71.47 57.17,-119.77 l 0,-125.88 c 0,-3.57 -2.09,-29.31 -5.11,-43.28 m -1475.235,0.52 c -2.973,14.09 -5.02,39.26 -5.02,42.79 l 0,125.85 c 0,21.43 4.387,41.84 12.317,60.4 -4.707,-11.76 -7.297,-24.58 -7.297,-38 l 0,-8.44 c -0.359,-4.22 -0.543,-8.49 -0.543,-12.81 l 0,-121.04 c 0,-0.77 0.195,-6.22 0.543,-13.35 l 0,-35.4 m 13.313,241.53 c 9.757,18.13 23.039,34.09 38.917,46.96 4.731,2.48 9.665,4.64 14.766,6.42 -9.75,-6.43 -18.707,-13.96 -26.695,-22.43 -10.938,-8.37 -20.145,-18.91 -26.988,-30.95"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4418"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4420"
+ d="m 1685.55,1776.57 c -4.74,2.5 -9.69,4.67 -14.81,6.47 -7.7,5.08 -15.91,9.48 -24.51,13.08 4.29,-0.48 8.51,-1.19 12.66,-2.11 9.5,-4.9 18.43,-10.75 26.66,-17.44 m -1370.945,0.08 c 8.207,6.66 17.102,12.48 26.571,17.36 4.14,0.92 8.359,1.63 12.648,2.11 -8.582,-3.6 -16.765,-7.98 -24.453,-13.05 -5.101,-1.78 -10.035,-3.94 -14.766,-6.42"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4406"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4408"
+ d="m 1658.89,1794.01 c -4.15,0.92 -8.37,1.63 -12.66,2.11 -8.51,3.58 -17.41,6.38 -26.63,8.33 l 11.96,0 c 0.52,0 1.05,0 1.57,-0.01 8.95,-2.71 17.57,-6.22 25.76,-10.43 m -1317.714,0 c 8.176,4.22 16.785,7.72 25.726,10.43 0.536,0.01 1.067,0.01 1.606,0.01 l 11.926,0 c -9.215,-1.95 -18.106,-4.75 -26.61,-8.33 -4.289,-0.48 -8.508,-1.19 -12.648,-2.11"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4394"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4396"
+ d="m 366.902,1804.44 c 14.145,4.29 29.145,6.6 44.672,6.6 l 1176.856,0 c 15.54,0 30.55,-2.31 44.7,-6.6 -0.52,0.01 -1.05,0.01 -1.57,0.01 l -11.96,0 c -10.06,2.14 -20.49,3.26 -31.17,3.26 l -1176.856,0 c -10.672,0 -21.094,-1.12 -31.14,-3.26 l -11.926,0 c -0.539,0 -1.07,0 -1.606,-0.01"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4382"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4384"
+ d="m 300.039,1626.46 0,20.63 c 14.762,37.39 37.5,69.4 70.551,82.45 11.797,5.57 33.953,8.71 49.566,8.71 l 1159.494,0 c 16.05,0 38.72,-3.17 50.74,-8.79 32.56,-12.76 54.94,-43.46 69.54,-79.58 l 0,-20.74 c -14.72,40.73 -38.77,76.51 -74.2,89 -10.68,5 -36.2,7.81 -50.47,7.81 l -1150.815,0 c -13.875,0 -38.812,-2.78 -49.3,-7.74 -35.868,-12.73 -60.274,-49.86 -75.106,-91.75"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4370"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4372"
+ d="m 292.504,1601.8 0,23.61 c 2.234,7.35 4.742,14.62 7.535,21.68 l 0,-20.63 c -2.863,-8.09 -5.371,-16.35 -7.535,-24.66 m 1414.956,3.18 c -2.17,8.15 -4.67,16.25 -7.53,24.16 l 0,20.74 c 2.79,-6.9 5.3,-14 7.53,-21.21 l 0,-23.69"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4358"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4360"
+ d="m 284.973,1564.2 0,31.52 c 2.058,9.93 4.554,19.9 7.531,29.69 l 0,-23.61 c -3.289,-12.61 -5.781,-25.31 -7.531,-37.6 M 1715,1568.43 c -1.79,12 -4.28,24.33 -7.54,36.55 l 0,23.69 c 2.97,-9.56 5.47,-19.31 7.54,-29.05 l 0,-31.19"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4346"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4348"
+ d="m 277.438,1509.34 0,32.91 c 0.542,4.64 1.05,9.38 1.527,14.19 1.269,12.67 3.238,25.94 6.008,39.28 l 0,-31.52 c -0.801,-5.62 -1.446,-11.16 -1.938,-16.56 -1.211,-13.6 -3.16,-26.63 -5.597,-38.3 m 1445.102,1.27 c -2.25,11.32 -4.02,23.86 -5.1,36.95 -0.57,6.77 -1.38,13.76 -2.44,20.87 l 0,31.19 c 3.12,-14.68 5.26,-29.34 6.56,-43.28 0.3,-3.38 0.63,-6.73 0.98,-10.03 l 0,-35.7"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4334"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4336"
+ d="m 269.906,1481.84 0,11.92 c 2.824,13.58 5.418,30.32 7.532,48.49 l 0,-32.91 c -2.18,-10.44 -4.75,-19.79 -7.532,-27.5 m 1460.164,0.36 c -2.82,7.95 -5.39,17.62 -7.53,28.41 l 0,35.7 c 2.02,-19.4 4.61,-37.36 7.53,-51.83 l 0,-12.28"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4322"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4324"
+ d="m 1733.79,1473.04 c -1.28,2.71 -2.52,5.78 -3.72,9.16 l 0,12.28 c 1.19,-5.9 2.44,-11.22 3.72,-15.82 1.37,0 2.66,3.63 3.82,8.98 l 0,-10.78 c -1.21,-2.39 -2.49,-3.82 -3.82,-3.82 m -1467.485,0 c -1.367,0 -2.688,1.52 -3.93,4.05 l 0,11.07 c 1.187,-5.63 2.52,-9.5 3.93,-9.5 1.226,4.41 2.433,9.49 3.601,15.1 l 0,-11.92 c -1.168,-3.23 -2.371,-6.18 -3.601,-8.8 m 3.367,244.16 c 1.726,4.31 3.742,8.49 6.016,12.49 -2.184,-4.05 -4.196,-8.23 -6.016,-12.49"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4310"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4312"
+ d="m 1737.61,1476.86 0,10.78 c 3.02,13.97 5.11,39.71 5.11,43.28 l 0,125.88 c 0,48.3 -22.31,91.47 -57.17,119.77 6.56,-3.45 12.73,-7.54 18.44,-12.18 21.18,-22.49 35.88,-51.14 41.1,-82.93 0.04,-1.14 0.05,-2.28 0.05,-3.43 l 0,-171.22 c -1.71,-10.96 -4.38,-23.72 -7.53,-29.95 m -1475.235,0.23 c -3.168,6.42 -5.84,19.36 -7.535,30.32 l 0,170.62 c 0,0.94 0.012,1.87 0.035,2.8 5.145,32.15 19.973,61.1 41.387,83.76 5.679,4.59 11.824,8.64 18.343,12.06 -15.878,-12.87 -29.16,-28.83 -38.917,-46.96 -2.274,-4 -4.29,-8.18 -6.016,-12.49 -7.93,-18.56 -12.317,-38.97 -12.317,-60.4 l 0,-125.85 c 0,-3.53 2.047,-28.7 5.02,-42.79 l 0,-11.07"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4298"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4300"
+ d="m 1745.14,1506.81 0,171.22 c 0,1.15 -0.01,2.29 -0.05,3.43 1.38,-8.4 2.1,-17.02 2.1,-25.8 l 0,-130.7 c 0,-2.61 -0.75,-9.87 -2.05,-18.15 m -1490.3,0.6 c -1.242,8.05 -1.957,15.02 -1.957,17.58 l 0,130.67 c 0,8.56 0.679,16.97 1.992,25.17 -0.023,-0.93 -0.035,-1.86 -0.035,-2.8 l 0,-170.62 m 1449.15,256.98 c -5.71,4.64 -11.88,8.73 -18.44,12.18 -8.23,6.69 -17.16,12.54 -26.66,17.44 4.83,-1.08 9.56,-2.46 14.15,-4.1 11.38,-7.19 21.77,-15.77 30.95,-25.52 m -1407.728,0.2 c 9.14,9.67 19.476,18.2 30.773,25.34 4.594,1.64 9.313,3 14.141,4.08 -9.469,-4.88 -18.364,-10.7 -26.571,-17.36 -6.519,-3.42 -12.664,-7.47 -18.343,-12.06"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4286"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4288"
+ d="m 1673.04,1789.91 c -4.59,1.64 -9.32,3.02 -14.15,4.1 -8.19,4.21 -16.81,7.72 -25.76,10.43 4.26,-0.05 8.47,-0.31 12.61,-0.76 9.58,-3.73 18.73,-8.35 27.3,-13.77 m -1346.005,0.02 c 8.57,5.41 17.688,10.03 27.25,13.74 4.149,0.46 8.36,0.72 12.617,0.77 -8.941,-2.71 -17.55,-6.21 -25.726,-10.43 -4.828,-1.08 -9.547,-2.44 -14.141,-4.08"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4274"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4276"
+ d="m 354.285,1803.67 c 9.606,3.73 19.664,6.56 30.063,8.36 l 1231.322,0 c 10.41,-1.8 20.47,-4.63 30.07,-8.35 -4.14,0.45 -8.35,0.71 -12.61,0.76 -14.15,4.29 -29.16,6.6 -44.7,6.6 l -1176.856,0 c -15.527,0 -30.527,-2.31 -44.672,-6.6 -4.257,-0.05 -8.468,-0.31 -12.617,-0.77"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4262"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4264"
+ d="m 1615.67,1812.03 -1231.322,0 c 8.847,1.54 17.945,2.34 27.226,2.34 l 1176.856,0 c 9.29,0 18.39,-0.8 27.24,-2.34"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4250"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4252"
+ d="m 300.039,1604.76 0,21.7 c 14.832,41.89 39.238,79.02 75.106,91.75 10.488,4.96 35.425,7.74 49.3,7.74 l 1150.815,0 c 14.27,0 39.79,-2.81 50.47,-7.81 35.43,-12.49 59.48,-48.27 74.2,-89 l 0,-21.81 c -14.49,45.48 -40.39,87.47 -78.86,99.49 -9.35,4.37 -37.72,6.84 -50.2,6.84 l -1142.132,0 c -12.144,0 -39.863,-2.44 -49.039,-6.78 -38.863,-12.2 -65.121,-55.61 -79.66,-102.12"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4238"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4240"
+ d="m 292.504,1575.71 0,26.09 c 2.164,8.31 4.672,16.57 7.535,24.66 l 0,-21.7 c -3.012,-9.63 -5.519,-19.4 -7.535,-29.05 m 1414.956,3.18 c -2.03,9.47 -4.54,19.03 -7.53,28.44 l 0,21.81 c 2.86,-7.91 5.36,-16.01 7.53,-24.16 l 0,-26.09"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4226"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4228"
+ d="m 284.973,1521.07 0,43.13 c 1.75,12.29 4.242,24.99 7.531,37.6 l 0,-26.09 c -2.645,-12.67 -4.438,-25.15 -5.395,-36.86 -0.48,-6.08 -1.207,-12.04 -2.136,-17.78 M 1715,1523.42 c -0.72,4.99 -1.29,10.13 -1.67,15.35 -0.96,12.71 -2.91,26.33 -5.87,40.12 l 0,26.09 c 3.26,-12.22 5.75,-24.55 7.54,-36.55 l 0,-45.01"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4214"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4216"
+ d="m 277.438,1490.42 0,18.92 c 2.437,11.67 4.386,24.7 5.597,38.3 0.492,5.4 1.137,10.94 1.938,16.56 l 0,-43.13 c -1.817,-11.22 -4.422,-21.64 -7.535,-30.65 m 1445.102,0.55 c -3.2,9.52 -5.82,20.57 -7.54,32.45 l 0,45.01 c 1.06,-7.11 1.87,-14.1 2.44,-20.87 1.08,-13.09 2.85,-25.63 5.1,-36.95 l 0,-19.64"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4202"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4204"
+ d="m 269.906,1473.14 0,8.7 c 2.782,7.71 5.352,17.06 7.532,27.5 l 0,-18.92 c -2.274,-6.58 -4.821,-12.42 -7.532,-17.28 m 1460.164,0.22 c -2.73,4.94 -5.28,10.9 -7.53,17.61 l 0,19.64 c 2.14,-10.79 4.71,-20.46 7.53,-28.41 l 0,-8.84"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4190"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4192"
+ d="m 1733.79,1467.42 c -1.27,1.77 -2.51,3.76 -3.72,5.94 l 0,8.84 c 1.2,-3.38 2.44,-6.45 3.72,-9.16 1.33,0 2.61,1.43 3.82,3.82 l 0,-7.4 c -1.23,-1.3 -2.51,-2.04 -3.82,-2.04 m -1467.485,0 c -1.352,0 -2.664,0.78 -3.93,2.15 l 0,7.52 c 1.242,-2.53 2.563,-4.05 3.93,-4.05 1.23,2.62 2.433,5.57 3.601,8.8 l 0,-8.7 c -1.172,-2.09 -2.375,-4.01 -3.601,-5.72"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4178"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4180"
+ d="m 1737.61,1469.46 0,7.4 c 3.15,6.23 5.82,18.99 7.53,29.95 l 0,-21.63 c -2.14,-6.82 -4.71,-12.75 -7.53,-15.72 m -1475.235,0.11 c -2.82,3.06 -5.391,9.06 -7.535,15.92 l 0,21.92 c 1.695,-10.96 4.367,-23.9 7.535,-30.32 l 0,-7.52 m -7.5,211.26 c 0.84,33.78 16.816,63.88 41.387,83.76 -21.414,-22.66 -36.242,-51.61 -41.387,-83.76 m 1490.215,0.63 c -5.22,31.79 -19.92,60.44 -41.1,82.93 24.27,-19.75 40.09,-49.52 41.1,-82.93"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4166"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4168"
+ d="m 1745.14,1485.18 0,21.63 c 1.3,8.28 2.05,15.54 2.05,18.15 l 0,130.7 c 0,8.78 -0.72,17.4 -2.1,25.8 -1.01,33.41 -16.83,63.18 -41.1,82.93 -9.18,9.75 -19.57,18.33 -30.95,25.52 5.72,-2.05 11.23,-4.52 16.51,-7.37 37.81,-29.91 62.1,-76.18 62.1,-128.03 l 0,-135.5 c 0,-5.56 -2.53,-21.22 -6.51,-33.83 m -1490.3,0.31 c -3.93,12.57 -6.434,28.02 -6.434,33.54 l 0,135.48 c 0,51.88 24.328,98.17 62.168,128.08 5.266,2.84 10.766,5.3 16.461,7.34 -11.297,-7.14 -21.633,-15.67 -30.773,-25.34 -24.571,-19.88 -40.547,-49.98 -41.387,-83.76 -1.313,-8.2 -1.992,-16.61 -1.992,-25.17 l 0,-130.67 c 0,-2.56 0.715,-9.53 1.957,-17.58 l 0,-21.92"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4154"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4156"
+ d="m 1689.55,1782.54 c -5.28,2.85 -10.79,5.32 -16.51,7.37 -8.57,5.42 -17.72,10.04 -27.3,13.77 4.69,-0.52 9.3,-1.29 13.82,-2.3 10.7,-5.2 20.74,-11.53 29.99,-18.84 m -1378.976,0.05 c 9.215,7.29 19.235,13.6 29.899,18.79 4.519,1 9.129,1.77 13.812,2.29 -9.562,-3.71 -18.68,-8.33 -27.25,-13.74 -5.695,-2.04 -11.195,-4.5 -16.461,-7.34"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4142"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4144-7"
+ d="m 340.473,1801.38 c 9.035,4.39 18.531,7.97 28.394,10.65 0.289,0 0.574,0 0.863,0 l 14.618,0 c -10.399,-1.8 -20.457,-4.63 -30.063,-8.36 -4.683,-0.52 -9.293,-1.29 -13.812,-2.29 m 1319.087,0 c -4.52,1.01 -9.13,1.78 -13.82,2.3 -9.6,3.72 -19.66,6.55 -30.07,8.35 l 14.68,0 c 0.27,0 0.54,0 0.81,0 9.86,-2.68 19.37,-6.26 28.4,-10.65"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4130"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4132"
+ d="m 368.867,1812.03 c 13.617,3.69 27.934,5.67 42.707,5.67 l 1176.856,0 c 14.78,0 29.1,-1.98 42.73,-5.67 -0.27,0 -0.54,0 -0.81,0 l -14.68,0 c -8.85,1.54 -17.95,2.34 -27.24,2.34 l -1176.856,0 c -9.281,0 -18.379,-0.8 -27.226,-2.34 l -14.618,0 c -0.289,0 -0.574,0 -0.863,0"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4118"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4120-5"
+ d="m 300.039,1581.56 0,23.2 c 14.539,46.51 40.797,89.92 79.66,102.12 9.176,4.34 36.895,6.78 49.039,6.78 l 1142.132,0 c 12.48,0 40.85,-2.47 50.2,-6.84 38.47,-12.02 64.37,-54.01 78.86,-99.49 l 0,-23.29 c -13.69,50.25 -41.7,100.12 -83.52,111.46 -8.02,3.75 -39.23,5.86 -49.93,5.86 l -1133.453,0 c -10.406,0 -40.91,-2.09 -48.773,-5.81 -42.18,-11.48 -70.563,-62.86 -84.215,-113.99"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4106"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4108"
+ d="m 292.504,1543.34 0,32.37 c 2.016,9.65 4.523,19.42 7.535,29.05 l 0,-23.2 c -3.465,-12.97 -5.98,-25.94 -7.535,-38.22 m 1414.956,3.8 c -1.62,11.93 -4.14,24.43 -7.53,36.9 l 0,23.29 c 2.99,-9.41 5.5,-18.97 7.53,-28.44 l 0,-31.75"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4094"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4096"
+ d="m 284.973,1496.09 0,24.98 c 0.929,5.74 1.656,11.7 2.136,17.78 0.957,11.71 2.75,24.19 5.395,36.86 l 0,-32.37 c -0.57,-4.53 -1.012,-8.96 -1.32,-13.28 -0.836,-12.15 -3.051,-23.72 -6.211,-33.97 m 1430.027,0.8 c -2.97,10.04 -5.03,21.3 -5.78,33.1 -0.37,5.54 -0.96,11.28 -1.76,17.15 l 0,31.75 c 2.96,-13.79 4.91,-27.41 5.87,-40.12 0.38,-5.22 0.95,-10.36 1.67,-15.35 l 0,-26.53"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4082"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4084"
+ d="m 277.438,1477.41 0,13.01 c 3.113,9.01 5.718,19.43 7.535,30.65 l 0,-24.98 c -2.125,-6.9 -4.68,-13.2 -7.535,-18.68 m 1445.102,0.3 c -2.88,5.63 -5.44,12.1 -7.54,19.18 l 0,26.53 c 1.72,-11.88 4.34,-22.93 7.54,-32.45 l 0,-13.26"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4070"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4072"
+ d="m 269.906,1465.72 0,7.42 c 2.711,4.86 5.258,10.7 7.532,17.28 l 0,-13.01 c -2.333,-4.48 -4.868,-8.42 -7.532,-11.69 m 1460.164,0.15 c -2.67,3.31 -5.21,7.3 -7.53,11.84 l 0,13.26 c 2.25,-6.71 4.8,-12.67 7.53,-17.61 l 0,-7.49"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4058"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4060"
+ d="m 1733.79,1461.8 c -1.26,1.21 -2.51,2.57 -3.72,4.07 l 0,7.49 c 1.21,-2.18 2.45,-4.17 3.72,-5.94 1.31,0 2.59,0.74 3.82,2.04 l 0,-6.44 c -1.24,-0.79 -2.52,-1.22 -3.82,-1.22 m -1467.485,0 c -1.34,0 -2.653,0.46 -3.93,1.29 l 0,6.48 c 1.266,-1.37 2.578,-2.15 3.93,-2.15 1.226,1.71 2.429,3.63 3.601,5.72 l 0,-7.42 c -1.176,-1.44 -2.379,-2.75 -3.601,-3.92"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4046"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4048"
+ d="m 1737.61,1463.02 0,6.44 c 2.82,2.97 5.39,8.9 7.53,15.72 l 0,-12.69 c -2.28,-4.32 -4.82,-7.74 -7.53,-9.47 m -1475.235,0.07 c -2.711,1.78 -5.254,5.24 -7.535,9.59 l 0,12.81 c 2.144,-6.86 4.715,-12.86 7.535,-15.92 l 0,-6.48"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4034"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4036"
+ d="m 1745.14,1472.49 0,12.69 c 3.98,12.61 6.51,28.27 6.51,33.83 l 0,135.5 c 0,51.85 -24.29,98.12 -62.1,128.03 7.61,-4.12 14.73,-9.04 21.24,-14.64 19.87,-21.2 34.3,-47.55 41.05,-76.81 0.55,-4.66 0.84,-9.41 0.84,-14.23 l 0,-184.09 c -1.89,-7.09 -4.48,-14.49 -7.54,-20.28 m -1490.3,0.19 c -3.059,5.85 -5.645,13.29 -7.531,20.39 l 0,183.79 c 0,4.62 0.261,9.18 0.773,13.67 6.715,29.57 21.266,56.19 41.344,77.56 6.488,5.55 13.578,10.42 21.148,14.5 -37.84,-29.91 -62.168,-76.2 -62.168,-128.08 l 0,-135.48 c 0,-5.52 2.504,-20.97 6.434,-33.54 l 0,-12.81"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4022"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4024"
+ d="m 1752.68,1492.77 0,184.09 c 0,4.82 -0.29,9.57 -0.84,14.23 2.8,-12.13 4.28,-24.75 4.28,-37.72 l 0,-140.32 c 0,-4.39 -1.26,-12.12 -3.44,-20.28 m -1505.371,0.3 c -2.141,8.05 -3.375,15.66 -3.375,20 l 0,140.3 c 0,12.76 1.433,25.2 4.148,37.16 -0.512,-4.49 -0.773,-9.05 -0.773,-13.67 l 0,-183.79 M 1710.79,1767.9 c -6.51,5.6 -13.63,10.52 -21.24,14.64 -9.25,7.31 -19.29,13.64 -29.99,18.84 5.32,-1.19 10.51,-2.7 15.56,-4.53 13.19,-7.99 25.19,-17.75 35.67,-28.95 m -1421.364,0.19 c 10.445,11.12 22.39,20.82 35.508,28.77 5.039,1.82 10.23,3.33 15.539,4.52 -10.664,-5.19 -20.684,-11.5 -29.899,-18.79 -7.57,-4.08 -14.66,-8.95 -21.148,-14.5"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath4010"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4012-9"
+ d="m 1675.12,1796.85 c -5.05,1.83 -10.24,3.34 -15.56,4.53 -9.03,4.39 -18.54,7.97 -28.4,10.65 4.62,-0.03 9.18,-0.28 13.68,-0.76 10.62,-3.81 20.76,-8.66 30.28,-14.42 m -1350.186,0.01 c 9.504,5.76 19.625,10.6 30.238,14.41 4.504,0.47 9.074,0.73 13.695,0.76 -9.863,-2.68 -19.359,-6.26 -28.394,-10.65 -5.309,-1.19 -10.5,-2.7 -15.539,-4.52"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3998"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path4000"
+ d="m 355.172,1811.27 c 11.035,3.95 22.594,6.78 34.555,8.34 l 1220.563,0 c 11.96,-1.56 23.52,-4.39 34.55,-8.34 -4.5,0.48 -9.06,0.73 -13.68,0.76 -13.63,3.69 -27.95,5.67 -42.73,5.67 l -1176.856,0 c -14.773,0 -29.09,-1.98 -42.707,-5.67 -4.621,-0.03 -9.191,-0.29 -13.695,-0.76"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3986"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3988-5"
+ d="m 1610.29,1819.61 -1220.563,0 c 7.148,0.93 14.445,1.41 21.847,1.41 l 1176.856,0 c 7.4,0 14.7,-0.48 21.86,-1.41"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3974"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3976"
+ d="m 300.039,1555.75 0,25.81 c 13.652,51.13 42.035,102.51 84.215,113.99 7.863,3.72 38.367,5.81 48.773,5.81 l 1133.453,0 c 10.7,0 41.91,-2.11 49.93,-5.86 41.82,-11.34 69.83,-61.21 83.52,-111.46 l 0,-25.8 c -11.81,54.85 -42.37,115.46 -88.19,125.94 -6.68,3.12 -40.73,4.88 -49.65,4.88 l -1124.77,0 c -8.675,0 -41.961,-1.74 -48.515,-4.83 -46.184,-10.61 -77.149,-72.96 -88.766,-128.48"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3962"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3964"
+ d="m 292.504,1501.79 0,41.55 c 1.555,12.28 4.07,25.25 7.535,38.22 l 0,-25.81 c -2.516,-12.01 -4.125,-23.7 -4.785,-34.48 -0.395,-6.74 -1.34,-13.28 -2.75,-19.48 m 1414.956,1.36 c -1.21,5.78 -2.02,11.83 -2.36,18.06 -0.65,11.54 -2.39,24.13 -5.17,37.03 l 0,25.8 c 3.39,-12.47 5.91,-24.97 7.53,-36.9 l 0,-43.99"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3950"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3952"
+ d="m 284.973,1479.79 0,16.3 c 3.16,10.25 5.375,21.82 6.211,33.97 0.308,4.32 0.75,8.75 1.32,13.28 l 0,-41.55 c -1.816,-8 -4.395,-15.44 -7.531,-22 M 1715,1480.2 c -3.2,6.83 -5.78,14.59 -7.54,22.95 l 0,43.99 c 0.8,-5.87 1.39,-11.61 1.76,-17.15 0.75,-11.8 2.81,-23.06 5.78,-33.1 l 0,-16.69"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3938"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3940"
+ d="m 277.438,1467.14 0,10.27 c 2.855,5.48 5.41,11.78 7.535,18.68 l 0,-16.3 c -2.25,-4.7 -4.789,-8.96 -7.535,-12.65 m 1445.102,0.19 c -2.76,3.75 -5.3,8.08 -7.54,12.87 l 0,16.69 c 2.1,-7.08 4.66,-13.55 7.54,-19.18 l 0,-10.38"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3926"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3928"
+ d="m 269.906,1458.92 0,6.8 c 2.664,3.27 5.199,7.21 7.532,11.69 l 0,-10.27 c -2.372,-3.18 -4.899,-5.95 -7.532,-8.22 m 1460.164,0.1 c -2.64,2.3 -5.17,5.09 -7.53,8.31 l 0,10.38 c 2.32,-4.54 4.86,-8.53 7.53,-11.84 l 0,-6.85"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3914"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3916"
+ d="m 1733.79,1456.18 c -1.26,0.84 -2.5,1.79 -3.72,2.84 l 0,6.85 c 1.21,-1.5 2.46,-2.86 3.72,-4.07 1.3,0 2.58,0.43 3.82,1.22 l 0,-6.05 c -1.25,-0.51 -2.52,-0.79 -3.82,-0.79 m -1467.485,0 c -1.332,0 -2.649,0.29 -3.93,0.84 l 0,6.07 c 1.277,-0.83 2.59,-1.29 3.93,-1.29 1.222,1.17 2.425,2.48 3.601,3.92 l 0,-6.8 c -1.179,-1.01 -2.383,-1.93 -3.601,-2.74"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3902"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3904"
+ d="m 1737.61,1456.97 0,6.05 c 2.71,1.73 5.25,5.15 7.53,9.47 l 0,-9.36 c -2.34,-2.88 -4.87,-5.06 -7.53,-6.16 m -1475.235,0.05 c -2.656,1.12 -5.187,3.33 -7.535,6.24 l 0,9.42 c 2.281,-4.35 4.824,-7.81 7.535,-9.59 l 0,-6.07"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3890"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3892"
+ d="m 1745.14,1463.13 0,9.36 c 3.06,5.79 5.65,13.19 7.54,20.28 l 0,-16.83 c -2.18,-4.86 -4.72,-9.34 -7.54,-12.81 m -1490.3,0.13 c -2.813,3.49 -5.356,7.99 -7.531,12.87 l 0,16.94 c 1.886,-7.1 4.472,-14.54 7.531,-20.39 l 0,-9.42 m -6.758,227.27 c 3.523,30.91 18.848,58.31 41.344,77.56 -20.078,-21.37 -34.629,-47.99 -41.344,-77.56 m 1503.758,0.56 c -6.75,29.26 -21.18,55.61 -41.05,76.81 22.24,-19.11 37.42,-46.22 41.05,-76.81"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3878"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3880"
+ d="m 1752.68,1475.94 0,16.83 c 2.18,8.16 3.44,15.89 3.44,20.28 l 0,140.32 c 0,12.97 -1.48,25.59 -4.28,37.72 -3.63,30.59 -18.81,57.7 -41.05,76.81 -10.48,11.2 -22.48,20.96 -35.67,28.95 6.36,-2.3 12.49,-5.09 18.35,-8.33 38,-29.34 63.43,-74.18 66.75,-124.96 l 0,-161.64 c -0.95,-7.42 -3.65,-17.3 -7.54,-25.98 m -1505.371,0.19 c -3.926,8.8 -6.645,18.82 -7.536,26.23 l 0,160.38 c 3.094,51.14 28.618,96.31 66.829,125.81 5.851,3.23 11.972,6.01 18.332,8.31 -13.118,-7.95 -25.063,-17.65 -35.508,-28.77 -22.496,-19.25 -37.821,-46.65 -41.344,-77.56 -2.715,-11.96 -4.148,-24.4 -4.148,-37.16 l 0,-140.3 c 0,-4.34 1.234,-11.95 3.375,-20 l 0,-16.94"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3866"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3868"
+ d="m 1760.22,1501.92 0,161.64 c 0.24,-3.75 0.37,-7.53 0.37,-11.34 l 0,-145.13 c 0,-1.52 -0.13,-3.27 -0.37,-5.17 m -1520.447,0.44 c -0.207,1.74 -0.316,3.34 -0.316,4.75 l 0,145.11 c 0,3.53 0.109,7.04 0.316,10.52 l 0,-160.38 m 1453.697,286.16 c -5.86,3.24 -11.99,6.03 -18.35,8.33 -9.52,5.76 -19.66,10.61 -30.28,14.42 5.1,-0.54 10.12,-1.36 15.03,-2.44 12.01,-5.49 23.27,-12.33 33.6,-20.31 m -1386.868,0.03 c 10.32,7.97 21.55,14.78 33.531,20.27 4.922,1.08 9.937,1.9 15.039,2.45 -10.613,-3.81 -20.734,-8.65 -30.238,-14.41 -6.36,-2.3 -12.481,-5.08 -18.332,-8.31"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3854"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3856"
+ d="m 340.133,1808.82 c 9.929,4.55 20.379,8.18 31.211,10.79 l 18.383,0 c -11.961,-1.56 -23.52,-4.39 -34.555,-8.34 -5.102,-0.55 -10.117,-1.37 -15.039,-2.45 m 1319.737,0.01 c -4.91,1.08 -9.93,1.9 -15.03,2.44 -11.03,3.95 -22.59,6.78 -34.55,8.34 l 18.38,0 c 10.83,-2.61 21.27,-6.23 31.2,-10.78"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3842"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3844"
+ d="m 1628.67,1819.61 -18.38,0 c -7.16,0.93 -14.46,1.41 -21.86,1.41 l -1176.856,0 c -7.402,0 -14.699,-0.48 -21.847,-1.41 l -18.383,0 c 7.406,1.78 14.992,3.08 22.73,3.86 l 1211.856,0 c 7.74,-0.78 15.34,-2.08 22.74,-3.86"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3830"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3832"
+ d="m 300.039,1521.79 0,33.96 c 11.617,55.52 42.582,117.87 88.766,128.48 6.554,3.09 39.84,4.83 48.515,4.83 l 1124.77,0 c 8.92,0 42.97,-1.76 49.65,-4.88 45.82,-10.48 76.38,-71.09 88.19,-125.94 l 0,-32.89 c -6.77,58.55 -40.91,137.88 -92.85,147.51 -5.34,2.5 -42.25,3.91 -49.38,3.91 l -1116.091,0 c -6.937,0 -43.007,-1.4 -48.25,-3.88 -52.687,-9.78 -87.371,-92.24 -93.32,-151.1"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3818"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3820"
+ d="m 292.504,1481.38 0,20.41 c 1.41,6.2 2.355,12.74 2.75,19.48 0.66,10.78 2.269,22.47 4.785,34.48 l 0,-33.96 c -0.32,-3.18 -0.559,-6.29 -0.711,-9.31 -0.531,-11.23 -2.996,-21.84 -6.824,-31.1 m 1414.956,0.54 c -3.65,9.12 -5.99,19.53 -6.47,30.51 -0.19,4.16 -0.55,8.48 -1.06,12.92 l 0,32.89 c 2.78,-12.9 4.52,-25.49 5.17,-37.03 0.34,-6.23 1.15,-12.28 2.36,-18.06 l 0,-21.23"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3806"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3808"
+ d="m 284.973,1467.34 0,12.45 c 3.136,6.56 5.715,14 7.531,22 l 0,-20.41 c -2.121,-5.15 -4.668,-9.87 -7.531,-14.04 M 1715,1467.57 c -2.88,4.27 -5.43,9.1 -7.54,14.35 l 0,21.23 c 1.76,-8.36 4.34,-16.12 7.54,-22.95 l 0,-12.63"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3794"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3796"
+ d="m 277.438,1458.34 0,8.8 c 2.746,3.69 5.285,7.95 7.535,12.65 l 0,-12.45 c -2.321,-3.38 -4.848,-6.4 -7.535,-9 m 1445.102,0.13 c -2.7,2.63 -5.23,5.68 -7.54,9.1 l 0,12.63 c 2.24,-4.79 4.78,-9.12 7.54,-12.87 l 0,-8.86"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3782"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3784"
+ d="m 269.906,1452.47 0,6.45 c 2.633,2.27 5.16,5.04 7.532,8.22 l 0,-8.8 c -2.395,-2.31 -4.918,-4.29 -7.532,-5.87 m 1460.164,0.07 c -2.62,1.6 -5.14,3.6 -7.53,5.93 l 0,8.86 c 2.36,-3.22 4.89,-6.01 7.53,-8.31 l 0,-6.48"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3770"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3772"
+ d="m 1733.79,1450.56 c -1.26,0.57 -2.5,1.23 -3.72,1.98 l 0,6.48 c 1.22,-1.05 2.46,-2 3.72,-2.84 1.3,0 2.57,0.28 3.82,0.79 l 0,-5.87 c -1.25,-0.36 -2.53,-0.54 -3.82,-0.54 m -1467.485,0 c -1.328,0 -2.645,0.19 -3.93,0.57 l 0,5.89 c 1.281,-0.55 2.598,-0.84 3.93,-0.84 1.218,0.81 2.422,1.73 3.601,2.74 l 0,-6.45 c -1.183,-0.72 -2.383,-1.36 -3.601,-1.91"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3758"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3760"
+ d="m 1737.61,1451.1 0,5.87 c 2.66,1.1 5.19,3.28 7.53,6.16 l 0,-7.82 c -2.38,-2.01 -4.91,-3.47 -7.53,-4.21 m -1475.235,0.03 c -2.629,0.76 -5.152,2.25 -7.535,4.27 l 0,7.86 c 2.348,-2.91 4.879,-5.12 7.535,-6.24 l 0,-5.89"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3746"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3748"
+ d="m 1745.14,1455.31 0,7.82 c 2.82,3.47 5.36,7.95 7.54,12.81 l 0,-11.94 c -2.29,-3.41 -4.82,-6.4 -7.54,-8.69 m -1490.3,0.09 c -2.715,2.31 -5.246,5.31 -7.531,8.73 l 0,12 c 2.175,-4.88 4.718,-9.38 7.531,-12.87 l 0,-7.86"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3734"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3736"
+ d="m 1752.68,1464 0,11.94 c 3.89,8.68 6.59,18.56 7.54,25.98 l 0,-23.11 c -2.01,-5.23 -4.57,-10.37 -7.54,-14.81 m -1505.371,0.13 c -2.977,4.46 -5.532,9.61 -7.536,14.85 l 0,23.38 c 0.891,-7.41 3.61,-17.43 7.536,-26.23 l 0,-12 m -7.536,198.61 0,12.95 c 0,9.08 0.946,17.93 2.743,26.49 7.847,25.92 21.515,49.35 39.464,68.75 7.461,6.79 15.723,12.72 24.622,17.62 -38.211,-29.5 -63.735,-74.67 -66.829,-125.81 m 1520.447,0.82 c -3.32,50.78 -28.75,95.62 -66.75,124.96 8.94,-4.93 17.23,-10.9 24.72,-17.74 17.78,-19.26 31.34,-42.46 39.19,-68.14 1.86,-8.69 2.84,-17.71 2.84,-26.95 l 0,-12.13"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3722"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3724"
+ d="m 1760.22,1478.81 0,23.11 c 0.24,1.9 0.37,3.65 0.37,5.17 l 0,145.13 c 0,3.81 -0.13,7.59 -0.37,11.34 l 0,12.13 c 0,9.24 -0.98,18.26 -2.84,26.95 4.99,-16.32 7.67,-33.64 7.67,-51.57 l 0,-149.93 c 0,-6.16 -1.77,-14.34 -4.83,-22.33 m -1520.447,0.17 c -3.035,7.93 -4.789,16.05 -4.789,22.16 l 0,149.93 c 0,17.77 2.633,34.92 7.532,51.11 -1.797,-8.56 -2.743,-17.41 -2.743,-26.49 l 0,-12.95 c -0.207,-3.48 -0.316,-6.99 -0.316,-10.52 l 0,-145.11 c 0,-1.41 0.109,-3.01 0.316,-4.75 l 0,-23.38 m 1478.417,291.8 c -7.49,6.84 -15.78,12.81 -24.72,17.74 -10.33,7.98 -21.59,14.82 -33.6,20.31 5.83,-1.28 11.51,-2.94 17.03,-4.94 15.38,-8.93 29.3,-20.12 41.29,-33.11 m -1436.21,0.15 c 11.958,12.92 25.809,24.05 41.122,32.95 5.523,2 11.207,3.66 17.031,4.94 -11.981,-5.49 -23.211,-12.3 -33.531,-20.27 -8.899,-4.9 -17.161,-10.83 -24.622,-17.62"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3710"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3712"
+ d="m 323.102,1803.88 c 10.507,6.11 21.699,11.17 33.425,15.02 4.75,0.47 9.555,0.71 14.422,0.71 l 0.395,0 c -10.832,-2.61 -21.282,-6.24 -31.211,-10.79 -5.824,-1.28 -11.508,-2.94 -17.031,-4.94 m 1353.798,0.01 c -5.52,2 -11.2,3.66 -17.03,4.94 -9.93,4.55 -20.37,8.17 -31.2,10.78 l 0.47,0 c 4.83,0 9.61,-0.24 14.33,-0.7 11.73,-3.86 22.92,-8.91 33.43,-15.02"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3698"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3700"
+ d="m 356.527,1818.9 c 5.426,1.78 10.977,3.31 16.618,4.57 l 20.929,0 c -7.738,-0.78 -15.324,-2.08 -22.73,-3.86 l -0.395,0 c -4.867,0 -9.672,-0.24 -14.422,-0.71 m 1286.943,0.01 c -4.72,0.46 -9.5,0.7 -14.33,0.7 l -0.47,0 c -7.4,1.78 -15,3.08 -22.74,3.86 l 20.94,0 c 5.64,-1.26 11.17,-2.78 16.6,-4.56"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3686"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3688"
+ d="m 300.039,1483.55 0,38.24 c 5.949,58.86 40.633,141.32 93.32,151.1 5.243,2.48 41.313,3.88 48.25,3.88 l 1116.091,0 c 7.13,0 44.04,-1.41 49.38,-3.91 51.94,-9.63 86.08,-88.96 92.85,-147.51 l 0,-40.96 c -1.76,6.06 -2.83,12.54 -3.05,19.26 -2.07,57.51 -39.3,150.12 -94.46,157.89 -4.01,1.87 -43.76,2.93 -49.11,2.93 l -1107.408,0 c -5.203,0 -44.058,-1.04 -47.988,-2.9 -54.883,-7.74 -92.285,-100.36 -94.516,-157.89 -0.253,-7.04 -1.429,-13.82 -3.359,-20.13"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3674"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3676"
+ d="m 292.504,1466.79 0,14.59 c 3.828,9.26 6.293,19.87 6.824,31.1 0.152,3.02 0.391,6.13 0.711,9.31 l 0,-38.24 c -1.863,-6.09 -4.43,-11.74 -7.535,-16.76 m 1414.956,0.3 c -3.14,5.18 -5.71,11.01 -7.53,17.3 l 0,40.96 c 0.51,-4.44 0.87,-8.76 1.06,-12.92 0.48,-10.98 2.82,-21.39 6.47,-30.51 l 0,-14.83"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3662"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3664"
+ d="m 284.973,1456.95 0,10.39 c 2.863,4.17 5.41,8.89 7.531,14.04 l 0,-14.59 c -2.246,-3.64 -4.777,-6.94 -7.531,-9.84 M 1715,1457.11 c -2.77,2.94 -5.3,6.29 -7.54,9.98 l 0,14.83 c 2.11,-5.25 4.66,-10.08 7.54,-14.35 l 0,-10.46"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3650"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3652"
+ d="m 277.438,1450.42 0,7.92 c 2.687,2.6 5.214,5.62 7.535,9 l 0,-10.39 c -2.36,-2.49 -4.883,-4.68 -7.535,-6.53 m 1445.102,0.08 c -2.66,1.88 -5.18,4.09 -7.54,6.61 l 0,10.46 c 2.31,-3.42 4.84,-6.47 7.54,-9.1 l 0,-7.97"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3638"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3640"
+ d="m 269.906,1446.23 0,6.24 c 2.614,1.58 5.137,3.56 7.532,5.87 l 0,-7.92 c -2.415,-1.69 -4.934,-3.1 -7.532,-4.19 m 1460.164,0.05 c -2.6,1.1 -5.12,2.52 -7.53,4.22 l 0,7.97 c 2.39,-2.33 4.91,-4.33 7.53,-5.93 l 0,-6.26"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3626"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3628"
+ d="m 1733.79,1444.94 c -1.26,0.37 -2.5,0.82 -3.72,1.34 l 0,6.26 c 1.22,-0.75 2.46,-1.41 3.72,-1.98 1.29,0 2.57,0.18 3.82,0.54 l 0,-5.78 c -1.26,-0.25 -2.53,-0.38 -3.82,-0.38 m -1467.485,0 c -1.328,0 -2.641,0.13 -3.93,0.4 l 0,5.79 c 1.285,-0.38 2.602,-0.57 3.93,-0.57 1.218,0.55 2.418,1.19 3.601,1.91 l 0,-6.24 c -1.183,-0.5 -2.386,-0.93 -3.601,-1.29"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3614"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3616"
+ d="m 1737.61,1445.32 0,5.78 c 2.62,0.74 5.15,2.2 7.53,4.21 l 0,-7.01 c -2.4,-1.44 -4.93,-2.47 -7.53,-2.98 m -1475.235,0.02 c -2.605,0.53 -5.129,1.57 -7.535,3.02 l 0,7.04 c 2.383,-2.02 4.906,-3.51 7.535,-4.27 l 0,-5.79"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3602"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3604"
+ d="m 1745.14,1448.3 0,7.01 c 2.72,2.29 5.25,5.28 7.54,8.69 l 0,-9.56 c -2.34,-2.46 -4.87,-4.55 -7.54,-6.14 m -1490.3,0.06 c -2.664,1.6 -5.188,3.71 -7.531,6.17 l 0,9.6 c 2.285,-3.42 4.816,-6.42 7.531,-8.73 l 0,-7.04"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3590"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3592"
+ d="m 1752.68,1454.44 0,9.56 c 2.97,4.44 5.53,9.58 7.54,14.81 l 0,-14.29 c -2.21,-3.71 -4.75,-7.16 -7.54,-10.08 m -1505.371,0.09 c -2.793,2.94 -5.329,6.39 -7.536,10.11 l 0,14.34 c 2.004,-5.24 4.559,-10.39 7.536,-14.85 l 0,-9.6 m -4.793,247.65 c 5.664,26.95 19.793,50.85 39.464,68.75 -17.949,-19.4 -31.617,-42.83 -39.464,-68.75 m 1514.864,0.46 c -7.85,25.68 -21.41,48.88 -39.19,68.14 19.47,-17.78 33.48,-41.44 39.19,-68.14"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3578"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3580"
+ d="m 1760.22,1464.52 0,14.29 c 3.06,7.99 4.83,16.17 4.83,22.33 l 0,149.93 c 0,17.93 -2.68,35.25 -7.67,51.57 -5.71,26.7 -19.72,50.36 -39.19,68.14 -11.99,12.99 -25.91,24.18 -41.29,33.11 7.09,-2.56 13.91,-5.69 20.41,-9.34 37.44,-28.26 63.61,-70.71 70.44,-119.28 0,-0.25 0,-0.5 0,-0.75 l 0,-191.95 c -1.58,-6.09 -4.18,-12.39 -7.53,-18.05 m -1520.447,0.12 c -3.359,5.68 -5.953,11.98 -7.531,18.09 l 0,191.79 c 0,0.17 0,0.35 0,0.52 6.778,48.67 32.965,91.2 70.469,119.51 6.492,3.64 13.305,6.77 20.391,9.33 -15.313,-8.9 -29.164,-20.03 -41.122,-32.95 -19.671,-17.9 -33.8,-41.8 -39.464,-68.75 -4.899,-16.19 -7.532,-33.34 -7.532,-51.11 l 0,-149.93 c 0,-6.11 1.754,-14.23 4.789,-22.16 l 0,-14.34"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3566"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3568"
+ d="m 1767.75,1482.57 0,191.95 c 0,0.25 0,0.5 0,0.75 1.16,-8.28 1.77,-16.74 1.77,-25.34 l 0,-154.75 c 0,-3.89 -0.62,-8.2 -1.77,-12.61 m -1535.508,0.16 c -1.125,4.36 -1.734,8.61 -1.734,12.46 l 0,154.74 c 0,8.52 0.594,16.9 1.734,25.11 0,-0.17 0,-0.35 0,-0.52 l 0,-191.79 m 70.469,311.82 c 11.512,8.68 24.082,16.03 37.492,21.8 5.34,1.15 10.789,2.01 16.324,2.55 -11.726,-3.85 -22.918,-8.91 -33.425,-15.02 -7.086,-2.56 -13.899,-5.69 -20.391,-9.33 m 1394.599,0 c -6.5,3.65 -13.32,6.78 -20.41,9.34 -10.51,6.11 -21.7,11.16 -33.43,15.02 5.53,-0.54 10.97,-1.39 16.3,-2.54 13.43,-5.78 26.02,-13.13 37.54,-21.82"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3554"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3556"
+ d="m 340.203,1816.35 c 6.352,2.74 12.895,5.12 19.594,7.12 l 13.348,0 c -5.641,-1.26 -11.192,-2.79 -16.618,-4.57 -5.535,-0.54 -10.984,-1.4 -16.324,-2.55 m 1319.567,0.02 c -5.33,1.15 -10.77,2 -16.3,2.54 -5.43,1.78 -10.96,3.3 -16.6,4.56 l 13.35,0 c 6.69,-2 13.21,-4.37 19.55,-7.1"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3542"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3544"
+ d="m 300.039,1466.03 0,17.52 c 1.93,6.31 3.106,13.09 3.359,20.13 2.231,57.53 39.633,150.15 94.516,157.89 3.93,1.86 42.785,2.9 47.988,2.9 l 1107.408,0 c 5.35,0 45.1,-1.06 49.11,-2.93 55.16,-7.77 92.39,-100.38 94.46,-157.89 0.22,-6.72 1.29,-13.2 3.05,-19.26 l 0,-17.98 c -4.32,8.36 -6.93,18.1 -7.17,28.46 -1.37,55.99 -40.55,150.17 -95.01,155.35 -2.67,1.25 -45.27,1.95 -48.83,1.95 l -1098.729,0 c -3.468,0 -45.101,-0.69 -47.722,-1.93 -54.235,-5.16 -93.508,-99.35 -94.996,-155.35 -0.258,-10.52 -2.969,-20.41 -7.434,-28.86"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3530"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3532"
+ d="m 292.504,1454.96 0,11.83 c 3.105,5.02 5.672,10.67 7.535,16.76 l 0,-17.52 c -2.137,-4.05 -4.676,-7.76 -7.535,-11.07 m 1414.956,0.2 c -2.87,3.36 -5.41,7.14 -7.53,11.25 l 0,17.98 c 1.82,-6.29 4.39,-12.12 7.53,-17.3 l 0,-11.93"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3518"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3520"
+ d="m 284.973,1447.81 0,9.14 c 2.754,2.9 5.285,6.2 7.531,9.84 l 0,-11.83 c -2.313,-2.67 -4.836,-5.07 -7.531,-7.15 M 1715,1447.92 c -2.7,2.11 -5.23,4.53 -7.54,7.24 l 0,11.93 c 2.24,-3.69 4.77,-7.04 7.54,-9.98 l 0,-9.19"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3506"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3508"
+ d="m 277.438,1443.05 0,7.37 c 2.652,1.85 5.175,4.04 7.535,6.53 l 0,-9.14 c -2.387,-1.85 -4.907,-3.45 -7.535,-4.76 m 1445.102,0.06 c -2.63,1.33 -5.16,2.94 -7.54,4.81 l 0,9.19 c 2.36,-2.52 4.88,-4.73 7.54,-6.61 l 0,-7.39"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3494"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3496"
+ d="m 269.906,1440.13 0,6.1 c 2.598,1.09 5.117,2.5 7.532,4.19 l 0,-7.37 c -2.426,-1.22 -4.946,-2.2 -7.532,-2.92 m 1460.164,0.03 c -2.59,0.73 -5.11,1.72 -7.53,2.95 l 0,7.39 c 2.41,-1.7 4.93,-3.12 7.53,-4.22 l 0,-6.12"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3482"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3484"
+ d="m 1733.79,1439.31 c -1.25,0.23 -2.49,0.51 -3.72,0.85 l 0,6.12 c 1.22,-0.52 2.46,-0.97 3.72,-1.34 1.29,0 2.56,0.13 3.82,0.38 l 0,-5.73 c -1.26,-0.18 -2.53,-0.28 -3.82,-0.28 m -1467.485,0 c -1.325,0 -2.637,0.1 -3.93,0.29 l 0,5.74 c 1.289,-0.27 2.602,-0.4 3.93,-0.4 1.215,0.36 2.418,0.79 3.601,1.29 l 0,-6.1 c -1.187,-0.33 -2.386,-0.6 -3.601,-0.82"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3470"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3472"
+ d="m 1737.61,1439.59 0,5.73 c 2.6,0.51 5.13,1.54 7.53,2.98 l 0,-6.55 c -2.42,-1.05 -4.94,-1.79 -7.53,-2.16 m -1475.235,0.01 c -2.59,0.38 -5.109,1.13 -7.535,2.19 l 0,6.57 c 2.406,-1.45 4.93,-2.49 7.535,-3.02 l 0,-5.74"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3458"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3460"
+ d="m 1745.14,1441.75 0,6.55 c 2.67,1.59 5.2,3.68 7.54,6.14 l 0,-8.24 c -2.38,-1.81 -4.9,-3.31 -7.54,-4.45 m -1490.3,0.04 c -2.633,1.15 -5.152,2.67 -7.531,4.48 l 0,8.26 c 2.343,-2.46 4.867,-4.57 7.531,-6.17 l 0,-6.57"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3446"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3448"
+ d="m 1752.68,1446.2 0,8.24 c 2.79,2.92 5.33,6.37 7.54,10.08 l 0,-11.1 c -2.3,-2.72 -4.83,-5.16 -7.54,-7.22 m -1505.371,0.07 c -2.711,2.07 -5.239,4.51 -7.536,7.23 l 0,11.14 c 2.207,-3.72 4.743,-7.17 7.536,-10.11 l 0,-8.26"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3434"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3436"
+ d="m 1760.22,1453.42 0,11.1 c 3.35,5.66 5.95,11.96 7.53,18.05 l 0,-17.7 c -2.08,-4.12 -4.62,-8.01 -7.53,-11.45 m -1520.447,0.08 c -2.91,3.46 -5.453,7.35 -7.531,11.47 l 0,17.76 c 1.578,-6.11 4.172,-12.41 7.531,-18.09 l 0,-11.14 m -7.531,221.54 c 0.055,14.34 2.32,28.18 6.469,41.19 8.187,20.91 20.055,39.98 34.816,56.42 8.688,8.52 18.493,15.9 29.184,21.9 -37.504,-28.31 -63.691,-70.84 -70.469,-119.51 m 1535.508,0.23 c -6.83,48.57 -33,91.02 -70.44,119.28 10.71,-6.02 20.55,-13.43 29.25,-21.98 14.65,-16.34 26.45,-35.27 34.62,-56.03 4.19,-13.02 6.49,-26.89 6.57,-41.27"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3422"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3424"
+ d="m 1767.75,1464.87 0,17.7 c 1.15,4.41 1.77,8.72 1.77,12.61 l 0,154.75 c 0,8.6 -0.61,17.06 -1.77,25.34 -0.08,14.38 -2.38,28.25 -6.57,41.27 8.27,-21 12.8,-43.85 12.8,-67.75 l 0,-159.57 c 0,-7.92 -2.28,-16.54 -6.23,-24.35 m -1535.508,0.1 c -3.93,7.78 -6.207,16.37 -6.207,24.26 l 0,159.56 c 0,23.77 4.496,46.53 12.676,67.44 -4.149,-13.01 -6.414,-26.85 -6.469,-41.19 -1.14,-8.21 -1.734,-16.59 -1.734,-25.11 l 0,-154.74 c 0,-3.85 0.609,-8.1 1.734,-12.46 l 0,-17.76 m 1494.318,307.6 c -8.7,8.55 -18.54,15.96 -29.25,21.98 -11.52,8.69 -24.11,16.04 -37.54,21.82 6.36,-1.37 12.57,-3.15 18.6,-5.32 18.14,-10.09 34.43,-23.14 48.19,-38.48 m -1453.033,0.08 c 13.739,15.3 29.977,28.31 48.063,38.38 6.035,2.17 12.246,3.95 18.613,5.32 -13.41,-5.77 -25.98,-13.12 -37.492,-21.8 -10.691,-6 -20.496,-13.38 -29.184,-21.9"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3410"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3412"
+ d="m 321.59,1811.03 c 8.715,4.85 17.871,9.02 27.371,12.44 l 10.836,0 c -6.699,-2 -13.242,-4.38 -19.594,-7.12 -6.367,-1.37 -12.578,-3.15 -18.613,-5.32 m 1356.78,0.02 c -6.03,2.17 -12.24,3.95 -18.6,5.32 -6.34,2.73 -12.86,5.1 -19.55,7.1 l 10.83,0 c 9.49,-3.41 18.62,-7.57 27.32,-12.42"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3398"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3400"
+ d="m 300.039,1452.66 0,13.37 c 4.465,8.45 7.176,18.34 7.434,28.86 1.488,56 40.761,150.19 94.996,155.35 2.621,1.24 44.254,1.93 47.722,1.93 l 1098.729,0 c 3.56,0 46.16,-0.7 48.83,-1.95 54.46,-5.18 93.64,-99.36 95.01,-155.35 0.24,-10.36 2.85,-20.1 7.17,-28.46 l 0,-13.53 c -6.9,9.07 -11.13,20.64 -11.28,33.21 -0.69,54.46 -41.82,150.22 -95.56,152.81 -1.34,0.62 -46.78,0.98 -48.56,0.98 l -1090.046,0 c -1.734,0 -46.152,-0.35 -47.464,-0.97 -53.582,-2.58 -94.731,-98.34 -95.473,-152.81 -0.16,-12.68 -4.485,-24.34 -11.508,-33.44"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3386"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3388"
+ d="m 292.504,1444.76 0,10.2 c 2.859,3.31 5.398,7.02 7.535,11.07 l 0,-13.37 c -2.25,-2.92 -4.777,-5.57 -7.535,-7.9 m 1414.956,0.13 c -2.76,2.36 -5.29,5.05 -7.53,7.99 l 0,13.53 c 2.12,-4.11 4.66,-7.89 7.53,-11.25 l 0,-10.27"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3374"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3376"
+ d="m 284.973,1439.48 0,8.33 c 2.695,2.08 5.218,4.48 7.531,7.15 l 0,-10.2 c -2.352,-2 -4.875,-3.77 -7.531,-5.28 M 1715,1439.56 c -2.66,1.53 -5.18,3.31 -7.54,5.33 l 0,10.27 c 2.31,-2.71 4.84,-5.13 7.54,-7.24 l 0,-8.36"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3362"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3364"
+ d="m 277.438,1436.05 0,7 c 2.628,1.31 5.148,2.91 7.535,4.76 l 0,-8.33 c -2.407,-1.36 -4.926,-2.51 -7.535,-3.43 m 1445.102,0.05 c -2.62,0.92 -5.13,2.08 -7.54,3.46 l 0,8.36 c 2.38,-1.87 4.91,-3.48 7.54,-4.81 l 0,-7.01"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3350"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3352"
+ d="m 269.906,1434.13 0,6 c 2.586,0.72 5.106,1.7 7.532,2.92 l 0,-7 c -2.438,-0.85 -4.954,-1.5 -7.532,-1.92 m 1460.164,0.02 c -2.58,0.43 -5.1,1.08 -7.53,1.95 l 0,7.01 c 2.42,-1.23 4.94,-2.22 7.53,-2.95 l 0,-6.01"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3338"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3340"
+ d="m 1733.79,1433.69 c -1.25,0.1 -2.49,0.26 -3.72,0.46 l 0,6.01 c 1.23,-0.34 2.47,-0.62 3.72,-0.85 1.29,0 2.56,0.1 3.82,0.28 l 0,-5.7 c -1.26,-0.13 -2.53,-0.2 -3.82,-0.2 m -1467.485,0 c -1.325,0 -2.637,0.08 -3.93,0.21 l 0,5.7 c 1.293,-0.19 2.605,-0.29 3.93,-0.29 1.215,0.22 2.414,0.49 3.601,0.82 l 0,-6 c -1.187,-0.19 -2.386,-0.34 -3.601,-0.44"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3326"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3328"
+ d="m 1737.61,1433.89 0,5.7 c 2.59,0.37 5.11,1.11 7.53,2.16 l 0,-6.27 c -2.43,-0.78 -4.95,-1.32 -7.53,-1.59 m -1475.235,0.01 c -2.578,0.28 -5.098,0.83 -7.535,1.61 l 0,6.28 c 2.426,-1.06 4.945,-1.81 7.535,-2.19 l 0,-5.7"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3314"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3316"
+ d="m 1745.14,1435.48 0,6.27 c 2.64,1.14 5.16,2.64 7.54,4.45 l 0,-7.43 c -2.4,-1.35 -4.92,-2.46 -7.54,-3.29 m -1490.3,0.03 c -2.613,0.84 -5.129,1.95 -7.531,3.31 l 0,7.45 c 2.379,-1.81 4.898,-3.33 7.531,-4.48 l 0,-6.28"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3302"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3304"
+ d="m 1752.68,1438.77 0,7.43 c 2.71,2.06 5.24,4.5 7.54,7.22 l 0,-9.35 c -2.35,-2.03 -4.87,-3.81 -7.54,-5.3 m -1505.371,0.05 c -2.664,1.5 -5.188,3.28 -7.536,5.31 l 0,9.37 c 2.297,-2.72 4.825,-5.16 7.536,-7.23 l 0,-7.45"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3290"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3292"
+ d="m 1760.22,1444.07 0,9.35 c 2.91,3.44 5.45,7.33 7.53,11.45 l 0,-12.71 c -2.23,-2.98 -4.76,-5.7 -7.53,-8.09 m -1520.447,0.06 c -2.769,2.39 -5.3,5.12 -7.531,8.1 l 0,12.74 c 2.078,-4.12 4.621,-8.01 7.531,-11.47 l 0,-9.37 m -1.062,272.1 c 6.894,21.59 18.992,40.89 34.816,56.42 -14.761,-16.44 -26.629,-35.51 -34.816,-56.42 m 1522.469,0.31 c -8.17,20.76 -19.97,39.69 -34.62,56.03 15.7,-15.43 27.72,-34.6 34.62,-56.03"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3278"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3280"
+ d="m 1767.75,1452.16 0,12.71 c 3.95,7.81 6.23,16.43 6.23,24.35 l 0,159.57 c 0,23.9 -4.53,46.75 -12.8,67.75 -6.9,21.43 -18.92,40.6 -34.62,56.03 -13.76,15.34 -30.05,28.39 -48.19,38.48 7.89,-2.83 15.47,-6.33 22.67,-10.42 37.49,-27.67 64.49,-68.78 73.83,-116.16 0.28,-3.67 0.42,-7.38 0.42,-11.12 l 0,-207.34 c -1.83,-4.96 -4.39,-9.65 -7.54,-13.85 m -1535.508,0.07 c -3.152,4.2 -5.711,8.89 -7.531,13.85 l 0,207.27 c 0,3.7 0.137,7.38 0.41,11.03 9.317,47.39 36.301,88.51 73.789,116.21 7.203,4.09 14.785,7.59 22.68,10.44 -18.086,-10.07 -34.324,-23.08 -48.063,-38.38 -15.824,-15.53 -27.922,-34.83 -34.816,-56.42 -8.18,-20.91 -12.676,-43.67 -12.676,-67.44 l 0,-159.56 c 0,-7.89 2.277,-16.48 6.207,-24.26 l 0,-12.74"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3266"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3268"
+ d="m 1775.29,1466.01 0,207.34 c 0,3.74 -0.14,7.45 -0.42,11.12 2.35,-11.92 3.58,-24.23 3.58,-36.83 l 0,-164.38 c 0,-5.85 -1.12,-11.71 -3.16,-17.25 m -1550.579,0.07 c -2.035,5.52 -3.152,11.36 -3.152,17.19 l 0,164.37 c 0,12.56 1.226,24.85 3.562,36.74 -0.273,-3.65 -0.41,-7.33 -0.41,-11.03 l 0,-207.27 m 74.199,334.51 c 12.457,9.2 26.07,16.91 40.582,22.88 l 9.469,0 c -9.5,-3.42 -18.656,-7.59 -27.371,-12.44 -7.895,-2.85 -15.477,-6.35 -22.68,-10.44 m 1402.13,0.04 c -7.2,4.09 -14.78,7.59 -22.67,10.42 -8.7,4.85 -17.83,9.01 -27.32,12.42 l 9.47,0 c 14.49,-5.96 28.08,-13.66 40.52,-22.84"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3254"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3256"
+ d="m 300.039,1441.39 0,11.27 c 7.023,9.1 11.348,20.76 11.508,33.44 0.742,54.47 41.891,150.23 95.473,152.81 1.312,0.62 45.73,0.97 47.464,0.97 l 1090.046,0 c 1.78,0 47.22,-0.36 48.56,-0.98 53.74,-2.59 94.87,-98.35 95.56,-152.81 0.15,-12.57 4.38,-24.14 11.28,-33.21 l 0,-11.33 c -9.48,8.98 -15.39,21.68 -15.39,35.75 0,52.94 -43.09,150.28 -96.11,150.28 l -1176.856,0 c -52.933,0 -95.957,-97.34 -95.957,-150.28 0,-14.15 -5.988,-26.92 -15.578,-35.91"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3242"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3244"
+ d="m 292.504,1435.59 0,9.17 c 2.758,2.33 5.285,4.98 7.535,7.9 l 0,-11.27 c -2.312,-2.16 -4.836,-4.11 -7.535,-5.8 m 1414.956,0.09 c -2.7,1.71 -5.22,3.68 -7.53,5.87 l 0,11.33 c 2.24,-2.94 4.77,-5.63 7.53,-7.99 l 0,-9.21"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3230"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3232"
+ d="m 284.973,1431.72 0,7.76 c 2.656,1.51 5.179,3.28 7.531,5.28 l 0,-9.17 c -2.383,-1.5 -4.899,-2.79 -7.531,-3.87 M 1715,1431.78 c -2.64,1.08 -5.16,2.39 -7.54,3.9 l 0,9.21 c 2.36,-2.02 4.88,-3.8 7.54,-5.33 l 0,-7.78"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3218"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3220"
+ d="m 277.438,1429.33 0,6.72 c 2.609,0.92 5.128,2.07 7.535,3.43 l 0,-7.76 c -2.422,-0.99 -4.938,-1.79 -7.535,-2.39 m 1445.102,0.03 c -2.6,0.6 -5.12,1.42 -7.54,2.42 l 0,7.78 c 2.41,-1.38 4.92,-2.54 7.54,-3.46 l 0,-6.74"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3206"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3208"
+ d="m 269.906,1428.2 0,5.93 c 2.578,0.42 5.094,1.07 7.532,1.92 l 0,-6.72 c -2.446,-0.56 -4.961,-0.94 -7.532,-1.13 m 1460.164,0.01 c -2.57,0.19 -5.09,0.58 -7.53,1.15 l 0,6.74 c 2.43,-0.87 4.95,-1.52 7.53,-1.95 l 0,-5.94"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3194"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3196"
+ d="m 1733.79,1428.07 c -1.25,0 -2.49,0.05 -3.72,0.14 l 0,5.94 c 1.23,-0.2 2.47,-0.36 3.72,-0.46 1.29,0 2.56,0.07 3.82,0.2 l 0,-5.67 c -1.26,-0.1 -2.54,-0.15 -3.82,-0.15 m -1467.485,0 c -1.321,0 -2.633,0.05 -3.93,0.16 l 0,5.67 c 1.293,-0.13 2.605,-0.21 3.93,-0.21 1.215,0.1 2.414,0.25 3.601,0.44 l 0,-5.93 c -1.187,-0.09 -2.39,-0.13 -3.601,-0.13"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3182"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3184"
+ d="m 1737.61,1428.22 0,5.67 c 2.58,0.27 5.1,0.81 7.53,1.59 l 0,-6.09 c -2.44,-0.58 -4.96,-0.97 -7.53,-1.17 m -1475.235,0.01 c -2.574,0.2 -5.086,0.6 -7.535,1.19 l 0,6.09 c 2.437,-0.78 4.957,-1.33 7.535,-1.61 l 0,-5.67"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3170"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3172"
+ d="m 1745.14,1429.39 0,6.09 c 2.62,0.83 5.14,1.94 7.54,3.29 l 0,-6.93 c -2.42,-1.01 -4.94,-1.83 -7.54,-2.45 m -1490.3,0.03 c -2.594,0.62 -5.113,1.45 -7.531,2.46 l 0,6.94 c 2.402,-1.36 4.918,-2.47 7.531,-3.31 l 0,-6.09"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3158"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3160"
+ d="m 1752.68,1431.84 0,6.93 c 2.67,1.49 5.19,3.27 7.54,5.3 l 0,-8.28 c -2.38,-1.52 -4.9,-2.84 -7.54,-3.95 m -1505.371,0.04 c -2.637,1.11 -5.157,2.44 -7.536,3.96 l 0,8.29 c 2.348,-2.03 4.872,-3.81 7.536,-5.31 l 0,-6.94"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3146"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3148"
+ d="m 1760.22,1435.79 0,8.28 c 2.77,2.39 5.3,5.11 7.53,8.09 l 0,-10.43 c -2.31,-2.21 -4.83,-4.2 -7.53,-5.94 m -1520.447,0.05 c -2.703,1.74 -5.222,3.73 -7.531,5.95 l 0,10.44 c 2.231,-2.98 4.762,-5.71 7.531,-8.1 l 0,-8.29"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3134"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3136"
+ d="m 1767.75,1441.73 0,10.43 c 3.15,4.2 5.71,8.89 7.54,13.85 l 0,-15.06 c -2.14,-3.38 -4.67,-6.47 -7.54,-9.22 m -1535.508,0.06 c -2.863,2.75 -5.398,5.84 -7.531,9.21 l 0,15.08 c 1.82,-4.96 4.379,-9.65 7.531,-13.85 l 0,-10.44 m -7.121,242.59 c 1.32,17.59 5.77,34.33 12.797,49.66 6.883,13.61 15.312,26.29 25.066,37.84 10.364,11.34 22.485,21.06 35.926,28.71 -37.488,-27.7 -64.472,-68.82 -73.789,-116.21 m 1549.749,0.09 c -9.34,47.38 -36.34,88.49 -73.83,116.16 13.43,-7.63 25.54,-17.34 35.9,-28.67 9.78,-11.55 18.23,-24.26 25.13,-37.89 7.02,-15.31 11.47,-32.02 12.8,-49.6"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3122"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3124"
+ d="m 1775.29,1450.95 0,15.06 c 2.04,5.54 3.16,11.4 3.16,17.25 l 0,164.38 c 0,12.6 -1.23,24.91 -3.58,36.83 -1.33,17.58 -5.78,34.29 -12.8,49.6 12.47,-24.64 19.86,-52.29 20.75,-81.55 l 0,-178.25 c -0.52,-8.54 -3.21,-16.5 -7.53,-23.32 M 224.711,1451 c -4.32,6.81 -7.016,14.75 -7.535,23.27 l 0,178.25 c 0.894,29.25 8.273,56.89 20.742,81.52 -7.027,-15.33 -11.477,-32.07 -12.797,-49.66 -2.336,-11.89 -3.562,-24.18 -3.562,-36.74 l 0,-164.37 c 0,-5.83 1.117,-11.67 3.152,-17.19 l 0,-15.08 m 38.273,320.88 c 15.965,18.89 35.457,34.7 57.454,46.42 5.832,2.07 11.82,3.8 17.945,5.17 l 1.109,0 c -14.512,-5.97 -28.125,-13.68 -40.582,-22.88 -13.441,-7.65 -25.562,-17.37 -35.926,-28.71 m 1473.956,0.08 c -10.36,11.33 -22.47,21.04 -35.9,28.67 -12.44,9.18 -26.03,16.88 -40.52,22.84 l 1.16,0 c 6.07,-1.36 12.01,-3.07 17.79,-5.12 22,-11.71 41.5,-27.51 57.47,-46.39"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath3110"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3112"
+ d="m 1782.82,1474.27 0,178.25 c 0.06,-2 0.1,-4.01 0.1,-6.03 l 0,-169.19 c 0,-1.01 -0.04,-2.03 -0.1,-3.03 m -1565.644,0 c -0.063,1.01 -0.09,2.02 -0.09,3.03 l 0,169.19 c 0,2.02 0.027,4.03 0.09,6.03 l 0,-178.25 m 103.262,344.03 c 3.425,1.82 6.917,3.55 10.46,5.17 l 7.485,0 c -6.125,-1.37 -12.113,-3.1 -17.945,-5.17 m 1359.032,0.05 c -5.78,2.05 -11.72,3.76 -17.79,5.12 l 7.42,0 c 3.52,-1.61 6.97,-3.31 10.37,-5.12"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient3094"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop3096"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f8f9f9" />
+ <stop
+ id="stop3098"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e9e8e8" />
+ <stop
+ id="stop3100"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e9e8e8" />
+ <stop
+ id="stop3102"
+ offset="1"
+ style="stop-opacity:1;stop-color:#f5f5f4" />
+ </linearGradient>
+ <clipPath
+ id="clipPath3090"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3092"
+ d="m 1605.93,1823.47 -1211.856,0 c 5.758,0.58 11.59,0.89 17.5,0.89 l 1176.856,0 c 5.91,0 11.74,-0.31 17.5,-0.89"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient3074"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop3076"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f7f7f7" />
+ <stop
+ id="stop3078"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e5e4e3" />
+ <stop
+ id="stop3080"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e5e4e3" />
+ <stop
+ id="stop3082"
+ offset="1"
+ style="stop-opacity:1;stop-color:#f2f2f2" />
+ </linearGradient>
+ <clipPath
+ id="clipPath3070"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3072"
+ d="m 1626.87,1823.47 -20.94,0 c -5.76,0.58 -11.59,0.89 -17.5,0.89 l -1176.856,0 c -5.91,0 -11.742,-0.31 -17.5,-0.89 l -20.929,0 c 8.171,1.82 16.55,3.07 25.101,3.71 l 1203.514,0 c 8.55,-0.64 16.93,-1.89 25.11,-3.71"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient3054"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop3056"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f5f5f4" />
+ <stop
+ id="stop3058"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e3e3e1" />
+ <stop
+ id="stop3060"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e3e3e1" />
+ <stop
+ id="stop3062"
+ offset="1"
+ style="stop-opacity:1;stop-color:#eff0ef" />
+ </linearGradient>
+ <clipPath
+ id="clipPath3050"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3052"
+ d="m 1601.76,1827.18 -1203.514,0 c 4.399,0.34 8.848,0.5 13.328,0.5 l 1176.856,0 c 4.48,0 8.93,-0.16 13.33,-0.5"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient3034"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop3036"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f6f6f6" />
+ <stop
+ id="stop3038"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e2dfde" />
+ <stop
+ id="stop3040"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e2dfde" />
+ <stop
+ id="stop3042"
+ offset="1"
+ style="stop-opacity:1;stop-color:#eff0ef" />
+ </linearGradient>
+ <clipPath
+ id="clipPath3030"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3032"
+ d="m 1640.22,1823.47 -13.35,0 c -8.18,1.82 -16.56,3.07 -25.11,3.71 l 23.81,0 c 4.95,-1.03 9.85,-2.27 14.65,-3.71 m -1267.075,0 -13.348,0 c 4.801,1.44 9.691,2.68 14.644,3.71 l 23.805,0 c -8.551,-0.64 -16.93,-1.89 -25.101,-3.71"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient3014"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop3016"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f2f2f2" />
+ <stop
+ id="stop3018"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dfdedc" />
+ <stop
+ id="stop3020"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dfdedc" />
+ <stop
+ id="stop3022"
+ offset="1"
+ style="stop-opacity:1;stop-color:#ededed" />
+ </linearGradient>
+ <clipPath
+ id="clipPath3010"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path3012"
+ d="m 1625.57,1827.18 -23.81,0 c -4.4,0.34 -8.85,0.5 -13.33,0.5 l -1176.856,0 c -4.48,0 -8.929,-0.16 -13.328,-0.5 l -23.805,0 c 10.235,2.14 20.778,3.42 31.559,3.75 l 1188,0 c 10.79,-0.33 21.33,-1.61 31.57,-3.75"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient2994"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop2996"
+ offset="0"
+ style="stop-opacity:1;stop-color:#eeefef" />
+ <stop
+ id="stop2998"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dbdad8" />
+ <stop
+ id="stop3000"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dbdad8" />
+ <stop
+ id="stop3002"
+ offset="1"
+ style="stop-opacity:1;stop-color:#eaebe9" />
+ </linearGradient>
+ <clipPath
+ id="clipPath2990"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2992"
+ d="m 1594,1830.93 -1188,0 c 1.852,0.05 3.711,0.08 5.574,0.08 l 1176.856,0 c 1.86,0 3.72,-0.03 5.57,-0.08"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient2974"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop2976"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f3f3f3" />
+ <stop
+ id="stop2978"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dddbd9" />
+ <stop
+ id="stop2980"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dddbd9" />
+ <stop
+ id="stop2982"
+ offset="1"
+ style="stop-opacity:1;stop-color:#ededed" />
+ </linearGradient>
+ <clipPath
+ id="clipPath2970"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2972"
+ d="m 1651.05,1823.47 -10.83,0 c -4.8,1.44 -9.7,2.68 -14.65,3.71 l 2.35,0 c 4.6,0 9.16,-0.2 13.66,-0.59 3.2,-0.96 6.35,-2 9.47,-3.12 m -1291.253,0 -10.836,0 c 3.113,1.12 6.25,2.15 9.434,3.11 4.539,0.4 9.136,0.6 13.777,0.6 l 2.269,0 c -4.953,-1.03 -9.843,-2.27 -14.644,-3.71"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient2954"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop2956"
+ offset="0"
+ style="stop-opacity:1;stop-color:#eff0ef" />
+ <stop
+ id="stop2958"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dad9d8" />
+ <stop
+ id="stop2960"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dad9d8" />
+ <stop
+ id="stop2962"
+ offset="1"
+ style="stop-opacity:1;stop-color:#eaebe9" />
+ </linearGradient>
+ <clipPath
+ id="clipPath2950"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2952"
+ d="m 358.395,1826.58 c 5.761,1.72 11.66,3.18 17.644,4.35 l 29.961,0 c -10.781,-0.33 -21.324,-1.61 -31.559,-3.75 l -2.269,0 c -4.641,0 -9.238,-0.2 -13.777,-0.6 m 1283.185,0.01 c -4.5,0.39 -9.06,0.59 -13.66,0.59 l -2.35,0 c -10.24,2.14 -20.78,3.42 -31.57,3.75 l 29.97,0 c 5.98,-1.17 11.85,-2.62 17.61,-4.34"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient2934"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop2936"
+ offset="0"
+ style="stop-opacity:1;stop-color:#ececec" />
+ <stop
+ id="stop2938"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d7d5d5" />
+ <stop
+ id="stop2940"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d7d5d5" />
+ <stop
+ id="stop2942"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e7e8e6" />
+ </linearGradient>
+ <clipPath
+ id="clipPath2930"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2932"
+ d="m 1623.97,1830.93 -29.97,0 c -1.85,0.05 -3.71,0.08 -5.57,0.08 l -1176.856,0 c -1.863,0 -3.722,-0.03 -5.574,-0.08 l -29.961,0 c 11.508,2.24 23.383,3.41 35.535,3.41 l 1176.856,0 c 12.15,0 24.03,-1.17 35.54,-3.41"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient2914"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop2916"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f2f2f2" />
+ <stop
+ id="stop2918"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d8d7d5" />
+ <stop
+ id="stop2920"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d8d7d5" />
+ <stop
+ id="stop2922"
+ offset="1"
+ style="stop-opacity:1;stop-color:#eaebe9" />
+ </linearGradient>
+ <clipPath
+ id="clipPath2910"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2912"
+ d="m 1660.52,1823.47 -9.47,0 c -3.12,1.12 -6.27,2.16 -9.47,3.12 5.98,-0.53 11.87,-1.4 17.63,-2.59 0.43,-0.17 0.88,-0.35 1.31,-0.53 m -1311.559,0 -9.469,0 c 0.41,0.17 0.824,0.34 1.238,0.51 5.778,1.19 11.672,2.07 17.665,2.6 -3.184,-0.96 -6.321,-1.99 -9.434,-3.11"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient2894"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop2896"
+ offset="0"
+ style="stop-opacity:1;stop-color:#ededed" />
+ <stop
+ id="stop2898"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d6d4d3" />
+ <stop
+ id="stop2900"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d6d4d3" />
+ <stop
+ id="stop2902"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e8e8e7" />
+ </linearGradient>
+ <clipPath
+ id="clipPath2890"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2892"
+ d="m 340.73,1823.98 c 6.254,2.52 12.668,4.72 19.227,6.57 3.633,0.25 7.297,0.38 10.992,0.38 l 5.09,0 c -5.984,-1.17 -11.883,-2.63 -17.644,-4.35 -5.993,-0.53 -11.887,-1.41 -17.665,-2.6 m 1318.48,0.02 c -5.76,1.19 -11.65,2.06 -17.63,2.59 -5.76,1.72 -11.63,3.17 -17.61,4.34 l 5.17,0 c 3.66,0 7.29,-0.13 10.89,-0.38 6.54,-1.85 12.94,-4.03 19.18,-6.55"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient2874"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop2876"
+ offset="0"
+ style="stop-opacity:1;stop-color:#eaeae8" />
+ <stop
+ id="stop2878"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d1d1cf" />
+ <stop
+ id="stop2880"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d1d1cf" />
+ <stop
+ id="stop2882"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e4e4e3" />
+ </linearGradient>
+ <clipPath
+ id="clipPath2870"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2872"
+ d="m 359.957,1830.55 c 5.848,1.65 11.813,3.03 17.875,4.12 l 1244.338,0 c 6.06,-1.09 12.01,-2.47 17.86,-4.12 -3.6,0.25 -7.23,0.38 -10.89,0.38 l -5.17,0 c -11.51,2.24 -23.39,3.41 -35.54,3.41 l -1176.856,0 c -12.152,0 -24.027,-1.17 -35.535,-3.41 l -5.09,0 c -3.695,0 -7.359,-0.13 -10.992,-0.38"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient2854"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop2856"
+ offset="0"
+ style="stop-opacity:1;stop-color:#e5e5e4" />
+ <stop
+ id="stop2858"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#cdccc9" />
+ <stop
+ id="stop2860"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#cdccc9" />
+ <stop
+ id="stop2862"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e1dedd" />
+ </linearGradient>
+ <clipPath
+ id="clipPath2850"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2852"
+ d="m 1622.17,1834.67 -1244.338,0 c 10.953,1.97 22.23,3 33.742,3 l 1176.856,0 c 11.51,0 22.79,-1.03 33.74,-3"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient2834"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop2836"
+ offset="0"
+ style="stop-opacity:1;stop-color:#eff0ef" />
+ <stop
+ id="stop2838"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d3d3d2" />
+ <stop
+ id="stop2840"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d3d3d2" />
+ <stop
+ id="stop2842"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e8e8e7" />
+ </linearGradient>
+ <clipPath
+ id="clipPath2830"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2832"
+ d="m 1661.68,1823.47 -1.16,0 c -0.43,0.18 -0.88,0.36 -1.31,0.53 0.83,-0.17 1.65,-0.34 2.47,-0.53 m -1322.188,0 -1.109,0 c 0.781,0.17 1.562,0.34 2.347,0.51 -0.414,-0.17 -0.828,-0.34 -1.238,-0.51"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient2814"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop2816"
+ offset="0"
+ style="stop-opacity:1;stop-color:#ebeceb" />
+ <stop
+ id="stop2818"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d0cfce" />
+ <stop
+ id="stop2820"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d0cfce" />
+ <stop
+ id="stop2822"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e5e5e4" />
+ </linearGradient>
+ <clipPath
+ id="clipPath2810"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2812"
+ d="m 1669.1,1823.47 -7.42,0 c -0.82,0.19 -1.64,0.36 -2.47,0.53 -6.24,2.52 -12.64,4.7 -19.18,6.55 5.86,-0.4 11.64,-1.12 17.31,-2.16 3.99,-1.51 7.91,-3.16 11.76,-4.92 m -1330.717,0 -7.485,0 c 3.84,1.76 7.739,3.39 11.707,4.9 5.684,1.04 11.473,1.77 17.352,2.18 -6.559,-1.85 -12.973,-4.05 -19.227,-6.57 -0.785,-0.17 -1.566,-0.34 -2.347,-0.51"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient2794"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop2796"
+ offset="0"
+ style="stop-opacity:1;stop-color:#e7e8e6" />
+ <stop
+ id="stop2798"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#cbcbc8" />
+ <stop
+ id="stop2800"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#cbcbc8" />
+ <stop
+ id="stop2802"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e2e1df" />
+ </linearGradient>
+ <clipPath
+ id="clipPath2790"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2792"
+ d="m 342.605,1828.37 c 6.149,2.34 12.446,4.38 18.872,6.09 2.73,0.14 5.488,0.21 8.253,0.21 l 8.102,0 c -6.062,-1.09 -12.027,-2.47 -17.875,-4.12 -5.879,-0.41 -11.668,-1.14 -17.352,-2.18 m 1314.735,0.02 c -5.67,1.04 -11.45,1.76 -17.31,2.16 -5.85,1.65 -11.8,3.03 -17.86,4.12 l 8.18,0 c 2.74,0 5.46,-0.07 8.16,-0.21 6.41,-1.71 12.69,-3.73 18.83,-6.07"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient2774"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop2776"
+ offset="0"
+ style="stop-opacity:1;stop-color:#e2e2e0" />
+ <stop
+ id="stop2778"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#c7c6c4" />
+ <stop
+ id="stop2780"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#c7c6c4" />
+ <stop
+ id="stop2782"
+ offset="1"
+ style="stop-opacity:1;stop-color:#dddbd9" />
+ </linearGradient>
+ <clipPath
+ id="clipPath2770"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2772"
+ d="m 361.477,1834.46 c 6.011,1.6 12.136,2.93 18.363,3.95 l 1240.32,0 c 6.22,-1.02 12.34,-2.34 18.35,-3.95 -2.7,0.14 -5.42,0.21 -8.16,0.21 l -8.18,0 c -10.95,1.97 -22.23,3 -33.74,3 l -1176.856,0 c -11.512,0 -22.789,-1.03 -33.742,-3 l -8.102,0 c -2.765,0 -5.523,-0.07 -8.253,-0.21"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient2754"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop2756"
+ offset="0"
+ style="stop-opacity:1;stop-color:#dfdedc" />
+ <stop
+ id="stop2758"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#c2c1c0" />
+ <stop
+ id="stop2760"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#c2c1c0" />
+ <stop
+ id="stop2762"
+ offset="1"
+ style="stop-opacity:1;stop-color:#d8d7d5" />
+ </linearGradient>
+ <clipPath
+ id="clipPath2750"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2752"
+ d="m 1620.16,1838.41 -1240.32,0 c 10.328,1.7 20.933,2.59 31.734,2.59 l 1176.856,0 c 10.8,0 21.4,-0.89 31.73,-2.59"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2738"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2740"
+ d="m 270.363,869.172 c 0,0.019 0,0.039 0,0.058 l 0,-0.058"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2726"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2728"
+ d="m 1641.26,343.949 -1282.53,0 c -4.168,0 -8.234,0.43 -12.16,1.262 -15.765,8.5 -29.785,19.84 -41.371,33.32 -3.312,7.328 -5.16,15.457 -5.16,24 l 0,139.258 C 320.723,446.949 355.73,369.34 414.906,369.34 l 1170.184,0 c 59.08,0 94.12,80.832 114.84,178.332 l 0,-145.141 c 0,-8.551 -1.85,-16.679 -5.17,-24.011 -11.54,-13.469 -25.53,-24.801 -41.27,-33.29 -3.94,-0.839 -8.03,-1.281 -12.23,-1.281"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2714"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2716"
+ d="m 1640.05,339.66 -1280.097,0 c -0.652,0 -1.301,0.012 -1.945,0.02 -3.899,1.679 -7.723,3.531 -11.438,5.531 3.926,-0.832 7.992,-1.262 12.16,-1.262 l 1282.53,0 c 4.2,0 8.29,0.442 12.23,1.281 -3.72,-2.011 -7.54,-3.859 -11.45,-5.539 -0.66,-0.019 -1.32,-0.031 -1.99,-0.031 m 54.71,38.86 c 3.32,7.332 5.17,15.46 5.17,24.011 l 0,145.141 c 2.75,12.969 5.26,26.258 7.53,39.66 l 0,-180.32 c 0,-4.563 -0.45,-9.024 -1.32,-13.332 -3.47,-5.309 -7.26,-10.371 -11.38,-15.16 m -1389.561,0.011 c -4.101,4.778 -7.898,9.821 -11.355,15.11 -0.879,4.32 -1.34,8.789 -1.34,13.371 l 0,173.488 c 2.269,-13.102 4.777,-26.078 7.535,-38.711 l 0,-139.258 c 0,-8.543 1.848,-16.672 5.16,-24"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2702"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2704"
+ d="m 1630.71,335.371 -1261.374,0 c -3.852,1.277 -7.625,2.719 -11.328,4.309 0.644,-0.008 1.293,-0.02 1.945,-0.02 l 1280.097,0 c 0.67,0 1.33,0.012 1.99,0.031 -3.7,-1.601 -7.48,-3.043 -11.33,-4.32 m -1336.866,58.27 c -3.25,4.961 -6.207,10.14 -8.836,15.5 -0.024,0.781 -0.035,1.558 -0.035,2.339 l 0,219.079 c 2.175,-16.758 4.668,-33.539 7.531,-50.059 l 0,-173.488 c 0,-4.582 0.461,-9.051 1.34,-13.371 m 1412.296,0.039 c 0.87,4.308 1.32,8.769 1.32,13.332 l 0,180.32 c 2.87,16.898 5.36,33.996 7.54,51.047 l 0,-226.899 c 0,-0.75 -0.01,-1.5 -0.03,-2.242 -2.63,-5.379 -5.58,-10.578 -8.83,-15.558"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2690"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2692"
+ d="m 1614.87,331.082 -1229.702,0 c -5.395,1.129 -10.676,2.566 -15.832,4.289 l 1261.374,0 c -5.16,-1.723 -10.44,-3.16 -15.84,-4.289 M 285.008,409.141 c -2.942,5.988 -5.473,12.199 -7.57,18.609 l 0,274.059 c 1.941,-23.129 4.406,-47.161 7.535,-71.25 l 0,-219.079 c 0,-0.781 0.011,-1.558 0.035,-2.339 m 1429.962,0.097 c 0.02,0.742 0.03,1.492 0.03,2.242 l 0,226.899 c 3.13,24.48 5.59,48.832 7.54,72.109 l 0,-282.5 c -2.09,-6.457 -4.63,-12.718 -7.57,-18.75"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2678"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2680"
+ d="m 1585.09,327.988 -1170.184,0 c -10.187,0 -20.136,1.071 -29.738,3.094 l 1229.702,0 c -9.61,-2.023 -19.57,-3.094 -29.78,-3.094 M 277.438,427.75 c -4.59,14.051 -7.075,29.051 -7.075,44.602 l 0,396.82 c 0,-26.902 0.782,-92.352 7.075,-167.363 l 0,-274.059 m 1445.102,0.238 0,282.5 c 2.84,34.063 4.55,65.864 5.57,92.621 0.15,3.84 0.28,7.59 0.4,11.211 0.13,3.891 0.24,7.649 0.34,11.27 0.11,3.961 0.2,7.73 0.28,11.34 0.08,4.019 0.15,7.832 0.21,11.39 0.06,4.16 0.1,7.989 0.13,11.461 0.03,3.528 0.04,6.688 0.04,9.449 l 0,-9.421 0,-11.27 0,-10.937 0,-10.301 0,-8.871 0,-4.461 0,-341.617 c 0,-15.473 -2.45,-30.383 -6.97,-44.364"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2666"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2668"
+ d="m 346.57,345.211 c -18.472,3.91 -33.773,16.527 -41.371,33.32 11.586,-13.48 25.606,-24.82 41.371,-33.32 m 1306.92,0.019 c 15.74,8.489 29.73,19.821 41.27,33.29 -7.58,-16.758 -22.83,-29.372 -41.27,-33.29 m -68.4,24.11 -1170.184,0 c -59.176,0 -94.183,77.609 -114.867,172.449 l 0,33.973 c 12.254,-63.84 30.117,-122.231 55.738,-155.66 15.95,-22.743 42.161,-36.473 65.891,-36.473 l 1163.422,0 c 59.64,0 94.93,93.293 114.84,197.019 l 0,-32.976 c -20.72,-97.5 -55.76,-178.332 -114.84,-178.332"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2654"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2656"
+ d="m 358.008,339.68 c -4.449,0.129 -8.793,0.691 -12.985,1.64 -18.277,9.692 -34.304,23.09 -47.074,39.2 -1.797,4.171 -3.183,8.562 -4.105,13.121 3.457,-5.289 7.254,-10.332 11.355,-15.11 7.598,-16.793 22.899,-29.41 41.371,-33.32 3.715,-2 7.539,-3.852 11.438,-5.531 m 1284.032,0.011 c 3.91,1.68 7.73,3.528 11.45,5.539 18.44,3.918 33.69,16.532 41.27,33.29 4.12,4.789 7.91,9.851 11.38,15.16 -0.93,-4.571 -2.32,-8.981 -4.12,-13.168 -12.74,-16.102 -28.73,-29.492 -46.99,-39.184 -4.2,-0.949 -8.54,-1.508 -12.99,-1.637 M 300.039,541.789 c -2.758,12.633 -5.266,25.609 -7.535,38.711 l 0,39.539 c 2.238,-14.891 4.738,-29.719 7.535,-44.277 l 0,-33.973 m 1399.891,5.883 0,32.976 c 2.81,14.653 5.31,29.5 7.53,44.332 l 0,-37.648 c -2.27,-13.402 -4.78,-26.691 -7.53,-39.66"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2642"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2644"
+ d="m 1638.84,335.371 -8.13,0 c 3.85,1.277 7.63,2.719 11.33,4.32 4.45,0.129 8.79,0.688 12.99,1.637 -4.05,-2.137 -8.2,-4.098 -12.45,-5.867 -1.24,-0.063 -2.49,-0.09 -3.74,-0.09 m -1269.504,0 -8.16,0 c -1.25,0 -2.488,0.027 -3.723,0.09 -4.246,1.758 -8.391,3.719 -12.43,5.859 4.192,-0.949 8.536,-1.511 12.985,-1.64 3.703,-1.59 7.476,-3.032 11.328,-4.309 m 1332.684,45.141 c 1.8,4.187 3.19,8.597 4.12,13.168 3.25,4.98 6.2,10.179 8.83,15.558 -0.12,-3.949 -0.54,-7.816 -1.23,-11.59 -3.51,-5.988 -7.43,-11.726 -11.72,-17.136 M 297.949,380.52 c -4.281,5.402 -8.195,11.101 -11.703,17.07 -0.699,3.762 -1.117,7.621 -1.238,11.551 2.629,-5.36 5.586,-10.539 8.836,-15.5 0.922,-4.559 2.308,-8.95 4.105,-13.121 m -5.445,199.98 c -2.863,16.52 -5.356,33.301 -7.531,50.059 l 0,48.261 c 2.086,-19.32 4.578,-39.101 7.531,-58.781 l 0,-39.539 m 1414.956,6.832 0,37.648 c 3.01,20.059 5.5,40.079 7.54,59.469 l 0,-46.07 c -2.18,-17.051 -4.67,-34.149 -7.54,-51.047"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2630"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2632"
+ d="m 1630.6,331.082 -15.73,0 c 5.4,1.129 10.68,2.566 15.84,4.289 l 8.13,0 c 1.25,0 2.5,0.027 3.74,0.09 -3.91,-1.633 -7.91,-3.09 -11.98,-4.379 m -1245.432,0 -15.746,0 c -4.067,1.289 -8.063,2.746 -11.969,4.379 1.235,-0.063 2.473,-0.09 3.723,-0.09 l 8.16,0 c 5.156,-1.723 10.437,-3.16 15.832,-4.289 m -98.922,66.508 c -3.305,5.621 -6.25,11.492 -8.805,17.551 0,0.269 -0.003,0.539 -0.003,0.82 l 0,11.789 c 2.097,-6.41 4.628,-12.621 7.57,-18.609 0.121,-3.93 0.539,-7.789 1.238,-11.551 m 1427.494,0.058 c 0.69,3.774 1.11,7.641 1.23,11.59 2.94,6.032 5.48,12.293 7.57,18.75 l 0,-12.027 c 0,-0.242 -0.01,-0.473 -0.01,-0.711 -2.55,-6.078 -5.49,-11.961 -8.79,-17.602 M 284.973,630.559 c -3.129,24.089 -5.594,48.121 -7.535,71.25 l 0,71.41 c 1.484,-28.231 3.89,-60.641 7.535,-94.399 l 0,-48.261 m 1430.027,7.82 0,46.07 c 1.33,12.641 2.46,25 3.42,36.942 1.11,13.828 2.57,27.211 4.12,39.839 l 0,-50.742 c -1.95,-23.277 -4.41,-47.629 -7.54,-72.109"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2618"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2620"
+ d="m 1613.6,326.789 -1227.209,0 c -5.782,1.102 -11.446,2.531 -16.969,4.293 l 15.746,0 c 9.602,-2.023 19.551,-3.094 29.738,-3.094 l 1170.184,0 c 10.21,0 20.17,1.071 29.78,3.094 l 15.73,0 c -5.53,-1.762 -11.21,-3.203 -17,-4.293 M 277.441,415.141 c -3.117,7.398 -5.648,15.109 -7.535,23.058 l 0,434.789 c 0.149,0.453 0.301,0.692 0.457,0.692 2.473,-14.41 4.707,-43.032 6.082,-78.918 0.27,-6.852 0.602,-14.043 0.993,-21.543 l 0,-71.41 c -6.293,75.011 -7.075,140.461 -7.075,167.363 l 0,0.058 c 0,-0.019 0,-0.039 0,-0.058 l 0,-396.82 c 0,-15.551 2.485,-30.551 7.075,-44.602 l 0,-11.789 c 0,-0.281 0.003,-0.551 0.003,-0.82 m 1445.089,0.109 c 0,0.238 0.01,0.469 0.01,0.711 l 0,12.027 c 4.52,13.981 6.97,28.891 6.97,44.364 l 0,341.617 c 0.19,1.582 0.38,3.14 0.56,4.672 l 0,-380.121 c -1.88,-8.02 -4.41,-15.801 -7.54,-23.27 m 0.01,295.238 0,50.742 c 1.7,13.93 3.52,26.942 5.13,38.602 0.15,1.098 0.3,2.188 0.44,3.277 -1.02,-26.757 -2.73,-58.558 -5.57,-92.621"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2606"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2608"
+ d="m 1539.19,323.539 -1078.674,0 c -1.715,0 -48.977,0.25 -50.543,0.711 -8.032,0.219 -15.911,1.082 -23.582,2.539 l 1227.209,0 c -7.66,-1.449 -15.52,-2.309 -23.54,-2.527 -1.57,-0.473 -49.14,-0.723 -50.87,-0.723 M 269.906,438.199 c -2.605,10.973 -3.984,22.403 -3.984,34.153 l 0,338.359 c 0,2.309 1.746,55.598 3.984,62.277 l 0,-434.789 m 1460.164,0.321 0,380.121 c 0.17,1.429 0.33,2.839 0.49,4.218 0.39,3.481 0.75,6.821 1.07,10.012 0.35,3.559 0.66,6.93 0.93,10.109 0.32,3.668 0.57,7.071 0.77,10.192 0.26,3.859 0.43,7.289 0.53,10.269 0.07,2.18 0.11,4.11 0.11,5.789 l 0,-5.699 0,-9.609 0,-8.473 0,-6.25 0,-0.808 0,-366.039 c 0,-11.641 -1.35,-22.961 -3.9,-33.832"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2594"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2596"
+ d="m 1729.51,813.969 0,4.461 c 0.19,0.789 0.38,1.582 0.56,2.359 l 0,-2.148 c -0.18,-1.532 -0.37,-3.09 -0.56,-4.672"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2582"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2584"
+ d="m 1730.07,818.641 0,2.148 c 0.17,0.691 0.33,1.383 0.49,2.07 -0.16,-1.379 -0.32,-2.789 -0.49,-4.218"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2570"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2572"
+ d="m 1585.09,383.629 -1163.422,0 c -23.73,0 -49.941,13.73 -65.891,36.473 -25.621,33.429 -43.484,91.82 -55.738,155.66 l 0,36.699 c 12.742,-75.371 32.477,-147.242 61.652,-181.723 14.352,-20.468 45.379,-32.816 66.735,-32.816 l 1156.664,0 c 60.33,0 95.99,108.226 114.84,217.758 l 0,-35.032 c -19.91,-103.726 -55.2,-197.019 -114.84,-197.019"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2558"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2560"
+ d="m 345.023,341.32 c -21.203,4.809 -38.652,19.641 -47.074,39.2 12.77,-16.11 28.797,-29.508 47.074,-39.2 m 1310.007,0.008 c 18.26,9.692 34.25,23.082 46.99,39.184 -8.41,-19.543 -25.82,-34.352 -46.99,-39.184 M 300.039,575.762 c -2.797,14.558 -5.297,29.386 -7.535,44.277 l 0,43.18 c 2.18,-16.84 4.684,-33.891 7.535,-50.758 l 0,-36.699 m 1399.891,4.886 0,35.032 c 2.9,16.851 5.4,33.742 7.53,50.261 l 0,-40.961 c -2.22,-14.832 -4.72,-29.679 -7.53,-44.332"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2546"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2548"
+ d="m 357.453,335.461 c -4.863,0.23 -9.617,0.93 -14.207,2.039 -20.926,10.969 -39.012,26.691 -52.82,45.719 -1.848,4.59 -3.258,9.402 -4.18,14.371 3.508,-5.969 7.422,-11.668 11.703,-17.07 8.422,-19.559 25.871,-34.391 47.074,-39.2 4.039,-2.14 8.184,-4.101 12.43,-5.859 m 1285.127,0 c 4.25,1.769 8.4,3.73 12.45,5.867 21.17,4.832 38.58,19.641 46.99,39.184 4.29,5.41 8.21,11.148 11.72,17.136 -0.93,-5 -2.34,-9.828 -4.19,-14.437 -13.78,-19.02 -31.84,-34.742 -52.76,-45.711 -4.59,-1.109 -9.34,-1.809 -14.21,-2.039 M 292.504,620.039 c -2.953,19.68 -5.445,39.461 -7.531,58.781 l 0,55.282 c 1.886,-22.43 4.367,-46.43 7.531,-70.883 l 0,-43.18 m 1414.956,4.941 0,40.961 c 3.19,24.637 5.54,48.481 7.18,70.239 0.11,1.468 0.23,2.941 0.36,4.41 l 0,-56.141 c -2.04,-19.39 -4.53,-39.41 -7.54,-59.469"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2534"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2536"
+ d="m 1637.63,331.082 -7.03,0 c 4.07,1.289 8.07,2.746 11.98,4.379 4.87,0.23 9.62,0.93 14.21,2.039 -4.37,-2.289 -8.87,-4.371 -13.47,-6.23 -1.88,-0.129 -3.78,-0.188 -5.69,-0.188 m -1268.208,0 -7.024,0 c -1.914,0 -3.82,0.059 -5.703,0.188 -4.593,1.859 -9.086,3.941 -13.449,6.23 4.59,-1.109 9.344,-1.809 14.207,-2.039 3.906,-1.633 7.902,-3.09 11.969,-4.379 m 1340.128,52.129 c 1.85,4.609 3.26,9.437 4.19,14.437 3.3,5.641 6.24,11.524 8.79,17.602 -0.03,-4.301 -0.39,-8.539 -1.05,-12.672 -3.5,-6.769 -7.49,-13.238 -11.93,-19.367 m -1419.124,0.008 c -4.434,6.109 -8.422,12.551 -11.922,19.293 -0.66,4.117 -1.02,8.34 -1.063,12.629 2.555,-6.059 5.5,-11.93 8.805,-17.551 0.922,-4.969 2.332,-9.781 4.18,-14.371 m -5.453,295.601 c -3.645,33.758 -6.051,66.168 -7.535,94.399 l 0,71.519 c 1.574,-12.226 2.746,-26.66 3.304,-42.527 0.731,-19.563 2.102,-42.82 4.231,-68.109 l 0,-55.282 m 1430.027,5.629 0,56.141 c 1.55,17.359 4.42,33.769 7.54,48.351 l 0,-27.711 c -1.55,-12.628 -3.01,-26.011 -4.12,-39.839 -0.96,-11.942 -2.09,-24.301 -3.42,-36.942"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2522"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2524"
+ d="m 1630.64,326.789 -17.04,0 c 5.79,1.09 11.47,2.531 17,4.293 l 7.03,0 c 1.91,0 3.81,0.059 5.69,0.188 -4.14,-1.68 -8.37,-3.168 -12.68,-4.481 m -1244.249,0 -17.032,0 c -4.308,1.313 -8.527,2.801 -12.664,4.481 1.883,-0.129 3.789,-0.188 5.703,-0.188 l 7.024,0 c 5.523,-1.762 11.187,-3.191 16.969,-4.293 m -107.887,75.723 c -3.316,6.398 -6.199,13.047 -8.598,19.929 l 0,15.758 c 1.887,-7.949 4.418,-15.66 7.535,-23.058 0.043,-4.289 0.403,-8.512 1.063,-12.629 m 1442.976,0.066 c 0.66,4.133 1.02,8.371 1.05,12.672 3.13,7.469 5.66,15.25 7.54,23.27 l 0,-15.942 c -2.39,-6.906 -5.27,-13.59 -8.59,-20 m 1.06,358.652 0,27.711 c 1.75,8.2 3.59,15.829 5.31,22.719 0.22,0.899 0.44,1.781 0.66,2.66 -0.12,-3.621 -0.25,-7.371 -0.4,-11.211 -0.14,-1.089 -0.29,-2.179 -0.44,-3.277 -1.61,-11.66 -3.43,-24.672 -5.13,-38.602 M 277.438,773.219 c -0.391,7.5 -0.723,14.691 -0.993,21.543 -1.375,35.886 -3.609,64.508 -6.082,78.918 -0.156,0 -0.308,-0.239 -0.457,-0.692 l 0,4.981 c 0.153,0.101 0.305,0.16 0.457,0.16 2.699,-7.09 5.18,-18.649 7.075,-33.391 l 0,-71.519"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2510"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2512"
+ d="m 1612.54,322.5 -1225.142,0 c -6.14,1.059 -12.171,2.5 -18.039,4.289 l 17.032,0 c 7.671,-1.457 15.55,-2.32 23.582,-2.539 1.566,-0.461 48.828,-0.711 50.543,-0.711 l 1078.674,0 c 1.73,0 49.3,0.25 50.87,0.723 8.02,0.218 15.88,1.078 23.54,2.527 l 17.04,0 c -5.89,-1.789 -11.93,-3.23 -18.1,-4.289 M 269.906,422.441 c -3.715,10.649 -6.277,21.829 -7.531,33.399 l 0,374.941 c 1.379,17.5 4.215,44.84 7.531,47.188 l 0,-4.981 c -2.238,-6.679 -3.984,-59.968 -3.984,-62.277 l 0,-338.359 c 0,-11.75 1.379,-23.18 3.984,-34.153 l 0,-15.758 m 1460.164,0.137 0,15.942 c 2.55,10.871 3.9,22.191 3.9,33.832 l 0,366.039 c 0.12,0.621 0.24,1.218 0.36,1.82 0.63,3.148 1.19,6.09 1.66,8.809 0.58,3.281 1.05,6.25 1.42,8.878 0.07,0.524 0.13,1.024 0.2,1.5 l 0,-402.867 c -1.22,-11.769 -3.79,-23.133 -7.54,-33.953"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2498"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2500"
+ d="m 1543.78,319.102 -1087.827,0 c -3.426,0 -47.781,0.488 -50.914,1.41 -5.98,0.316 -11.863,0.988 -17.641,1.988 l 1225.142,0 c -5.73,-0.988 -11.57,-1.648 -17.5,-1.969 -3.16,-0.929 -47.8,-1.429 -51.26,-1.429 M 262.375,455.84 c -0.59,5.422 -0.895,10.941 -0.895,16.512 l 0,344.207 c 0,1.402 0.325,6.972 0.895,14.222 l 0,-374.941 m 1475.235,0.691 0,402.867 c 0.38,2.934 0.62,5.411 0.74,7.422 0.05,0.899 0.07,1.7 0.07,2.41 l 0,-2.351 0,-7.828 0,-5.742 0,-1.309 0,-379.648 c 0,-5.34 -0.27,-10.622 -0.81,-15.821"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2486"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2488"
+ d="m 1733.97,838.391 0,0.808 c 0.12,0.34 0.24,0.68 0.36,1.012 -0.12,-0.602 -0.24,-1.199 -0.36,-1.82"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2474"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2476"
+ d="m 1729.51,818.43 0,8.871 c 0.19,0.5 0.38,0.988 0.56,1.469 l 0,-7.981 c -0.18,-0.777 -0.37,-1.57 -0.56,-2.359"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2462"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2464"
+ d="m 1730.07,820.789 0,7.981 c 0.54,1.402 1.06,2.769 1.56,4.101 -0.32,-3.191 -0.68,-6.531 -1.07,-10.012 -0.16,-0.687 -0.32,-1.379 -0.49,-2.07"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2450"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2452"
+ d="m 1585.09,397.922 -1156.664,0 c -21.356,0 -52.383,12.348 -66.735,32.816 -29.175,34.481 -48.91,106.352 -61.652,181.723 l 0,39.59 c 12.93,-86.852 34.645,-175.86 67.563,-210.672 12.761,-18.188 48.597,-29.18 67.582,-29.18 l 1149.906,0 c 61.25,0 97.42,126.653 114.84,240.981 l 0,-37.5 C 1681.08,506.148 1645.42,397.922 1585.09,397.922"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2438"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2440"
+ d="m 300.039,612.461 c -2.851,16.867 -5.355,33.918 -7.535,50.758 l 0,47.511 c 2.07,-19 4.57,-38.781 7.535,-58.679 l 0,-39.59 m 1399.891,3.219 0,37.5 c 3.09,20.281 5.59,40.172 7.53,58.91 l 0,-46.149 c -2.13,-16.519 -4.63,-33.41 -7.53,-50.261"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2426"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2428"
+ d="m 343.246,337.5 c -10.391,2.512 -19.961,7.16 -28.211,13.461 -2.336,1.891 -4.621,3.859 -6.844,5.879 -7.636,7.39 -13.738,16.371 -17.765,26.379 13.808,-19.028 31.894,-34.75 52.82,-45.719 m 1313.544,0 c 20.92,10.969 38.98,26.691 52.76,45.711 -4.1,-10.191 -10.34,-19.301 -18.17,-26.77 -1.95,-1.761 -3.95,-3.48 -5.99,-5.152 -8.33,-6.449 -18.04,-11.219 -28.6,-13.789 M 292.504,663.219 c -3.164,24.453 -5.645,48.453 -7.531,70.883 l 0,77.539 c 0.023,-0.661 0.047,-1.321 0.07,-1.981 0.918,-26.23 3.328,-61.012 7.461,-98.93 l 0,-47.511 m 1414.956,2.722 0,46.149 c 1.42,13.672 2.55,26.742 3.39,38.871 0.71,10.238 2.2,20.098 4.15,29.367 l 0,-39.738 c -0.13,-1.469 -0.25,-2.942 -0.36,-4.41 -1.64,-21.758 -3.99,-45.602 -7.18,-70.239"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2414"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2416"
+ d="m 1643.32,331.27 c 4.6,1.859 9.1,3.941 13.47,6.23 10.56,2.57 20.27,7.34 28.6,13.789 -8.21,-6.711 -17.11,-12.598 -26.57,-17.527 -5.01,-1.301 -10.19,-2.141 -15.5,-2.492 m -1286.625,0 c -5.312,0.351 -10.488,1.191 -15.492,2.48 -9.305,4.859 -18.066,10.629 -26.168,17.211 8.25,-6.301 17.82,-10.949 28.211,-13.461 4.363,-2.289 8.856,-4.371 13.449,-6.23 m 1334.685,25.171 c 7.83,7.469 14.07,16.579 18.17,26.77 4.44,6.129 8.43,12.598 11.93,19.367 -0.87,-5.437 -2.25,-10.707 -4.1,-15.75 -7.35,-11.219 -16.1,-21.43 -26,-30.387 M 308.191,356.84 c -9.726,8.871 -18.339,18.941 -25.593,29.988 -1.844,5.031 -3.227,10.274 -4.094,15.684 3.5,-6.742 7.488,-13.184 11.922,-19.293 4.027,-10.008 10.129,-18.989 17.765,-26.379 m -23.218,377.262 c -2.129,25.289 -3.5,48.546 -4.231,68.109 -0.558,15.867 -1.73,30.301 -3.304,42.527 l 0,20.633 c 3.874,-13.551 6.71,-32.223 7.535,-53.73 l 0,-77.539 M 1715,740.59 l 0,39.738 c 2.11,10.07 4.76,19.453 7.54,27.883 l 0,-19.27 c -3.12,-14.582 -5.99,-30.992 -7.54,-48.351"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2402"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2404"
+ d="m 1636.41,326.789 -5.77,0 c 4.31,1.313 8.54,2.801 12.68,4.481 5.31,0.351 10.49,1.191 15.5,2.492 -4.71,-2.461 -9.54,-4.672 -14.51,-6.641 -2.6,-0.223 -5.24,-0.332 -7.9,-0.332 m -1267.051,0 -5.742,0 c -2.668,0 -5.32,0.109 -7.933,0.332 -4.954,1.969 -9.786,4.18 -14.481,6.629 5.004,-1.289 10.18,-2.129 15.492,-2.48 4.137,-1.68 8.356,-3.168 12.664,-4.481 m 1348.021,60.039 c 1.85,5.043 3.23,10.313 4.1,15.75 3.32,6.41 6.2,13.094 8.59,20 l 0,-2.148 c 0,-3.969 -0.25,-7.891 -0.73,-11.739 -3.41,-7.632 -7.42,-14.941 -11.96,-21.863 m -1434.782,0 c -4.536,6.91 -8.536,14.192 -11.95,21.801 -0.492,3.871 -0.742,7.812 -0.742,11.801 l 0,2.011 c 2.399,-6.882 5.282,-13.531 8.598,-19.929 0.867,-5.41 2.25,-10.653 4.094,-15.684 m 1439.942,402.113 0,19.27 c 1.82,5.527 3.69,10.66 5.5,15.289 0.27,0.699 0.54,1.398 0.81,2.09 -0.1,-3.621 -0.21,-7.379 -0.34,-11.27 -0.22,-0.879 -0.44,-1.761 -0.66,-2.66 -1.72,-6.89 -3.56,-14.519 -5.31,-22.719 M 277.438,844.738 c -1.895,14.742 -4.376,26.301 -7.075,33.391 -0.152,0 -0.304,-0.059 -0.457,-0.16 l 0,4.543 c 0.153,0.047 0.305,0.07 0.457,0.07 2.559,-3.98 4.973,-9.844 7.075,-17.211 l 0,-20.633"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2390"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2392"
+ d="m 1630.88,322.5 -18.34,0 c 6.17,1.059 12.21,2.5 18.1,4.289 l 5.77,0 c 2.66,0 5.3,0.109 7.9,0.332 -4.38,-1.742 -8.86,-3.281 -13.43,-4.621 m -1243.482,0 -18.308,0 c -4.559,1.34 -9.031,2.879 -13.406,4.621 2.613,-0.223 5.265,-0.332 7.933,-0.332 l 5.742,0 c 5.868,-1.789 11.899,-3.23 18.039,-4.289 m -116.75,86.129 c -3.343,7.453 -6.121,15.211 -8.273,23.223 l 0,23.988 c 1.254,-11.57 3.816,-22.75 7.531,-33.399 l 0,-2.011 c 0,-3.989 0.25,-7.93 0.742,-11.801 m 1458.692,0.062 c 0.48,3.848 0.73,7.77 0.73,11.739 l 0,2.148 c 3.75,10.82 6.32,22.184 7.54,33.953 l 0,-24.519 c -2.15,-8.051 -4.93,-15.84 -8.27,-23.321 m -1466.965,422.09 0,32.16 c 2.109,10.321 4.711,18.739 7.531,19.571 l 0,-4.543 c -3.316,-2.348 -6.152,-29.688 -7.531,-47.188"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2378"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2380"
+ d="m 1611.82,318.211 -1223.761,0 c -6.461,1.027 -12.793,2.469 -18.969,4.289 l 18.308,0 c 5.778,-1 11.661,-1.672 17.641,-1.988 3.133,-0.922 47.488,-1.41 50.914,-1.41 l 1087.827,0 c 3.46,0 48.1,0.5 51.26,1.429 5.93,0.321 11.77,0.981 17.5,1.969 l 18.34,0 c -6.2,-1.82 -12.56,-3.262 -19.06,-4.289 M 262.375,431.852 c -3.477,12.918 -5.332,26.5 -5.332,40.5 l 0,350.07 c 0,4.367 2.094,24.687 5.332,40.519 l 0,-32.16 c -0.57,-7.25 -0.895,-12.82 -0.895,-14.222 l 0,-344.207 c 0,-5.571 0.305,-11.09 0.895,-16.512 l 0,-23.988 m 1475.235,0.16 0,24.519 c 0.54,5.199 0.81,10.481 0.81,15.821 l 0,379.648 c 0.35,1.059 0.68,2.07 0.99,3.039 0.91,2.891 1.64,5.371 2.19,7.449 0.86,3.262 1.28,5.524 1.28,6.742 l 0,-5.41 0,-2.621 0,-388.847 c 0,-13.942 -1.83,-27.473 -5.27,-40.34"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2366"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2368"
+ d="m 1548.37,314.648 -1096.975,0 c -5.141,0 -46.594,0.731 -51.293,2.114 -4.059,0.328 -8.075,0.808 -12.043,1.449 l 1223.761,0 c -3.89,-0.621 -7.83,-1.09 -11.81,-1.422 -4.73,-1.391 -46.45,-2.141 -51.64,-2.141"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2354"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2356"
+ d="m 1738.42,852 0,1.309 c 0.34,0.589 0.67,1.171 0.99,1.73 -0.31,-0.969 -0.64,-1.98 -0.99,-3.039"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2342"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2344"
+ d="m 1733.97,839.199 0,6.25 c 0.7,1.242 1.38,2.43 2.02,3.571 -0.47,-2.719 -1.03,-5.661 -1.66,-8.809 -0.12,-0.332 -0.24,-0.672 -0.36,-1.012"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2330"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2332"
+ d="m 1729.51,827.301 0,10.301 c 0.19,0.328 0.38,0.668 0.56,0.988 l 0,-9.82 c -0.18,-0.481 -0.37,-0.969 -0.56,-1.469"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2318"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2320"
+ d="m 1730.07,828.77 0,9.82 c 0.86,1.519 1.7,2.98 2.49,4.39 -0.27,-3.179 -0.58,-6.55 -0.93,-10.109 -0.5,-1.332 -1.02,-2.699 -1.56,-4.101"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2306"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2308"
+ d="m 1585.09,412.199 -1149.906,0 c -18.985,0 -54.821,10.992 -67.582,29.18 -32.918,34.812 -54.633,123.82 -67.563,210.672 l 0,42.711 c 12.633,-97.102 36.523,-208.332 73.477,-242.742 11.164,-15.918 51.816,-25.532 68.425,-25.532 l 1143.149,0 c 62.58,0 99.48,150.371 114.84,267.473 l 0,-40.781 C 1682.51,538.852 1646.34,412.199 1585.09,412.199"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2294"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2296"
+ d="m 300.039,652.051 c -2.965,19.898 -5.465,39.679 -7.535,58.679 l 0,54.43 c 1.793,-21.512 4.293,-45.488 7.535,-70.398 l 0,-42.711 m 1399.891,1.129 0,40.781 c 3.45,26.301 5.81,50.918 7.14,71.777 0.1,1.653 0.24,3.293 0.39,4.922 l 0,-58.57 c -1.94,-18.738 -4.44,-38.629 -7.53,-58.91"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2282"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2284"
+ d="m 315.035,350.961 c -2.394,1.82 -4.68,3.789 -6.844,5.879 2.223,-2.02 4.508,-3.988 6.844,-5.879 m 1370.355,0.328 c 2.04,1.672 4.04,3.391 5.99,5.152 -1.91,-1.82 -3.9,-3.543 -5.99,-5.152 M 292.504,710.73 c -4.133,37.918 -6.543,72.7 -7.461,98.93 -0.023,0.66 -0.047,1.32 -0.07,1.981 l 0,42.07 c 2.398,-10.66 3.976,-23.082 4.367,-36.609 0.469,-14.422 1.515,-32.133 3.164,-51.942 l 0,-54.43 m 1414.956,1.36 0,58.57 c 1.23,12.559 4.02,24.352 7.54,34.891 l 0,-25.223 c -1.95,-9.269 -3.44,-19.129 -4.15,-29.367 -0.84,-12.129 -1.97,-25.199 -3.39,-38.871"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2270"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2272"
+ d="m 341.203,333.75 c -10.058,2.602 -19.406,6.988 -27.668,12.82 -5.347,4.239 -10.422,8.809 -15.187,13.692 -6.766,7.758 -12.145,16.738 -15.75,26.566 7.254,-11.047 15.867,-21.117 25.593,-29.988 2.164,-2.09 4.45,-4.059 6.844,-5.879 8.102,-6.582 16.863,-12.352 26.168,-17.211 m 1317.617,0.012 c 9.46,4.929 18.36,10.816 26.57,17.527 2.09,1.609 4.08,3.332 5.99,5.152 9.9,8.957 18.65,19.168 26,30.387 -3.64,-9.93 -9.09,-18.996 -15.95,-26.797 -4.64,-4.742 -9.57,-9.179 -14.76,-13.32 -8.31,-5.902 -17.72,-10.34 -27.85,-12.949 m 56.18,446.566 0,25.223 c 2.28,6.828 4.86,13.129 7.54,18.808 l 0,-16.148 c -2.78,-8.43 -5.43,-17.813 -7.54,-27.883 M 284.973,811.641 c -0.825,21.507 -3.661,40.179 -7.535,53.73 l 0,11 c 2.945,-6.062 5.527,-13.742 7.535,-22.66 l 0,-42.07"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2258"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2260"
+ d="m 1644.31,327.121 c 4.97,1.969 9.8,4.18 14.51,6.641 10.13,2.609 19.54,7.047 27.85,12.949 -7.93,-6.313 -16.47,-11.879 -25.51,-16.602 -5.44,-1.5 -11.07,-2.507 -16.85,-2.988 m -1288.626,0 c -5.778,0.488 -11.399,1.5 -16.832,2.988 -8.965,4.692 -17.438,10.211 -25.317,16.461 8.262,-5.832 17.61,-10.218 27.668,-12.82 4.695,-2.449 9.527,-4.66 14.481,-6.629 m 1345.746,32.91 c 6.86,7.801 12.31,16.867 15.95,26.797 4.54,6.922 8.55,14.231 11.96,21.863 -0.74,-5.89 -2.03,-11.613 -3.82,-17.109 -6.72,-11.512 -14.82,-22.102 -24.09,-31.551 m -1403.082,0.231 c -9.176,9.398 -17.215,19.918 -23.891,31.328 -1.781,5.48 -3.066,11.18 -3.809,17.039 3.414,-7.609 7.414,-14.891 11.95,-21.801 3.605,-9.828 8.984,-18.808 15.75,-26.566 m 1424.192,447.949 0,16.148 c 1.87,3.981 3.79,7.661 5.68,10.969 0.31,0.543 0.61,1.07 0.91,1.602 -0.08,-3.61 -0.17,-7.379 -0.28,-11.34 -0.27,-0.692 -0.54,-1.391 -0.81,-2.09 -1.81,-4.629 -3.68,-9.762 -5.5,-15.289 m -1445.102,57.16 c -2.102,7.367 -4.516,13.231 -7.075,17.211 -0.152,0 -0.304,-0.023 -0.457,-0.07 l 0,4.476 c 0.153,0.032 0.305,0.043 0.457,0.043 2.5,-2.551 4.887,-6.16 7.075,-10.66 l 0,-11"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2246"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2248"
+ d="m 1635.2,322.5 -4.32,0 c 4.57,1.34 9.05,2.879 13.43,4.621 5.78,0.481 11.41,1.488 16.85,2.988 -5.03,-2.629 -10.21,-5 -15.54,-7.078 -3.43,-0.351 -6.9,-0.531 -10.42,-0.531 m -1266.11,0 -4.25,0 c -3.535,0 -7.035,0.18 -10.485,0.531 -5.308,2.09 -10.484,4.449 -15.503,7.078 5.433,-1.488 11.054,-2.5 16.832,-2.988 4.375,-1.742 8.847,-3.281 13.406,-4.621 m 1356.43,69.082 c 1.79,5.496 3.08,11.219 3.82,17.109 3.34,7.481 6.12,15.27 8.27,23.321 l 0,-7.102 c 0,-2.898 -0.12,-5.781 -0.36,-8.621 -3.22,-8.609 -7.15,-16.867 -11.73,-24.707 M 274.457,391.59 c -4.57,7.82 -8.5,16.051 -11.719,24.64 -0.242,2.86 -0.363,5.758 -0.363,8.68 l 0,6.942 c 2.152,-8.012 4.93,-15.77 8.273,-23.223 0.743,-5.859 2.028,-11.559 3.809,-17.039 m -12.082,471.351 0,13.707 c 2.273,5.852 4.828,9.93 7.531,10.34 l 0,-4.476 c -2.82,-0.832 -5.422,-9.25 -7.531,-19.571"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2234"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2236"
+ d="m 1631.37,318.211 -19.55,0 c 6.5,1.027 12.86,2.469 19.06,4.289 l 4.32,0 c 3.52,0 6.99,0.18 10.42,0.531 -4.65,-1.832 -9.4,-3.441 -14.25,-4.82 m -1243.311,0 -19.473,0 c -4.84,1.379 -9.59,3 -14.231,4.82 3.45,-0.351 6.95,-0.531 10.485,-0.531 l 4.25,0 c 6.176,-1.82 12.508,-3.262 18.969,-4.289 M 262.738,416.23 c -3.519,9.391 -6.187,19.211 -7.898,29.34 l 0,401.239 c 1.73,10.011 4.359,21.66 7.535,29.839 l 0,-13.707 c -3.238,-15.832 -5.332,-36.152 -5.332,-40.519 l 0,-350.07 c 0,-14 1.855,-27.582 5.332,-40.5 l 0,-6.942 c 0,-2.922 0.121,-5.82 0.363,-8.68 m 1474.512,0.059 c 0.24,2.84 0.36,5.723 0.36,8.621 l 0,7.102 c 3.44,12.867 5.27,26.398 5.27,40.34 l 0,388.847 c 0.89,1.571 1.64,2.91 2.26,4.02 l 0,-419.43 c -1.7,-10.18 -4.36,-20.059 -7.89,-29.5"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2222"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2224"
+ d="m 1611.62,313.922 -1223.397,0 c -6.692,1.019 -13.243,2.457 -19.637,4.289 l 19.473,0 c 3.968,-0.641 7.984,-1.121 12.043,-1.449 4.699,-1.383 46.152,-2.114 51.293,-2.114 l 1096.975,0 c 5.19,0 46.91,0.75 51.64,2.141 3.98,0.332 7.92,0.801 11.81,1.422 l 19.55,0 c -6.43,-1.84 -13.02,-3.281 -19.75,-4.289 M 254.84,445.57 c -1.469,8.711 -2.238,17.66 -2.238,26.782 l 0,355.918 c 0,3.152 0.812,10.281 2.238,18.539 l 0,-401.239 m 1490.3,0.219 0,419.43 c 0.36,0.64 0.68,1.211 0.95,1.703 0.83,1.488 1.25,2.258 1.25,2.308 l 0,-1.23 0,-395.648 c 0,-9.051 -0.75,-17.922 -2.2,-26.563"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2210"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2212"
+ d="m 1552.96,310.199 -1106.128,0 c -6.852,0 -45.398,0.981 -51.664,2.821 -2.328,0.25 -4.648,0.55 -6.945,0.902 l 1223.397,0 c -2.2,-0.332 -4.41,-0.621 -6.63,-0.863 -6.31,-1.86 -45.12,-2.86 -52.03,-2.86"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2198"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2200"
+ d="m 1742.88,861.199 0,2.621 c 0.81,0.821 1.56,1.559 2.26,2.219 l 0,-0.82 c -0.62,-1.11 -1.37,-2.449 -2.26,-4.02"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2186"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2188"
+ d="m 1745.14,865.219 0,0.82 c 0.33,0.313 0.65,0.609 0.95,0.883 -0.27,-0.492 -0.59,-1.063 -0.95,-1.703"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2174"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2176"
+ d="m 1738.42,853.309 0,5.742 c 1.13,1.25 2.19,2.398 3.18,3.437 -0.55,-2.078 -1.28,-4.558 -2.19,-7.449 -0.32,-0.559 -0.65,-1.141 -0.99,-1.73"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2162"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2164"
+ d="m 1733.97,845.449 0,8.473 c 1.2,1.418 2.35,2.75 3.44,3.976 -0.37,-2.628 -0.84,-5.597 -1.42,-8.878 -0.64,-1.141 -1.32,-2.329 -2.02,-3.571"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2150"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2152"
+ d="m 1729.51,837.602 0,10.937 c 0.19,0.231 0.38,0.461 0.56,0.691 l 0,-10.64 c -0.18,-0.32 -0.37,-0.66 -0.56,-0.988"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2138"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2140"
+ d="m 1730.07,838.59 0,10.64 c 1.13,1.379 2.22,2.7 3.26,3.942 -0.2,-3.121 -0.45,-6.524 -0.77,-10.192 -0.79,-1.41 -1.63,-2.871 -2.49,-4.39"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2126"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2128"
+ d="m 1585.09,426.488 -1143.149,0 c -16.609,0 -57.261,9.614 -68.425,25.532 -36.954,34.41 -60.844,145.64 -73.477,242.742 l 0,45.937 c 11.457,-103.777 37.934,-244.738 79.391,-278.039 9.566,-13.648 55.035,-21.879 69.269,-21.879 l 1136.391,0 c 64.85,0 102.83,184.09 114.84,299.16 l 0,-45.98 C 1684.57,576.859 1647.67,426.488 1585.09,426.488"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2114"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2116"
+ d="m 1699.93,693.961 0,45.98 c 1.55,14.86 2.67,28.571 3.35,40.59 0.51,8.789 2.01,17.168 4.18,24.969 l 0,-34.84 c -0.15,-1.629 -0.29,-3.269 -0.39,-4.922 -1.33,-20.859 -3.69,-45.476 -7.14,-71.777 m -1399.891,0.801 c -3.242,24.91 -5.742,48.886 -7.535,70.398 l 0,74.641 c 0.601,-4.879 0.988,-9.981 1.133,-15.25 0.578,-20.871 2.711,-50.442 6.402,-83.852 l 0,-45.937"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2102"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2104"
+ d="m 292.504,765.16 c -1.649,19.809 -2.695,37.52 -3.164,51.942 -0.391,13.527 -1.969,25.949 -4.367,36.609 l 0,16.68 c 3.457,-8.532 6.101,-18.942 7.531,-30.59 l 0,-74.641 m 1414.956,5.5 0,34.84 c 2.02,7.23 4.62,13.961 7.54,20.078 l 0,-20.027 c -3.52,-10.539 -6.31,-22.332 -7.54,-34.891"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2090"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2092"
+ d="m 313.535,346.57 c -5.594,3.942 -10.695,8.551 -15.187,13.692 4.765,-4.883 9.84,-9.453 15.187,-13.692 m 1373.135,0.141 c 5.19,4.141 10.12,8.578 14.76,13.32 -4.38,-4.992 -9.34,-9.461 -14.76,-13.32 m 28.33,458.84 0,20.027 c 2.35,4.91 4.9,9.422 7.54,13.461 l 0,-14.68 c -2.68,-5.679 -5.26,-11.98 -7.54,-18.808 m -1430.027,48.16 c -2.008,8.918 -4.59,16.598 -7.535,22.66 l 0,7.938 c 2.777,-3.758 5.32,-8.45 7.535,-13.918 l 0,-16.68"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2078"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2080"
+ d="m 1661.16,330.109 c 9.04,4.723 17.58,10.289 25.51,16.602 5.42,3.859 10.38,8.328 14.76,13.32 9.27,9.449 17.37,20.039 24.09,31.551 -3.29,-10.133 -8.27,-19.512 -14.59,-27.812 -6.55,-7.461 -13.76,-14.329 -21.53,-20.508 -8.5,-5.864 -18.03,-10.352 -28.24,-13.153 m -1322.308,0 c -10.153,2.782 -19.625,7.243 -28.098,13.051 -7.902,6.262 -15.219,13.238 -21.856,20.828 -6.257,8.25 -11.175,17.551 -14.441,27.602 6.676,-11.41 14.715,-21.93 23.891,-31.328 4.492,-5.141 9.593,-9.75 15.187,-13.692 7.879,-6.25 16.352,-11.769 25.317,-16.461 m 1383.688,494.25 0,14.68 c 1.93,2.973 3.9,5.691 5.86,8.133 0.32,0.387 0.63,0.769 0.94,1.148 -0.06,-3.558 -0.13,-7.371 -0.21,-11.39 -0.3,-0.532 -0.6,-1.059 -0.91,-1.602 -1.89,-3.308 -3.81,-6.988 -5.68,-10.969 M 277.438,876.371 c -2.188,4.5 -4.575,8.109 -7.075,10.66 -0.152,0 -0.304,-0.011 -0.457,-0.043 l 0,4.473 c 0.153,0.008 0.305,0.019 0.457,0.019 2.469,-1.73 4.848,-4.148 7.075,-7.171 l 0,-7.938"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2066"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2068"
+ d="m 1645.62,323.031 c 5.33,2.078 10.51,4.449 15.54,7.078 10.21,2.801 19.74,7.289 28.24,13.153 -7.95,-6.321 -16.49,-11.91 -25.54,-16.68 -5.88,-1.711 -11.98,-2.922 -18.24,-3.551 m -1291.265,0 c -6.257,0.641 -12.343,1.84 -18.222,3.559 -8.981,4.738 -17.469,10.289 -25.379,16.57 8.473,-5.808 17.945,-10.269 28.098,-13.051 5.019,-2.629 10.195,-4.988 15.503,-7.078 M 1710.93,363.77 c 6.32,8.3 11.3,17.679 14.59,27.812 4.58,7.84 8.51,16.098 11.73,24.707 -0.53,-6.348 -1.65,-12.551 -3.3,-18.519 -6.26,-12.309 -14.01,-23.719 -23.02,-34 m -1422.032,0.218 c -8.941,10.231 -16.648,21.582 -22.875,33.801 -1.636,5.949 -2.75,12.109 -3.285,18.441 3.219,-8.589 7.149,-16.82 11.719,-24.64 3.266,-10.051 8.184,-19.352 14.441,-27.602 m -26.523,512.66 0,8.641 c 2.344,3.609 4.879,5.93 7.531,6.172 l 0,-4.473 c -2.703,-0.41 -5.258,-4.488 -7.531,-10.34"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2054"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2056"
+ d="m 1633.99,318.211 -2.62,0 c 4.85,1.379 9.6,2.988 14.25,4.82 6.26,0.629 12.36,1.84 18.24,3.551 -5.35,-2.82 -10.88,-5.352 -16.56,-7.582 -4.36,-0.52 -8.81,-0.789 -13.31,-0.789 m -1265.404,0 -2.524,0 c -4.535,0 -9.007,0.269 -13.406,0.801 -5.664,2.226 -11.179,4.758 -16.523,7.578 5.879,-1.719 11.965,-2.918 18.222,-3.559 4.641,-1.82 9.391,-3.441 14.231,-4.82 M 1733.95,397.77 c 1.65,5.968 2.77,12.171 3.3,18.519 3.53,9.441 6.19,19.32 7.89,29.5 l 0,-16.398 c 0,-1.231 -0.02,-2.461 -0.06,-3.68 -2.86,-9.711 -6.61,-19.063 -11.13,-27.941 m -1467.927,0.019 c -4.515,8.859 -8.25,18.18 -11.121,27.871 -0.039,1.238 -0.062,2.481 -0.062,3.731 l 0,16.179 c 1.711,-10.129 4.379,-19.949 7.898,-29.34 0.535,-6.332 1.649,-12.492 3.285,-18.441 m -11.183,449.02 0,21.16 c 2.137,6.711 4.695,12.961 7.535,17.32 l 0,-8.641 c -3.176,-8.179 -5.805,-19.828 -7.535,-29.839"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2042"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2044"
+ d="m 1632.15,313.922 -20.53,0 c 6.73,1.008 13.32,2.449 19.75,4.289 l 2.62,0 c 4.5,0 8.95,0.269 13.31,0.789 -4.94,-1.93 -9.99,-3.629 -15.15,-5.078 m -1243.927,0 -20.43,0 c -5.152,1.449 -10.199,3.148 -15.137,5.09 4.399,-0.532 8.871,-0.801 13.406,-0.801 l 2.524,0 c 6.394,-1.832 12.945,-3.27 19.637,-4.289 M 254.902,425.66 c -4.382,14.809 -6.742,30.481 -6.742,46.692 l 0,361.769 c 0,6.238 2.559,20.91 6.68,33.848 l 0,-21.16 c -1.426,-8.258 -2.238,-15.387 -2.238,-18.539 l 0,-355.918 c 0,-9.122 0.769,-18.071 2.238,-26.782 l 0,-16.179 c 0,-1.25 0.023,-2.493 0.062,-3.731 m 1490.178,0.051 c 0.04,1.219 0.06,2.449 0.06,3.68 l 0,16.398 c 1.45,8.641 2.2,17.512 2.2,26.563 l 0,395.648 c 1.76,1.461 3.01,2.18 3.73,2.18 0.48,0 0.73,-0.321 0.73,-0.95 l 0,-396.878 c 0,-16.192 -2.35,-31.84 -6.72,-46.641"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2030"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2032"
+ d="m 1612.08,309.629 -1224.35,0 c -6.785,1.012 -13.445,2.449 -19.937,4.293 l 20.43,0 c 2.297,-0.352 4.617,-0.652 6.945,-0.902 6.266,-1.84 44.812,-2.821 51.664,-2.821 l 1106.128,0 c 6.91,0 45.72,1 52.03,2.86 2.22,0.242 4.43,0.531 6.63,0.863 l 20.53,0 c -6.53,-1.844 -13.24,-3.281 -20.07,-4.293"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2018"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2020"
+ d="m 1557.55,305.75 -1115.277,0 c -8.562,0 -44.207,1.23 -52.039,3.52 -0.839,0.121 -1.668,0.23 -2.504,0.359 l 1224.35,0 c -0.7,-0.109 -1.41,-0.207 -2.12,-0.301 -7.89,-2.328 -43.77,-3.578 -52.41,-3.578"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath2006"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path2008"
+ d="m 1733.97,853.922 0,9.609 c 1.26,1 2.47,1.918 3.64,2.758 l 0,-6.891 c -0.07,-0.476 -0.13,-0.976 -0.2,-1.5 -1.09,-1.226 -2.24,-2.558 -3.44,-3.976"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1994"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1996"
+ d="m 1737.61,859.398 0,6.891 c 0.25,0.18 0.49,0.359 0.74,0.531 -0.12,-2.011 -0.36,-4.488 -0.74,-7.422"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1982"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1984"
+ d="m 1729.51,848.539 0,11.27 c 0.19,0.16 0.38,0.332 0.56,0.492 l 0,-11.071 c -0.18,-0.23 -0.37,-0.46 -0.56,-0.691"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1970"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1972"
+ d="m 1730.07,849.23 0,11.071 c 1.31,1.121 2.57,2.168 3.79,3.14 -0.1,-2.98 -0.27,-6.41 -0.53,-10.269 -1.04,-1.242 -2.13,-2.563 -3.26,-3.942"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1958"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1960"
+ d="m 1585.09,440.781 -1136.391,0 c -14.234,0 -59.703,8.231 -69.269,21.879 -41.457,33.301 -67.934,174.262 -79.391,278.039 l 0,54.071 c 8.016,-100.59 37.711,-289.399 85.305,-321.469 7.972,-11.371 58.25,-18.242 70.117,-18.242 l 1129.629,0 c 69.81,0 109.57,243.929 114.41,340.25 0.09,1.832 0.23,3.652 0.43,5.441 l 0,-60.809 c -12.01,-115.07 -49.99,-299.16 -114.84,-299.16"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1946"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1948"
+ d="m 1699.93,739.941 0,60.809 c 1.11,10.281 3.82,19.828 7.53,28.32 l 0,-23.57 c -2.17,-7.801 -3.67,-16.18 -4.18,-24.969 -0.68,-12.019 -1.8,-25.73 -3.35,-40.59 m -1399.891,0.758 c -3.691,33.41 -5.824,62.981 -6.402,83.852 -0.145,5.269 -0.532,10.371 -1.133,15.25 l 0,25.238 c 3.168,-9.629 5.137,-20.867 5.434,-33.039 0.242,-10.102 0.945,-22.75 2.101,-37.23 l 0,-54.071"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1934"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1936"
+ d="m 1707.46,805.5 0,23.57 c 2.21,5.051 4.77,9.731 7.54,13.969 l 0,-17.461 c -2.92,-6.117 -5.52,-12.848 -7.54,-20.078 M 292.504,839.801 c -1.43,11.648 -4.074,22.058 -7.531,30.59 l 0,11.148 c 2.925,-4.699 5.48,-10.258 7.531,-16.5 l 0,-25.238"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1922"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1924"
+ d="m 1715,825.578 0,17.461 c 2.38,3.633 4.92,6.941 7.54,9.902 l 0,-13.902 C 1719.9,835 1717.35,830.488 1715,825.578 M 284.973,870.391 c -2.215,5.468 -4.758,10.16 -7.535,13.918 l 0,6.632 c 2.699,-2.543 5.23,-5.703 7.535,-9.402 l 0,-11.148"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1910"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1912"
+ d="m 310.754,343.16 c -8.356,5.719 -15.746,12.77 -21.856,20.828 6.637,-7.59 13.954,-14.566 21.856,-20.828 m 1378.646,0.102 c 7.77,6.179 14.98,13.047 21.53,20.508 -6.04,-7.918 -13.31,-14.848 -21.53,-20.508 m 33.14,495.777 0,13.902 c 1.98,2.231 4.01,4.258 6.05,6.059 0.29,0.262 0.59,0.52 0.88,0.781 -0.03,-3.472 -0.07,-7.301 -0.13,-11.461 -0.31,-0.379 -0.62,-0.761 -0.94,-1.148 -1.96,-2.442 -3.93,-5.16 -5.86,-8.133 m -1445.102,45.27 c -2.227,3.023 -4.606,5.441 -7.075,7.171 -0.152,0 -0.304,-0.011 -0.457,-0.019 l 0,4.461 c 0.153,0 0.305,0.008 0.457,0.008 2.449,-1.192 4.821,-2.871 7.075,-4.989 l 0,-6.632"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1898"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1900"
+ d="m 1663.86,326.582 c 9.05,4.77 17.59,10.359 25.54,16.68 8.22,5.66 15.49,12.59 21.53,20.508 9.01,10.281 16.76,21.691 23.02,34 -2.87,-10.438 -7.36,-20.211 -13.17,-29.04 -8.2,-10.57 -17.63,-20.14 -28.05,-28.5 -8.75,-5.96 -18.47,-10.609 -28.87,-13.648 M 336.133,326.59 c -10.34,3.019 -20.008,7.629 -28.723,13.551 -10.551,8.441 -20.074,18.121 -28.351,28.82 -5.75,8.777 -10.188,18.48 -13.036,28.828 6.227,-12.219 13.934,-23.57 22.875,-33.801 6.11,-8.058 13.5,-15.109 21.856,-20.828 7.91,-6.281 16.398,-11.832 25.379,-16.57 m -73.758,558.699 0,6.672 c 2.383,2.359 4.91,3.801 7.531,3.961 l 0,-4.461 c -2.652,-0.242 -5.187,-2.563 -7.531,-6.172"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1886"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1888"
+ d="m 1647.3,319 c 5.68,2.23 11.21,4.762 16.56,7.582 10.4,3.039 20.12,7.688 28.87,13.648 -8.03,-6.429 -16.65,-12.14 -25.77,-17.019 -6.33,-1.981 -12.9,-3.402 -19.66,-4.211 m -1294.644,0.012 c -6.746,0.82 -13.304,2.238 -19.629,4.207 -9.054,4.859 -17.632,10.543 -25.617,16.922 8.715,-5.922 18.383,-10.532 28.723,-13.551 5.344,-2.82 10.859,-5.352 16.523,-7.578 M 1720.78,368.73 c 5.81,8.829 10.3,18.602 13.17,29.04 4.52,8.878 8.27,18.23 11.13,27.941 -0.22,-6.813 -1.06,-13.481 -2.46,-19.941 -5.71,-13.321 -13.08,-25.75 -21.84,-37.04 m -1441.721,0.231 c -8.7,11.25 -16.02,23.617 -21.704,36.859 -1.39,6.418 -2.226,13.059 -2.453,19.84 2.871,-9.691 6.606,-19.012 11.121,-27.871 2.848,-10.348 7.286,-20.051 13.036,-28.828 m 1459.361,490.09 0,7.828 c 2.47,1.742 4.72,3.121 6.72,4.152 l 0,-4.992 c -0.7,-0.66 -1.45,-1.398 -2.26,-2.219 l 0,5.41 c 0,-1.218 -0.42,-3.48 -1.28,-6.742 -0.99,-1.039 -2.05,-2.187 -3.18,-3.437 m -1483.58,8.918 0,12.941 c 2.269,4.481 4.808,8.36 7.535,11.051 l 0,-6.672 c -2.84,-4.359 -5.398,-10.609 -7.535,-17.32"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1874"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1876"
+ d="m 1632.77,313.922 -0.62,0 c 5.16,1.449 10.21,3.148 15.15,5.078 6.76,0.809 13.33,2.23 19.66,4.211 -5.66,-3.039 -11.51,-5.762 -17.54,-8.141 -5.44,-0.761 -11,-1.148 -16.65,-1.148 m -1264.977,0 -0.508,0 c -5.683,0 -11.277,0.398 -16.758,1.156 -6.004,2.383 -11.847,5.102 -17.5,8.141 6.325,-1.969 12.883,-3.387 19.629,-4.207 4.938,-1.942 9.985,-3.641 15.137,-5.09 M 1742.62,405.77 c 1.4,6.46 2.24,13.128 2.46,19.941 4.37,14.801 6.72,30.449 6.72,46.641 l 0,396.878 c 0,0.629 -0.25,0.95 -0.73,0.95 -0.72,0 -1.97,-0.719 -3.73,-2.18 l 0,1.23 c 0,-0.05 -0.42,-0.82 -1.25,-2.308 -0.3,-0.274 -0.62,-0.57 -0.95,-0.883 l 0,4.992 c 3,1.539 5.45,2.289 7.29,2.289 0.08,0 0.17,0 0.25,0 l 0,-435.672 c -2.31,-11.058 -5.71,-21.726 -10.06,-31.878 m -1485.265,0.05 c -4.347,10.129 -7.734,20.77 -10.046,31.801 l 0,423.238 c 1.898,6.84 4.472,14 7.531,20.051 l 0,-12.941 c -4.121,-12.938 -6.68,-27.61 -6.68,-33.848 l 0,-361.769 c 0,-16.211 2.36,-31.883 6.742,-46.692 0.227,-6.781 1.063,-13.422 2.453,-19.84"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1862"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1864"
+ d="m 1631.56,309.629 -19.48,0 c 6.83,1.012 13.54,2.449 20.07,4.293 l 0.62,0 c 5.65,0 11.21,0.387 16.65,1.148 -5.25,-2.07 -10.63,-3.89 -16.12,-5.429 -0.58,-0.012 -1.16,-0.012 -1.74,-0.012 m -1243.83,0 -19.222,0 c -0.625,0 -1.254,0 -1.875,0.012 -5.488,1.55 -10.856,3.359 -16.106,5.437 5.481,-0.758 11.075,-1.156 16.758,-1.156 l 0.508,0 c 6.492,-1.844 13.152,-3.281 19.937,-4.293 M 247.309,437.621 c -2.352,11.219 -3.586,22.828 -3.586,34.731 l 0,367.617 c 0,4.89 1.304,12.672 3.586,20.89 l 0,-423.238 m 1505.371,0.027 0,435.672 c 2.33,-0.101 3.57,-1.48 3.57,-4.09 l 0,-396.878 c 0,-11.891 -1.23,-23.5 -3.57,-34.704"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1850"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1852"
+ d="m 1613.98,305.34 -1227.984,0 c -0.242,0.058 -0.476,0.121 -0.695,0.191 -6.348,1.02 -12.574,2.399 -18.668,4.11 0.621,-0.012 1.25,-0.012 1.875,-0.012 l 19.222,0 c 0.836,-0.129 1.665,-0.238 2.504,-0.359 7.832,-2.29 43.477,-3.52 52.039,-3.52 l 1115.277,0 c 8.64,0 44.52,1.25 52.41,3.578 0.71,0.094 1.42,0.192 2.12,0.301 l 19.48,0 c 0.58,0 1.16,0 1.74,0.012 -5.99,-1.68 -12.12,-3.039 -18.36,-4.039 -0.3,-0.09 -0.62,-0.18 -0.96,-0.262"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1838"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1840"
+ d="m 1562.14,301.301 -1124.429,0 c -10.035,0 -41.492,1.41 -51.715,4.039 l 1227.984,0 c -10.55,-2.629 -41.8,-4.039 -51.84,-4.039"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1826"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1828"
+ d="m 1585.09,455.059 -1129.629,0 c -11.867,0 -62.145,6.871 -70.117,18.242 -47.594,32.07 -77.289,220.879 -85.305,321.469 l 0,63.66 c 1.293,-5.961 2.059,-12.328 2.195,-18.989 1.52,-74.722 34.938,-326.152 89.024,-355.5 6.379,-9.101 61.469,-14.589 70.961,-14.589 l 1122.871,0 c 66.4,0 106.88,253.136 110.62,340.738 0.35,8.031 1.85,15.629 4.22,22.609 l 0,-31.949 c -0.2,-1.789 -0.34,-3.609 -0.43,-5.441 -4.84,-96.321 -44.6,-340.25 -114.41,-340.25"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1814"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1816"
+ d="m 300.039,794.77 c -1.156,14.48 -1.859,27.128 -2.101,37.23 -0.297,12.172 -2.266,23.41 -5.434,33.039 l 0,14.281 c 3.258,-6.058 5.848,-13.121 7.535,-20.89 l 0,-63.66 m 1399.891,5.98 0,31.949 c 1.97,5.821 4.54,11.211 7.53,16.09 l 0,-19.719 c -3.71,-8.492 -6.42,-18.039 -7.53,-28.32"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1802"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1804"
+ d="m 1707.46,829.07 0,19.719 c 2.29,3.723 4.83,7.152 7.54,10.231 l 0,-15.981 c -2.77,-4.238 -5.33,-8.918 -7.54,-13.969 M 292.504,865.039 c -2.051,6.242 -4.606,11.801 -7.531,16.5 l 0,8.68 c 2.773,-3.098 5.308,-6.77 7.531,-10.899 l 0,-14.281"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1790"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1792"
+ d="m 1715,843.039 0,15.981 c 2.4,2.718 4.92,5.171 7.54,7.332 l 0,-13.411 c -2.62,-2.961 -5.16,-6.269 -7.54,-9.902 m -1430.027,38.5 c -2.305,3.699 -4.836,6.859 -7.535,9.402 l 0,5.93 c 2.656,-1.781 5.179,-4.012 7.535,-6.652 l 0,-8.68"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1778"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1780"
+ d="m 1722.54,852.941 0,13.411 c 2.03,1.679 4.12,3.179 6.23,4.488 0.44,0.269 0.87,0.531 1.3,0.789 l 0,-11.328 c -0.18,-0.16 -0.37,-0.332 -0.56,-0.492 l 0,9.421 c 0,-2.761 -0.01,-5.921 -0.04,-9.449 -0.29,-0.261 -0.59,-0.519 -0.88,-0.781 -2.04,-1.801 -4.07,-3.828 -6.05,-6.059 m -1445.102,38 c -2.254,2.118 -4.626,3.797 -7.075,4.989 -0.152,0 -0.304,-0.008 -0.457,-0.008 l 0,4.449 c 0.153,0.008 0.305,0.008 0.457,0.008 2.434,-0.809 4.801,-1.988 7.075,-3.508 l 0,-5.93"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1766"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1768"
+ d="m 307.41,340.141 c -11.242,7.64 -20.898,17.449 -28.351,28.82 8.277,-10.699 17.8,-20.379 28.351,-28.82 m 1385.32,0.089 c 10.42,8.36 19.85,17.93 28.05,28.5 -7.4,-11.23 -16.95,-20.929 -28.05,-28.5 m 37.34,520.071 0,11.328 c 2.64,1.562 5.16,2.859 7.54,3.902 l 0,-9.242 c -1.17,-0.84 -2.38,-1.758 -3.64,-2.758 l 0,5.699 c 0,-1.679 -0.04,-3.609 -0.11,-5.789 -1.22,-0.972 -2.48,-2.019 -3.79,-3.14 m -1467.695,31.66 0,5.758 c 2.406,1.601 4.93,2.551 7.531,2.652 l 0,-4.449 c -2.621,-0.16 -5.148,-1.602 -7.531,-3.961"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1754"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1756"
+ d="m 1666.96,323.211 c 9.12,4.879 17.74,10.59 25.77,17.019 11.1,7.571 20.65,17.27 28.05,28.5 8.76,11.29 16.13,23.719 21.84,37.04 -2.34,-10.75 -6.23,-20.918 -11.44,-30.27 -9.65,-14.34 -21.37,-27.16 -34.73,-38.031 -8.98,-6.117 -18.89,-10.969 -29.49,-14.258 m -1333.933,0.008 c -10.531,3.281 -20.398,8.09 -29.336,14.16 -13.488,10.949 -25.32,23.902 -35.035,38.391 -5.14,9.289 -8.984,19.378 -11.301,30.05 5.684,-13.242 13.004,-25.609 21.704,-36.859 7.453,-11.371 17.109,-21.18 28.351,-28.82 7.985,-6.379 16.563,-12.063 25.617,-16.922 m 1404.583,543.07 0,9.242 c 2.7,1.188 5.23,2.039 7.53,2.571 l 0,-7.071 c -2,-1.031 -4.25,-2.41 -6.72,-4.152 l 0,2.351 c 0,-0.71 -0.02,-1.511 -0.07,-2.41 -0.25,-0.172 -0.49,-0.351 -0.74,-0.531 m -1482.77,14.621 0,9.371 c 2.336,3.098 4.863,5.668 7.535,7.438 l 0,-5.758 c -2.727,-2.691 -5.266,-6.57 -7.535,-11.051"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1742"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1744"
+ d="m 1649.42,315.07 c 6.03,2.379 11.88,5.102 17.54,8.141 10.6,3.289 20.51,8.141 29.49,14.258 -8.09,-6.571 -16.78,-12.43 -25.96,-17.469 -6.78,-2.25 -13.82,-3.918 -21.07,-4.93 m -1298.893,0.008 c -7.234,1.024 -14.261,2.684 -21.027,4.934 -9.129,5.019 -17.766,10.84 -25.809,17.367 8.938,-6.07 18.805,-10.879 29.336,-14.16 5.653,-3.039 11.496,-5.758 17.5,-8.141 M 1731.18,375.5 c 5.21,9.352 9.1,19.52 11.44,30.27 4.35,10.152 7.75,20.82 10.06,31.878 l 0,-3.789 c 0,-6.05 -0.45,-11.988 -1.32,-17.808 -4.96,-14.469 -11.79,-28.082 -20.18,-40.551 m -1462.524,0.27 c -8.328,12.421 -15.105,25.968 -20.043,40.371 -0.859,5.781 -1.304,11.699 -1.304,17.718 l 0,3.762 c 2.312,-11.031 5.699,-21.672 10.046,-31.801 2.317,-10.672 6.161,-20.761 11.301,-30.05 m -21.347,485.089 0,16.422 c 2.171,4.77 4.711,9.27 7.531,13 l 0,-9.371 c -3.059,-6.051 -5.633,-13.211 -7.531,-20.051 m 1497.831,10.172 0,7.071 c 1.98,0.457 3.79,0.679 5.43,0.679 0.74,0 1.44,-0.043 2.11,-0.133 l 0,-5.328 c -0.08,0 -0.17,0 -0.25,0 -1.84,0 -4.29,-0.75 -7.29,-2.289"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1730"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1732"
+ d="m 1633.3,309.641 c 5.49,1.539 10.87,3.359 16.12,5.429 7.25,1.012 14.29,2.68 21.07,4.93 -5.95,-3.27 -12.1,-6.191 -18.45,-8.738 -6.12,-0.992 -12.37,-1.543 -18.74,-1.621 m -1266.667,0 c -6.363,0.089 -12.617,0.648 -18.731,1.64 -6.324,2.547 -12.468,5.469 -18.402,8.731 6.766,-2.25 13.793,-3.91 21.027,-4.934 5.25,-2.078 10.618,-3.887 16.106,-5.437 m 1384.727,106.41 c 0.87,5.82 1.32,11.758 1.32,17.808 l 0,3.789 c 2.34,11.204 3.57,22.813 3.57,34.704 l 0,396.878 c 0,2.61 -1.24,3.989 -3.57,4.09 l 0,5.328 c 3.88,-0.519 6.5,-2.539 7.54,-5.878 l 0,-413.598 c -1.13,-14.981 -4.17,-29.434 -8.86,-43.121 m -1502.747,0.09 c -4.683,13.668 -7.711,28.097 -8.84,43.058 l 0,392.981 c 1.051,7.48 3.723,16.718 7.536,25.101 l 0,-16.422 c -2.282,-8.218 -3.586,-16 -3.586,-20.89 l 0,-367.617 c 0,-11.903 1.234,-23.512 3.586,-34.731 l 0,-3.762 c 0,-6.019 0.445,-11.937 1.304,-17.718"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1718"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1720"
+ d="m 1630.35,305.34 -16.37,0 c 0.34,0.082 0.66,0.172 0.96,0.262 6.24,1 12.37,2.359 18.36,4.039 6.37,0.078 12.62,0.629 18.74,1.621 -5.55,-2.242 -11.25,-4.192 -17.06,-5.852 -1.54,-0.051 -3.08,-0.07 -4.63,-0.07 m -1244.354,0 -16.266,0 c -1.601,0 -3.199,0.031 -4.785,0.082 -5.808,1.656 -11.496,3.617 -17.043,5.859 6.114,-0.992 12.368,-1.551 18.731,-1.64 6.094,-1.711 12.32,-3.09 18.668,-4.11 0.219,-0.07 0.453,-0.133 0.695,-0.191 m 1374.224,153.832 0,413.598 c 0.32,-1.051 0.49,-2.231 0.49,-3.54 l 0,-396.878 c 0,-4.43 -0.17,-8.832 -0.49,-13.18 m -1520.447,0.027 c -0.324,4.34 -0.492,8.731 -0.492,13.153 l 0,373.468 c 0,1.899 0.168,4.051 0.492,6.36 l 0,-392.981"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1706"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1708"
+ d="m 1616.63,301.051 -1233.314,0 c -1.089,0.23 -2.082,0.48 -2.953,0.73 -5.226,0.981 -10.367,2.199 -15.418,3.641 1.586,-0.051 3.184,-0.082 4.785,-0.082 l 16.266,0 c 10.223,-2.629 41.68,-4.039 51.715,-4.039 l 1124.429,0 c 10.04,0 41.29,1.41 51.84,4.039 l 16.37,0 c 1.55,0 3.09,0.019 4.63,0.07 -4.94,-1.398 -9.96,-2.59 -15.07,-3.551 -0.95,-0.277 -2.06,-0.55 -3.28,-0.808"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1694"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1696"
+ d="m 1566.73,296.852 -1133.582,0 c -11.035,0 -37.191,1.457 -49.832,4.199 l 1233.314,0 c -12.84,-2.742 -38.86,-4.199 -49.9,-4.199"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1682"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1684"
+ d="m 1585.09,469.352 -1122.871,0 c -9.492,0 -64.582,5.488 -70.961,14.589 -54.086,29.348 -87.504,280.778 -89.024,355.5 -0.136,6.661 -0.902,13.028 -2.195,18.989 l 0,18.832 c 3.941,-8.813 6.313,-19.172 6.492,-30.371 1.117,-69.231 36.91,-330.301 90.637,-352.313 4.785,-6.828 64.687,-10.949 71.809,-10.949 l 1116.113,0 c 62.98,0 104.13,262.359 106.84,341.25 0.38,11.172 3.34,21.453 8,30.25 l 0,-22.43 c -2.37,-6.98 -3.87,-14.578 -4.22,-22.609 -3.74,-87.602 -44.22,-340.738 -110.62,-340.738"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1670"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1672"
+ d="m 1699.93,832.699 0,22.43 c 2.17,4.101 4.71,7.883 7.53,11.293 l 0,-17.633 c -2.99,-4.879 -5.56,-10.269 -7.53,-16.09 M 300.039,858.43 c -1.687,7.769 -4.277,14.832 -7.535,20.89 l 0,10.559 c 2.894,-3.688 5.437,-7.93 7.535,-12.617 l 0,-18.832"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1658"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1660"
+ d="m 1707.46,848.789 0,17.633 c 2.34,2.808 4.87,5.367 7.54,7.637 l 0,-15.039 c -2.71,-3.079 -5.25,-6.508 -7.54,-10.231 M 292.504,879.32 c -2.223,4.129 -4.758,7.801 -7.531,10.899 l 0,7.371 c 2.703,-2.18 5.226,-4.77 7.531,-7.711 l 0,-10.559"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1646"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1648"
+ d="m 1715,859.02 0,15.039 c 2.41,2.043 4.93,3.851 7.54,5.402 l 0,-13.109 c -2.62,-2.161 -5.14,-4.614 -7.54,-7.332 M 284.973,890.219 c -2.356,2.64 -4.879,4.871 -7.535,6.652 l 0,5.508 c 2.628,-1.25 5.148,-2.859 7.535,-4.789 l 0,-7.371"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1634"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1636"
+ d="m 1722.54,866.352 0,13.109 c 2.09,1.238 4.24,2.32 6.42,3.211 0.37,0.156 0.74,0.308 1.11,0.449 l 0,-11.492 c -0.43,-0.258 -0.86,-0.52 -1.3,-0.789 -2.11,-1.309 -4.2,-2.809 -6.23,-4.488 M 277.438,896.871 c -2.274,1.52 -4.641,2.699 -7.075,3.508 -0.152,0 -0.304,0 -0.457,-0.008 l 0,4.449 c 0.153,0.012 0.305,0.012 0.457,0.012 2.422,-0.531 4.789,-1.352 7.075,-2.453 l 0,-5.508"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1622"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1624"
+ d="m 1730.07,871.629 0,11.492 c 2.61,1.02 5.13,1.789 7.54,2.34 l 0,-9.93 c -2.38,-1.043 -4.9,-2.34 -7.54,-3.902 m -1467.695,26.09 0,5.269 c 2.426,1.121 4.945,1.774 7.531,1.832 l 0,-4.449 c -2.601,-0.101 -5.125,-1.051 -7.531,-2.652"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1610"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1612"
+ d="m 303.691,337.379 c -14.48,9.84 -26.527,23.012 -35.035,38.391 9.715,-14.489 21.547,-27.442 35.035,-38.391 m 1392.759,0.09 c 13.36,10.871 25.08,23.691 34.73,38.031 -8.46,-15.219 -20.4,-28.25 -34.73,-38.031 m 41.16,538.062 0,9.93 c 2.65,0.598 5.17,0.918 7.53,0.988 l 0,-8.347 c -2.3,-0.532 -4.83,-1.383 -7.53,-2.571 m -1482.77,14.75 0,7.547 c 2.379,2.184 4.898,3.953 7.535,5.16 l 0,-5.269 c -2.672,-1.77 -5.199,-4.34 -7.535,-7.438"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1598"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1600"
+ d="m 1670.49,320 c 9.18,5.039 17.87,10.898 25.96,17.469 14.33,9.781 26.27,22.812 34.73,38.031 8.39,12.469 15.22,26.082 20.18,40.551 -1.65,-11.012 -4.8,-21.539 -9.23,-31.371 -10.78,-19.039 -24.95,-35.91 -41.67,-49.77 -9.16,-6.289 -19.23,-11.34 -29.97,-14.91 M 329.5,320.012 c -10.676,3.547 -20.699,8.57 -29.812,14.808 -16.864,13.95 -31.141,30.969 -41.965,50.18 -4.375,9.762 -7.481,20.211 -9.11,31.141 4.938,-14.403 11.715,-27.95 20.043,-40.371 8.508,-15.379 20.555,-28.551 35.035,-38.391 8.043,-6.527 16.68,-12.348 25.809,-17.367 m -82.191,557.269 0,11.617 c 2.281,3.383 4.808,6.422 7.531,8.93 l 0,-7.547 c -2.82,-3.73 -5.36,-8.23 -7.531,-13 m 1497.831,0.821 0,8.347 c 0.3,0 0.59,0.012 0.88,0.012 2.41,0 4.64,-0.281 6.66,-0.813 l 0,-7 c -0.67,0.09 -1.37,0.133 -2.11,0.133 -1.64,0 -3.45,-0.222 -5.43,-0.679"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1586"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1588"
+ d="m 1652.04,311.262 c 6.35,2.547 12.5,5.468 18.45,8.738 10.74,3.57 20.81,8.621 29.97,14.91 -8.1,-6.711 -16.8,-12.719 -26.01,-17.922 -7.2,-2.558 -14.69,-4.488 -22.41,-5.726 m -1304.138,0.019 c -7.703,1.239 -15.172,3.168 -22.359,5.719 -9.145,5.18 -17.801,11.148 -25.855,17.82 9.113,-6.238 19.136,-11.261 29.812,-14.808 5.934,-3.262 12.078,-6.184 18.402,-8.731 M 1742.13,384.68 c 4.43,9.832 7.58,20.359 9.23,31.371 4.69,13.687 7.73,28.14 8.86,43.121 l 0,-20.832 c 0,-3.078 -0.11,-6.121 -0.33,-9.141 -3.92,-15.769 -9.95,-30.711 -17.76,-44.519 M 257.723,385 c -7.754,13.762 -13.735,28.629 -17.637,44.328 -0.207,2.981 -0.313,5.981 -0.313,9.012 l 0,20.859 c 1.129,-14.961 4.157,-29.39 8.84,-43.058 1.629,-10.93 4.735,-21.379 9.11,-31.141 m -17.95,467.18 0,22.242 c 2.008,5.078 4.559,10.058 7.536,14.476 l 0,-11.617 c -3.813,-8.383 -6.485,-17.621 -7.536,-25.101 m 1520.447,20.59 c -1.04,3.339 -3.66,5.359 -7.54,5.878 l 0,7 c 3,-0.789 5.54,-2.148 7.54,-4.007 l 0,-8.871"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1574"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1576"
+ d="m 1634.98,305.41 c 5.81,1.66 11.51,3.61 17.06,5.852 7.72,1.238 15.21,3.168 22.41,5.726 -6.19,-3.508 -12.62,-6.648 -19.25,-9.398 -6.59,-1.211 -13.34,-1.949 -20.22,-2.18 m -1270.035,0.012 c -6.871,0.238 -13.621,0.976 -20.199,2.187 -6.613,2.75 -13.016,5.891 -19.203,9.391 7.187,-2.551 14.656,-4.48 22.359,-5.719 5.547,-2.242 11.235,-4.203 17.043,-5.859 M 1759.89,429.199 c 0.22,3.02 0.33,6.063 0.33,9.141 l 0,20.832 c 0.32,4.348 0.49,8.75 0.49,13.18 l 0,396.878 c 0,1.309 -0.17,2.489 -0.49,3.54 l 0,8.871 c 3.17,-2.95 4.95,-7.172 4.95,-12.411 l 0,-396.878 c 0,-14.872 -1.83,-29.332 -5.28,-43.153 m -1519.804,0.129 c -3.426,13.781 -5.242,28.203 -5.242,43.024 l 0,379.32 c 0,6.629 1.797,14.808 4.929,22.75 l 0,-22.242 c -0.324,-2.309 -0.492,-4.461 -0.492,-6.36 l 0,-373.468 c 0,-4.422 0.168,-8.813 0.492,-13.153 l 0,-20.859 c 0,-3.031 0.106,-6.031 0.313,-9.012"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1562"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1564"
+ d="m 1629.14,301.051 -12.51,0 c 1.22,0.258 2.33,0.531 3.28,0.808 5.11,0.961 10.13,2.153 15.07,3.551 6.88,0.231 13.63,0.969 20.22,2.18 -5.82,-2.41 -11.8,-4.531 -17.92,-6.32 -2.69,-0.149 -5.41,-0.219 -8.14,-0.219 m -1245.824,0 -12.367,0 c -2.789,0 -5.554,0.078 -8.308,0.23 -6.106,1.797 -12.079,3.91 -17.895,6.328 6.578,-1.211 13.328,-1.949 20.199,-2.187 5.051,-1.442 10.192,-2.66 15.418,-3.641 0.871,-0.25 1.864,-0.5 2.953,-0.73"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1550"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1552"
+ d="m 1619.26,296.762 -1238.576,0 c -1.938,0.398 -3.704,0.828 -5.254,1.277 -4.321,0.922 -8.59,2.012 -12.789,3.242 2.754,-0.152 5.519,-0.23 8.308,-0.23 l 12.367,0 c 12.641,-2.742 38.797,-4.199 49.832,-4.199 l 1133.582,0 c 11.04,0 37.06,1.457 49.9,4.199 l 12.51,0 c 2.73,0 5.45,0.07 8.14,0.219 -4.07,-1.192 -8.2,-2.239 -12.39,-3.141 -1.65,-0.488 -3.55,-0.938 -5.63,-1.367"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1538"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1540"
+ d="m 1617.32,296.379 -1234.707,0 c -0.66,0.121 -1.301,0.25 -1.929,0.383 l 1238.576,0 c -0.63,-0.133 -1.28,-0.262 -1.94,-0.383"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1526"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1528"
+ d="m 1585.09,483.629 -1116.113,0 c -7.122,0 -67.024,4.121 -71.809,10.949 -53.727,22.012 -89.52,283.082 -90.637,352.313 -0.179,11.199 -2.551,21.558 -6.492,30.371 l 0,12.609 c 6.598,-9.562 10.66,-21.922 10.789,-35.531 0.852,-63.738 38.887,-334.449 92.254,-349.129 3.191,-4.539 67.906,-7.289 72.652,-7.289 l 1109.356,0 c 59.57,0 101.32,271.566 103.05,341.738 0.33,13.281 4.79,25.281 11.79,34.731 l 0,-19.262 c -4.66,-8.797 -7.62,-19.078 -8,-30.25 -2.71,-78.891 -43.86,-341.25 -106.84,-341.25"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1514"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1516"
+ d="m 1699.93,855.129 0,19.262 c 2.26,3.058 4.79,5.859 7.53,8.339 l 0,-16.308 c -2.82,-3.41 -5.36,-7.192 -7.53,-11.293 M 300.039,877.262 c -2.098,4.687 -4.641,8.929 -7.535,12.617 l 0,8.691 c 2.766,-2.539 5.297,-5.461 7.535,-8.699 l 0,-12.609"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1502"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1504"
+ d="m 1707.46,866.422 0,16.308 c 2.37,2.149 4.89,4.059 7.54,5.719 l 0,-14.39 c -2.67,-2.27 -5.2,-4.829 -7.54,-7.637 M 292.504,889.879 c -2.305,2.941 -4.828,5.531 -7.531,7.711 l 0,6.59 c 2.66,-1.571 5.179,-3.45 7.531,-5.61 l 0,-8.691"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1490"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1492"
+ d="m 1715,874.059 0,14.39 c 2.42,1.52 4.94,2.821 7.54,3.891 l 0,-12.879 c -2.61,-1.551 -5.13,-3.359 -7.54,-5.402 M 284.973,897.59 c -2.387,1.93 -4.907,3.539 -7.535,4.789 l 0,5.262 c 2.609,-0.879 5.128,-2.039 7.535,-3.461 l 0,-6.59"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1478"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1480"
+ d="m 1722.54,879.461 0,12.879 c 2.15,0.89 4.36,1.621 6.6,2.172 0.31,0.078 0.62,0.148 0.93,0.218 l 0,-11.609 c -0.37,-0.141 -0.74,-0.293 -1.11,-0.449 -2.18,-0.891 -4.33,-1.973 -6.42,-3.211 M 277.438,902.379 c -2.286,1.101 -4.653,1.922 -7.075,2.453 -0.152,0 -0.304,0 -0.457,-0.012 l 0,4.461 c 0.153,0 0.305,0 0.457,0 2.414,-0.312 4.778,-0.871 7.075,-1.64 l 0,-5.262"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1466"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1468"
+ d="m 1730.07,883.121 0,11.609 c 2.59,0.59 5.11,0.95 7.54,1.11 l 0,-10.379 c -2.41,-0.551 -4.93,-1.32 -7.54,-2.34 m -1467.695,19.867 0,5 c 2.437,0.793 4.953,1.242 7.531,1.293 l 0,-4.461 c -2.586,-0.058 -5.105,-0.711 -7.531,-1.832"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1454"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1456"
+ d="m 1737.61,885.461 0,10.379 c 0.92,0.058 1.83,0.09 2.73,0.09 1.65,0 3.25,-0.102 4.8,-0.289 l 0,-9.192 c -2.36,-0.07 -4.88,-0.39 -7.53,-0.988 m -1482.77,12.367 0,6.5 c 2.402,1.563 4.922,2.813 7.535,3.66 l 0,-5 c -2.637,-1.207 -5.156,-2.976 -7.535,-5.16"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1442"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1444"
+ d="m 299.688,334.82 c -18.227,12.469 -32.848,29.828 -41.965,50.18 10.824,-19.211 25.101,-36.23 41.965,-50.18 m 1400.772,0.09 c 16.72,13.86 30.89,30.731 41.67,49.77 -9.1,-20.16 -23.61,-37.371 -41.67,-49.77 m 52.22,550.738 c -2.02,0.532 -4.25,0.813 -6.66,0.813 -0.29,0 -0.58,-0.012 -0.88,-0.012 l 0,9.192 c 2.68,-0.34 5.21,-0.961 7.54,-1.832 l 0,-8.161 m -1505.371,3.25 0,9.122 c 2.336,2.429 4.863,4.57 7.531,6.308 l 0,-6.5 c -2.723,-2.508 -5.25,-5.547 -7.531,-8.93"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1430"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1432"
+ d="m 1674.45,316.988 c 9.21,5.203 17.91,11.211 26.01,17.922 18.06,12.399 32.57,29.61 41.67,49.77 7.81,13.808 13.84,28.75 17.76,44.519 -0.79,-11.199 -3.02,-22.019 -6.5,-32.25 -11.31,-24.961 -28.05,-46.949 -48.69,-64.437 -9.27,-6.442 -19.43,-11.684 -30.25,-15.524 M 325.543,317 c -10.754,3.82 -20.859,9.031 -30.094,15.41 -20.793,17.602 -37.64,39.762 -48.976,64.922 -3.426,10.168 -5.614,20.887 -6.387,31.996 3.902,-15.699 9.883,-30.566 17.637,-44.328 9.117,-20.352 23.738,-37.711 41.965,-50.18 8.054,-6.672 16.71,-12.64 25.855,-17.82 m -85.77,557.422 0,13.758 c 2.204,3.59 4.739,6.929 7.536,9.84 l 0,-9.122 c -2.977,-4.418 -5.528,-9.398 -7.536,-14.476 m 1520.447,7.219 c -2,1.859 -4.54,3.218 -7.54,4.007 l 0,8.161 c 2.81,-1.047 5.34,-2.469 7.54,-4.219 l 0,-7.949"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1418"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1420"
+ d="m 1655.2,307.59 c 6.63,2.75 13.06,5.89 19.25,9.398 10.82,3.84 20.98,9.082 30.25,15.524 -8.06,-6.832 -16.71,-12.973 -25.86,-18.332 -7.59,-2.871 -15.49,-5.09 -23.64,-6.59 m -1310.454,0.019 c -8.133,1.5 -16.012,3.719 -23.574,6.582 -9.106,5.34 -17.703,11.438 -25.723,18.219 9.235,-6.379 19.34,-11.59 30.094,-15.41 6.187,-3.5 12.59,-6.641 19.203,-9.391 m 1408.644,89.34 c 3.48,10.231 5.71,21.051 6.5,32.25 3.45,13.821 5.28,28.281 5.28,43.153 l 0,396.878 c 0,5.239 -1.78,9.461 -4.95,12.411 l 0,7.949 c 3.35,-2.668 5.93,-6.11 7.53,-10.149 l 0,-433.332 c -2.49,-17.281 -7.39,-33.777 -14.36,-49.16 m -1506.917,0.383 c -6.911,15.348 -11.774,31.797 -14.231,49.02 l 0,424.339 c 1.602,6.008 4.188,12.039 7.531,17.489 l 0,-13.758 c -3.132,-7.942 -4.929,-16.121 -4.929,-22.75 l 0,-379.32 c 0,-14.821 1.816,-29.243 5.242,-43.024 0.773,-11.109 2.961,-21.828 6.387,-31.996"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1406"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1408"
+ d="m 1637.28,301.27 c 6.12,1.789 12.1,3.91 17.92,6.32 8.15,1.5 16.05,3.719 23.64,6.59 -6.4,-3.75 -13.04,-7.121 -19.9,-10.071 -7.05,-1.468 -14.28,-2.429 -21.66,-2.839 m -1274.639,0.011 c -7.368,0.418 -14.586,1.379 -21.621,2.848 -6.84,2.949 -13.469,6.32 -19.848,10.062 7.562,-2.863 15.441,-5.082 23.574,-6.582 5.816,-2.418 11.789,-4.531 17.895,-6.328 m 1405.109,144.828 0,433.332 c 1.22,-3.07 1.88,-6.5 1.88,-10.211 l 0,-396.878 c 0,-8.911 -0.64,-17.672 -1.88,-26.243 m -1535.508,0.243 c -1.211,8.488 -1.84,17.179 -1.84,26 l 0,385.168 c 0,4.21 0.645,8.679 1.84,13.171 l 0,-424.339"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1394"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1396"
+ d="m 1627.92,296.762 -8.66,0 c 2.08,0.429 3.98,0.879 5.63,1.367 4.19,0.902 8.32,1.949 12.39,3.141 7.38,0.41 14.61,1.371 21.66,2.839 -6.06,-2.621 -12.29,-4.91 -18.67,-6.859 -4.07,-0.328 -8.19,-0.488 -12.35,-0.488 m -1247.236,0 -8.512,0 c -4.207,0 -8.387,0.168 -12.512,0.5 -6.371,1.949 -12.586,4.25 -18.64,6.867 7.035,-1.469 14.253,-2.43 21.621,-2.848 4.199,-1.23 8.468,-2.32 12.789,-3.242 1.55,-0.449 3.316,-0.879 5.254,-1.277"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1382"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1384"
+ d="m 1637.35,296.379 -20.03,0 c 0.66,0.121 1.31,0.25 1.94,0.383 l 8.66,0 c 4.16,0 8.28,0.16 12.35,0.488 -0.97,-0.301 -1.94,-0.59 -2.92,-0.871 m -1254.737,0 -19.996,0 c -0.988,0.281 -1.976,0.582 -2.957,0.883 4.125,-0.332 8.305,-0.5 12.512,-0.5 l 8.512,0 c 0.628,-0.133 1.269,-0.262 1.929,-0.383"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1370"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1372"
+ d="m 1585.09,497.922 -1109.356,0 c -4.746,0 -69.461,2.75 -72.652,7.289 -53.367,14.68 -91.402,285.391 -92.254,349.129 -0.129,13.609 -4.191,25.969 -10.789,35.531 l 0,9.93 c 9.207,-9.473 15.016,-22.961 15.09,-38.02 0.422,-58.242 40.859,-338.59 93.867,-345.929 1.594,-2.27 71.125,-3.641 73.496,-3.641 l 1102.598,0 c 56.16,0 98.44,280.777 99.27,342.238 0.2,14.789 6.21,27.992 15.57,37.422 l 0,-17.48 c -7,-9.45 -11.46,-21.45 -11.79,-34.731 -1.73,-70.172 -43.48,-341.738 -103.05,-341.738"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1358"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1360"
+ d="m 1699.93,874.391 0,17.48 c 2.32,2.34 4.84,4.438 7.53,6.277 l 0,-15.418 c -2.74,-2.48 -5.27,-5.281 -7.53,-8.339 m -1399.891,15.48 c -2.238,3.238 -4.769,6.16 -7.535,8.699 l 0,7.551 c 2.703,-1.832 5.223,-3.949 7.535,-6.32 l 0,-9.93"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1346"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1348"
+ d="m 1707.46,882.73 0,15.418 c 2.39,1.633 4.91,3.051 7.54,4.243 l 0,-13.942 c -2.65,-1.66 -5.17,-3.57 -7.54,-5.719 M 292.504,898.57 c -2.352,2.16 -4.871,4.039 -7.531,5.61 l 0,6.082 c 2.629,-1.141 5.152,-2.524 7.531,-4.141 l 0,-7.551"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1334"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1336"
+ d="m 1715,888.449 0,13.942 c 2.43,1.097 4.95,2 7.54,2.679 l 0,-12.73 c -2.6,-1.07 -5.12,-2.371 -7.54,-3.891 M 284.973,904.18 c -2.407,1.422 -4.926,2.582 -7.535,3.461 l 0,5.078 c 2.593,-0.59 5.113,-1.418 7.535,-2.457 l 0,-6.082"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1322"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1324"
+ d="m 1722.54,892.34 0,12.73 c 2.21,0.59 4.48,1.02 6.78,1.282 0.25,0.019 0.5,0.046 0.75,0.07 l 0,-11.692 c -0.31,-0.07 -0.62,-0.14 -0.93,-0.218 -2.24,-0.551 -4.45,-1.282 -6.6,-2.172 M 277.438,907.641 c -2.297,0.769 -4.661,1.328 -7.075,1.64 -0.152,0 -0.304,0 -0.457,0 l 0,4.449 c 0.153,0 0.305,0 0.457,0 2.41,-0.14 4.774,-0.48 7.075,-1.011 l 0,-5.078"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1310"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1312"
+ d="m 1730.07,894.73 0,11.692 c 1.57,0.148 3.11,0.226 4.64,0.226 0.97,0 1.94,-0.027 2.9,-0.089 l 0,-10.719 c -2.43,-0.16 -4.95,-0.52 -7.54,-1.11 m -1467.695,13.258 0,4.821 c 2.445,0.57 4.965,0.882 7.531,0.921 l 0,-4.449 c -2.578,-0.051 -5.094,-0.5 -7.531,-1.293"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1298"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1300"
+ d="m 1745.14,895.641 c -1.55,0.187 -3.15,0.289 -4.8,0.289 -0.9,0 -1.81,-0.032 -2.73,-0.09 l 0,10.719 c 2.6,-0.168 5.12,-0.547 7.53,-1.129 l 0,-9.789 m -1490.3,8.687 0,5.871 c 2.418,1.133 4.937,2.012 7.535,2.61 l 0,-4.821 c -2.613,-0.847 -5.133,-2.097 -7.535,-3.66"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1286"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1288"
+ d="m 1752.68,893.809 c -2.33,0.871 -4.86,1.492 -7.54,1.832 l 0,9.789 c 2.65,-0.641 5.17,-1.532 7.54,-2.629 l 0,-8.992 m -1505.371,4.211 0,7.652 c 2.375,1.769 4.894,3.297 7.531,4.527 l 0,-5.871 c -2.668,-1.738 -5.195,-3.879 -7.531,-6.308"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1274"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1276"
+ d="m 295.449,332.41 c -22.629,15.66 -40.023,38.371 -48.976,64.922 11.336,-25.16 28.183,-47.32 48.976,-64.922 m 1409.251,0.102 c 20.64,17.488 37.38,39.476 48.69,64.437 -8.97,-26.34 -26.25,-48.871 -48.69,-64.437 M 239.773,888.18 l 0,10.539 c 2.293,2.59 4.821,4.929 7.536,6.953 l 0,-7.652 c -2.797,-2.911 -5.332,-6.25 -7.536,-9.84 m 1520.447,1.41 c -2.2,1.75 -4.73,3.172 -7.54,4.219 l 0,8.992 c 2.72,-1.262 5.24,-2.801 7.54,-4.602 l 0,-8.609"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1262"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1264"
+ d="m 1678.84,314.18 c 9.15,5.359 17.8,11.5 25.86,18.332 22.44,15.566 39.72,38.097 48.69,64.437 6.97,15.383 11.87,31.879 14.36,49.16 l 0,-3.3 c 0,-10.207 -1.12,-20.18 -3.24,-29.77 -10.79,-32.391 -30.15,-60.891 -55.38,-82.801 -9.32,-6.547 -19.48,-11.968 -30.29,-16.058 m -1357.668,0.011 c -10.746,4.071 -20.86,9.45 -30.133,15.95 -25.406,22.019 -44.883,50.738 -55.656,83.379 -2.055,9.441 -3.141,19.25 -3.141,29.289 l 0,3.543 c 2.457,-17.223 7.32,-33.672 14.231,-49.02 8.953,-26.551 26.347,-49.262 48.976,-64.922 8.02,-6.781 16.617,-12.879 25.723,-18.219 m -88.93,556.5 0,17.098 c 2.078,3.941 4.617,7.633 7.531,10.93 l 0,-10.539 c -3.343,-5.45 -5.929,-11.481 -7.531,-17.489 m 1535.508,8.75 c -1.6,4.039 -4.18,7.481 -7.53,10.149 l 0,8.609 c 2.91,-2.301 5.45,-5 7.53,-8.039 l 0,-10.719"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1250"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1252"
+ d="m 1658.94,304.109 c 6.86,2.95 13.5,6.321 19.9,10.071 10.81,4.09 20.97,9.511 30.29,16.058 -7.95,-6.898 -16.48,-13.136 -25.51,-18.648 -7.91,-3.192 -16.16,-5.711 -24.68,-7.481 m -1317.92,0.02 c -8.497,1.769 -16.727,4.281 -24.614,7.473 -8.972,5.468 -17.457,11.679 -25.367,18.539 9.273,-6.5 19.387,-11.879 30.133,-15.95 6.379,-3.742 13.008,-7.113 19.848,-10.062 m 1423.49,108.91 c 2.12,9.59 3.24,19.563 3.24,29.77 l 0,3.3 c 1.24,8.571 1.88,17.332 1.88,26.243 l 0,396.878 c 0,3.711 -0.66,7.141 -1.88,10.211 l 0,10.719 c 4.03,-5.879 6.33,-13.031 6.33,-20.93 l 0,-396.878 c 0,-20.711 -3.36,-40.653 -9.57,-59.313 M 235.383,413.52 c -6.11,18.519 -9.422,38.3 -9.422,58.832 l 0,391.027 c 0,8.359 2.293,16.84 6.281,24.41 l 0,-17.098 c -1.195,-4.492 -1.84,-8.961 -1.84,-13.171 l 0,-385.168 c 0,-8.821 0.629,-17.512 1.84,-26 l 0,-3.543 c 0,-10.039 1.086,-19.848 3.141,-29.289"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1238"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1240"
+ d="m 1640.27,297.25 c 6.38,1.949 12.61,4.238 18.67,6.859 8.52,1.77 16.77,4.289 24.68,7.481 -6.54,-3.988 -13.34,-7.59 -20.37,-10.762 -7.46,-1.746 -15.14,-2.957 -22.98,-3.578 m -1280.61,0.012 c -7.824,0.629 -15.48,1.84 -22.933,3.59 -7.008,3.168 -13.797,6.769 -20.321,10.75 7.887,-3.192 16.117,-5.704 24.614,-7.473 6.054,-2.617 12.269,-4.918 18.64,-6.867"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1226"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1228"
+ d="m 1652.53,296.379 -15.18,0 c 0.98,0.281 1.95,0.57 2.92,0.871 7.84,0.621 15.52,1.832 22.98,3.578 -3.52,-1.59 -7.09,-3.078 -10.72,-4.449 m -1289.913,0 -15.14,0 c -3.641,1.383 -7.219,2.871 -10.75,4.473 7.453,-1.75 15.109,-2.961 22.933,-3.59 0.981,-0.301 1.969,-0.602 2.957,-0.883"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1214"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1216"
+ d="m 1585.09,512.211 -1102.598,0 c -2.371,0 -71.902,1.371 -73.496,3.641 -53.008,7.339 -93.445,287.687 -93.867,345.929 -0.074,15.059 -5.883,28.547 -15.09,38.02 l 0,8.461 c 11.797,-8.934 19.387,-23.082 19.387,-39.032 0,-52.75 42.836,-342.742 95.48,-342.742 l 1170.184,0 c 52.74,0 95.48,289.992 95.48,342.742 0,15.911 7.62,30.032 19.36,38.961 l 0,-16.32 c -9.36,-9.43 -15.37,-22.633 -15.57,-37.422 -0.83,-61.461 -43.11,-342.238 -99.27,-342.238"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1202"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1204"
+ d="m 1699.93,891.871 0,16.32 c 2.35,1.789 4.88,3.379 7.53,4.731 l 0,-14.774 c -2.69,-1.839 -5.21,-3.937 -7.53,-6.277 m -1399.891,7.93 c -2.312,2.371 -4.832,4.488 -7.535,6.32 l 0,6.828 c 2.66,-1.34 5.18,-2.91 7.535,-4.687 l 0,-8.461"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1190"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1192"
+ d="m 1707.46,898.148 0,14.774 c 2.41,1.219 4.93,2.25 7.54,3.058 l 0,-13.589 c -2.63,-1.192 -5.15,-2.61 -7.54,-4.243 m -1414.956,7.973 c -2.379,1.617 -4.902,3 -7.531,4.141 l 0,5.726 c 2.613,-0.808 5.129,-1.828 7.531,-3.039 l 0,-6.828"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1178"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1180"
+ d="m 1715,902.391 0,13.589 c 2.44,0.758 4.95,1.329 7.54,1.7 l 0,-12.61 c -2.59,-0.679 -5.11,-1.582 -7.54,-2.679 m -1430.027,7.871 c -2.422,1.039 -4.942,1.867 -7.535,2.457 l 0,4.961 c 2.585,-0.371 5.101,-0.942 7.535,-1.692 l 0,-5.726"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1166"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1168"
+ d="m 1722.54,905.07 0,12.61 c 2.28,0.332 4.6,0.5 6.97,0.5 l 0,0 c 0.19,0 0.38,0 0.56,0 l 0,-11.758 c -0.25,-0.024 -0.5,-0.051 -0.75,-0.07 -2.3,-0.262 -4.57,-0.692 -6.78,-1.282 m -1445.102,7.649 c -2.301,0.531 -4.665,0.871 -7.075,1.011 -0.152,0 -0.304,0 -0.457,0 l 0,4.45 c 0.153,0 0.305,0 0.457,0 l 0,0 c 2.403,0 4.766,-0.168 7.075,-0.5 l 0,-4.961"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1154"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1156"
+ d="m 1730.07,906.422 0,11.758 c 2.57,-0.032 5.08,-0.258 7.54,-0.66 l 0,-10.961 c -0.96,0.062 -1.93,0.089 -2.9,0.089 -1.53,0 -3.07,-0.078 -4.64,-0.226 m -1467.695,6.387 0,4.722 c 2.453,0.399 4.969,0.617 7.531,0.649 l 0,-4.45 c -2.566,-0.039 -5.086,-0.351 -7.531,-0.921"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1142"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1144"
+ d="m 1745.14,905.43 c -2.41,0.582 -4.93,0.961 -7.53,1.129 l 0,10.961 c 2.58,-0.43 5.1,-1.051 7.53,-1.872 l 0,-10.218 m -1490.3,4.769 0,5.461 c 2.433,0.82 4.949,1.442 7.535,1.871 l 0,-4.722 c -2.598,-0.598 -5.117,-1.477 -7.535,-2.61"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1130"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1132"
+ d="m 1752.68,902.801 c -2.37,1.097 -4.89,1.988 -7.54,2.629 l 0,10.218 c 2.62,-0.867 5.14,-1.957 7.54,-3.238 l 0,-9.609 m -1505.371,2.871 0,6.726 c 2.398,1.293 4.914,2.383 7.531,3.262 l 0,-5.461 c -2.637,-1.23 -5.156,-2.758 -7.531,-4.527"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1118"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1120"
+ d="m 1760.22,898.199 c -2.3,1.801 -4.82,3.34 -7.54,4.602 l 0,9.609 c 2.67,-1.43 5.19,-3.101 7.54,-4.98 l 0,-9.231 m -1520.447,0.52 0,8.691 c 2.344,1.879 4.868,3.559 7.536,4.988 l 0,-6.726 c -2.715,-2.024 -5.243,-4.363 -7.536,-6.953"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1106"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1108"
+ d="m 291.039,330.141 c -27.859,19.507 -48.18,49.07 -55.656,83.379 10.773,-32.641 30.25,-61.36 55.656,-83.379 m 1418.091,0.097 c 25.23,21.91 44.59,50.41 55.38,82.801 -7.55,-34.027 -27.75,-63.379 -55.38,-82.801 m -1476.888,557.551 0,12.063 c 2.231,2.789 4.754,5.32 7.531,7.558 l 0,-8.691 c -2.914,-3.297 -5.453,-6.989 -7.531,-10.93 m 1535.508,2.371 c -2.08,3.039 -4.62,5.738 -7.53,8.039 l 0,9.231 c 2.77,-2.219 5.3,-4.739 7.53,-7.508 l 0,-9.762"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1094"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1096"
+ d="m 1683.62,311.59 c 9.03,5.512 17.56,11.75 25.51,18.648 27.63,19.422 47.83,48.774 55.38,82.801 6.21,18.66 9.57,38.602 9.57,59.313 l 0,396.878 c 0,7.899 -2.3,15.051 -6.33,20.93 l 0,9.762 c 3.15,-3.91 5.71,-8.32 7.54,-13.082 l 0,-439.551 c 0,-4.551 -0.21,-9.059 -0.62,-13.508 -8.47,-41.609 -30.38,-78.429 -60.98,-105.703 -9.28,-6.609 -19.36,-12.168 -30.07,-16.488 m -1367.214,0.012 c -10.644,4.289 -20.672,9.796 -29.91,16.359 -30.805,27.398 -52.824,64.48 -61.223,106.398 -0.371,4.262 -0.562,8.582 -0.562,12.93 l 0,439.383 c 1.824,4.808 4.379,9.238 7.531,13.18 l 0,-12.063 c -3.988,-7.57 -6.281,-16.051 -6.281,-24.41 l 0,-391.027 c 0,-20.532 3.312,-40.313 9.422,-58.832 7.476,-34.309 27.797,-63.872 55.656,-83.379 7.91,-6.86 16.395,-13.071 25.367,-18.539"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1082"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1084"
+ d="m 1663.25,300.828 c 7.03,3.172 13.83,6.774 20.37,10.762 10.71,4.32 20.79,9.879 30.07,16.488 -7.77,-6.93 -16.12,-13.238 -24.94,-18.859 -8.16,-3.508 -16.69,-6.328 -25.5,-8.391 m -1326.523,0.024 c -8.782,2.058 -17.278,4.867 -25.418,8.359 -8.778,5.59 -17.071,11.859 -24.813,18.75 9.238,-6.563 19.266,-12.07 29.91,-16.359 6.524,-3.981 13.313,-7.582 20.321,-10.75 M 1774.67,433.781 c 0.41,4.449 0.62,8.957 0.62,13.508 l 0,439.551 c 2.1,-5.461 3.25,-11.399 3.25,-17.61 l 0,-396.878 c 0,-13.211 -1.33,-26.102 -3.87,-38.571 m -1549.397,0.578 c -2.461,12.289 -3.75,24.993 -3.75,37.993 l 0,396.878 c 0,6.149 1.125,12.032 3.188,17.442 l 0,-439.383 c 0,-4.348 0.191,-8.668 0.562,-12.93"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <clipPath
+ id="clipPath1070"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1072"
+ d="m 1665.11,296.379 -12.58,0 c 3.63,1.371 7.2,2.859 10.72,4.449 8.81,2.063 17.34,4.883 25.5,8.391 -7.55,-4.809 -15.44,-9.098 -23.64,-12.84 m -1317.633,0 -12.543,0 c -8.2,3.73 -16.086,8.031 -23.625,12.832 8.14,-3.492 16.636,-6.301 25.418,-8.359 3.531,-1.602 7.109,-3.09 10.75,-4.473"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient1054"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop1056"
+ offset="0"
+ style="stop-opacity:1;stop-color:#ededed" />
+ <stop
+ id="stop1058"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d4d3d2" />
+ <stop
+ id="stop1060"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d4d3d2" />
+ <stop
+ id="stop1062"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e7e8e6" />
+ </linearGradient>
+ <clipPath
+ id="clipPath1050"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1052"
+ d="m 1571.32,292.398 -1142.73,0 c -11.457,0 -32.172,1.383 -45.977,3.981 l 1234.707,0 c -13.91,-2.598 -34.53,-3.981 -46,-3.981"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient1034"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop1036"
+ offset="0"
+ style="stop-opacity:1;stop-color:#ececec" />
+ <stop
+ id="stop1038"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d3d3d2" />
+ <stop
+ id="stop1040"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d3d3d2" />
+ <stop
+ id="stop1042"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e7e8e6" />
+ </linearGradient>
+ <clipPath
+ id="clipPath1030"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1032"
+ d="m 1604.44,289.719 -1208.948,0 c -9.25,1.07 -18.258,2.601 -25,4.582 -2.644,0.629 -5.273,1.328 -7.875,2.078 l 19.996,0 c 13.805,-2.598 34.52,-3.981 45.977,-3.981 l 1142.73,0 c 11.47,0 32.09,1.383 46,3.981 l 20.03,0 c -2.48,-0.707 -4.97,-1.367 -7.49,-1.981 -6.84,-2.027 -16.02,-3.597 -25.42,-4.679"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient1014"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop1016"
+ offset="0"
+ style="stop-opacity:1;stop-color:#e9e9e8" />
+ <stop
+ id="stop1018"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#cfcecd" />
+ <stop
+ id="stop1020"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#cfcecd" />
+ <stop
+ id="stop1022"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e3e3e1" />
+ </linearGradient>
+ <clipPath
+ id="clipPath1010"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path1012"
+ d="m 1575.91,287.949 -1151.883,0 c -8.043,0 -18.433,0.61 -28.535,1.77 l 1208.948,0 c -10.11,-1.16 -20.48,-1.77 -28.53,-1.77"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient994"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop996"
+ offset="0"
+ style="stop-opacity:1;stop-color:#ececec" />
+ <stop
+ id="stop998"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d3d0d1" />
+ <stop
+ id="stop1000"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d3d0d1" />
+ <stop
+ id="stop1002"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e6e6e5" />
+ </linearGradient>
+ <clipPath
+ id="clipPath990"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path992"
+ d="m 1629.14,289.719 -24.7,0 c 9.4,1.082 18.58,2.652 25.42,4.679 2.52,0.614 5.01,1.274 7.49,1.981 l 15.18,0 c -5.77,-2.188 -11.67,-4.098 -17.69,-5.719 -1.08,-0.308 -2.18,-0.621 -3.31,-0.922 -0.8,-0.008 -1.59,-0.019 -2.39,-0.019 m -1233.648,0 -24.543,0 c -0.824,0 -1.648,0.011 -2.472,0.019 -0.993,0.262 -1.965,0.532 -2.918,0.813 -6.157,1.64 -12.188,3.59 -18.082,5.828 l 15.14,0 c 2.602,-0.75 5.231,-1.449 7.875,-2.078 6.742,-1.981 15.75,-3.512 25,-4.582"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient974"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop976"
+ offset="0"
+ style="stop-opacity:1;stop-color:#e8e8e7" />
+ <stop
+ id="stop978"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#cecdcc" />
+ <stop
+ id="stop980"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#cecdcc" />
+ <stop
+ id="stop982"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e2e2e0" />
+ </linearGradient>
+ <clipPath
+ id="clipPath970"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path972"
+ d="m 1580.5,283.5 -1161.031,0 c -16.082,0 -35.692,2.172 -50.992,6.238 0.824,-0.008 1.648,-0.019 2.472,-0.019 l 24.543,0 c 10.102,-1.16 20.492,-1.77 28.535,-1.77 l 1151.883,0 c 8.05,0 18.42,0.61 28.53,1.77 l 24.7,0 c 0.8,0 1.59,0.011 2.39,0.019 -15.36,-4.066 -34.94,-6.238 -51.03,-6.238"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient954"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop956"
+ offset="0"
+ style="stop-opacity:1;stop-color:#ebeceb" />
+ <stop
+ id="stop958"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d0cfce" />
+ <stop
+ id="stop960"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d0cfce" />
+ <stop
+ id="stop962"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e5e5e4" />
+ </linearGradient>
+ <clipPath
+ id="clipPath950"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path952"
+ d="m 1631.53,289.738 c 1.13,0.301 2.23,0.614 3.31,0.922 6.02,1.621 11.92,3.531 17.69,5.719 l 12.58,0 c -3.71,-1.688 -7.49,-3.27 -11.32,-4.731 -7.27,-1.148 -14.7,-1.796 -22.26,-1.91 m -1263.053,0 c -7.559,0.121 -14.997,0.774 -22.262,1.922 -3.82,1.461 -7.578,3.031 -11.281,4.719 l 12.543,0 c 5.894,-2.238 11.925,-4.188 18.082,-5.828 0.953,-0.281 1.925,-0.551 2.918,-0.813"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient934"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop936"
+ offset="0"
+ style="stop-opacity:1;stop-color:#e7e8e6" />
+ <stop
+ id="stop938"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#cbcbc8" />
+ <stop
+ id="stop940"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#cbcbc8" />
+ <stop
+ id="stop942"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e2e1df" />
+ </linearGradient>
+ <clipPath
+ id="clipPath930"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path932"
+ d="m 1622.5,282.68 -1244.98,0 c -10.778,2.121 -21.247,5.14 -31.305,8.98 7.265,-1.148 14.703,-1.801 22.262,-1.922 15.3,-4.066 34.91,-6.238 50.992,-6.238 l 1161.031,0 c 16.09,0 35.67,2.172 51.03,6.238 7.56,0.114 14.99,0.762 22.26,1.91 -10.05,-3.828 -20.52,-6.847 -31.29,-8.968"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient914"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop916"
+ offset="0"
+ style="stop-opacity:1;stop-color:#e2e2e0" />
+ <stop
+ id="stop918"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#c7c6c4" />
+ <stop
+ id="stop920"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#c7c6c4" />
+ <stop
+ id="stop922"
+ offset="1"
+ style="stop-opacity:1;stop-color:#dddbd9" />
+ </linearGradient>
+ <clipPath
+ id="clipPath910"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path912"
+ d="m 1585.09,279.051 -1170.184,0 c -12.785,0 -25.285,1.25 -37.386,3.629 l 1244.98,0 c -12.11,-2.379 -24.62,-3.629 -37.41,-3.629"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient894"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop896"
+ offset="0"
+ style="stop-opacity:1;stop-color:#ffffff" />
+ <stop
+ id="stop898"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e4e4e3" />
+ <stop
+ id="stop900"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e4e4e3" />
+ <stop
+ id="stop902"
+ offset="1"
+ style="stop-opacity:1;stop-color:#fafafa" />
+ </linearGradient>
+ <clipPath
+ id="clipPath890"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path892"
+ d="m 1585.09,526.488 -1170.184,0 c -52.644,0 -95.48,289.992 -95.48,342.742 0,15.95 -7.59,30.098 -19.387,39.032 l 0,533.128 c 9.59,8.99 15.578,21.76 15.578,35.91 0,52.94 43.024,150.28 95.957,150.28 l 1176.856,0 c 53.02,0 96.11,-97.34 96.11,-150.28 0,-14.07 5.91,-26.77 15.39,-35.75 l 0,-533.359 c -11.74,-8.929 -19.36,-23.05 -19.36,-38.961 0,-52.75 -42.74,-342.742 -95.48,-342.742"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient874"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop876"
+ offset="0"
+ style="stop-opacity:1;stop-color:#ffffff" />
+ <stop
+ id="stop878"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e2e2e0" />
+ <stop
+ id="stop880"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e2e2e0" />
+ <stop
+ id="stop882"
+ offset="1"
+ style="stop-opacity:1;stop-color:#f9f9f9" />
+ </linearGradient>
+ <clipPath
+ id="clipPath870"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path872"
+ d="m 1699.93,908.191 0,533.359 c 2.31,-2.19 4.83,-4.16 7.53,-5.87 l 0,-522.758 c -2.65,-1.352 -5.18,-2.942 -7.53,-4.731 m -1399.891,0.071 c -2.355,1.777 -4.875,3.347 -7.535,4.687 l 0,522.641 c 2.699,1.69 5.223,3.64 7.535,5.8 l 0,-533.128"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient854"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop856"
+ offset="0"
+ style="stop-opacity:1;stop-color:#feffff" />
+ <stop
+ id="stop858"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e2e1df" />
+ <stop
+ id="stop860"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e2e1df" />
+ <stop
+ id="stop862"
+ offset="1"
+ style="stop-opacity:1;stop-color:#f8f9f9" />
+ </linearGradient>
+ <clipPath
+ id="clipPath850"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path852"
+ d="m 1707.46,912.922 0,522.758 c 2.38,-1.51 4.9,-2.82 7.54,-3.9 l 0,-515.8 c -2.61,-0.808 -5.13,-1.839 -7.54,-3.058 m -1414.956,0.027 c -2.402,1.211 -4.918,2.231 -7.531,3.039 l 0,515.732 c 2.632,1.08 5.148,2.37 7.531,3.87 l 0,-522.641"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient834"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop836"
+ offset="0"
+ style="stop-opacity:1;stop-color:#fcfcfc" />
+ <stop
+ id="stop838"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e1e0df" />
+ <stop
+ id="stop840"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#e1e0df" />
+ <stop
+ id="stop842"
+ offset="1"
+ style="stop-opacity:1;stop-color:#f6f6f6" />
+ </linearGradient>
+ <clipPath
+ id="clipPath830"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path832"
+ d="m 1715,915.98 0,515.8 c 2.42,-1 4.94,-1.82 7.54,-2.42 l 0,-511.68 c -2.59,-0.371 -5.1,-0.942 -7.54,-1.7 m -1430.027,0.008 c -2.434,0.75 -4.95,1.321 -7.535,1.692 l 0,511.65 c 2.597,0.6 5.113,1.4 7.535,2.39 l 0,-515.732"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient814"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop816"
+ offset="0"
+ style="stop-opacity:1;stop-color:#fafafa" />
+ <stop
+ id="stop818"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dfdedc" />
+ <stop
+ id="stop820"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dfdedc" />
+ <stop
+ id="stop822"
+ offset="1"
+ style="stop-opacity:1;stop-color:#f5f5f4" />
+ </linearGradient>
+ <clipPath
+ id="clipPath810"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path812"
+ d="m 277.438,917.68 c -2.309,0.332 -4.672,0.5 -7.075,0.5 l 0,0 0,0 c -0.152,0 -0.304,0 -0.457,0 l 0,510.02 c 2.571,0.19 5.086,0.57 7.532,1.13 l 0,-511.65 m 1445.102,0 0,511.68 c 2.44,-0.57 4.96,-0.96 7.53,-1.15 l 0,-510.03 c -0.18,0 -0.37,0 -0.56,0 l 0,0 0,0 c -2.37,0 -4.69,-0.168 -6.97,-0.5"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient794"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop796"
+ offset="0"
+ style="stop-opacity:1;stop-color:#fafafa" />
+ <stop
+ id="stop798"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dedcdb" />
+ <stop
+ id="stop800"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dedcdb" />
+ <stop
+ id="stop802"
+ offset="1"
+ style="stop-opacity:1;stop-color:#f3f3f3" />
+ </linearGradient>
+ <clipPath
+ id="clipPath790"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path792"
+ d="m 1737.61,917.52 c -2.46,0.402 -4.97,0.628 -7.54,0.66 l 0,510.03 c 1.23,-0.09 2.47,-0.14 3.72,-0.14 1.28,0 2.56,0.05 3.82,0.15 l 0,-510.7 m -1475.235,0.011 0,510.699 c 1.297,-0.11 2.609,-0.16 3.93,-0.16 1.211,0 2.414,0.04 3.601,0.13 l 0,-510.02 c -2.562,-0.032 -5.078,-0.25 -7.531,-0.649"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient774"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop776"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f8f9f9" />
+ <stop
+ id="stop778"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dbdad8" />
+ <stop
+ id="stop780"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dbdad8" />
+ <stop
+ id="stop782"
+ offset="1"
+ style="stop-opacity:1;stop-color:#f1f1f0" />
+ </linearGradient>
+ <clipPath
+ id="clipPath770"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path772"
+ d="m 1745.14,915.648 c -2.43,0.821 -4.95,1.442 -7.53,1.872 l 0,510.7 c 2.57,0.2 5.09,0.59 7.53,1.17 l 0,-513.742 m -1490.3,0.012 0,513.76 c 2.449,-0.59 4.961,-0.99 7.535,-1.19 l 0,-510.699 c -2.586,-0.429 -5.102,-1.051 -7.535,-1.871"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient754"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop756"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f7f7f7" />
+ <stop
+ id="stop758"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dad9d8" />
+ <stop
+ id="stop760"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#dad9d8" />
+ <stop
+ id="stop762"
+ offset="1"
+ style="stop-opacity:1;stop-color:#eff0ef" />
+ </linearGradient>
+ <clipPath
+ id="clipPath750"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path752"
+ d="m 247.309,912.398 0,519.482 c 2.418,-1.01 4.937,-1.84 7.531,-2.46 l 0,-513.76 c -2.617,-0.879 -5.133,-1.969 -7.531,-3.262 m 1505.371,0.012 c -2.4,1.281 -4.92,2.371 -7.54,3.238 l 0,513.742 c 2.6,0.62 5.12,1.44 7.54,2.45 l 0,-519.43"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient734"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop736"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f6f6f6" />
+ <stop
+ id="stop738"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d8d7d5" />
+ <stop
+ id="stop740"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d8d7d5" />
+ <stop
+ id="stop742"
+ offset="1"
+ style="stop-opacity:1;stop-color:#ededed" />
+ </linearGradient>
+ <clipPath
+ id="clipPath730"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path732"
+ d="m 239.773,907.41 0,528.43 c 2.379,-1.52 4.899,-2.85 7.536,-3.96 l 0,-519.482 c -2.668,-1.429 -5.192,-3.109 -7.536,-4.988 m 1520.447,0.02 c -2.35,1.879 -4.87,3.55 -7.54,4.98 l 0,519.43 c 2.64,1.11 5.16,2.43 7.54,3.95 l 0,-528.36"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient714"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop716"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f3f3f3" />
+ <stop
+ id="stop718"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d7d6d4" />
+ <stop
+ id="stop720"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d7d6d4" />
+ <stop
+ id="stop722"
+ offset="1"
+ style="stop-opacity:1;stop-color:#ebeceb" />
+ </linearGradient>
+ <clipPath
+ id="clipPath710"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path712"
+ d="m 232.242,899.852 0,541.938 c 2.309,-2.22 4.828,-4.21 7.531,-5.95 l 0,-528.43 c -2.777,-2.238 -5.3,-4.769 -7.531,-7.558 m 1535.508,0.07 c -2.23,2.769 -4.76,5.289 -7.53,7.508 l 0,528.36 c 2.7,1.74 5.22,3.73 7.53,5.94 l 0,-541.808"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient694"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop696"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f2f2f2" />
+ <stop
+ id="stop698"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d5d4d3" />
+ <stop
+ id="stop700"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d5d4d3" />
+ <stop
+ id="stop702"
+ offset="1"
+ style="stop-opacity:1;stop-color:#eaebe9" />
+ </linearGradient>
+ <clipPath
+ id="clipPath690"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path692"
+ d="m 286.496,327.961 c -34.055,24.168 -57.363,62.539 -61.223,106.398 8.399,-41.918 30.418,-79 61.223,-106.398 m 1427.194,0.117 c 30.6,27.274 52.51,64.094 60.98,105.703 -4.01,-43.551 -27.18,-81.633 -60.98,-105.703 m -1488.979,558.594 0,564.328 c 2.133,-3.37 4.668,-6.46 7.531,-9.21 l 0,-541.938 c -3.152,-3.942 -5.707,-8.372 -7.531,-13.18 m 1550.579,0.168 c -1.83,4.762 -4.39,9.172 -7.54,13.082 l 0,541.808 c 2.87,2.75 5.4,5.84 7.54,9.22 l 0,-564.11 m -1537.372,847.2 c 6.375,13.91 14.867,26.66 25.066,37.84 -9.754,-11.55 -18.183,-24.23 -25.066,-37.84 m 1524.152,0.03 c -6.9,13.63 -15.35,26.34 -25.13,37.89 10.22,-11.18 18.74,-23.95 25.13,-37.89"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient674"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop676"
+ offset="0"
+ style="stop-opacity:1;stop-color:#eff0ef" />
+ <stop
+ id="stop678"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d3d3d2" />
+ <stop
+ id="stop680"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d3d3d2" />
+ <stop
+ id="stop682"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e8e8e7" />
+ </linearGradient>
+ <clipPath
+ id="clipPath670"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path672"
+ d="m 311.309,309.211 c -55.301,23.699 -94.133,78.68 -94.133,142.559 l 0,1022.5 c 0.519,-8.52 3.215,-16.46 7.535,-23.27 l 0,-564.328 c -2.063,-5.41 -3.188,-11.293 -3.188,-17.442 l 0,0 0,-396.878 0,0 c 0,-13 1.289,-25.704 3.75,-37.993 3.86,-43.859 27.168,-82.23 61.223,-106.398 7.742,-6.891 16.035,-13.16 24.813,-18.75 m 1377.441,0.008 c 8.82,5.621 17.17,11.929 24.94,18.859 33.8,24.07 56.97,62.152 60.98,105.703 2.54,12.469 3.87,25.36 3.87,38.571 l 0,396.878 c 0,6.211 -1.15,12.149 -3.25,17.61 l 0,564.11 c 4.32,6.82 7.01,14.78 7.53,23.32 l 0,-1022.5 c 0,-63.879 -38.82,-118.848 -94.07,-142.551 m 94.07,1343.301 c -0.89,29.26 -8.28,56.91 -20.75,81.55 -6.39,13.94 -14.91,26.71 -25.13,37.89 -15.97,18.88 -35.47,34.68 -57.47,46.39 60.14,-21.33 103.35,-78.86 103.35,-146.17 l 0,-19.66 m -1565.644,0 0,19.66 c 0,67.26 43.152,124.75 103.262,146.12 -21.997,-11.72 -41.489,-27.53 -57.454,-46.42 -10.199,-11.18 -18.691,-23.93 -25.066,-37.84 -12.469,-24.63 -19.848,-52.27 -20.742,-81.52"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient654"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop656"
+ offset="0"
+ style="stop-opacity:1;stop-color:#ebeceb" />
+ <stop
+ id="stop658"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d0cfce" />
+ <stop
+ id="stop660"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#d0cfce" />
+ <stop
+ id="stop662"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e5e5e4" />
+ </linearGradient>
+ <clipPath
+ id="clipPath650"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path652"
+ d="m 1653.79,291.648 c 3.83,1.461 7.61,3.043 11.32,4.731 8.2,3.742 16.09,8.031 23.64,12.84 55.25,23.703 94.07,78.672 94.07,142.551 l 0,1022.5 c 0.06,1 0.1,2.02 0.1,3.03 l 0,169.19 c 0,2.02 -0.04,4.03 -0.1,6.03 l 0,19.66 c 0,67.31 -43.21,124.84 -103.35,146.17 -3.4,1.81 -6.85,3.51 -10.37,5.12 -3.85,1.76 -7.77,3.41 -11.76,4.92 73.41,-13.35 129.27,-77.85 129.27,-155.04 l 0,-1226.061 c 0,-78.488 -57.67,-143.758 -132.82,-155.641 M 346.215,291.66 c -75.188,11.899 -132.824,77.149 -132.824,155.629 l 0,1226.061 c 0,77.15 55.8,141.62 129.214,155.02 -3.968,-1.51 -7.867,-3.14 -11.707,-4.9 -3.543,-1.62 -7.035,-3.35 -10.46,-5.17 -60.11,-21.37 -103.262,-78.86 -103.262,-146.12 l 0,-19.66 c -0.063,-2 -0.09,-4.01 -0.09,-6.03 l 0,0 0,-169.19 0,0 c 0,-1.01 0.027,-2.02 0.09,-3.03 l 0,-1022.5 c 0,-63.879 38.832,-118.86 94.133,-142.559 7.539,-4.801 15.425,-9.102 23.625,-12.832 3.703,-1.688 7.461,-3.258 11.281,-4.719"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient634"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop636"
+ offset="0"
+ style="stop-opacity:1;stop-color:#e7e8e6" />
+ <stop
+ id="stop638"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#cbcbc8" />
+ <stop
+ id="stop640"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#cbcbc8" />
+ <stop
+ id="stop642"
+ offset="1"
+ style="stop-opacity:1;stop-color:#e2e1df" />
+ </linearGradient>
+ <clipPath
+ id="clipPath630"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path632"
+ d="m 1630.35,282.68 -7.85,0 c 10.77,2.121 21.24,5.14 31.29,8.968 75.15,11.883 132.82,77.153 132.82,155.641 l 0,1226.061 c 0,77.19 -55.86,141.69 -129.27,155.04 -6.14,2.34 -12.42,4.36 -18.83,6.07 84.47,-4.26 151.88,-74.41 151.88,-159.94 l 0,-1231.711 c 0,-88.297 -71.79,-160.129 -160.04,-160.129 m -1252.83,0 -7.79,0 c -88.324,0 -160.125,71.832 -160.125,160.129 l 0,1231.711 c 0,85.5 67.368,155.63 151.872,159.94 -6.426,-1.71 -12.723,-3.75 -18.872,-6.09 -73.414,-13.4 -129.214,-77.87 -129.214,-155.02 l 0,-1226.061 c 0,-78.48 57.636,-143.73 132.824,-155.629 10.058,-3.84 20.527,-6.859 31.305,-8.98"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient614"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop616"
+ offset="0"
+ style="stop-opacity:1;stop-color:#e2e2e0" />
+ <stop
+ id="stop618"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#c7c6c4" />
+ <stop
+ id="stop620"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#c7c6c4" />
+ <stop
+ id="stop622"
+ offset="1"
+ style="stop-opacity:1;stop-color:#dddbd9" />
+ </linearGradient>
+ <clipPath
+ id="clipPath610"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path612"
+ d="m 1631.56,275.641 -1263.052,0 c -89.75,0 -162.688,72.98 -162.688,162.699 l 0,1237.35 c 0,89.7 72.938,162.72 162.688,162.72 l 11.332,0 c -6.227,-1.02 -12.352,-2.35 -18.363,-3.95 -84.504,-4.31 -151.872,-74.44 -151.872,-159.94 l 0,-1231.711 c 0,-88.297 71.801,-160.129 160.125,-160.129 l 7.79,0 c 12.101,-2.379 24.601,-3.629 37.386,-3.629 l 1170.184,0 c 12.79,0 25.3,1.25 37.41,3.629 l 7.85,0 c 88.25,0 160.04,71.832 160.04,160.129 l 0,1231.711 c 0,85.53 -67.41,155.68 -151.88,159.94 -6.01,1.61 -12.13,2.93 -18.35,3.95 l 11.4,0 c 89.68,0 162.62,-73.02 162.62,-162.72 l 0,-1237.35 c 0,-89.719 -72.94,-162.699 -162.62,-162.699"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient594"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop596"
+ offset="0"
+ style="stop-opacity:1;stop-color:#dfdedc" />
+ <stop
+ id="stop598"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#c2c1c0" />
+ <stop
+ id="stop600"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#c2c1c0" />
+ <stop
+ id="stop602"
+ offset="1"
+ style="stop-opacity:1;stop-color:#d8d7d5" />
+ </linearGradient>
+ <clipPath
+ id="clipPath590"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path592"
+ d="m 1632.77,268.609 -1265.485,0 c -91.172,0 -165.25,74.11 -165.25,165.25 l 0,1243.001 c 0,91.15 74.078,165.29 165.25,165.29 l 1265.485,0 c 91.12,0 165.19,-74.14 165.19,-165.29 l 0,-1243.001 c 0,-91.14 -74.07,-165.25 -165.19,-165.25 M 368.508,1838.41 c -89.75,0 -162.688,-73.02 -162.688,-162.72 l 0,-1237.35 c 0,-89.719 72.938,-162.699 162.688,-162.699 l 1263.052,0 c 89.68,0 162.62,72.98 162.62,162.699 l 0,1237.35 c 0,89.7 -72.94,162.72 -162.62,162.72 l -11.4,0 c -10.33,1.7 -20.93,2.59 -31.73,2.59 l 0,0 -1176.856,0 0,0 c -10.801,0 -21.406,-0.89 -31.734,-2.59 l -11.332,0"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient574"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop576"
+ offset="0"
+ style="stop-opacity:1;stop-color:#dad9d8" />
+ <stop
+ id="stop578"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#bfbdbb" />
+ <stop
+ id="stop580"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#bfbdbb" />
+ <stop
+ id="stop582"
+ offset="1"
+ style="stop-opacity:1;stop-color:#d3d3d2" />
+ </linearGradient>
+ <clipPath
+ id="clipPath570"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path572"
+ d="m 1633.99,261.57 -1267.928,0 c -92.597,0 -167.808,75.258 -167.808,167.821 l 0,1248.639 c 0,92.59 75.211,167.86 167.808,167.86 l 1267.928,0 c 92.55,0 167.76,-75.27 167.76,-167.86 l 0,-1248.639 c 0,-92.563 -75.21,-167.821 -167.76,-167.821 M 367.285,1842.15 c -91.172,0 -165.25,-74.14 -165.25,-165.29 l 0,-1243.001 c 0,-91.14 74.078,-165.25 165.25,-165.25 l 1265.485,0 c 91.12,0 165.19,74.11 165.19,165.25 l 0,1243.001 c 0,91.15 -74.07,165.29 -165.19,165.29 l -1265.485,0"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient554"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop556"
+ offset="0"
+ style="stop-opacity:1;stop-color:#d5d4d3" />
+ <stop
+ id="stop558"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#bbbab8" />
+ <stop
+ id="stop560"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#bbbab8" />
+ <stop
+ id="stop562"
+ offset="1"
+ style="stop-opacity:1;stop-color:#cfcecd" />
+ </linearGradient>
+ <clipPath
+ id="clipPath550"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path552"
+ d="m 1635.2,254.531 -1270.36,0 c -94.02,0 -170.371,76.41 -170.371,170.379 l 0,1254.29 c 0,94.03 76.351,170.44 170.371,170.44 l 1270.36,0 c 93.98,0 170.33,-76.41 170.33,-170.44 l 0,-1254.29 c 0,-93.969 -76.35,-170.379 -170.33,-170.379 M 366.062,1845.89 c -92.597,0 -167.808,-75.27 -167.808,-167.86 l 0,-1248.639 c 0,-92.563 75.211,-167.821 167.808,-167.821 l 1267.928,0 c 92.55,0 167.76,75.258 167.76,167.821 l 0,1248.639 c 0,92.59 -75.21,167.86 -167.76,167.86 l -1267.928,0"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient534"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop536"
+ offset="0"
+ style="stop-opacity:1;stop-color:#d1d1cf" />
+ <stop
+ id="stop538"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#b7b6b5" />
+ <stop
+ id="stop540"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#b7b6b5" />
+ <stop
+ id="stop542"
+ offset="1"
+ style="stop-opacity:1;stop-color:#cac9c8" />
+ </linearGradient>
+ <clipPath
+ id="clipPath530"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path532"
+ d="m 1636.41,247.488 -1272.793,0 c -95.441,0 -172.933,77.563 -172.933,172.942 l 0,1259.95 c 0,95.47 77.492,173 172.933,173 l 1272.793,0 c 95.42,0 172.91,-77.53 172.91,-173 l 0,-1259.95 c 0,-95.379 -77.49,-172.942 -172.91,-172.942 M 364.84,1849.64 c -94.02,0 -170.371,-76.41 -170.371,-170.44 l 0,-1254.29 c 0,-93.969 76.351,-170.379 170.371,-170.379 l 1270.36,0 c 93.98,0 170.33,76.41 170.33,170.379 l 0,1254.29 c 0,94.03 -76.35,170.44 -170.33,170.44 l -1270.36,0"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient514"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop516"
+ offset="0"
+ style="stop-opacity:1;stop-color:#cdccc9" />
+ <stop
+ id="stop518"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#b3b3b2" />
+ <stop
+ id="stop520"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#b3b3b2" />
+ <stop
+ id="stop522"
+ offset="1"
+ style="stop-opacity:1;stop-color:#c6c5c3" />
+ </linearGradient>
+ <clipPath
+ id="clipPath510"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path512"
+ d="m 1637.63,240.449 -1275.232,0 c -96.871,0 -175.5,78.699 -175.5,175.512 l 0,1265.589 c 0,96.91 78.629,175.57 175.5,175.57 l 1275.232,0 c 96.84,0 175.47,-78.66 175.47,-175.57 l 0,-1265.589 c 0,-96.813 -78.63,-175.512 -175.47,-175.512 M 363.617,1853.38 c -95.441,0 -172.933,-77.53 -172.933,-173 l 0,-1259.95 c 0,-95.379 77.492,-172.942 172.933,-172.942 l 1272.793,0 c 95.42,0 172.91,77.563 172.91,172.942 l 0,1259.95 c 0,95.47 -77.49,173 -172.91,173 l -1272.793,0"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient494"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop496"
+ offset="0"
+ style="stop-opacity:1;stop-color:#c7c6c4" />
+ <stop
+ id="stop498"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#aeaead" />
+ <stop
+ id="stop500"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#aeaead" />
+ <stop
+ id="stop502"
+ offset="1"
+ style="stop-opacity:1;stop-color:#c1c0bf" />
+ </linearGradient>
+ <clipPath
+ id="clipPath490"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path492"
+ d="m 1638.84,233.422 -1277.664,0 c -98.293,0 -178.063,79.84 -178.063,178.058 l 0,1271.24 c 0,98.36 79.77,178.14 178.063,178.14 l 1277.664,0 c 98.28,0 178.05,-79.78 178.05,-178.14 l 0,-1271.24 c 0,-98.218 -79.77,-178.058 -178.05,-178.058 M 362.398,1857.12 c -96.871,0 -175.5,-78.66 -175.5,-175.57 l 0,-1265.589 c 0,-96.813 78.629,-175.512 175.5,-175.512 l 1275.232,0 c 96.84,0 175.47,78.699 175.47,175.512 l 0,1265.589 c 0,96.91 -78.63,175.57 -175.47,175.57 l -1275.232,0"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient474"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop476"
+ offset="0"
+ style="stop-opacity:1;stop-color:#c2c1c0" />
+ <stop
+ id="stop478"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#ababaa" />
+ <stop
+ id="stop480"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#ababaa" />
+ <stop
+ id="stop482"
+ offset="1"
+ style="stop-opacity:1;stop-color:#bebcba" />
+ </linearGradient>
+ <clipPath
+ id="clipPath470"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path472"
+ d="m 1640.05,226.379 -1280.097,0 c -99.719,0 -180.625,80.992 -180.625,180.633 l 0,1276.878 c 0,99.8 80.906,180.72 180.625,180.72 l 1280.097,0 c 99.72,0 180.62,-80.92 180.62,-180.72 l 0,-1276.878 c 0,-99.641 -80.9,-180.633 -180.62,-180.633 M 361.176,1860.86 c -98.293,0 -178.063,-79.78 -178.063,-178.14 l 0,-1271.24 c 0,-98.218 79.77,-178.058 178.063,-178.058 l 1277.664,0 c 98.28,0 178.05,79.84 178.05,178.058 l 0,1271.24 c 0,98.36 -79.77,178.14 -178.05,178.14 l -1277.664,0"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient454"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,-164.901,-164.901,0,100,186.835)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop456"
+ offset="0"
+ style="stop-opacity:1;stop-color:#bfbdbb" />
+ <stop
+ id="stop458"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#a6a6a5" />
+ <stop
+ id="stop460"
+ offset="0.714464"
+ style="stop-opacity:1;stop-color:#a6a6a5" />
+ <stop
+ id="stop462"
+ offset="1"
+ style="stop-opacity:1;stop-color:#b9b8b7" />
+ </linearGradient>
+ <clipPath
+ id="clipPath450"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path452"
+ d="m 1641.26,219.34 -1282.53,0 c -101.14,0 -183.187,82.14 -183.187,183.191 l 0,1282.529 c 0,101.24 82.047,183.29 183.187,183.29 l 1282.53,0 c 101.15,0 183.2,-82.05 183.2,-183.29 l 0,-1282.529 c 0,-101.051 -82.05,-183.191 -183.2,-183.191 M 359.953,1864.61 c -99.719,0 -180.625,-80.92 -180.625,-180.72 l 0,-1276.878 c 0,-99.641 80.906,-180.633 180.625,-180.633 l 1280.097,0 c 99.72,0 180.62,80.992 180.62,180.633 l 0,1276.878 c 0,99.8 -80.9,180.72 -180.62,180.72 l -1280.097,0"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient438"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop440"
+ offset="0"
+ style="stop-opacity:1;stop-color:#95968f" />
+ <stop
+ id="stop442"
+ offset="1"
+ style="stop-opacity:1;stop-color:#686a68" />
+ </linearGradient>
+ <clipPath
+ id="clipPath434"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path436"
+ d="m 1698.32,211.551 -1396.636,0 c 17.867,4.578 36.941,7.051 56.742,7.051 l 1283.144,0 c 19.8,0 38.88,-2.473 56.75,-7.051"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient420"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop422"
+ offset="0"
+ style="stop-opacity:1;stop-color:#9b9c94" />
+ <stop
+ id="stop424"
+ offset="1"
+ style="stop-opacity:1;stop-color:#6f716d" />
+ </linearGradient>
+ <clipPath
+ id="clipPath416"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path418"
+ d="m 1704.28,208.461 -1408.499,0 c -1.398,0 -2.758,0.098 -4.062,0.277 3.273,1.012 6.597,1.953 9.965,2.813 l 1396.636,0 c 3.37,-0.86 6.7,-1.801 9.99,-2.813 -1.3,-0.179 -2.64,-0.277 -4.03,-0.277"
+ inkscape:connector-curvature="0" />
+ </clipPath>
<linearGradient
- id="linearGradient3151">
+ id="linearGradient402"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop404"
+ offset="0"
+ style="stop-opacity:1;stop-color:#a0a19a" />
+ <stop
+ id="stop406"
+ offset="1"
+ style="stop-opacity:1;stop-color:#737471" />
+ </linearGradient>
+ <clipPath
+ id="clipPath398"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path400"
+ d="m 1707.28,205.371 -1414.495,0 c -2.93,0 -5.719,0.359 -8.242,1.027 2.367,0.821 4.754,1.602 7.176,2.34 1.304,-0.179 2.664,-0.277 4.062,-0.277 l 1408.499,0 c 1.39,0 2.73,0.098 4.03,0.277 2.42,-0.75 4.81,-1.527 7.18,-2.347 -2.51,-0.661 -5.29,-1.02 -8.21,-1.02"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient384"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop386"
+ offset="0"
+ style="stop-opacity:1;stop-color:#a9aaa2" />
+ <stop
+ id="stop388"
+ offset="1"
+ style="stop-opacity:1;stop-color:#787a77" />
+ </linearGradient>
+ <clipPath
+ id="clipPath380"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path382"
+ d="m 1710.28,202.27 -1420.495,0 c -4.203,0 -8.156,0.66 -11.574,1.812 2.086,0.797 4.199,1.578 6.332,2.316 2.523,-0.668 5.312,-1.027 8.242,-1.027 l 1414.495,0 c 2.92,0 5.7,0.359 8.21,1.02 2.13,-0.743 4.24,-1.52 6.33,-2.321 -3.4,-1.14 -7.34,-1.8 -11.54,-1.8"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient366"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop368"
+ offset="0"
+ style="stop-opacity:1;stop-color:#b0b1a8" />
+ <stop
+ id="stop370"
+ offset="1"
+ style="stop-opacity:1;stop-color:#7e7f7c" />
+ </linearGradient>
+ <clipPath
+ id="clipPath362"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path364"
+ d="m 1713.28,199.18 -1426.491,0 c -5.332,0 -10.305,0.929 -14.465,2.539 1.942,0.812 3.903,1.601 5.887,2.363 3.418,-1.152 7.371,-1.812 11.574,-1.812 l 1420.495,0 c 4.2,0 8.14,0.66 11.54,1.8 1.98,-0.761 3.94,-1.55 5.88,-2.359 -4.14,-1.602 -9.09,-2.531 -14.42,-2.531"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient348"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop350"
+ offset="0"
+ style="stop-opacity:1;stop-color:#b8b8ae" />
+ <stop
+ id="stop352"
+ offset="1"
+ style="stop-opacity:1;stop-color:#848581" />
+ </linearGradient>
+ <clipPath
+ id="clipPath344"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path346"
+ d="m 1716.28,196.09 -1432.491,0 c -6.34,0 -12.223,1.18 -17.039,3.191 1.84,0.84 3.695,1.649 5.574,2.438 4.16,-1.61 9.133,-2.539 14.465,-2.539 l 1426.491,0 c 5.33,0 10.28,0.929 14.42,2.531 1.88,-0.789 3.74,-1.602 5.57,-2.441 -4.79,-2.008 -10.65,-3.18 -16.99,-3.18"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient330"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop332"
+ offset="0"
+ style="stop-opacity:1;stop-color:#bfbfb5" />
+ <stop
+ id="stop334"
+ offset="1"
+ style="stop-opacity:1;stop-color:#888a85" />
+ </linearGradient>
+ <clipPath
+ id="clipPath326"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path328"
+ d="m 1719.29,192.988 -1438.497,0 c -7.25,0 -13.957,1.403 -19.371,3.774 1.758,0.859 3.531,1.699 5.328,2.519 4.816,-2.011 10.699,-3.191 17.039,-3.191 l 1432.491,0 c 6.34,0 12.2,1.172 16.99,3.18 1.8,-0.821 3.58,-1.661 5.33,-2.52 -5.39,-2.359 -12.07,-3.762 -19.31,-3.762"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient312"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop314"
+ offset="0"
+ style="stop-opacity:1;stop-color:#c6c6bb" />
+ <stop
+ id="stop316"
+ offset="1"
+ style="stop-opacity:1;stop-color:#8e908a" />
+ </linearGradient>
+ <clipPath
+ id="clipPath308"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path310"
+ d="m 1722.29,189.898 -1444.497,0 c -8.066,0 -15.516,1.582 -21.484,4.25 1.683,0.891 3.39,1.762 5.113,2.614 5.414,-2.371 12.121,-3.774 19.371,-3.774 l 1438.497,0 c 7.24,0 13.92,1.403 19.31,3.762 1.73,-0.852 3.43,-1.719 5.11,-2.621 -5.94,-2.649 -13.36,-4.231 -21.42,-4.231"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient294"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
<stop
- style="stop-color:#b5b5b5;stop-opacity:1;"
+ id="stop296"
offset="0"
- id="stop3153" />
+ style="stop-opacity:1;stop-color:#cecec3" />
<stop
- style="stop-color:#ffffff;stop-opacity:1;"
+ id="stop298"
offset="1"
- id="stop3155" />
+ style="stop-opacity:1;stop-color:#94958e" />
</linearGradient>
+ <clipPath
+ id="clipPath290"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path292"
+ d="m 1725.29,186.809 -1450.493,0 c -8.797,0 -16.914,1.73 -23.41,4.64 1.621,0.922 3.261,1.821 4.922,2.699 5.968,-2.668 13.418,-4.25 21.484,-4.25 l 1444.497,0 c 8.06,0 15.48,1.582 21.42,4.231 1.66,-0.867 3.3,-1.77 4.92,-2.688 -6.46,-2.91 -14.55,-4.632 -23.34,-4.632"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient276"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop278"
+ offset="0"
+ style="stop-opacity:1;stop-color:#d6d6cb" />
+ <stop
+ id="stop280"
+ offset="1"
+ style="stop-opacity:1;stop-color:#999a93" />
+ </linearGradient>
+ <clipPath
+ id="clipPath272"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path274"
+ d="m 1728.29,183.711 -1456.493,0 c -9.442,0 -18.16,1.848 -25.145,4.961 1.559,0.949 3.137,1.867 4.735,2.777 6.496,-2.91 14.613,-4.64 23.41,-4.64 l 1450.493,0 c 8.79,0 16.88,1.722 23.34,4.632 1.6,-0.91 3.18,-1.839 4.74,-2.781 -6.96,-3.101 -15.65,-4.949 -25.08,-4.949"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient258"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop260"
+ offset="0"
+ style="stop-opacity:1;stop-color:#dcdcd2" />
+ <stop
+ id="stop262"
+ offset="1"
+ style="stop-opacity:1;stop-color:#9c9d96" />
+ </linearGradient>
+ <clipPath
+ id="clipPath254"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path256"
+ d="m 1731.29,180.621 -1462.493,0 c -10.008,0 -19.258,1.93 -26.703,5.188 1.5,0.98 3.019,1.929 4.558,2.863 6.985,-3.113 15.703,-4.961 25.145,-4.961 l 1456.493,0 c 9.43,0 18.12,1.848 25.08,4.949 1.53,-0.93 3.06,-1.89 4.55,-2.859 -7.41,-3.25 -16.63,-5.18 -26.63,-5.18"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient240"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop242"
+ offset="0"
+ style="stop-opacity:1;stop-color:#e2e3d8" />
+ <stop
+ id="stop244"
+ offset="1"
+ style="stop-opacity:1;stop-color:#a1a39b" />
+ </linearGradient>
+ <clipPath
+ id="clipPath236"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path238"
+ d="m 1734.29,177.531 -1468.489,0 c -10.5,0 -20.215,1.989 -28.09,5.36 1.441,0.988 2.902,1.961 4.383,2.918 7.445,-3.258 16.695,-5.188 26.703,-5.188 l 1462.493,0 c 10,0 19.22,1.93 26.63,5.18 1.49,-0.961 2.95,-1.93 4.39,-2.93 -7.85,-3.359 -17.53,-5.34 -28.02,-5.34"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient222"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop224"
+ offset="0"
+ style="stop-opacity:1;stop-color:#e4e4db" />
+ <stop
+ id="stop226"
+ offset="1"
+ style="stop-opacity:1;stop-color:#a5a59c" />
+ </linearGradient>
+ <clipPath
+ id="clipPath218"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path220"
+ d="m 1740.22,169.219 -1480.353,0 c -12.113,0 -23.351,2.179 -32.594,5.883 3.348,2.699 6.832,5.296 10.438,7.789 7.875,-3.371 17.59,-5.36 28.09,-5.36 l 1468.489,0 c 10.49,0 20.17,1.981 28.02,5.34 3.6,-2.48 7.09,-5.082 10.44,-7.781 -9.22,-3.699 -20.43,-5.871 -32.53,-5.871"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient204"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop206"
+ offset="0"
+ style="stop-opacity:1;stop-color:#e8e9de" />
+ <stop
+ id="stop208"
+ offset="1"
+ style="stop-opacity:1;stop-color:#a7a89f" />
+ </linearGradient>
+ <clipPath
+ id="clipPath200"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path202"
+ d="m 1746.16,160.91 -1492.226,0 c -13.278,0 -25.653,2.219 -36.039,6.031 2.996,2.821 6.121,5.539 9.378,8.161 9.243,-3.704 20.481,-5.883 32.594,-5.883 l 1480.353,0 c 12.1,0 23.31,2.172 32.53,5.871 3.25,-2.629 6.38,-5.352 9.37,-8.16 -10.36,-3.809 -22.7,-6.02 -35.96,-6.02"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient186"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop188"
+ offset="0"
+ style="stop-opacity:1;stop-color:#eaeae0" />
+ <stop
+ id="stop190"
+ offset="1"
+ style="stop-opacity:1;stop-color:#a8a9a1" />
+ </linearGradient>
+ <clipPath
+ id="clipPath182"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path184"
+ d="m 1752.09,152.602 -1504.09,0 c -14.023,0 -27.168,2.148 -38.449,5.886 2.648,2.903 5.437,5.723 8.344,8.453 10.386,-3.812 22.761,-6.031 36.039,-6.031 l 1492.226,0 c 13.26,0 25.6,2.211 35.96,6.02 2.91,-2.739 5.69,-5.551 8.35,-8.461 -11.26,-3.731 -24.38,-5.867 -38.38,-5.867"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient168"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop170"
+ offset="0"
+ style="stop-opacity:1;stop-color:#ecede3" />
+ <stop
+ id="stop172"
+ offset="1"
+ style="stop-opacity:1;stop-color:#aaaba2" />
+ </linearGradient>
+ <clipPath
+ id="clipPath164"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path166"
+ d="m 1758.03,144.289 -1515.964,0 c -14.39,0 -27.957,2 -39.859,5.52 2.316,2.972 4.77,5.863 7.344,8.679 11.281,-3.738 24.426,-5.886 38.449,-5.886 l 1504.09,0 c 14,0 27.12,2.136 38.38,5.867 2.57,-2.809 5.02,-5.707 7.34,-8.668 -11.88,-3.52 -25.42,-5.512 -39.78,-5.512"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient150"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop152"
+ offset="0"
+ style="stop-opacity:1;stop-color:#eff0e6" />
+ <stop
+ id="stop154"
+ offset="1"
+ style="stop-opacity:1;stop-color:#acada4" />
+ </linearGradient>
+ <clipPath
+ id="clipPath146"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path148"
+ d="m 1763.96,135.98 -1527.827,0 c -14.403,0 -28.063,1.79 -40.297,5 1.996,3.008 4.117,5.95 6.371,8.829 11.902,-3.52 25.469,-5.52 39.859,-5.52 l 1515.964,0 c 14.36,0 27.9,1.992 39.78,5.512 2.24,-2.879 4.37,-5.832 6.36,-8.84 -12.2,-3.191 -25.83,-4.981 -40.21,-4.981"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient132"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop134"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f2f2e8" />
+ <stop
+ id="stop136"
+ offset="1"
+ style="stop-opacity:1;stop-color:#aeaea6" />
+ </linearGradient>
+ <clipPath
+ id="clipPath128"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path130"
+ d="m 1769.89,127.672 -1539.691,0 c -14.09,0 -27.531,1.547 -39.801,4.367 1.684,3.031 3.504,6.02 5.438,8.941 12.234,-3.21 25.894,-5 40.297,-5 l 1527.827,0 c 14.38,0 28.01,1.79 40.21,4.981 1.94,-2.922 3.75,-5.902 5.44,-8.941 -12.24,-2.801 -25.66,-4.348 -39.72,-4.348"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient114"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop116"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f5f5ea" />
+ <stop
+ id="stop118"
+ offset="1"
+ style="stop-opacity:1;stop-color:#b0b0a8" />
+ </linearGradient>
+ <clipPath
+ id="clipPath110"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path112"
+ d="m 1775.83,119.359 -1551.564,0 c -13.473,0 -26.407,1.301 -38.407,3.68 1.387,3.051 2.903,6.051 4.539,9 12.27,-2.82 25.711,-4.367 39.801,-4.367 l 1539.691,0 c 14.06,0 27.48,1.547 39.72,4.348 1.64,-2.95 3.15,-5.95 4.54,-9 -11.98,-2.372 -24.88,-3.661 -38.32,-3.661"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient96"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop98"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f7f8ed" />
+ <stop
+ id="stop100"
+ offset="1"
+ style="stop-opacity:1;stop-color:#b1b2a9" />
+ </linearGradient>
+ <clipPath
+ id="clipPath92"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path94"
+ d="m 1781.76,111.051 -1563.432,0 c -12.574,0 -24.715,1.039 -36.152,2.98 1.105,3.039 2.332,6.047 3.683,9.008 12,-2.379 24.934,-3.68 38.407,-3.68 l 1551.564,0 c 13.44,0 26.34,1.289 38.32,3.661 1.34,-2.95 2.58,-5.961 3.68,-9.008 -11.41,-1.922 -23.52,-2.961 -36.07,-2.961"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient78"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop80"
+ offset="0"
+ style="stop-opacity:1;stop-color:#f9f9ef" />
+ <stop
+ id="stop82"
+ offset="1"
+ style="stop-opacity:1;stop-color:#b2b3a9" />
+ </linearGradient>
+ <clipPath
+ id="clipPath74"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path76"
+ d="m 1787.69,102.738 -1575.292,0 c -11.421,0 -22.507,0.801 -33.089,2.293 0.836,3.039 1.793,6.028 2.867,9 11.437,-1.941 23.578,-2.98 36.152,-2.98 l 1563.432,0 c 12.55,0 24.66,1.039 36.07,2.961 1.07,-2.961 2.03,-5.953 2.86,-8.992 -10.55,-1.489 -21.61,-2.282 -33,-2.282"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient60"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop62"
+ offset="0"
+ style="stop-opacity:1;stop-color:#fbfbf2" />
+ <stop
+ id="stop64"
+ offset="1"
+ style="stop-opacity:1;stop-color:#b6b6ac" />
+ </linearGradient>
+ <clipPath
+ id="clipPath56"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path58"
+ d="m 1793.63,94.4297 -1587.165,0 c -10.024,0 -19.805,0.5703 -29.246,1.6601 0.578,3.0118 1.277,6.0002 2.09,8.9412 10.582,-1.492 21.668,-2.293 33.089,-2.293 l 1575.292,0 c 11.39,0 22.45,0.793 33,2.282 0.82,-2.95 1.51,-5.9302 2.09,-8.938 -9.41,-1.082 -19.16,-1.6523 -29.15,-1.6523"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient42"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop44"
+ offset="0"
+ style="stop-opacity:1;stop-color:#fcfdf4" />
+ <stop
+ id="stop46"
+ offset="1"
+ style="stop-opacity:1;stop-color:#b7b7ad" />
+ </linearGradient>
+ <clipPath
+ id="clipPath38"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path40"
+ d="m 1799.56,86.1211 -1599.033,0 c -8.39,0 -16.632,0.3789 -24.656,1.0977 0.336,2.9804 0.785,5.9414 1.348,8.871 9.441,-1.0898 19.222,-1.6601 29.246,-1.6601 l 1587.165,0 c 9.99,0 19.74,0.5703 29.15,1.6523 0.57,-2.9336 1.01,-5.8828 1.35,-8.8711 -8,-0.7109 -16.21,-1.0898 -24.57,-1.0898"
+ inkscape:connector-curvature="0" />
+ </clipPath>
+ <linearGradient
+ id="linearGradient24"
+ spreadMethod="pad"
+ gradientTransform="matrix(0,20.8601,20.8601,0,100,1)"
+ gradientUnits="userSpaceOnUse"
+ y2="0"
+ x2="1"
+ y1="0"
+ x1="0">
+ <stop
+ id="stop26"
+ offset="0"
+ style="stop-opacity:1;stop-color:#fcfdf4" />
+ <stop
+ id="stop28"
+ offset="1"
+ style="stop-opacity:1;stop-color:#b7b7ad" />
+ </linearGradient>
+ <clipPath
+ id="clipPath20"
+ clipPathUnits="userSpaceOnUse">
+ <path
+ id="path22-8"
+ d="m 1824.85,10 -1649.702,0 0,64.3281 c 0,4.3438 0.247,8.6407 0.723,12.8907 8.024,-0.7188 16.266,-1.0977 24.656,-1.0977 l 1599.033,0 c 8.36,0 16.57,0.3789 24.57,1.0898 0.48,-4.2421 0.72,-8.539 0.72,-12.8828 l 0,-64.3281"
+ inkscape:connector-curvature="0" />
+ </clipPath>
<inkscape:perspective
- sodipodi:type="inkscape:persp3d"
- inkscape:vp_x="0 : 526.18109 : 1"
+ id="perspective2390"
+ inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
+ inkscape:vp_z="744.09448 : 526.18109 : 1"
inkscape:vp_y="0 : 1000 : 0"
+ inkscape:vp_x="0 : 526.18109 : 1"
+ sodipodi:type="inkscape:persp3d" />
+ <linearGradient
+ id="linearGradient3150">
+ <stop
+ id="stop3152"
+ offset="0"
+ style="stop-color:#235071;stop-opacity:1;" />
+ <stop
+ id="stop3154"
+ offset="1"
+ style="stop-color:#ffffff;stop-opacity:1;" />
+ </linearGradient>
+ <linearGradient
+ id="linearGradient3170">
+ <stop
+ id="stop3172"
+ offset="0"
+ style="stop-color:#000000;stop-opacity:1;" />
+ <stop
+ id="stop3174"
+ offset="1"
+ style="stop-color:#848484;stop-opacity:1;" />
+ </linearGradient>
+ <linearGradient
+ y2="0.52999997"
+ x2="97.685806"
+ y1="51.163727"
+ x1="80.78746"
+ gradientTransform="matrix(1.0000709,0,0,0.988411,-151.89821,-7.7970763)"
+ gradientUnits="userSpaceOnUse"
+ id="linearGradient3802"
+ xlink:href="#linearGradient3150-4"
+ inkscape:collect="always" />
+ <linearGradient
+ y2="0.52999997"
+ x2="97.685806"
+ y1="51.163727"
+ x1="80.78746"
+ gradientTransform="matrix(1.0000709,0,0,0.988411,-154.02756,-2.82859)"
+ gradientUnits="userSpaceOnUse"
+ id="linearGradient3796"
+ xlink:href="#linearGradient3150-4"
+ inkscape:collect="always" />
+ <linearGradient
+ gradientTransform="matrix(1.0000709,0,0,0.988411,-0.00448627,0.010545)"
+ y2="0.52999997"
+ x2="97.685806"
+ y1="51.163727"
+ x1="80.78746"
+ gradientUnits="userSpaceOnUse"
+ id="linearGradient3168-3"
+ xlink:href="#linearGradient3150-4"
+ inkscape:collect="always" />
+ <inkscape:perspective
+ id="perspective2390-2"
+ inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
inkscape:vp_z="744.09448 : 526.18109 : 1"
+ inkscape:vp_y="0 : 1000 : 0"
+ inkscape:vp_x="0 : 526.18109 : 1"
+ sodipodi:type="inkscape:persp3d" />
+ <linearGradient
+ id="linearGradient3150-4">
+ <stop
+ id="stop3152-7"
+ offset="0"
+ style="stop-color:#235071;stop-opacity:1;" />
+ <stop
+ id="stop3154-3"
+ offset="1"
+ style="stop-color:#ffffff;stop-opacity:1;" />
+ </linearGradient>
+ <linearGradient
+ id="linearGradient3170-7">
+ <stop
+ id="stop3172-6"
+ offset="0"
+ style="stop-color:#000000;stop-opacity:1;" />
+ <stop
+ id="stop3174-8"
+ offset="1"
+ style="stop-color:#848484;stop-opacity:1;" />
+ </linearGradient>
+ <inkscape:perspective
+ id="perspective2390-3"
inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
- id="perspective2390" />
+ inkscape:vp_z="744.09448 : 526.18109 : 1"
+ inkscape:vp_y="0 : 1000 : 0"
+ inkscape:vp_x="0 : 526.18109 : 1"
+ sodipodi:type="inkscape:persp3d" />
<linearGradient
- inkscape:collect="always"
- xlink:href="#linearGradient3151"
- id="linearGradient3157"
- x1="17.991968"
- y1="115.66266"
- x2="96.913872"
- y2="12.610445"
- gradientUnits="userSpaceOnUse"
- gradientTransform="matrix(0.9442617,0,0,0.9442617,4.0741457,4.0741457)" />
+ id="linearGradient3150-6">
+ <stop
+ id="stop3152-6"
+ offset="0"
+ style="stop-color:#235071;stop-opacity:1;" />
+ <stop
+ id="stop3154-4"
+ offset="1"
+ style="stop-color:#ffffff;stop-opacity:1;" />
+ </linearGradient>
+ <linearGradient
+ id="linearGradient3170-6">
+ <stop
+ id="stop3172-1"
+ offset="0"
+ style="stop-color:#000000;stop-opacity:1;" />
+ <stop
+ id="stop3174-1"
+ offset="1"
+ style="stop-color:#848484;stop-opacity:1;" />
+ </linearGradient>
</defs>
<sodipodi:namedview
- id="base"
pagecolor="#ffffff"
bordercolor="#666666"
- borderopacity="1.0"
- gridtolerance="10000"
- guidetolerance="10"
+ borderopacity="1"
objecttolerance="10"
- inkscape:pageopacity="0.0"
+ gridtolerance="10"
+ guidetolerance="10"
+ inkscape:pageopacity="0"
inkscape:pageshadow="2"
- inkscape:zoom="1.9453125"
- inkscape:cx="64"
- inkscape:cy="48.751619"
- inkscape:document-units="px"
- inkscape:current-layer="layer1"
+ inkscape:window-width="1680"
+ inkscape:window-height="1001"
+ id="namedview4"
showgrid="false"
- inkscape:window-width="996"
- inkscape:window-height="701"
- inkscape:window-x="1503"
- inkscape:window-y="236" />
- <metadata
- id="metadata2464">
- <rdf:RDF>
- <cc:Work
- rdf:about="">
- <dc:format>image/svg+xml</dc:format>
- <dc:type
- rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
- </cc:Work>
- </rdf:RDF>
- </metadata>
+ inkscape:zoom="6.6691528"
+ inkscape:cx="64.454266"
+ inkscape:cy="68.648241"
+ inkscape:window-x="0"
+ inkscape:window-y="23"
+ inkscape:window-maximized="0"
+ inkscape:current-layer="g10"
+ fit-margin-top="0"
+ fit-margin-left="0"
+ fit-margin-right="0"
+ fit-margin-bottom="0" />
<g
- inkscape:label="Layer 1"
+ id="g10"
inkscape:groupmode="layer"
- id="layer1">
- <rect
- style="opacity:1;fill:url(#linearGradient3157);fill-opacity:1;stroke:#8c8c8c;stroke-width:9.59699999999999953;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
- id="rect2380"
- width="116.94396"
- height="116.94396"
- x="5.9135523"
- y="5.9135523"
- ry="28.779495"
- inkscape:export-filename="/Users/remko/src/swift/Swift/resources/icons/avatar.png"
- inkscape:export-xdpi="34.093784"
- inkscape:export-ydpi="34.093784" />
+ inkscape:label="ink_ext_XXXXXX"
+ transform="matrix(1.25,0,0,-1.25,-508.98876,369.64004)">
+ <circle
+ style="opacity:1;fill:#dddddd;fill-opacity:1;stroke:#ffffff;stroke-width:0;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
+ id="backgroundCircle"
+ cx="442.77222"
+ cy="-260.09323"
+ transform="scale(1,-1)"
+ r="32.661972" />
+ <g
+ id="g2734"
+ transform="matrix(0.03695799,0,0,0.03695799,357.71523,119.9194)">
+ <g
+ clip-path="url(#clipPath2738)"
+ id="g2736">
+ <g
+ transform="matrix(15.2,0,0,15.2,263.9,861.9)"
+ id="g2742">
+ <image
+ id="image2744"
+ xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAYAAABWKLW/AAAABHNCSVQICAgIfAhkiAAAABVJREFUCJljfPbs6X8GKGBiQAIoHACHDwO2XpusvQAAAABJRU5ErkJggg=="
+ transform="matrix(1,0,0,-1,0,1)"
+ height="1"
+ width="1" />
+ </g>
+ </g>
+ </g>
+ <g
+ transform="matrix(0.43868508,0,0,-0.43868508,477.6681,346.11711)"
+ id="layer1-0"
+ inkscape:label="Layer 1">
+ <path
+ id="path3804-2"
+ d="m -116.04602,140.16881 c 63.47233,14.0107 52.472994,34.41414 26.064348,51.55181 -12.825068,4.12386 -28.784578,9.13824 -49.659768,14.98061 9.85394,-1.19384 18.77655,-1.96723 26.84565,-2.37837 -8.07516,3.9199 -16.15628,7.45211 -23.12664,10.37832 16.08126,-4.16073 29.80986,-7.64031 41.752958,-10.59453 43.679839,1.70458 46.902784,20.93179 6.531716,58.03826 60.709281,-31.2105 76.647981,-54.18473 40.59663,-69.00345 18.498251,-3.84931 25.553871,-4.38862 29.470841,-4.04631 -9.4225,-5.84736 -15.93053,-8.83589 -23.2204,-9.3899 16.00173,-21.3204 -18.176669,-34.68275 -75.255335,-39.53644 z"
+ style="fill:#235071;fill-opacity:1;fill-rule:nonzero;stroke:#235071;stroke-width:2.39899993;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"
+ inkscape:connector-curvature="0" />
+ <path
+ id="path3806-8"
+ d="m -37.962505,185.06086 c 0,1.09434 -0.97348,1.9825 -2.17294,1.9825 -1.19948,0 -2.172957,-0.88816 -2.172957,-1.9825 0,-1.09433 0.973477,-1.98249 2.172957,-1.98249 1.19946,0 2.17294,0.88816 2.17294,1.98249 z"
+ style="fill:#ffa859;fill-opacity:1;fill-rule:nonzero;stroke:none"
+ inkscape:connector-curvature="0" />
+ </g>
<path
- id="path2469"
- style="fill:#8c8c8c;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0.17320289000000000px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
- d="M 84.186703,55.87472 C 115.18862,33.344515 86.918967,19.476275 33.840876,14.909522 C 111.17407,32.181205 49.997334,61.470216 17.987699,75.066628 C 91.222651,55.894928 106.3968,53.862851 112.44381,54.397544 C 88.313377,39.246156 87.961827,47.960949 15.015231,68.617437 C 82.095674,60.394538 97.654781,75.133863 56.523078,113.38543 C 107.45479,86.892681 118.9257,67.742581 84.186703,55.87472 z M 96.159637,51.145757 C 96.159637,52.029347 95.382795,52.74646 94.425618,52.74646 C 93.46843,52.74646 92.69159,52.029347 92.69159,51.145757 C 92.69159,50.262174 93.46843,49.545057 94.425618,49.545057 C 95.382795,49.545057 96.159637,50.262174 96.159637,51.145757 z"
- inkscape:export-filename="/Users/remko/src/swift/Swift/resources/icons/avatar.png"
- inkscape:export-xdpi="34.093784"
- inkscape:export-ydpi="34.093784" />
+ sodipodi:open="true"
+ sodipodi:end="9.4489119"
+ sodipodi:start="3.2027767"
+ sodipodi:type="arc"
+ style="fill:#ffd632;fill-opacity:0;fill-rule:nonzero;stroke:#235071;stroke-width:5.0999999;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none;stroke-dashoffset:0"
+ id="path6540"
+ sodipodi:cx="-102"
+ sodipodi:cy="82.462494"
+ sodipodi:rx="32"
+ sodipodi:ry="32"
+ d="m -133.94012,80.505826 a 32,32 0 0 1 33.60086,-30.000208 32,32 0 0 1 30.310148,33.32155 32,32 0 0 1 -33.039378,30.617482 32,32 0 0 1 -30.92219,-32.754367"
+ transform="matrix(1.0298331,0,0,-1.0298331,547.81489,345.01645)" />
</g>
</svg>
diff --git a/Swift/resources/icons/delivery-failure.svg b/Swift/resources/icons/delivery-failure.svg
new file mode 100644
index 0000000..c1a0c08
--- /dev/null
+++ b/Swift/resources/icons/delivery-failure.svg
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg width="100%" height="100%" viewBox="0 0 133 133" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:1.41421;">
+ <g id="Layer-1" transform="matrix(1,0,0,1,0,-164.708)">
+ <g id="path4233" transform="matrix(1.00826,0,0,1.00826,-0.546361,-1.90685)">
+ <circle cx="66.146" cy="230.854" r="65.604" style="fill:rgb(224,102,102);"/>
+ <path d="M66.57,165.252L66.993,165.256L67.416,165.262L67.838,165.272L68.259,165.284L68.68,165.298L69.1,165.316L69.52,165.336L69.938,165.358L70.356,165.383L70.774,165.411L71.19,165.442L71.606,165.475L72.021,165.51L72.436,165.548L72.849,165.589L73.262,165.632L73.675,165.678L74.086,165.727L74.497,165.778L74.906,165.831L75.315,165.887L75.724,165.946L76.131,166.007L76.538,166.07L76.943,166.136L77.348,166.205L77.753,166.276L78.156,166.349L78.558,166.425L78.96,166.503L79.36,166.584L79.76,166.667L80.159,166.753L80.557,166.841L80.954,166.931L81.35,167.024L81.746,167.119L82.14,167.217L82.533,167.317L82.926,167.419L83.317,167.524L83.708,167.631L84.097,167.741L84.486,167.852L84.873,167.967L85.26,168.083L85.645,168.202L86.03,168.323L86.414,168.446L86.796,168.572L87.178,168.7L87.558,168.83L87.937,168.962L88.316,169.097L88.693,169.234L89.069,169.373L89.444,169.514L89.818,169.658L90.191,169.804L90.563,169.952L90.934,170.102L91.303,170.255L91.672,170.409L92.039,170.566L92.405,170.725L92.77,170.886L93.134,171.049L93.496,171.215L93.858,171.382L94.218,171.552L94.577,171.724L94.935,171.898L95.292,172.074L95.647,172.252L96.001,172.432L96.354,172.614L96.706,172.798L97.057,172.985L97.406,173.173L97.754,173.364L98.1,173.556L98.446,173.751L98.79,173.947L99.133,174.146L99.474,174.346L99.814,174.549L100.153,174.754L100.491,174.96L100.827,175.169L101.162,175.379L101.495,175.592L101.827,175.806L102.158,176.022L102.487,176.241L102.815,176.461L103.141,176.683L103.467,176.907L103.79,177.133L104.113,177.361L104.433,177.59L104.753,177.822L105.071,178.055L105.387,178.291L105.702,178.528L106.016,178.767L106.328,179.007L106.639,179.25L106.948,179.495L107.255,179.741L107.561,179.989L107.866,180.239L108.169,180.49L108.471,180.744L108.77,180.999L109.069,181.256L109.366,181.515L109.661,181.775L109.955,182.037L110.247,182.301L110.537,182.567L110.826,182.834L111.114,183.104L111.399,183.374L111.683,183.647L111.966,183.921L112.247,184.197L112.526,184.474L112.803,184.753L113.079,185.034L113.353,185.317L113.626,185.601L113.896,185.886L114.166,186.174L114.433,186.463L114.699,186.753L114.963,187.045L115.225,187.339L115.485,187.634L115.744,187.931L116.001,188.23L116.256,188.529L116.51,188.831L116.761,189.134L117.011,189.439L117.259,189.745L117.505,190.052L117.75,190.361L117.993,190.672L118.233,190.984L118.472,191.298L118.709,191.613L118.945,191.929L119.178,192.247L119.41,192.567L119.639,192.887L119.867,193.21L120.093,193.533L120.317,193.859L120.539,194.185L120.759,194.513L120.978,194.842L121.194,195.173L121.408,195.505L121.621,195.838L121.831,196.173L122.04,196.509L122.246,196.847L122.451,197.186L122.654,197.526L122.854,197.867L123.053,198.21L123.249,198.554L123.444,198.9L123.636,199.246L123.827,199.594L124.015,199.943L124.202,200.294L124.386,200.646L124.568,200.999L124.748,201.353L124.927,201.708L125.102,202.065L125.276,202.423L125.448,202.782L125.618,203.142L125.785,203.504L125.951,203.866L126.114,204.23L126.275,204.595L126.434,204.961L126.591,205.328L126.746,205.697L126.898,206.066L127.048,206.437L127.196,206.809L127.342,207.182L127.486,207.556L127.627,207.931L127.766,208.307L127.903,208.684L128.038,209.063L128.17,209.442L128.3,209.822L128.428,210.204L128.554,210.586L128.677,210.97L128.798,211.355L128.917,211.74L129.033,212.127L129.148,212.514L129.259,212.903L129.369,213.292L129.476,213.683L129.581,214.074L129.683,214.467L129.783,214.86L129.881,215.255L129.976,215.65L130.069,216.046L130.159,216.443L130.247,216.841L130.333,217.24L130.416,217.64L130.497,218.04L130.575,218.442L130.651,218.844L130.724,219.247L130.795,219.652L130.864,220.057L130.93,220.462L130.993,220.869L131.054,221.276L131.113,221.685L131.169,222.094L131.222,222.503L131.273,222.914L131.322,223.325L131.368,223.738L131.411,224.151L131.452,224.564L131.49,224.979L131.525,225.394L131.558,225.81L131.589,226.226L131.617,226.644L131.642,227.062L131.664,227.48L131.684,227.9L131.702,228.32L131.716,228.741L131.728,229.162L131.738,229.584L131.744,230.007L131.748,230.43L131.75,230.854L131.748,231.278L131.744,231.702L131.738,232.124L131.728,232.546L131.716,232.968L131.702,233.389L131.684,233.809L131.664,234.228L131.642,234.647L131.617,235.065L131.589,235.482L131.558,235.899L131.525,236.315L131.49,236.73L131.452,237.144L131.411,237.558L131.368,237.971L131.322,238.383L131.273,238.794L131.222,239.205L131.169,239.615L131.113,240.024L131.054,240.432L130.993,240.839L130.93,241.246L130.864,241.652L130.795,242.057L130.724,242.461L130.651,242.864L130.575,243.266L130.497,243.668L130.416,244.069L130.333,244.468L130.247,244.867L130.159,245.265L130.069,245.662L129.976,246.059L129.881,246.454L129.783,246.848L129.683,247.242L129.581,247.634L129.476,248.025L129.369,248.416L129.259,248.805L129.148,249.194L129.033,249.582L128.917,249.968L128.798,250.354L128.677,250.738L128.554,251.122L128.428,251.504L128.3,251.886L128.17,252.266L128.038,252.646L127.903,253.024L127.766,253.401L127.627,253.777L127.486,254.153L127.342,254.527L127.196,254.899L127.048,255.271L126.898,255.642L126.746,256.012L126.591,256.38L126.434,256.747L126.275,257.113L126.114,257.478L125.951,257.842L125.785,258.205L125.618,258.566L125.448,258.927L125.276,259.286L125.102,259.643L124.927,260L124.748,260.356L124.568,260.71L124.386,261.063L124.202,261.414L124.015,261.765L123.827,262.114L123.636,262.462L123.444,262.809L123.249,263.154L123.053,263.498L122.854,263.841L122.654,264.182L122.451,264.523L122.246,264.861L122.04,265.199L121.831,265.535L121.621,265.87L121.408,266.203L121.194,266.535L120.978,266.866L120.759,267.195L120.539,267.523L120.317,267.85L120.093,268.175L119.867,268.499L119.639,268.821L119.41,269.142L119.178,269.461L118.945,269.779L118.709,270.096L118.472,270.411L118.233,270.724L117.993,271.036L117.75,271.347L117.505,271.656L117.259,271.964L117.011,272.27L116.761,272.574L116.51,272.877L116.256,273.179L116.001,273.479L115.744,273.777L115.485,274.074L115.225,274.369L114.963,274.663L114.699,274.955L114.433,275.246L114.166,275.535L113.896,275.822L113.626,276.108L113.353,276.392L113.079,276.674L112.803,276.955L112.526,277.234L112.247,277.512L111.966,277.787L111.683,278.062L111.399,278.334L111.114,278.605L110.826,278.874L110.537,279.141L110.247,279.407L109.955,279.671L109.661,279.933L109.366,280.194L109.069,280.452L108.77,280.709L108.471,280.964L108.169,281.218L107.866,281.47L107.561,281.719L107.255,281.967L106.948,282.214L106.639,282.458L106.328,282.701L106.016,282.942L105.702,283.181L105.387,283.418L105.071,283.653L104.753,283.887L104.433,284.118L104.113,284.348L103.79,284.576L103.467,284.801L103.141,285.025L102.815,285.248L102.487,285.468L102.158,285.686L101.827,285.902L101.495,286.117L101.162,286.329L100.827,286.54L100.491,286.748L100.153,286.955L99.814,287.159L99.474,287.362L99.133,287.563L98.79,287.761L98.446,287.958L98.1,288.152L97.754,288.345L97.406,288.535L97.057,288.724L96.706,288.91L96.354,289.094L96.001,289.277L95.647,289.457L95.292,289.635L94.935,289.811L94.577,289.985L94.218,290.157L93.858,290.326L93.496,290.494L93.134,290.659L92.77,290.822L92.405,290.983L92.039,291.142L91.672,291.299L91.303,291.454L90.934,291.606L90.563,291.757L90.191,291.905L89.818,292.05L89.444,292.194L89.069,292.335L88.693,292.475L88.316,292.611L87.937,292.746L87.558,292.879L87.178,293.009L86.796,293.137L86.414,293.262L86.03,293.386L85.645,293.507L85.26,293.625L84.873,293.742L84.486,293.856L84.097,293.968L83.708,294.077L83.317,294.184L82.926,294.289L82.533,294.391L82.14,294.491L81.746,294.589L81.35,294.684L80.954,294.777L80.557,294.867L80.159,294.955L79.76,295.041L79.36,295.124L78.96,295.205L78.558,295.283L78.156,295.359L77.753,295.433L77.348,295.504L76.943,295.572L76.538,295.638L76.131,295.702L75.724,295.763L75.315,295.821L74.906,295.877L74.497,295.931L74.086,295.982L73.675,296.03L73.262,296.076L72.849,296.119L72.436,296.16L72.021,296.198L71.606,296.234L71.19,296.267L70.774,296.297L70.356,296.325L69.938,296.35L69.52,296.373L69.1,296.393L68.68,296.41L68.259,296.425L67.838,296.437L67.416,296.446L66.993,296.453L66.57,296.457L66.146,296.458L65.722,296.457L65.298,296.453L64.876,296.446L64.454,296.437L64.032,296.425L63.611,296.41L63.191,296.393L62.772,296.373L62.353,296.35L61.935,296.325L61.518,296.297L61.101,296.267L60.685,296.234L60.27,296.198L59.856,296.16L59.442,296.119L59.029,296.076L58.617,296.03L58.206,295.982L57.795,295.931L57.385,295.877L56.976,295.821L56.568,295.763L56.161,295.702L55.754,295.638L55.348,295.572L54.943,295.504L54.539,295.433L54.136,295.359L53.734,295.283L53.332,295.205L52.931,295.124L52.532,295.041L52.133,294.955L51.735,294.867L51.338,294.777L50.941,294.684L50.546,294.589L50.152,294.491L49.758,294.391L49.366,294.289L48.975,294.184L48.584,294.077L48.195,293.968L47.806,293.856L47.418,293.742L47.032,293.625L46.646,293.507L46.262,293.386L45.878,293.262L45.496,293.137L45.114,293.009L44.734,292.879L44.354,292.746L43.976,292.611L43.599,292.475L43.223,292.335L42.847,292.194L42.473,292.05L42.101,291.905L41.729,291.757L41.358,291.606L40.988,291.454L40.62,291.299L40.253,291.142L39.887,290.983L39.522,290.822L39.158,290.659L38.795,290.494L38.434,290.326L38.073,290.157L37.714,289.985L37.357,289.811L37,289.635L36.644,289.457L36.29,289.277L35.937,289.094L35.586,288.91L35.235,288.724L34.886,288.535L34.538,288.345L34.191,288.152L33.846,287.958L33.502,287.761L33.159,287.563L32.818,287.362L32.477,287.159L32.139,286.955L31.801,286.748L31.465,286.54L31.13,286.329L30.797,286.117L30.465,285.902L30.134,285.686L29.805,285.468L29.477,285.248L29.15,285.025L28.825,284.801L28.501,284.576L28.179,284.348L27.858,284.118L27.539,283.887L27.221,283.653L26.904,283.418L26.589,283.181L26.276,282.942L25.964,282.701L25.653,282.458L25.344,282.214L25.036,281.967L24.73,281.719L24.426,281.47L24.123,281.218L23.821,280.964L23.521,280.709L23.223,280.452L22.926,280.194L22.631,279.933L22.337,279.671L22.045,279.407L21.754,279.141L21.465,278.874L21.178,278.605L20.892,278.334L20.608,278.062L20.326,277.787L20.045,277.512L19.766,277.234L19.488,276.955L19.213,276.674L18.938,276.392L18.666,276.108L18.395,275.822L18.126,275.535L17.859,275.246L17.593,274.955L17.329,274.663L17.067,274.369L16.806,274.074L16.548,273.777L16.291,273.479L16.036,273.179L15.782,272.877L15.53,272.574L15.281,272.27L15.033,271.964L14.786,271.656L14.542,271.347L14.299,271.036L14.058,270.724L13.819,270.411L13.582,270.096L13.347,269.779L13.113,269.461L12.882,269.142L12.652,268.821L12.424,268.499L12.199,268.175L11.975,267.85L11.752,267.523L11.532,267.195L11.314,266.866L11.098,266.535L10.883,266.203L10.671,265.87L10.46,265.535L10.252,265.199L10.045,264.861L9.841,264.523L9.638,264.182L9.437,263.841L9.239,263.498L9.042,263.154L8.848,262.809L8.655,262.462L8.465,262.114L8.276,261.765L8.09,261.414L7.906,261.063L7.723,260.71L7.543,260.356L7.365,260L7.189,259.643L7.015,259.286L6.844,258.927L6.674,258.566L6.506,258.205L6.341,257.842L6.178,257.478L6.017,257.113L5.858,256.747L5.701,256.38L5.546,256.012L5.394,255.642L5.243,255.271L5.095,254.899L4.95,254.527L4.806,254.153L4.665,253.777L4.525,253.401L4.389,253.024L4.254,252.646L4.121,252.266L3.991,251.886L3.863,251.504L3.738,251.122L3.614,250.738L3.493,250.354L3.375,249.968L3.258,249.582L3.144,249.194L3.032,248.805L2.923,248.416L2.816,248.025L2.711,247.634L2.609,247.242L2.509,246.848L2.411,246.454L2.316,246.059L2.223,245.662L2.133,245.265L2.045,244.867L1.959,244.468L1.876,244.069L1.795,243.668L1.717,243.266L1.641,242.864L1.567,242.461L1.496,242.057L1.428,241.652L1.362,241.246L1.298,240.839L1.237,240.432L1.179,240.024L1.123,239.615L1.069,239.205L1.018,238.794L0.97,238.383L0.924,237.971L0.881,237.558L0.84,237.144L0.802,236.73L0.766,236.315L0.733,235.899L0.703,235.482L0.675,235.065L0.65,234.647L0.627,234.228L0.607,233.809L0.59,233.389L0.575,232.968L0.563,232.546L0.554,232.124L0.547,231.702L0.543,231.278L0.542,230.854L0.543,230.43L0.547,230.007L0.554,229.584L0.563,229.162L0.575,228.741L0.59,228.32L0.607,227.9L0.627,227.48L0.65,227.062L0.675,226.644L0.703,226.226L0.733,225.81L0.766,225.394L0.802,224.979L0.84,224.564L0.881,224.151L0.924,223.738L0.97,223.325L1.018,222.914L1.069,222.503L1.123,222.094L1.179,221.685L1.237,221.276L1.298,220.869L1.362,220.462L1.428,220.057L1.496,219.652L1.567,219.247L1.641,218.844L1.717,218.442L1.795,218.04L1.876,217.64L1.959,217.24L2.045,216.841L2.133,216.443L2.223,216.046L2.316,215.65L2.411,215.255L2.509,214.86L2.609,214.467L2.711,214.074L2.816,213.683L2.923,213.292L3.032,212.903L3.144,212.514L3.258,212.127L3.375,211.74L3.493,211.355L3.614,210.97L3.738,210.586L3.863,210.204L3.991,209.822L4.121,209.442L4.254,209.063L4.389,208.684L4.525,208.307L4.665,207.931L4.806,207.556L4.95,207.182L5.095,206.809L5.243,206.437L5.394,206.066L5.546,205.697L5.701,205.328L5.858,204.961L6.017,204.595L6.178,204.23L6.341,203.866L6.506,203.504L6.674,203.142L6.844,202.782L7.015,202.423L7.189,202.065L7.365,201.708L7.543,201.353L7.723,200.999L7.906,200.646L8.09,200.294L8.276,199.943L8.465,199.594L8.655,199.246L8.848,198.9L9.042,198.554L9.239,198.21L9.437,197.867L9.638,197.526L9.841,197.186L10.045,196.847L10.252,196.509L10.46,196.173L10.671,195.838L10.883,195.505L11.098,195.173L11.314,194.842L11.532,194.513L11.752,194.185L11.975,193.859L12.199,193.533L12.424,193.21L12.652,192.887L12.882,192.567L13.113,192.247L13.347,191.929L13.582,191.613L13.819,191.298L14.058,190.984L14.299,190.672L14.542,190.361L14.786,190.052L15.033,189.745L15.281,189.439L15.53,189.134L15.782,188.831L16.036,188.529L16.291,188.23L16.548,187.931L16.806,187.634L17.067,187.339L17.329,187.045L17.593,186.753L17.859,186.463L18.126,186.174L18.395,185.886L18.666,185.601L18.938,185.317L19.213,185.034L19.488,184.753L19.766,184.474L20.045,184.197L20.326,183.921L20.608,183.647L20.892,183.374L21.178,183.104L21.465,182.834L21.754,182.567L22.045,182.301L22.337,182.037L22.631,181.775L22.926,181.515L23.223,181.256L23.521,180.999L23.821,180.744L24.123,180.49L24.426,180.239L24.73,179.989L25.036,179.741L25.344,179.495L25.653,179.25L25.964,179.007L26.276,178.767L26.589,178.528L26.904,178.291L27.221,178.055L27.539,177.822L27.858,177.59L28.179,177.361L28.501,177.133L28.825,176.907L29.15,176.683L29.477,176.461L29.805,176.241L30.134,176.022L30.465,175.806L30.797,175.592L31.13,175.379L31.465,175.169L31.801,174.96L32.139,174.754L32.477,174.549L32.818,174.346L33.159,174.146L33.502,173.947L33.846,173.751L34.191,173.556L34.538,173.364L34.886,173.173L35.235,172.985L35.586,172.798L35.937,172.614L36.29,172.432L36.644,172.252L37,172.074L37.357,171.898L37.714,171.724L38.073,171.552L38.434,171.382L38.795,171.215L39.158,171.049L39.522,170.886L39.887,170.725L40.253,170.566L40.62,170.409L40.988,170.255L41.358,170.102L41.729,169.952L42.101,169.804L42.473,169.658L42.847,169.514L43.223,169.373L43.599,169.234L43.976,169.097L44.354,168.962L44.734,168.83L45.114,168.7L45.496,168.572L45.878,168.446L46.262,168.323L46.646,168.202L47.032,168.083L47.418,167.967L47.806,167.852L48.195,167.741L48.584,167.631L48.975,167.524L49.366,167.419L49.758,167.317L50.152,167.217L50.546,167.119L50.941,167.024L51.338,166.931L51.735,166.841L52.133,166.753L52.532,166.667L52.931,166.584L53.332,166.503L53.734,166.425L54.136,166.349L54.539,166.276L54.943,166.205L55.348,166.136L55.754,166.07L56.161,166.007L56.568,165.946L56.976,165.887L57.385,165.831L57.795,165.778L58.206,165.727L58.617,165.678L59.029,165.632L59.442,165.589L59.856,165.548L60.27,165.51L60.685,165.475L61.101,165.442L61.518,165.411L61.935,165.383L62.353,165.358L62.772,165.336L63.191,165.316L63.611,165.298L64.032,165.284L64.454,165.272L64.876,165.262L65.298,165.256L65.722,165.252L66.146,165.25L66.57,165.252ZM65.741,168.252L65.337,168.255L64.933,168.262L64.53,168.271L64.127,168.282L63.726,168.296L63.325,168.313L62.924,168.332L62.524,168.353L62.125,168.377L61.727,168.404L61.329,168.433L60.932,168.465L60.536,168.498L60.141,168.535L59.746,168.574L59.352,168.615L58.958,168.659L58.566,168.705L58.174,168.754L57.783,168.805L57.393,168.858L57.003,168.914L56.614,168.972L56.226,169.033L55.839,169.096L55.453,169.161L55.067,169.229L54.683,169.299L54.299,169.371L53.916,169.446L53.533,169.523L53.152,169.602L52.771,169.684L52.392,169.768L52.013,169.854L51.635,169.943L51.258,170.034L50.882,170.127L50.507,170.222L50.132,170.32L49.759,170.42L49.386,170.522L49.015,170.626L48.644,170.733L48.275,170.842L47.906,170.953L47.538,171.066L47.171,171.182L46.805,171.299L46.44,171.419L46.076,171.541L45.714,171.665L45.352,171.792L44.991,171.92L44.631,172.051L44.272,172.183L43.914,172.318L43.557,172.455L43.202,172.594L42.847,172.736L42.493,172.879L42.141,173.024L41.789,173.172L41.439,173.321L41.09,173.473L40.742,173.627L40.394,173.783L40.048,173.94L39.704,174.1L39.36,174.262L39.017,174.426L38.676,174.592L38.336,174.76L37.996,174.93L37.658,175.102L37.322,175.275L36.986,175.451L36.652,175.629L36.318,175.809L35.986,175.991L35.656,176.174L35.326,176.36L34.998,176.548L34.671,176.737L34.345,176.929L34.02,177.122L33.697,177.317L33.375,177.514L33.054,177.713L32.735,177.914L32.416,178.117L32.099,178.321L31.784,178.528L31.47,178.736L31.157,178.946L30.845,179.158L30.535,179.372L30.226,179.588L29.918,179.805L29.612,180.024L29.307,180.245L29.003,180.468L28.701,180.693L28.401,180.919L28.101,181.147L27.803,181.377L27.507,181.609L27.212,181.842L26.918,182.077L26.626,182.314L26.335,182.552L26.046,182.793L25.758,183.035L25.472,183.278L25.187,183.524L24.904,183.77L24.622,184.019L24.342,184.269L24.063,184.521L23.785,184.775L23.51,185.03L23.235,185.287L22.963,185.546L22.691,185.806L22.422,186.067L22.154,186.331L21.887,186.596L21.622,186.862L21.359,187.13L21.097,187.4L20.837,187.671L20.579,187.944L20.322,188.218L20.067,188.494L19.813,188.771L19.561,189.05L19.311,189.33L19.062,189.612L18.815,189.896L18.57,190.18L18.326,190.467L18.084,190.754L17.844,191.044L17.606,191.334L17.369,191.627L17.134,191.92L16.9,192.215L16.669,192.512L16.439,192.81L16.211,193.109L15.984,193.41L15.76,193.712L15.537,194.015L15.316,194.32L15.097,194.626L14.879,194.934L14.664,195.243L14.45,195.553L14.238,195.865L14.028,196.178L13.82,196.492L13.613,196.808L13.408,197.125L13.206,197.443L13.005,197.762L12.806,198.083L12.609,198.405L12.414,198.729L12.22,199.053L12.029,199.379L11.839,199.706L11.652,200.034L11.466,200.364L11.282,200.695L11.101,201.027L10.921,201.36L10.743,201.694L10.567,202.03L10.393,202.367L10.221,202.705L10.051,203.044L9.884,203.384L9.718,203.726L9.554,204.068L9.392,204.412L9.232,204.757L9.074,205.103L8.918,205.45L8.765,205.798L8.613,206.147L8.464,206.498L8.316,206.849L8.171,207.202L8.027,207.555L7.886,207.91L7.747,208.266L7.61,208.623L7.475,208.98L7.342,209.339L7.212,209.699L7.083,210.06L6.957,210.422L6.833,210.785L6.711,211.149L6.591,211.514L6.473,211.879L6.358,212.246L6.245,212.614L6.134,212.983L6.025,213.353L5.918,213.723L5.814,214.095L5.712,214.467L5.612,214.841L5.514,215.215L5.419,215.59L5.325,215.966L5.235,216.343L5.146,216.721L5.06,217.1L4.976,217.48L4.894,217.86L4.815,218.242L4.738,218.624L4.663,219.007L4.591,219.391L4.52,219.776L4.453,220.161L4.387,220.547L4.324,220.935L4.264,221.323L4.206,221.711L4.15,222.101L4.096,222.491L4.045,222.882L3.997,223.274L3.951,223.667L3.907,224.06L3.865,224.454L3.827,224.849L3.79,225.244L3.756,225.641L3.725,226.038L3.696,226.435L3.669,226.834L3.645,227.233L3.623,227.632L3.604,228.033L3.588,228.434L3.574,228.836L3.562,229.238L3.553,229.641L3.547,230.045L3.543,230.449L3.542,230.854L3.543,231.259L3.547,231.663L3.553,232.067L3.562,232.47L3.574,232.873L3.588,233.274L3.604,233.676L3.623,234.076L3.645,234.476L3.669,234.875L3.696,235.273L3.725,235.671L3.756,236.068L3.79,236.464L3.827,236.859L3.865,237.254L3.907,237.648L3.951,238.042L3.997,238.434L4.045,238.826L4.096,239.217L4.15,239.607L4.206,239.997L4.264,240.386L4.324,240.774L4.387,241.161L4.453,241.547L4.52,241.933L4.591,242.317L4.663,242.701L4.738,243.084L4.815,243.467L4.894,243.848L4.976,244.229L5.06,244.608L5.146,244.987L5.235,245.365L5.325,245.742L5.419,246.118L5.514,246.493L5.612,246.868L5.712,247.241L5.814,247.614L5.918,247.985L6.025,248.356L6.134,248.725L6.245,249.094L6.358,249.462L6.473,249.829L6.591,250.195L6.711,250.56L6.833,250.924L6.957,251.286L7.083,251.648L7.212,252.009L7.342,252.369L7.475,252.728L7.61,253.086L7.747,253.443L7.886,253.798L8.027,254.153L8.171,254.507L8.316,254.859L8.464,255.211L8.613,255.561L8.765,255.91L8.918,256.258L9.074,256.606L9.232,256.952L9.392,257.296L9.554,257.64L9.718,257.983L9.884,258.324L10.051,258.664L10.221,259.004L10.393,259.342L10.567,259.678L10.743,260.014L10.921,260.348L11.101,260.682L11.282,261.014L11.466,261.344L11.652,261.674L11.839,262.002L12.029,262.329L12.22,262.655L12.414,262.98L12.609,263.303L12.806,263.625L13.005,263.946L13.206,264.265L13.408,264.584L13.613,264.901L13.82,265.216L14.028,265.531L14.238,265.843L14.45,266.155L14.664,266.465L14.879,266.774L15.097,267.082L15.316,267.388L15.537,267.693L15.76,267.997L15.984,268.299L16.211,268.599L16.439,268.899L16.669,269.197L16.9,269.493L17.134,269.788L17.369,270.082L17.606,270.374L17.844,270.665L18.084,270.954L18.326,271.242L18.57,271.528L18.815,271.813L19.062,272.096L19.311,272.378L19.561,272.658L19.813,272.937L20.067,273.215L20.322,273.49L20.579,273.765L20.837,274.037L21.097,274.309L21.359,274.578L21.622,274.846L21.887,275.113L22.154,275.378L22.422,275.641L22.691,275.903L22.963,276.163L23.235,276.421L23.51,276.678L23.785,276.933L24.063,277.187L24.342,277.439L24.622,277.689L24.904,277.938L25.187,278.185L25.472,278.43L25.758,278.674L26.046,278.916L26.335,279.156L26.626,279.394L26.918,279.631L27.212,279.866L27.507,280.1L27.803,280.331L28.101,280.561L28.401,280.789L28.701,281.016L29.003,281.24L29.307,281.463L29.612,281.684L29.918,281.903L30.226,282.121L30.535,282.336L30.845,282.55L31.157,282.762L31.47,282.972L31.784,283.18L32.099,283.387L32.416,283.592L32.735,283.794L33.054,283.995L33.375,284.194L33.697,284.391L34.02,284.586L34.345,284.78L34.671,284.971L34.998,285.161L35.326,285.348L35.656,285.534L35.986,285.718L36.318,285.899L36.652,286.079L36.986,286.257L37.322,286.433L37.658,286.607L37.996,286.779L38.336,286.949L38.676,287.117L39.017,287.282L39.36,287.446L39.704,287.608L40.048,287.768L40.394,287.926L40.742,288.082L41.09,288.235L41.439,288.387L41.789,288.537L42.141,288.684L42.493,288.829L42.847,288.973L43.202,289.114L43.557,289.253L43.914,289.39L44.272,289.525L44.631,289.658L44.991,289.788L45.352,289.917L45.714,290.043L46.076,290.167L46.44,290.289L46.805,290.409L47.171,290.527L47.538,290.642L47.906,290.755L48.275,290.866L48.644,290.975L49.015,291.082L49.386,291.186L49.759,291.288L50.132,291.388L50.507,291.486L50.882,291.581L51.258,291.675L51.635,291.765L52.013,291.854L52.392,291.94L52.771,292.024L53.152,292.106L53.533,292.185L53.916,292.262L54.299,292.337L54.683,292.409L55.067,292.48L55.453,292.547L55.839,292.613L56.226,292.676L56.614,292.736L57.003,292.794L57.393,292.85L57.783,292.904L58.174,292.955L58.566,293.003L58.958,293.049L59.352,293.093L59.746,293.135L60.14,293.173L60.536,293.21L60.932,293.244L61.329,293.275L61.727,293.304L62.125,293.331L62.524,293.355L62.924,293.377L63.324,293.396L63.726,293.412L64.127,293.426L64.53,293.438L64.933,293.447L65.337,293.453L65.741,293.457L66.146,293.458L66.551,293.457L66.955,293.453L67.359,293.447L67.762,293.438L68.164,293.426L68.566,293.412L68.967,293.396L69.368,293.377L69.767,293.355L70.166,293.331L70.565,293.304L70.962,293.275L71.359,293.244L71.756,293.21L72.151,293.173L72.546,293.135L72.94,293.093L73.333,293.049L73.726,293.003L74.118,292.955L74.509,292.904L74.899,292.85L75.289,292.794L75.677,292.736L76.065,292.676L76.453,292.613L76.839,292.547L77.224,292.48L77.609,292.409L77.993,292.337L78.376,292.262L78.758,292.185L79.14,292.106L79.52,292.024L79.9,291.94L80.279,291.854L80.657,291.765L81.034,291.675L81.41,291.581L81.785,291.486L82.159,291.388L82.533,291.288L82.905,291.186L83.277,291.082L83.647,290.975L84.017,290.866L84.386,290.755L84.754,290.642L85.121,290.527L85.486,290.409L85.851,290.289L86.215,290.167L86.578,290.043L86.94,289.917L87.301,289.788L87.661,289.658L88.02,289.525L88.377,289.39L88.734,289.253L89.09,289.114L89.445,288.973L89.798,288.829L90.151,288.684L90.502,288.537L90.853,288.387L91.202,288.235L91.55,288.082L91.897,287.926L92.243,287.768L92.588,287.608L92.932,287.446L93.274,287.282L93.616,287.117L93.956,286.949L94.295,286.779L94.633,286.607L94.97,286.433L95.306,286.257L95.64,286.079L95.973,285.899L96.305,285.718L96.636,285.534L96.966,285.348L97.294,285.161L97.621,284.971L97.947,284.78L98.271,284.586L98.595,284.391L98.917,284.194L99.238,283.995L99.557,283.794L99.875,283.592L100.192,283.387L100.508,283.18L100.822,282.972L101.135,282.762L101.447,282.55L101.757,282.336L102.066,282.121L102.374,281.903L102.68,281.684L102.985,281.463L103.288,281.24L103.59,281.016L103.891,280.789L104.19,280.561L104.488,280.331L104.785,280.1L105.08,279.866L105.373,279.631L105.665,279.394L105.956,279.156L106.246,278.916L106.533,278.674L106.82,278.43L107.104,278.185L107.388,277.938L107.67,277.689L107.95,277.439L108.229,277.187L108.506,276.933L108.782,276.678L109.056,276.421L109.329,276.163L109.6,275.903L109.87,275.641L110.138,275.378L110.404,275.113L110.669,274.846L110.933,274.578L111.194,274.309L111.454,274.037L111.713,273.765L111.97,273.49L112.225,273.215L112.479,272.937L112.731,272.658L112.981,272.378L113.23,272.096L113.476,271.813L113.722,271.528L113.965,271.242L114.207,270.954L114.448,270.665L114.686,270.374L114.923,270.082L115.158,269.788L115.391,269.493L115.623,269.197L115.853,268.899L116.081,268.599L116.307,268.299L116.532,267.997L116.755,267.693L116.976,267.388L117.195,267.082L117.412,266.774L117.628,266.465L117.842,266.155L118.054,265.843L118.264,265.531L118.472,265.216L118.679,264.901L118.883,264.584L119.086,264.265L119.287,263.946L119.486,263.625L119.683,263.303L119.878,262.98L120.071,262.655L120.263,262.329L120.452,262.002L120.64,261.674L120.826,261.344L121.009,261.014L121.191,260.682L121.371,260.348L121.549,260.014L121.725,259.678L121.898,259.342L122.07,259.004L122.24,258.664L122.408,258.324L122.574,257.983L122.738,257.64L122.9,257.296L123.06,256.952L123.217,256.606L123.373,256.258L123.527,255.91L123.679,255.561L123.828,255.211L123.976,254.859L124.121,254.507L124.264,254.153L124.406,253.798L124.545,253.443L124.682,253.086L124.817,252.728L124.949,252.369L125.08,252.009L125.208,251.648L125.335,251.286L125.459,250.923L125.581,250.56L125.701,250.195L125.818,249.829L125.934,249.462L126.047,249.094L126.158,248.726L126.267,248.356L126.374,247.985L126.478,247.614L126.58,247.241L126.68,246.868L126.778,246.493L126.873,246.118L126.966,245.742L127.057,245.365L127.146,244.987L127.232,244.608L127.316,244.229L127.398,243.848L127.477,243.467L127.554,243.084L127.629,242.701L127.701,242.317L127.771,241.933L127.839,241.547L127.904,241.161L127.967,240.774L128.028,240.386L128.086,239.997L128.142,239.608L128.195,239.217L128.246,238.826L128.295,238.434L128.341,238.042L128.385,237.648L128.426,237.254L128.465,236.859L128.502,236.464L128.535,236.068L128.567,235.671L128.596,235.273L128.623,234.875L128.647,234.476L128.668,234.076L128.687,233.676L128.704,233.274L128.718,232.873L128.729,232.47L128.738,232.067L128.745,231.664L128.748,231.259L128.75,230.854L128.748,230.449L128.745,230.045L128.738,229.641L128.729,229.238L128.718,228.836L128.704,228.434L128.687,228.033L128.668,227.632L128.647,227.233L128.623,226.834L128.596,226.435L128.567,226.038L128.535,225.641L128.502,225.244L128.465,224.849L128.426,224.454L128.385,224.06L128.341,223.667L128.295,223.274L128.246,222.882L128.195,222.491L128.142,222.101L128.086,221.711L128.028,221.323L127.967,220.935L127.904,220.547L127.839,220.161L127.771,219.776L127.701,219.391L127.629,219.007L127.554,218.624L127.477,218.242L127.398,217.86L127.316,217.48L127.232,217.1L127.146,216.721L127.057,216.343L126.966,215.966L126.873,215.59L126.778,215.215L126.68,214.841L126.58,214.467L126.478,214.095L126.374,213.723L126.267,213.353L126.158,212.983L126.047,212.614L125.934,212.246L125.818,211.879L125.701,211.514L125.581,211.149L125.459,210.785L125.335,210.422L125.208,210.06L125.08,209.699L124.949,209.339L124.817,208.98L124.682,208.623L124.545,208.266L124.406,207.91L124.264,207.555L124.121,207.202L123.976,206.849L123.828,206.498L123.679,206.147L123.527,205.798L123.373,205.45L123.217,205.103L123.06,204.757L122.9,204.412L122.738,204.068L122.574,203.726L122.408,203.384L122.24,203.044L122.07,202.705L121.898,202.367L121.725,202.03L121.549,201.694L121.371,201.36L121.191,201.027L121.009,200.695L120.826,200.364L120.64,200.034L120.452,199.706L120.263,199.379L120.071,199.053L119.878,198.729L119.683,198.405L119.486,198.083L119.287,197.762L119.086,197.443L118.883,197.125L118.679,196.808L118.472,196.492L118.264,196.178L118.054,195.865L117.842,195.553L117.628,195.243L117.412,194.934L117.195,194.626L116.976,194.32L116.755,194.015L116.532,193.712L116.307,193.41L116.081,193.109L115.853,192.81L115.623,192.512L115.391,192.215L115.158,191.92L114.923,191.627L114.686,191.334L114.448,191.044L114.207,190.755L113.965,190.467L113.722,190.18L113.476,189.896L113.23,189.612L112.981,189.33L112.731,189.05L112.479,188.771L112.225,188.494L111.97,188.218L111.713,187.944L111.454,187.671L111.194,187.4L110.933,187.13L110.669,186.862L110.404,186.596L110.138,186.331L109.87,186.067L109.6,185.806L109.329,185.546L109.056,185.287L108.782,185.03L108.506,184.775L108.229,184.521L107.95,184.269L107.67,184.019L107.388,183.77L107.104,183.524L106.82,183.278L106.533,183.035L106.246,182.793L105.956,182.552L105.666,182.314L105.373,182.077L105.08,181.842L104.785,181.609L104.488,181.377L104.19,181.147L103.891,180.919L103.59,180.693L103.288,180.468L102.985,180.245L102.68,180.024L102.374,179.805L102.066,179.588L101.757,179.372L101.447,179.158L101.135,178.946L100.822,178.736L100.508,178.528L100.192,178.321L99.875,178.117L99.557,177.914L99.238,177.713L98.917,177.514L98.595,177.317L98.271,177.122L97.947,176.929L97.621,176.737L97.294,176.548L96.966,176.36L96.636,176.174L96.305,175.991L95.973,175.809L95.64,175.629L95.306,175.451L94.97,175.275L94.633,175.102L94.295,174.93L93.956,174.76L93.616,174.592L93.274,174.426L92.932,174.262L92.588,174.1L92.243,173.94L91.897,173.783L91.55,173.627L91.202,173.473L90.853,173.321L90.502,173.172L90.151,173.024L89.798,172.879L89.445,172.736L89.09,172.594L88.734,172.455L88.377,172.318L88.02,172.183L87.661,172.051L87.301,171.92L86.94,171.792L86.578,171.665L86.215,171.541L85.851,171.419L85.486,171.299L85.121,171.182L84.754,171.066L84.386,170.953L84.017,170.842L83.647,170.733L83.277,170.626L82.905,170.522L82.533,170.42L82.159,170.32L81.785,170.222L81.41,170.127L81.034,170.034L80.657,169.943L80.279,169.854L79.9,169.768L79.52,169.684L79.14,169.602L78.758,169.523L78.376,169.446L77.993,169.371L77.609,169.299L77.224,169.229L76.839,169.161L76.453,169.096L76.065,169.033L75.677,168.972L75.289,168.914L74.899,168.858L74.509,168.805L74.118,168.754L73.726,168.705L73.333,168.659L72.94,168.615L72.546,168.574L72.151,168.535L71.756,168.498L71.359,168.465L70.962,168.433L70.565,168.404L70.166,168.377L69.767,168.353L69.368,168.332L68.967,168.313L68.566,168.296L68.164,168.282L67.762,168.271L67.359,168.262L66.955,168.255L66.551,168.252L66.146,168.25L65.741,168.252Z" style="fill:white;"/>
+ </g>
+ <g id="g4154" transform="matrix(1,0,0,1,-2.58446,2.58446)">
+ <path id="path4982" d="M104.215,201.977L42.438,263.755L33.245,254.562L95.023,192.785L104.215,201.977Z" style="fill:white;"/>
+ <path id="path4152" d="M104.215,254.562L95.023,263.755L33.245,201.977L42.438,192.785L104.215,254.562Z" style="fill:white;"/>
+ </g>
+ </g>
+</svg>
diff --git a/Swift/resources/icons/delivery-success.svg b/Swift/resources/icons/delivery-success.svg
new file mode 100644
index 0000000..faf6ae1
--- /dev/null
+++ b/Swift/resources/icons/delivery-success.svg
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg width="100%" height="100%" viewBox="0 0 133 133" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:1.41421;">
+ <g id="Layer-1" transform="matrix(1,0,0,1,0,-164.708)">
+ <g id="path4233" transform="matrix(1.00826,0,0,1.00826,-0.546361,-1.90685)">
+ <circle cx="66.146" cy="230.854" r="65.604" style="fill:rgb(146,196,126);"/>
+ <path d="M66.57,165.252L66.993,165.256L67.416,165.262L67.838,165.272L68.259,165.284L68.68,165.298L69.1,165.316L69.52,165.336L69.938,165.358L70.356,165.383L70.774,165.411L71.19,165.442L71.606,165.475L72.021,165.51L72.436,165.548L72.849,165.589L73.262,165.632L73.675,165.678L74.086,165.727L74.497,165.778L74.906,165.831L75.315,165.887L75.724,165.946L76.131,166.007L76.538,166.07L76.943,166.136L77.348,166.205L77.753,166.276L78.156,166.349L78.558,166.425L78.96,166.503L79.36,166.584L79.76,166.667L80.159,166.753L80.557,166.841L80.954,166.931L81.35,167.024L81.746,167.119L82.14,167.217L82.533,167.317L82.926,167.419L83.317,167.524L83.708,167.631L84.097,167.741L84.486,167.852L84.873,167.967L85.26,168.083L85.645,168.202L86.03,168.323L86.414,168.446L86.796,168.572L87.178,168.7L87.558,168.83L87.937,168.962L88.316,169.097L88.693,169.234L89.069,169.373L89.444,169.514L89.818,169.658L90.191,169.804L90.563,169.952L90.934,170.102L91.303,170.255L91.672,170.409L92.039,170.566L92.405,170.725L92.77,170.886L93.134,171.049L93.496,171.215L93.858,171.382L94.218,171.552L94.577,171.724L94.935,171.898L95.292,172.074L95.647,172.252L96.001,172.432L96.354,172.614L96.706,172.798L97.057,172.985L97.406,173.173L97.754,173.364L98.1,173.556L98.446,173.751L98.79,173.947L99.133,174.146L99.474,174.346L99.814,174.549L100.153,174.754L100.491,174.96L100.827,175.169L101.162,175.379L101.495,175.592L101.827,175.806L102.158,176.022L102.487,176.241L102.815,176.461L103.141,176.683L103.467,176.907L103.79,177.133L104.113,177.361L104.433,177.59L104.753,177.822L105.071,178.055L105.387,178.291L105.702,178.528L106.016,178.767L106.328,179.007L106.639,179.25L106.948,179.495L107.255,179.741L107.561,179.989L107.866,180.239L108.169,180.49L108.471,180.744L108.77,180.999L109.069,181.256L109.366,181.515L109.661,181.775L109.955,182.037L110.247,182.301L110.537,182.567L110.826,182.834L111.114,183.104L111.399,183.374L111.683,183.647L111.966,183.921L112.247,184.197L112.526,184.474L112.803,184.753L113.079,185.034L113.353,185.317L113.626,185.601L113.896,185.886L114.166,186.174L114.433,186.463L114.699,186.753L114.963,187.045L115.225,187.339L115.485,187.634L115.744,187.931L116.001,188.23L116.256,188.529L116.51,188.831L116.761,189.134L117.011,189.439L117.259,189.745L117.505,190.052L117.75,190.361L117.993,190.672L118.233,190.984L118.472,191.298L118.709,191.613L118.945,191.929L119.178,192.247L119.41,192.567L119.639,192.887L119.867,193.21L120.093,193.533L120.317,193.859L120.539,194.185L120.759,194.513L120.978,194.842L121.194,195.173L121.408,195.505L121.621,195.838L121.831,196.173L122.04,196.509L122.246,196.847L122.451,197.186L122.654,197.526L122.854,197.867L123.053,198.21L123.249,198.554L123.444,198.9L123.636,199.246L123.827,199.594L124.015,199.943L124.202,200.294L124.386,200.646L124.568,200.999L124.748,201.353L124.927,201.708L125.102,202.065L125.276,202.423L125.448,202.782L125.618,203.142L125.785,203.504L125.951,203.866L126.114,204.23L126.275,204.595L126.434,204.961L126.591,205.328L126.746,205.697L126.898,206.066L127.048,206.437L127.196,206.809L127.342,207.182L127.486,207.556L127.627,207.931L127.766,208.307L127.903,208.684L128.038,209.063L128.17,209.442L128.3,209.822L128.428,210.204L128.554,210.586L128.677,210.97L128.798,211.355L128.917,211.74L129.033,212.127L129.148,212.514L129.259,212.903L129.369,213.292L129.476,213.683L129.581,214.074L129.683,214.467L129.783,214.86L129.881,215.255L129.976,215.65L130.069,216.046L130.159,216.443L130.247,216.841L130.333,217.24L130.416,217.64L130.497,218.04L130.575,218.442L130.651,218.844L130.724,219.247L130.795,219.652L130.864,220.057L130.93,220.462L130.993,220.869L131.054,221.276L131.113,221.685L131.169,222.094L131.222,222.503L131.273,222.914L131.322,223.325L131.368,223.738L131.411,224.151L131.452,224.564L131.49,224.979L131.525,225.394L131.558,225.81L131.589,226.226L131.617,226.644L131.642,227.062L131.664,227.48L131.684,227.9L131.702,228.32L131.716,228.741L131.728,229.162L131.738,229.584L131.744,230.007L131.748,230.43L131.75,230.854L131.748,231.278L131.744,231.702L131.738,232.124L131.728,232.546L131.716,232.968L131.702,233.389L131.684,233.809L131.664,234.228L131.642,234.647L131.617,235.065L131.589,235.482L131.558,235.899L131.525,236.315L131.49,236.73L131.452,237.144L131.411,237.558L131.368,237.971L131.322,238.383L131.273,238.794L131.222,239.205L131.169,239.615L131.113,240.024L131.054,240.432L130.993,240.839L130.93,241.246L130.864,241.652L130.795,242.057L130.724,242.461L130.651,242.864L130.575,243.266L130.497,243.668L130.416,244.069L130.333,244.468L130.247,244.867L130.159,245.265L130.069,245.662L129.976,246.059L129.881,246.454L129.783,246.848L129.683,247.242L129.581,247.634L129.476,248.025L129.369,248.416L129.259,248.805L129.148,249.194L129.033,249.582L128.917,249.968L128.798,250.354L128.677,250.738L128.554,251.122L128.428,251.504L128.3,251.886L128.17,252.266L128.038,252.646L127.903,253.024L127.766,253.401L127.627,253.777L127.486,254.153L127.342,254.527L127.196,254.899L127.048,255.271L126.898,255.642L126.746,256.012L126.591,256.38L126.434,256.747L126.275,257.113L126.114,257.478L125.951,257.842L125.785,258.205L125.618,258.566L125.448,258.927L125.276,259.286L125.102,259.643L124.927,260L124.748,260.356L124.568,260.71L124.386,261.063L124.202,261.414L124.015,261.765L123.827,262.114L123.636,262.462L123.444,262.809L123.249,263.154L123.053,263.498L122.854,263.841L122.654,264.182L122.451,264.523L122.246,264.861L122.04,265.199L121.831,265.535L121.621,265.87L121.408,266.203L121.194,266.535L120.978,266.866L120.759,267.195L120.539,267.523L120.317,267.85L120.093,268.175L119.867,268.499L119.639,268.821L119.41,269.142L119.178,269.461L118.945,269.779L118.709,270.096L118.472,270.411L118.233,270.724L117.993,271.036L117.75,271.347L117.505,271.656L117.259,271.964L117.011,272.27L116.761,272.574L116.51,272.877L116.256,273.179L116.001,273.479L115.744,273.777L115.485,274.074L115.225,274.369L114.963,274.663L114.699,274.955L114.433,275.246L114.166,275.535L113.896,275.822L113.626,276.108L113.353,276.392L113.079,276.674L112.803,276.955L112.526,277.234L112.247,277.512L111.966,277.787L111.683,278.062L111.399,278.334L111.114,278.605L110.826,278.874L110.537,279.141L110.247,279.407L109.955,279.671L109.661,279.933L109.366,280.194L109.069,280.452L108.77,280.709L108.471,280.964L108.169,281.218L107.866,281.47L107.561,281.719L107.255,281.967L106.948,282.214L106.639,282.458L106.328,282.701L106.016,282.942L105.702,283.181L105.387,283.418L105.071,283.653L104.753,283.887L104.433,284.118L104.113,284.348L103.79,284.576L103.467,284.801L103.141,285.025L102.815,285.248L102.487,285.468L102.158,285.686L101.827,285.902L101.495,286.117L101.162,286.329L100.827,286.54L100.491,286.748L100.153,286.955L99.814,287.159L99.474,287.362L99.133,287.563L98.79,287.761L98.446,287.958L98.1,288.152L97.754,288.345L97.406,288.535L97.057,288.724L96.706,288.91L96.354,289.094L96.001,289.277L95.647,289.457L95.292,289.635L94.935,289.811L94.577,289.985L94.218,290.157L93.858,290.326L93.496,290.494L93.134,290.659L92.77,290.822L92.405,290.983L92.039,291.142L91.672,291.299L91.303,291.454L90.934,291.606L90.563,291.757L90.191,291.905L89.818,292.05L89.444,292.194L89.069,292.335L88.693,292.475L88.316,292.611L87.937,292.746L87.558,292.879L87.178,293.009L86.796,293.137L86.414,293.262L86.03,293.386L85.645,293.507L85.26,293.625L84.873,293.742L84.486,293.856L84.097,293.968L83.708,294.077L83.317,294.184L82.926,294.289L82.533,294.391L82.14,294.491L81.746,294.589L81.35,294.684L80.954,294.777L80.557,294.867L80.159,294.955L79.76,295.041L79.36,295.124L78.96,295.205L78.558,295.283L78.156,295.359L77.753,295.433L77.348,295.504L76.943,295.572L76.538,295.638L76.131,295.702L75.724,295.763L75.315,295.821L74.906,295.877L74.497,295.931L74.086,295.982L73.675,296.03L73.262,296.076L72.849,296.119L72.436,296.16L72.021,296.198L71.606,296.234L71.19,296.267L70.774,296.297L70.356,296.325L69.938,296.35L69.52,296.373L69.1,296.393L68.68,296.41L68.259,296.425L67.838,296.437L67.416,296.446L66.993,296.453L66.57,296.457L66.146,296.458L65.722,296.457L65.298,296.453L64.876,296.446L64.454,296.437L64.032,296.425L63.611,296.41L63.191,296.393L62.772,296.373L62.353,296.35L61.935,296.325L61.518,296.297L61.101,296.267L60.685,296.234L60.27,296.198L59.856,296.16L59.442,296.119L59.029,296.076L58.617,296.03L58.206,295.982L57.795,295.931L57.385,295.877L56.976,295.821L56.568,295.763L56.161,295.702L55.754,295.638L55.348,295.572L54.943,295.504L54.539,295.433L54.136,295.359L53.734,295.283L53.332,295.205L52.931,295.124L52.532,295.041L52.133,294.955L51.735,294.867L51.338,294.777L50.941,294.684L50.546,294.589L50.152,294.491L49.758,294.391L49.366,294.289L48.975,294.184L48.584,294.077L48.195,293.968L47.806,293.856L47.418,293.742L47.032,293.625L46.646,293.507L46.262,293.386L45.878,293.262L45.496,293.137L45.114,293.009L44.734,292.879L44.354,292.746L43.976,292.611L43.599,292.475L43.223,292.335L42.847,292.194L42.473,292.05L42.101,291.905L41.729,291.757L41.358,291.606L40.988,291.454L40.62,291.299L40.253,291.142L39.887,290.983L39.522,290.822L39.158,290.659L38.795,290.494L38.434,290.326L38.073,290.157L37.714,289.985L37.357,289.811L37,289.635L36.644,289.457L36.29,289.277L35.937,289.094L35.586,288.91L35.235,288.724L34.886,288.535L34.538,288.345L34.191,288.152L33.846,287.958L33.502,287.761L33.159,287.563L32.818,287.362L32.477,287.159L32.139,286.955L31.801,286.748L31.465,286.54L31.13,286.329L30.797,286.117L30.465,285.902L30.134,285.686L29.805,285.468L29.477,285.248L29.15,285.025L28.825,284.801L28.501,284.576L28.179,284.348L27.858,284.118L27.539,283.887L27.221,283.653L26.904,283.418L26.589,283.181L26.276,282.942L25.964,282.701L25.653,282.458L25.344,282.214L25.036,281.967L24.73,281.719L24.426,281.47L24.123,281.218L23.821,280.964L23.521,280.709L23.223,280.452L22.926,280.194L22.631,279.933L22.337,279.671L22.045,279.407L21.754,279.141L21.465,278.874L21.178,278.605L20.892,278.334L20.608,278.062L20.326,277.787L20.045,277.512L19.766,277.234L19.488,276.955L19.213,276.674L18.938,276.392L18.666,276.108L18.395,275.822L18.126,275.535L17.859,275.246L17.593,274.955L17.329,274.663L17.067,274.369L16.806,274.074L16.548,273.777L16.291,273.479L16.036,273.179L15.782,272.877L15.53,272.574L15.281,272.27L15.033,271.964L14.786,271.656L14.542,271.347L14.299,271.036L14.058,270.724L13.819,270.411L13.582,270.096L13.347,269.779L13.113,269.461L12.882,269.142L12.652,268.821L12.424,268.499L12.199,268.175L11.975,267.85L11.752,267.523L11.532,267.195L11.314,266.866L11.098,266.535L10.883,266.203L10.671,265.87L10.46,265.535L10.252,265.199L10.045,264.861L9.841,264.523L9.638,264.182L9.437,263.841L9.239,263.498L9.042,263.154L8.848,262.809L8.655,262.462L8.465,262.114L8.276,261.765L8.09,261.414L7.906,261.063L7.723,260.71L7.543,260.356L7.365,260L7.189,259.643L7.015,259.286L6.844,258.927L6.674,258.566L6.506,258.205L6.341,257.842L6.178,257.478L6.017,257.113L5.858,256.747L5.701,256.38L5.546,256.012L5.394,255.642L5.243,255.271L5.095,254.899L4.95,254.527L4.806,254.153L4.665,253.777L4.525,253.401L4.389,253.024L4.254,252.646L4.121,252.266L3.991,251.886L3.863,251.504L3.738,251.122L3.614,250.738L3.493,250.354L3.375,249.968L3.258,249.582L3.144,249.194L3.032,248.805L2.923,248.416L2.816,248.025L2.711,247.634L2.609,247.242L2.509,246.848L2.411,246.454L2.316,246.059L2.223,245.662L2.133,245.265L2.045,244.867L1.959,244.468L1.876,244.069L1.795,243.668L1.717,243.266L1.641,242.864L1.567,242.461L1.496,242.057L1.428,241.652L1.362,241.246L1.298,240.839L1.237,240.432L1.179,240.024L1.123,239.615L1.069,239.205L1.018,238.794L0.97,238.383L0.924,237.971L0.881,237.558L0.84,237.144L0.802,236.73L0.766,236.315L0.733,235.899L0.703,235.482L0.675,235.065L0.65,234.647L0.627,234.228L0.607,233.809L0.59,233.389L0.575,232.968L0.563,232.546L0.554,232.124L0.547,231.702L0.543,231.278L0.542,230.854L0.543,230.43L0.547,230.007L0.554,229.584L0.563,229.162L0.575,228.741L0.59,228.32L0.607,227.9L0.627,227.48L0.65,227.062L0.675,226.644L0.703,226.226L0.733,225.81L0.766,225.394L0.802,224.979L0.84,224.564L0.881,224.151L0.924,223.738L0.97,223.325L1.018,222.914L1.069,222.503L1.123,222.094L1.179,221.685L1.237,221.276L1.298,220.869L1.362,220.462L1.428,220.057L1.496,219.652L1.567,219.247L1.641,218.844L1.717,218.442L1.795,218.04L1.876,217.64L1.959,217.24L2.045,216.841L2.133,216.443L2.223,216.046L2.316,215.65L2.411,215.255L2.509,214.86L2.609,214.467L2.711,214.074L2.816,213.683L2.923,213.292L3.032,212.903L3.144,212.514L3.258,212.127L3.375,211.74L3.493,211.355L3.614,210.97L3.738,210.586L3.863,210.204L3.991,209.822L4.121,209.442L4.254,209.063L4.389,208.684L4.525,208.307L4.665,207.931L4.806,207.556L4.95,207.182L5.095,206.809L5.243,206.437L5.394,206.066L5.546,205.697L5.701,205.328L5.858,204.961L6.017,204.595L6.178,204.23L6.341,203.866L6.506,203.504L6.674,203.142L6.844,202.782L7.015,202.423L7.189,202.065L7.365,201.708L7.543,201.353L7.723,200.999L7.906,200.646L8.09,200.294L8.276,199.943L8.465,199.594L8.655,199.246L8.848,198.9L9.042,198.554L9.239,198.21L9.437,197.867L9.638,197.526L9.841,197.186L10.045,196.847L10.252,196.509L10.46,196.173L10.671,195.838L10.883,195.505L11.098,195.173L11.314,194.842L11.532,194.513L11.752,194.185L11.975,193.859L12.199,193.533L12.424,193.21L12.652,192.887L12.882,192.567L13.113,192.247L13.347,191.929L13.582,191.613L13.819,191.298L14.058,190.984L14.299,190.672L14.542,190.361L14.786,190.052L15.033,189.745L15.281,189.439L15.53,189.134L15.782,188.831L16.036,188.529L16.291,188.23L16.548,187.931L16.806,187.634L17.067,187.339L17.329,187.045L17.593,186.753L17.859,186.463L18.126,186.174L18.395,185.886L18.666,185.601L18.938,185.317L19.213,185.034L19.488,184.753L19.766,184.474L20.045,184.197L20.326,183.921L20.608,183.647L20.892,183.374L21.178,183.104L21.465,182.834L21.754,182.567L22.045,182.301L22.337,182.037L22.631,181.775L22.926,181.515L23.223,181.256L23.521,180.999L23.821,180.744L24.123,180.49L24.426,180.239L24.73,179.989L25.036,179.741L25.344,179.495L25.653,179.25L25.964,179.007L26.276,178.767L26.589,178.528L26.904,178.291L27.221,178.055L27.539,177.822L27.858,177.59L28.179,177.361L28.501,177.133L28.825,176.907L29.15,176.683L29.477,176.461L29.805,176.241L30.134,176.022L30.465,175.806L30.797,175.592L31.13,175.379L31.465,175.169L31.801,174.96L32.139,174.754L32.477,174.549L32.818,174.346L33.159,174.146L33.502,173.947L33.846,173.751L34.191,173.556L34.538,173.364L34.886,173.173L35.235,172.985L35.586,172.798L35.937,172.614L36.29,172.432L36.644,172.252L37,172.074L37.357,171.898L37.714,171.724L38.073,171.552L38.434,171.382L38.795,171.215L39.158,171.049L39.522,170.886L39.887,170.725L40.253,170.566L40.62,170.409L40.988,170.255L41.358,170.102L41.729,169.952L42.101,169.804L42.473,169.658L42.847,169.514L43.223,169.373L43.599,169.234L43.976,169.097L44.354,168.962L44.734,168.83L45.114,168.7L45.496,168.572L45.878,168.446L46.262,168.323L46.646,168.202L47.032,168.083L47.418,167.967L47.806,167.852L48.195,167.741L48.584,167.631L48.975,167.524L49.366,167.419L49.758,167.317L50.152,167.217L50.546,167.119L50.941,167.024L51.338,166.931L51.735,166.841L52.133,166.753L52.532,166.667L52.931,166.584L53.332,166.503L53.734,166.425L54.136,166.349L54.539,166.276L54.943,166.205L55.348,166.136L55.754,166.07L56.161,166.007L56.568,165.946L56.976,165.887L57.385,165.831L57.795,165.778L58.206,165.727L58.617,165.678L59.029,165.632L59.442,165.589L59.856,165.548L60.27,165.51L60.685,165.475L61.101,165.442L61.518,165.411L61.935,165.383L62.353,165.358L62.772,165.336L63.191,165.316L63.611,165.298L64.032,165.284L64.454,165.272L64.876,165.262L65.298,165.256L65.722,165.252L66.146,165.25L66.57,165.252ZM65.741,168.252L65.337,168.255L64.933,168.262L64.53,168.271L64.127,168.282L63.726,168.296L63.325,168.313L62.924,168.332L62.524,168.353L62.125,168.377L61.727,168.404L61.329,168.433L60.932,168.465L60.536,168.498L60.141,168.535L59.746,168.574L59.352,168.615L58.958,168.659L58.566,168.705L58.174,168.754L57.783,168.805L57.393,168.858L57.003,168.914L56.614,168.972L56.226,169.033L55.839,169.096L55.453,169.161L55.067,169.229L54.683,169.299L54.299,169.371L53.916,169.446L53.533,169.523L53.152,169.602L52.771,169.684L52.392,169.768L52.013,169.854L51.635,169.943L51.258,170.034L50.882,170.127L50.507,170.222L50.132,170.32L49.759,170.42L49.386,170.522L49.015,170.626L48.644,170.733L48.275,170.842L47.906,170.953L47.538,171.066L47.171,171.182L46.805,171.299L46.44,171.419L46.076,171.541L45.714,171.665L45.352,171.792L44.991,171.92L44.631,172.051L44.272,172.183L43.914,172.318L43.557,172.455L43.202,172.594L42.847,172.736L42.493,172.879L42.141,173.024L41.789,173.172L41.439,173.321L41.09,173.473L40.742,173.627L40.394,173.783L40.048,173.94L39.704,174.1L39.36,174.262L39.017,174.426L38.676,174.592L38.336,174.76L37.996,174.93L37.658,175.102L37.322,175.275L36.986,175.451L36.652,175.629L36.318,175.809L35.986,175.991L35.656,176.174L35.326,176.36L34.998,176.548L34.671,176.737L34.345,176.929L34.02,177.122L33.697,177.317L33.375,177.514L33.054,177.713L32.735,177.914L32.416,178.117L32.099,178.321L31.784,178.528L31.47,178.736L31.157,178.946L30.845,179.158L30.535,179.372L30.226,179.588L29.918,179.805L29.612,180.024L29.307,180.245L29.003,180.468L28.701,180.693L28.401,180.919L28.101,181.147L27.803,181.377L27.507,181.609L27.212,181.842L26.918,182.077L26.626,182.314L26.335,182.552L26.046,182.793L25.758,183.035L25.472,183.278L25.187,183.524L24.904,183.77L24.622,184.019L24.342,184.269L24.063,184.521L23.785,184.775L23.51,185.03L23.235,185.287L22.963,185.546L22.691,185.806L22.422,186.067L22.154,186.331L21.887,186.596L21.622,186.862L21.359,187.13L21.097,187.4L20.837,187.671L20.579,187.944L20.322,188.218L20.067,188.494L19.813,188.771L19.561,189.05L19.311,189.33L19.062,189.612L18.815,189.896L18.57,190.18L18.326,190.467L18.084,190.754L17.844,191.044L17.606,191.334L17.369,191.627L17.134,191.92L16.9,192.215L16.669,192.512L16.439,192.81L16.211,193.109L15.984,193.41L15.76,193.712L15.537,194.015L15.316,194.32L15.097,194.626L14.879,194.934L14.664,195.243L14.45,195.553L14.238,195.865L14.028,196.178L13.82,196.492L13.613,196.808L13.408,197.125L13.206,197.443L13.005,197.762L12.806,198.083L12.609,198.405L12.414,198.729L12.22,199.053L12.029,199.379L11.839,199.706L11.652,200.034L11.466,200.364L11.282,200.695L11.101,201.027L10.921,201.36L10.743,201.694L10.567,202.03L10.393,202.367L10.221,202.705L10.051,203.044L9.884,203.384L9.718,203.726L9.554,204.068L9.392,204.412L9.232,204.757L9.074,205.103L8.918,205.45L8.765,205.798L8.613,206.147L8.464,206.498L8.316,206.849L8.171,207.202L8.027,207.555L7.886,207.91L7.747,208.266L7.61,208.623L7.475,208.98L7.342,209.339L7.212,209.699L7.083,210.06L6.957,210.422L6.833,210.785L6.711,211.149L6.591,211.514L6.473,211.879L6.358,212.246L6.245,212.614L6.134,212.983L6.025,213.353L5.918,213.723L5.814,214.095L5.712,214.467L5.612,214.841L5.514,215.215L5.419,215.59L5.325,215.966L5.235,216.343L5.146,216.721L5.06,217.1L4.976,217.48L4.894,217.86L4.815,218.242L4.738,218.624L4.663,219.007L4.591,219.391L4.52,219.776L4.453,220.161L4.387,220.547L4.324,220.935L4.264,221.323L4.206,221.711L4.15,222.101L4.096,222.491L4.045,222.882L3.997,223.274L3.951,223.667L3.907,224.06L3.865,224.454L3.827,224.849L3.79,225.244L3.756,225.641L3.725,226.038L3.696,226.435L3.669,226.834L3.645,227.233L3.623,227.632L3.604,228.033L3.588,228.434L3.574,228.836L3.562,229.238L3.553,229.641L3.547,230.045L3.543,230.449L3.542,230.854L3.543,231.259L3.547,231.663L3.553,232.067L3.562,232.47L3.574,232.873L3.588,233.274L3.604,233.676L3.623,234.076L3.645,234.476L3.669,234.875L3.696,235.273L3.725,235.671L3.756,236.068L3.79,236.464L3.827,236.859L3.865,237.254L3.907,237.648L3.951,238.042L3.997,238.434L4.045,238.826L4.096,239.217L4.15,239.607L4.206,239.997L4.264,240.386L4.324,240.774L4.387,241.161L4.453,241.547L4.52,241.933L4.591,242.317L4.663,242.701L4.738,243.084L4.815,243.467L4.894,243.848L4.976,244.229L5.06,244.608L5.146,244.987L5.235,245.365L5.325,245.742L5.419,246.118L5.514,246.493L5.612,246.868L5.712,247.241L5.814,247.614L5.918,247.985L6.025,248.356L6.134,248.725L6.245,249.094L6.358,249.462L6.473,249.829L6.591,250.195L6.711,250.56L6.833,250.924L6.957,251.286L7.083,251.648L7.212,252.009L7.342,252.369L7.475,252.728L7.61,253.086L7.747,253.443L7.886,253.798L8.027,254.153L8.171,254.507L8.316,254.859L8.464,255.211L8.613,255.561L8.765,255.91L8.918,256.258L9.074,256.606L9.232,256.952L9.392,257.296L9.554,257.64L9.718,257.983L9.884,258.324L10.051,258.664L10.221,259.004L10.393,259.342L10.567,259.678L10.743,260.014L10.921,260.348L11.101,260.682L11.282,261.014L11.466,261.344L11.652,261.674L11.839,262.002L12.029,262.329L12.22,262.655L12.414,262.98L12.609,263.303L12.806,263.625L13.005,263.946L13.206,264.265L13.408,264.584L13.613,264.901L13.82,265.216L14.028,265.531L14.238,265.843L14.45,266.155L14.664,266.465L14.879,266.774L15.097,267.082L15.316,267.388L15.537,267.693L15.76,267.997L15.984,268.299L16.211,268.599L16.439,268.899L16.669,269.197L16.9,269.493L17.134,269.788L17.369,270.082L17.606,270.374L17.844,270.665L18.084,270.954L18.326,271.242L18.57,271.528L18.815,271.813L19.062,272.096L19.311,272.378L19.561,272.658L19.813,272.937L20.067,273.215L20.322,273.49L20.579,273.765L20.837,274.037L21.097,274.309L21.359,274.578L21.622,274.846L21.887,275.113L22.154,275.378L22.422,275.641L22.691,275.903L22.963,276.163L23.235,276.421L23.51,276.678L23.785,276.933L24.063,277.187L24.342,277.439L24.622,277.689L24.904,277.938L25.187,278.185L25.472,278.43L25.758,278.674L26.046,278.916L26.335,279.156L26.626,279.394L26.918,279.631L27.212,279.866L27.507,280.1L27.803,280.331L28.101,280.561L28.401,280.789L28.701,281.016L29.003,281.24L29.307,281.463L29.612,281.684L29.918,281.903L30.226,282.121L30.535,282.336L30.845,282.55L31.157,282.762L31.47,282.972L31.784,283.18L32.099,283.387L32.416,283.592L32.735,283.794L33.054,283.995L33.375,284.194L33.697,284.391L34.02,284.586L34.345,284.78L34.671,284.971L34.998,285.161L35.326,285.348L35.656,285.534L35.986,285.718L36.318,285.899L36.652,286.079L36.986,286.257L37.322,286.433L37.658,286.607L37.996,286.779L38.336,286.949L38.676,287.117L39.017,287.282L39.36,287.446L39.704,287.608L40.048,287.768L40.394,287.926L40.742,288.082L41.09,288.235L41.439,288.387L41.789,288.537L42.141,288.684L42.493,288.829L42.847,288.973L43.202,289.114L43.557,289.253L43.914,289.39L44.272,289.525L44.631,289.658L44.991,289.788L45.352,289.917L45.714,290.043L46.076,290.167L46.44,290.289L46.805,290.409L47.171,290.527L47.538,290.642L47.906,290.755L48.275,290.866L48.644,290.975L49.015,291.082L49.386,291.186L49.759,291.288L50.132,291.388L50.507,291.486L50.882,291.581L51.258,291.675L51.635,291.765L52.013,291.854L52.392,291.94L52.771,292.024L53.152,292.106L53.533,292.185L53.916,292.262L54.299,292.337L54.683,292.409L55.067,292.48L55.453,292.547L55.839,292.613L56.226,292.676L56.614,292.736L57.003,292.794L57.393,292.85L57.783,292.904L58.174,292.955L58.566,293.003L58.958,293.049L59.352,293.093L59.746,293.135L60.14,293.173L60.536,293.21L60.932,293.244L61.329,293.275L61.727,293.304L62.125,293.331L62.524,293.355L62.924,293.377L63.324,293.396L63.726,293.412L64.127,293.426L64.53,293.438L64.933,293.447L65.337,293.453L65.741,293.457L66.146,293.458L66.551,293.457L66.955,293.453L67.359,293.447L67.762,293.438L68.164,293.426L68.566,293.412L68.967,293.396L69.368,293.377L69.767,293.355L70.166,293.331L70.565,293.304L70.962,293.275L71.359,293.244L71.756,293.21L72.151,293.173L72.546,293.135L72.94,293.093L73.333,293.049L73.726,293.003L74.118,292.955L74.509,292.904L74.899,292.85L75.289,292.794L75.677,292.736L76.065,292.676L76.453,292.613L76.839,292.547L77.224,292.48L77.609,292.409L77.993,292.337L78.376,292.262L78.758,292.185L79.14,292.106L79.52,292.024L79.9,291.94L80.279,291.854L80.657,291.765L81.034,291.675L81.41,291.581L81.785,291.486L82.159,291.388L82.533,291.288L82.905,291.186L83.277,291.082L83.647,290.975L84.017,290.866L84.386,290.755L84.754,290.642L85.121,290.527L85.486,290.409L85.851,290.289L86.215,290.167L86.578,290.043L86.94,289.917L87.301,289.788L87.661,289.658L88.02,289.525L88.377,289.39L88.734,289.253L89.09,289.114L89.445,288.973L89.798,288.829L90.151,288.684L90.502,288.537L90.853,288.387L91.202,288.235L91.55,288.082L91.897,287.926L92.243,287.768L92.588,287.608L92.932,287.446L93.274,287.282L93.616,287.117L93.956,286.949L94.295,286.779L94.633,286.607L94.97,286.433L95.306,286.257L95.64,286.079L95.973,285.899L96.305,285.718L96.636,285.534L96.966,285.348L97.294,285.161L97.621,284.971L97.947,284.78L98.271,284.586L98.595,284.391L98.917,284.194L99.238,283.995L99.557,283.794L99.875,283.592L100.192,283.387L100.508,283.18L100.822,282.972L101.135,282.762L101.447,282.55L101.757,282.336L102.066,282.121L102.374,281.903L102.68,281.684L102.985,281.463L103.288,281.24L103.59,281.016L103.891,280.789L104.19,280.561L104.488,280.331L104.785,280.1L105.08,279.866L105.373,279.631L105.665,279.394L105.956,279.156L106.246,278.916L106.533,278.674L106.82,278.43L107.104,278.185L107.388,277.938L107.67,277.689L107.95,277.439L108.229,277.187L108.506,276.933L108.782,276.678L109.056,276.421L109.329,276.163L109.6,275.903L109.87,275.641L110.138,275.378L110.404,275.113L110.669,274.846L110.933,274.578L111.194,274.309L111.454,274.037L111.713,273.765L111.97,273.49L112.225,273.215L112.479,272.937L112.731,272.658L112.981,272.378L113.23,272.096L113.476,271.813L113.722,271.528L113.965,271.242L114.207,270.954L114.448,270.665L114.686,270.374L114.923,270.082L115.158,269.788L115.391,269.493L115.623,269.197L115.853,268.899L116.081,268.599L116.307,268.299L116.532,267.997L116.755,267.693L116.976,267.388L117.195,267.082L117.412,266.774L117.628,266.465L117.842,266.155L118.054,265.843L118.264,265.531L118.472,265.216L118.679,264.901L118.883,264.584L119.086,264.265L119.287,263.946L119.486,263.625L119.683,263.303L119.878,262.98L120.071,262.655L120.263,262.329L120.452,262.002L120.64,261.674L120.826,261.344L121.009,261.014L121.191,260.682L121.371,260.348L121.549,260.014L121.725,259.678L121.898,259.342L122.07,259.004L122.24,258.664L122.408,258.324L122.574,257.983L122.738,257.64L122.9,257.296L123.06,256.952L123.217,256.606L123.373,256.258L123.527,255.91L123.679,255.561L123.828,255.211L123.976,254.859L124.121,254.507L124.264,254.153L124.406,253.798L124.545,253.443L124.682,253.086L124.817,252.728L124.949,252.369L125.08,252.009L125.208,251.648L125.335,251.286L125.459,250.923L125.581,250.56L125.701,250.195L125.818,249.829L125.934,249.462L126.047,249.094L126.158,248.726L126.267,248.356L126.374,247.985L126.478,247.614L126.58,247.241L126.68,246.868L126.778,246.493L126.873,246.118L126.966,245.742L127.057,245.365L127.146,244.987L127.232,244.608L127.316,244.229L127.398,243.848L127.477,243.467L127.554,243.084L127.629,242.701L127.701,242.317L127.771,241.933L127.839,241.547L127.904,241.161L127.967,240.774L128.028,240.386L128.086,239.997L128.142,239.608L128.195,239.217L128.246,238.826L128.295,238.434L128.341,238.042L128.385,237.648L128.426,237.254L128.465,236.859L128.502,236.464L128.535,236.068L128.567,235.671L128.596,235.273L128.623,234.875L128.647,234.476L128.668,234.076L128.687,233.676L128.704,233.274L128.718,232.873L128.729,232.47L128.738,232.067L128.745,231.664L128.748,231.259L128.75,230.854L128.748,230.449L128.745,230.045L128.738,229.641L128.729,229.238L128.718,228.836L128.704,228.434L128.687,228.033L128.668,227.632L128.647,227.233L128.623,226.834L128.596,226.435L128.567,226.038L128.535,225.641L128.502,225.244L128.465,224.849L128.426,224.454L128.385,224.06L128.341,223.667L128.295,223.274L128.246,222.882L128.195,222.491L128.142,222.101L128.086,221.711L128.028,221.323L127.967,220.935L127.904,220.547L127.839,220.161L127.771,219.776L127.701,219.391L127.629,219.007L127.554,218.624L127.477,218.242L127.398,217.86L127.316,217.48L127.232,217.1L127.146,216.721L127.057,216.343L126.966,215.966L126.873,215.59L126.778,215.215L126.68,214.841L126.58,214.467L126.478,214.095L126.374,213.723L126.267,213.353L126.158,212.983L126.047,212.614L125.934,212.246L125.818,211.879L125.701,211.514L125.581,211.149L125.459,210.785L125.335,210.422L125.208,210.06L125.08,209.699L124.949,209.339L124.817,208.98L124.682,208.623L124.545,208.266L124.406,207.91L124.264,207.555L124.121,207.202L123.976,206.849L123.828,206.498L123.679,206.147L123.527,205.798L123.373,205.45L123.217,205.103L123.06,204.757L122.9,204.412L122.738,204.068L122.574,203.726L122.408,203.384L122.24,203.044L122.07,202.705L121.898,202.367L121.725,202.03L121.549,201.694L121.371,201.36L121.191,201.027L121.009,200.695L120.826,200.364L120.64,200.034L120.452,199.706L120.263,199.379L120.071,199.053L119.878,198.729L119.683,198.405L119.486,198.083L119.287,197.762L119.086,197.443L118.883,197.125L118.679,196.808L118.472,196.492L118.264,196.178L118.054,195.865L117.842,195.553L117.628,195.243L117.412,194.934L117.195,194.626L116.976,194.32L116.755,194.015L116.532,193.712L116.307,193.41L116.081,193.109L115.853,192.81L115.623,192.512L115.391,192.215L115.158,191.92L114.923,191.627L114.686,191.334L114.448,191.044L114.207,190.755L113.965,190.467L113.722,190.18L113.476,189.896L113.23,189.612L112.981,189.33L112.731,189.05L112.479,188.771L112.225,188.494L111.97,188.218L111.713,187.944L111.454,187.671L111.194,187.4L110.933,187.13L110.669,186.862L110.404,186.596L110.138,186.331L109.87,186.067L109.6,185.806L109.329,185.546L109.056,185.287L108.782,185.03L108.506,184.775L108.229,184.521L107.95,184.269L107.67,184.019L107.388,183.77L107.104,183.524L106.82,183.278L106.533,183.035L106.246,182.793L105.956,182.552L105.666,182.314L105.373,182.077L105.08,181.842L104.785,181.609L104.488,181.377L104.19,181.147L103.891,180.919L103.59,180.693L103.288,180.468L102.985,180.245L102.68,180.024L102.374,179.805L102.066,179.588L101.757,179.372L101.447,179.158L101.135,178.946L100.822,178.736L100.508,178.528L100.192,178.321L99.875,178.117L99.557,177.914L99.238,177.713L98.917,177.514L98.595,177.317L98.271,177.122L97.947,176.929L97.621,176.737L97.294,176.548L96.966,176.36L96.636,176.174L96.305,175.991L95.973,175.809L95.64,175.629L95.306,175.451L94.97,175.275L94.633,175.102L94.295,174.93L93.956,174.76L93.616,174.592L93.274,174.426L92.932,174.262L92.588,174.1L92.243,173.94L91.897,173.783L91.55,173.627L91.202,173.473L90.853,173.321L90.502,173.172L90.151,173.024L89.798,172.879L89.445,172.736L89.09,172.594L88.734,172.455L88.377,172.318L88.02,172.183L87.661,172.051L87.301,171.92L86.94,171.792L86.578,171.665L86.215,171.541L85.851,171.419L85.486,171.299L85.121,171.182L84.754,171.066L84.386,170.953L84.017,170.842L83.647,170.733L83.277,170.626L82.905,170.522L82.533,170.42L82.159,170.32L81.785,170.222L81.41,170.127L81.034,170.034L80.657,169.943L80.279,169.854L79.9,169.768L79.52,169.684L79.14,169.602L78.758,169.523L78.376,169.446L77.993,169.371L77.609,169.299L77.224,169.229L76.839,169.161L76.453,169.096L76.065,169.033L75.677,168.972L75.289,168.914L74.899,168.858L74.509,168.805L74.118,168.754L73.726,168.705L73.333,168.659L72.94,168.615L72.546,168.574L72.151,168.535L71.756,168.498L71.359,168.465L70.962,168.433L70.565,168.404L70.166,168.377L69.767,168.353L69.368,168.332L68.967,168.313L68.566,168.296L68.164,168.282L67.762,168.271L67.359,168.262L66.955,168.255L66.551,168.252L66.146,168.25L65.741,168.252Z" style="fill:white;"/>
+ </g>
+ <path id="path4982" d="M106.02,213.402L57.326,262.095L26.272,231.041L35.464,221.848L57.326,243.71L96.827,204.209L106.02,213.402Z" style="fill:white;"/>
+ </g>
+</svg>
diff --git a/Swift/resources/icons/delivery-warning.svg b/Swift/resources/icons/delivery-warning.svg
new file mode 100644
index 0000000..940552e
--- /dev/null
+++ b/Swift/resources/icons/delivery-warning.svg
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg width="100%" height="100%" viewBox="0 0 133 133" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:1.41421;">
+ <g id="Layer-1" transform="matrix(1,0,0,1,0,-164.708)">
+ <g id="path4233" transform="matrix(1.00826,0,0,1.00826,-0.546361,-1.90685)">
+ <circle cx="66.146" cy="230.854" r="65.604" style="fill:rgb(219,203,103);"/>
+ <path d="M66.57,165.252L66.993,165.256L67.416,165.262L67.838,165.272L68.259,165.284L68.68,165.298L69.1,165.316L69.52,165.336L69.938,165.358L70.356,165.383L70.774,165.411L71.19,165.442L71.606,165.475L72.021,165.51L72.436,165.548L72.849,165.589L73.262,165.632L73.675,165.678L74.086,165.727L74.497,165.778L74.906,165.831L75.315,165.887L75.724,165.946L76.131,166.007L76.538,166.07L76.943,166.136L77.348,166.205L77.753,166.276L78.156,166.349L78.558,166.425L78.96,166.503L79.36,166.584L79.76,166.667L80.159,166.753L80.557,166.841L80.954,166.931L81.35,167.024L81.746,167.119L82.14,167.217L82.533,167.317L82.926,167.419L83.317,167.524L83.708,167.631L84.097,167.741L84.486,167.852L84.873,167.967L85.26,168.083L85.645,168.202L86.03,168.323L86.414,168.446L86.796,168.572L87.178,168.7L87.558,168.83L87.937,168.962L88.316,169.097L88.693,169.234L89.069,169.373L89.444,169.514L89.818,169.658L90.191,169.804L90.563,169.952L90.934,170.102L91.303,170.255L91.672,170.409L92.039,170.566L92.405,170.725L92.77,170.886L93.134,171.049L93.496,171.215L93.858,171.382L94.218,171.552L94.577,171.724L94.935,171.898L95.292,172.074L95.647,172.252L96.001,172.432L96.354,172.614L96.706,172.798L97.057,172.985L97.406,173.173L97.754,173.364L98.1,173.556L98.446,173.751L98.79,173.947L99.133,174.146L99.474,174.346L99.814,174.549L100.153,174.754L100.491,174.96L100.827,175.169L101.162,175.379L101.495,175.592L101.827,175.806L102.158,176.022L102.487,176.241L102.815,176.461L103.141,176.683L103.467,176.907L103.79,177.133L104.113,177.361L104.433,177.59L104.753,177.822L105.071,178.055L105.387,178.291L105.702,178.528L106.016,178.767L106.328,179.007L106.639,179.25L106.948,179.495L107.255,179.741L107.561,179.989L107.866,180.239L108.169,180.49L108.471,180.744L108.77,180.999L109.069,181.256L109.366,181.515L109.661,181.775L109.955,182.037L110.247,182.301L110.537,182.567L110.826,182.834L111.114,183.104L111.399,183.374L111.683,183.647L111.966,183.921L112.247,184.197L112.526,184.474L112.803,184.753L113.079,185.034L113.353,185.317L113.626,185.601L113.896,185.886L114.166,186.174L114.433,186.463L114.699,186.753L114.963,187.045L115.225,187.339L115.485,187.634L115.744,187.931L116.001,188.23L116.256,188.529L116.51,188.831L116.761,189.134L117.011,189.439L117.259,189.745L117.505,190.052L117.75,190.361L117.993,190.672L118.233,190.984L118.472,191.298L118.709,191.613L118.945,191.929L119.178,192.247L119.41,192.567L119.639,192.887L119.867,193.21L120.093,193.533L120.317,193.859L120.539,194.185L120.759,194.513L120.978,194.842L121.194,195.173L121.408,195.505L121.621,195.838L121.831,196.173L122.04,196.509L122.246,196.847L122.451,197.186L122.654,197.526L122.854,197.867L123.053,198.21L123.249,198.554L123.444,198.9L123.636,199.246L123.827,199.594L124.015,199.943L124.202,200.294L124.386,200.646L124.568,200.999L124.748,201.353L124.927,201.708L125.102,202.065L125.276,202.423L125.448,202.782L125.618,203.142L125.785,203.504L125.951,203.866L126.114,204.23L126.275,204.595L126.434,204.961L126.591,205.328L126.746,205.697L126.898,206.066L127.048,206.437L127.196,206.809L127.342,207.182L127.486,207.556L127.627,207.931L127.766,208.307L127.903,208.684L128.038,209.063L128.17,209.442L128.3,209.822L128.428,210.204L128.554,210.586L128.677,210.97L128.798,211.355L128.917,211.74L129.033,212.127L129.148,212.514L129.259,212.903L129.369,213.292L129.476,213.683L129.581,214.074L129.683,214.467L129.783,214.86L129.881,215.255L129.976,215.65L130.069,216.046L130.159,216.443L130.247,216.841L130.333,217.24L130.416,217.64L130.497,218.04L130.575,218.442L130.651,218.844L130.724,219.247L130.795,219.652L130.864,220.057L130.93,220.462L130.993,220.869L131.054,221.276L131.113,221.685L131.169,222.094L131.222,222.503L131.273,222.914L131.322,223.325L131.368,223.738L131.411,224.151L131.452,224.564L131.49,224.979L131.525,225.394L131.558,225.81L131.589,226.226L131.617,226.644L131.642,227.062L131.664,227.48L131.684,227.9L131.702,228.32L131.716,228.741L131.728,229.162L131.738,229.584L131.744,230.007L131.748,230.43L131.75,230.854L131.748,231.278L131.744,231.702L131.738,232.124L131.728,232.546L131.716,232.968L131.702,233.389L131.684,233.809L131.664,234.228L131.642,234.647L131.617,235.065L131.589,235.482L131.558,235.899L131.525,236.315L131.49,236.73L131.452,237.144L131.411,237.558L131.368,237.971L131.322,238.383L131.273,238.794L131.222,239.205L131.169,239.615L131.113,240.024L131.054,240.432L130.993,240.839L130.93,241.246L130.864,241.652L130.795,242.057L130.724,242.461L130.651,242.864L130.575,243.266L130.497,243.668L130.416,244.069L130.333,244.468L130.247,244.867L130.159,245.265L130.069,245.662L129.976,246.059L129.881,246.454L129.783,246.848L129.683,247.242L129.581,247.634L129.476,248.025L129.369,248.416L129.259,248.805L129.148,249.194L129.033,249.582L128.917,249.968L128.798,250.354L128.677,250.738L128.554,251.122L128.428,251.504L128.3,251.886L128.17,252.266L128.038,252.646L127.903,253.024L127.766,253.401L127.627,253.777L127.486,254.153L127.342,254.527L127.196,254.899L127.048,255.271L126.898,255.642L126.746,256.012L126.591,256.38L126.434,256.747L126.275,257.113L126.114,257.478L125.951,257.842L125.785,258.205L125.618,258.566L125.448,258.927L125.276,259.286L125.102,259.643L124.927,260L124.748,260.356L124.568,260.71L124.386,261.063L124.202,261.414L124.015,261.765L123.827,262.114L123.636,262.462L123.444,262.809L123.249,263.154L123.053,263.498L122.854,263.841L122.654,264.182L122.451,264.523L122.246,264.861L122.04,265.199L121.831,265.535L121.621,265.87L121.408,266.203L121.194,266.535L120.978,266.866L120.759,267.195L120.539,267.523L120.317,267.85L120.093,268.175L119.867,268.499L119.639,268.821L119.41,269.142L119.178,269.461L118.945,269.779L118.709,270.096L118.472,270.411L118.233,270.724L117.993,271.036L117.75,271.347L117.505,271.656L117.259,271.964L117.011,272.27L116.761,272.574L116.51,272.877L116.256,273.179L116.001,273.479L115.744,273.777L115.485,274.074L115.225,274.369L114.963,274.663L114.699,274.955L114.433,275.246L114.166,275.535L113.896,275.822L113.626,276.108L113.353,276.392L113.079,276.674L112.803,276.955L112.526,277.234L112.247,277.512L111.966,277.787L111.683,278.062L111.399,278.334L111.114,278.605L110.826,278.874L110.537,279.141L110.247,279.407L109.955,279.671L109.661,279.933L109.366,280.194L109.069,280.452L108.77,280.709L108.471,280.964L108.169,281.218L107.866,281.47L107.561,281.719L107.255,281.967L106.948,282.214L106.639,282.458L106.328,282.701L106.016,282.942L105.702,283.181L105.387,283.418L105.071,283.653L104.753,283.887L104.433,284.118L104.113,284.348L103.79,284.576L103.467,284.801L103.141,285.025L102.815,285.248L102.487,285.468L102.158,285.686L101.827,285.902L101.495,286.117L101.162,286.329L100.827,286.54L100.491,286.748L100.153,286.955L99.814,287.159L99.474,287.362L99.133,287.563L98.79,287.761L98.446,287.958L98.1,288.152L97.754,288.345L97.406,288.535L97.057,288.724L96.706,288.91L96.354,289.094L96.001,289.277L95.647,289.457L95.292,289.635L94.935,289.811L94.577,289.985L94.218,290.157L93.858,290.326L93.496,290.494L93.134,290.659L92.77,290.822L92.405,290.983L92.039,291.142L91.672,291.299L91.303,291.454L90.934,291.606L90.563,291.757L90.191,291.905L89.818,292.05L89.444,292.194L89.069,292.335L88.693,292.475L88.316,292.611L87.937,292.746L87.558,292.879L87.178,293.009L86.796,293.137L86.414,293.262L86.03,293.386L85.645,293.507L85.26,293.625L84.873,293.742L84.486,293.856L84.097,293.968L83.708,294.077L83.317,294.184L82.926,294.289L82.533,294.391L82.14,294.491L81.746,294.589L81.35,294.684L80.954,294.777L80.557,294.867L80.159,294.955L79.76,295.041L79.36,295.124L78.96,295.205L78.558,295.283L78.156,295.359L77.753,295.433L77.348,295.504L76.943,295.572L76.538,295.638L76.131,295.702L75.724,295.763L75.315,295.821L74.906,295.877L74.497,295.931L74.086,295.982L73.675,296.03L73.262,296.076L72.849,296.119L72.436,296.16L72.021,296.198L71.606,296.234L71.19,296.267L70.774,296.297L70.356,296.325L69.938,296.35L69.52,296.373L69.1,296.393L68.68,296.41L68.259,296.425L67.838,296.437L67.416,296.446L66.993,296.453L66.57,296.457L66.146,296.458L65.722,296.457L65.298,296.453L64.876,296.446L64.454,296.437L64.032,296.425L63.611,296.41L63.191,296.393L62.772,296.373L62.353,296.35L61.935,296.325L61.518,296.297L61.101,296.267L60.685,296.234L60.27,296.198L59.856,296.16L59.442,296.119L59.029,296.076L58.617,296.03L58.206,295.982L57.795,295.931L57.385,295.877L56.976,295.821L56.568,295.763L56.161,295.702L55.754,295.638L55.348,295.572L54.943,295.504L54.539,295.433L54.136,295.359L53.734,295.283L53.332,295.205L52.931,295.124L52.532,295.041L52.133,294.955L51.735,294.867L51.338,294.777L50.941,294.684L50.546,294.589L50.152,294.491L49.758,294.391L49.366,294.289L48.975,294.184L48.584,294.077L48.195,293.968L47.806,293.856L47.418,293.742L47.032,293.625L46.646,293.507L46.262,293.386L45.878,293.262L45.496,293.137L45.114,293.009L44.734,292.879L44.354,292.746L43.976,292.611L43.599,292.475L43.223,292.335L42.847,292.194L42.473,292.05L42.101,291.905L41.729,291.757L41.358,291.606L40.988,291.454L40.62,291.299L40.253,291.142L39.887,290.983L39.522,290.822L39.158,290.659L38.795,290.494L38.434,290.326L38.073,290.157L37.714,289.985L37.357,289.811L37,289.635L36.644,289.457L36.29,289.277L35.937,289.094L35.586,288.91L35.235,288.724L34.886,288.535L34.538,288.345L34.191,288.152L33.846,287.958L33.502,287.761L33.159,287.563L32.818,287.362L32.477,287.159L32.139,286.955L31.801,286.748L31.465,286.54L31.13,286.329L30.797,286.117L30.465,285.902L30.134,285.686L29.805,285.468L29.477,285.248L29.15,285.025L28.825,284.801L28.501,284.576L28.179,284.348L27.858,284.118L27.539,283.887L27.221,283.653L26.904,283.418L26.589,283.181L26.276,282.942L25.964,282.701L25.653,282.458L25.344,282.214L25.036,281.967L24.73,281.719L24.426,281.47L24.123,281.218L23.821,280.964L23.521,280.709L23.223,280.452L22.926,280.194L22.631,279.933L22.337,279.671L22.045,279.407L21.754,279.141L21.465,278.874L21.178,278.605L20.892,278.334L20.608,278.062L20.326,277.787L20.045,277.512L19.766,277.234L19.488,276.955L19.213,276.674L18.938,276.392L18.666,276.108L18.395,275.822L18.126,275.535L17.859,275.246L17.593,274.955L17.329,274.663L17.067,274.369L16.806,274.074L16.548,273.777L16.291,273.479L16.036,273.179L15.782,272.877L15.53,272.574L15.281,272.27L15.033,271.964L14.786,271.656L14.542,271.347L14.299,271.036L14.058,270.724L13.819,270.411L13.582,270.096L13.347,269.779L13.113,269.461L12.882,269.142L12.652,268.821L12.424,268.499L12.199,268.175L11.975,267.85L11.752,267.523L11.532,267.195L11.314,266.866L11.098,266.535L10.883,266.203L10.671,265.87L10.46,265.535L10.252,265.199L10.045,264.861L9.841,264.523L9.638,264.182L9.437,263.841L9.239,263.498L9.042,263.154L8.848,262.809L8.655,262.462L8.465,262.114L8.276,261.765L8.09,261.414L7.906,261.063L7.723,260.71L7.543,260.356L7.365,260L7.189,259.643L7.015,259.286L6.844,258.927L6.674,258.566L6.506,258.205L6.341,257.842L6.178,257.478L6.017,257.113L5.858,256.747L5.701,256.38L5.546,256.012L5.394,255.642L5.243,255.271L5.095,254.899L4.95,254.527L4.806,254.153L4.665,253.777L4.525,253.401L4.389,253.024L4.254,252.646L4.121,252.266L3.991,251.886L3.863,251.504L3.738,251.122L3.614,250.738L3.493,250.354L3.375,249.968L3.258,249.582L3.144,249.194L3.032,248.805L2.923,248.416L2.816,248.025L2.711,247.634L2.609,247.242L2.509,246.848L2.411,246.454L2.316,246.059L2.223,245.662L2.133,245.265L2.045,244.867L1.959,244.468L1.876,244.069L1.795,243.668L1.717,243.266L1.641,242.864L1.567,242.461L1.496,242.057L1.428,241.652L1.362,241.246L1.298,240.839L1.237,240.432L1.179,240.024L1.123,239.615L1.069,239.205L1.018,238.794L0.97,238.383L0.924,237.971L0.881,237.558L0.84,237.144L0.802,236.73L0.766,236.315L0.733,235.899L0.703,235.482L0.675,235.065L0.65,234.647L0.627,234.228L0.607,233.809L0.59,233.389L0.575,232.968L0.563,232.546L0.554,232.124L0.547,231.702L0.543,231.278L0.542,230.854L0.543,230.43L0.547,230.007L0.554,229.584L0.563,229.162L0.575,228.741L0.59,228.32L0.607,227.9L0.627,227.48L0.65,227.062L0.675,226.644L0.703,226.226L0.733,225.81L0.766,225.394L0.802,224.979L0.84,224.564L0.881,224.151L0.924,223.738L0.97,223.325L1.018,222.914L1.069,222.503L1.123,222.094L1.179,221.685L1.237,221.276L1.298,220.869L1.362,220.462L1.428,220.057L1.496,219.652L1.567,219.247L1.641,218.844L1.717,218.442L1.795,218.04L1.876,217.64L1.959,217.24L2.045,216.841L2.133,216.443L2.223,216.046L2.316,215.65L2.411,215.255L2.509,214.86L2.609,214.467L2.711,214.074L2.816,213.683L2.923,213.292L3.032,212.903L3.144,212.514L3.258,212.127L3.375,211.74L3.493,211.355L3.614,210.97L3.738,210.586L3.863,210.204L3.991,209.822L4.121,209.442L4.254,209.063L4.389,208.684L4.525,208.307L4.665,207.931L4.806,207.556L4.95,207.182L5.095,206.809L5.243,206.437L5.394,206.066L5.546,205.697L5.701,205.328L5.858,204.961L6.017,204.595L6.178,204.23L6.341,203.866L6.506,203.504L6.674,203.142L6.844,202.782L7.015,202.423L7.189,202.065L7.365,201.708L7.543,201.353L7.723,200.999L7.906,200.646L8.09,200.294L8.276,199.943L8.465,199.594L8.655,199.246L8.848,198.9L9.042,198.554L9.239,198.21L9.437,197.867L9.638,197.526L9.841,197.186L10.045,196.847L10.252,196.509L10.46,196.173L10.671,195.838L10.883,195.505L11.098,195.173L11.314,194.842L11.532,194.513L11.752,194.185L11.975,193.859L12.199,193.533L12.424,193.21L12.652,192.887L12.882,192.567L13.113,192.247L13.347,191.929L13.582,191.613L13.819,191.298L14.058,190.984L14.299,190.672L14.542,190.361L14.786,190.052L15.033,189.745L15.281,189.439L15.53,189.134L15.782,188.831L16.036,188.529L16.291,188.23L16.548,187.931L16.806,187.634L17.067,187.339L17.329,187.045L17.593,186.753L17.859,186.463L18.126,186.174L18.395,185.886L18.666,185.601L18.938,185.317L19.213,185.034L19.488,184.753L19.766,184.474L20.045,184.197L20.326,183.921L20.608,183.647L20.892,183.374L21.178,183.104L21.465,182.834L21.754,182.567L22.045,182.301L22.337,182.037L22.631,181.775L22.926,181.515L23.223,181.256L23.521,180.999L23.821,180.744L24.123,180.49L24.426,180.239L24.73,179.989L25.036,179.741L25.344,179.495L25.653,179.25L25.964,179.007L26.276,178.767L26.589,178.528L26.904,178.291L27.221,178.055L27.539,177.822L27.858,177.59L28.179,177.361L28.501,177.133L28.825,176.907L29.15,176.683L29.477,176.461L29.805,176.241L30.134,176.022L30.465,175.806L30.797,175.592L31.13,175.379L31.465,175.169L31.801,174.96L32.139,174.754L32.477,174.549L32.818,174.346L33.159,174.146L33.502,173.947L33.846,173.751L34.191,173.556L34.538,173.364L34.886,173.173L35.235,172.985L35.586,172.798L35.937,172.614L36.29,172.432L36.644,172.252L37,172.074L37.357,171.898L37.714,171.724L38.073,171.552L38.434,171.382L38.795,171.215L39.158,171.049L39.522,170.886L39.887,170.725L40.253,170.566L40.62,170.409L40.988,170.255L41.358,170.102L41.729,169.952L42.101,169.804L42.473,169.658L42.847,169.514L43.223,169.373L43.599,169.234L43.976,169.097L44.354,168.962L44.734,168.83L45.114,168.7L45.496,168.572L45.878,168.446L46.262,168.323L46.646,168.202L47.032,168.083L47.418,167.967L47.806,167.852L48.195,167.741L48.584,167.631L48.975,167.524L49.366,167.419L49.758,167.317L50.152,167.217L50.546,167.119L50.941,167.024L51.338,166.931L51.735,166.841L52.133,166.753L52.532,166.667L52.931,166.584L53.332,166.503L53.734,166.425L54.136,166.349L54.539,166.276L54.943,166.205L55.348,166.136L55.754,166.07L56.161,166.007L56.568,165.946L56.976,165.887L57.385,165.831L57.795,165.778L58.206,165.727L58.617,165.678L59.029,165.632L59.442,165.589L59.856,165.548L60.27,165.51L60.685,165.475L61.101,165.442L61.518,165.411L61.935,165.383L62.353,165.358L62.772,165.336L63.191,165.316L63.611,165.298L64.032,165.284L64.454,165.272L64.876,165.262L65.298,165.256L65.722,165.252L66.146,165.25L66.57,165.252ZM65.741,168.252L65.337,168.255L64.933,168.262L64.53,168.271L64.127,168.282L63.726,168.296L63.325,168.313L62.924,168.332L62.524,168.353L62.125,168.377L61.727,168.404L61.329,168.433L60.932,168.465L60.536,168.498L60.141,168.535L59.746,168.574L59.352,168.615L58.958,168.659L58.566,168.705L58.174,168.754L57.783,168.805L57.393,168.858L57.003,168.914L56.614,168.972L56.226,169.033L55.839,169.096L55.453,169.161L55.067,169.229L54.683,169.299L54.299,169.371L53.916,169.446L53.533,169.523L53.152,169.602L52.771,169.684L52.392,169.768L52.013,169.854L51.635,169.943L51.258,170.034L50.882,170.127L50.507,170.222L50.132,170.32L49.759,170.42L49.386,170.522L49.015,170.626L48.644,170.733L48.275,170.842L47.906,170.953L47.538,171.066L47.171,171.182L46.805,171.299L46.44,171.419L46.076,171.541L45.714,171.665L45.352,171.792L44.991,171.92L44.631,172.051L44.272,172.183L43.914,172.318L43.557,172.455L43.202,172.594L42.847,172.736L42.493,172.879L42.141,173.024L41.789,173.172L41.439,173.321L41.09,173.473L40.742,173.627L40.394,173.783L40.048,173.94L39.704,174.1L39.36,174.262L39.017,174.426L38.676,174.592L38.336,174.76L37.996,174.93L37.658,175.102L37.322,175.275L36.986,175.451L36.652,175.629L36.318,175.809L35.986,175.991L35.656,176.174L35.326,176.36L34.998,176.548L34.671,176.737L34.345,176.929L34.02,177.122L33.697,177.317L33.375,177.514L33.054,177.713L32.735,177.914L32.416,178.117L32.099,178.321L31.784,178.528L31.47,178.736L31.157,178.946L30.845,179.158L30.535,179.372L30.226,179.588L29.918,179.805L29.612,180.024L29.307,180.245L29.003,180.468L28.701,180.693L28.401,180.919L28.101,181.147L27.803,181.377L27.507,181.609L27.212,181.842L26.918,182.077L26.626,182.314L26.335,182.552L26.046,182.793L25.758,183.035L25.472,183.278L25.187,183.524L24.904,183.77L24.622,184.019L24.342,184.269L24.063,184.521L23.785,184.775L23.51,185.03L23.235,185.287L22.963,185.546L22.691,185.806L22.422,186.067L22.154,186.331L21.887,186.596L21.622,186.862L21.359,187.13L21.097,187.4L20.837,187.671L20.579,187.944L20.322,188.218L20.067,188.494L19.813,188.771L19.561,189.05L19.311,189.33L19.062,189.612L18.815,189.896L18.57,190.18L18.326,190.467L18.084,190.754L17.844,191.044L17.606,191.334L17.369,191.627L17.134,191.92L16.9,192.215L16.669,192.512L16.439,192.81L16.211,193.109L15.984,193.41L15.76,193.712L15.537,194.015L15.316,194.32L15.097,194.626L14.879,194.934L14.664,195.243L14.45,195.553L14.238,195.865L14.028,196.178L13.82,196.492L13.613,196.808L13.408,197.125L13.206,197.443L13.005,197.762L12.806,198.083L12.609,198.405L12.414,198.729L12.22,199.053L12.029,199.379L11.839,199.706L11.652,200.034L11.466,200.364L11.282,200.695L11.101,201.027L10.921,201.36L10.743,201.694L10.567,202.03L10.393,202.367L10.221,202.705L10.051,203.044L9.884,203.384L9.718,203.726L9.554,204.068L9.392,204.412L9.232,204.757L9.074,205.103L8.918,205.45L8.765,205.798L8.613,206.147L8.464,206.498L8.316,206.849L8.171,207.202L8.027,207.555L7.886,207.91L7.747,208.266L7.61,208.623L7.475,208.98L7.342,209.339L7.212,209.699L7.083,210.06L6.957,210.422L6.833,210.785L6.711,211.149L6.591,211.514L6.473,211.879L6.358,212.246L6.245,212.614L6.134,212.983L6.025,213.353L5.918,213.723L5.814,214.095L5.712,214.467L5.612,214.841L5.514,215.215L5.419,215.59L5.325,215.966L5.235,216.343L5.146,216.721L5.06,217.1L4.976,217.48L4.894,217.86L4.815,218.242L4.738,218.624L4.663,219.007L4.591,219.391L4.52,219.776L4.453,220.161L4.387,220.547L4.324,220.935L4.264,221.323L4.206,221.711L4.15,222.101L4.096,222.491L4.045,222.882L3.997,223.274L3.951,223.667L3.907,224.06L3.865,224.454L3.827,224.849L3.79,225.244L3.756,225.641L3.725,226.038L3.696,226.435L3.669,226.834L3.645,227.233L3.623,227.632L3.604,228.033L3.588,228.434L3.574,228.836L3.562,229.238L3.553,229.641L3.547,230.045L3.543,230.449L3.542,230.854L3.543,231.259L3.547,231.663L3.553,232.067L3.562,232.47L3.574,232.873L3.588,233.274L3.604,233.676L3.623,234.076L3.645,234.476L3.669,234.875L3.696,235.273L3.725,235.671L3.756,236.068L3.79,236.464L3.827,236.859L3.865,237.254L3.907,237.648L3.951,238.042L3.997,238.434L4.045,238.826L4.096,239.217L4.15,239.607L4.206,239.997L4.264,240.386L4.324,240.774L4.387,241.161L4.453,241.547L4.52,241.933L4.591,242.317L4.663,242.701L4.738,243.084L4.815,243.467L4.894,243.848L4.976,244.229L5.06,244.608L5.146,244.987L5.235,245.365L5.325,245.742L5.419,246.118L5.514,246.493L5.612,246.868L5.712,247.241L5.814,247.614L5.918,247.985L6.025,248.356L6.134,248.725L6.245,249.094L6.358,249.462L6.473,249.829L6.591,250.195L6.711,250.56L6.833,250.924L6.957,251.286L7.083,251.648L7.212,252.009L7.342,252.369L7.475,252.728L7.61,253.086L7.747,253.443L7.886,253.798L8.027,254.153L8.171,254.507L8.316,254.859L8.464,255.211L8.613,255.561L8.765,255.91L8.918,256.258L9.074,256.606L9.232,256.952L9.392,257.296L9.554,257.64L9.718,257.983L9.884,258.324L10.051,258.664L10.221,259.004L10.393,259.342L10.567,259.678L10.743,260.014L10.921,260.348L11.101,260.682L11.282,261.014L11.466,261.344L11.652,261.674L11.839,262.002L12.029,262.329L12.22,262.655L12.414,262.98L12.609,263.303L12.806,263.625L13.005,263.946L13.206,264.265L13.408,264.584L13.613,264.901L13.82,265.216L14.028,265.531L14.238,265.843L14.45,266.155L14.664,266.465L14.879,266.774L15.097,267.082L15.316,267.388L15.537,267.693L15.76,267.997L15.984,268.299L16.211,268.599L16.439,268.899L16.669,269.197L16.9,269.493L17.134,269.788L17.369,270.082L17.606,270.374L17.844,270.665L18.084,270.954L18.326,271.242L18.57,271.528L18.815,271.813L19.062,272.096L19.311,272.378L19.561,272.658L19.813,272.937L20.067,273.215L20.322,273.49L20.579,273.765L20.837,274.037L21.097,274.309L21.359,274.578L21.622,274.846L21.887,275.113L22.154,275.378L22.422,275.641L22.691,275.903L22.963,276.163L23.235,276.421L23.51,276.678L23.785,276.933L24.063,277.187L24.342,277.439L24.622,277.689L24.904,277.938L25.187,278.185L25.472,278.43L25.758,278.674L26.046,278.916L26.335,279.156L26.626,279.394L26.918,279.631L27.212,279.866L27.507,280.1L27.803,280.331L28.101,280.561L28.401,280.789L28.701,281.016L29.003,281.24L29.307,281.463L29.612,281.684L29.918,281.903L30.226,282.121L30.535,282.336L30.845,282.55L31.157,282.762L31.47,282.972L31.784,283.18L32.099,283.387L32.416,283.592L32.735,283.794L33.054,283.995L33.375,284.194L33.697,284.391L34.02,284.586L34.345,284.78L34.671,284.971L34.998,285.161L35.326,285.348L35.656,285.534L35.986,285.718L36.318,285.899L36.652,286.079L36.986,286.257L37.322,286.433L37.658,286.607L37.996,286.779L38.336,286.949L38.676,287.117L39.017,287.282L39.36,287.446L39.704,287.608L40.048,287.768L40.394,287.926L40.742,288.082L41.09,288.235L41.439,288.387L41.789,288.537L42.141,288.684L42.493,288.829L42.847,288.973L43.202,289.114L43.557,289.253L43.914,289.39L44.272,289.525L44.631,289.658L44.991,289.788L45.352,289.917L45.714,290.043L46.076,290.167L46.44,290.289L46.805,290.409L47.171,290.527L47.538,290.642L47.906,290.755L48.275,290.866L48.644,290.975L49.015,291.082L49.386,291.186L49.759,291.288L50.132,291.388L50.507,291.486L50.882,291.581L51.258,291.675L51.635,291.765L52.013,291.854L52.392,291.94L52.771,292.024L53.152,292.106L53.533,292.185L53.916,292.262L54.299,292.337L54.683,292.409L55.067,292.48L55.453,292.547L55.839,292.613L56.226,292.676L56.614,292.736L57.003,292.794L57.393,292.85L57.783,292.904L58.174,292.955L58.566,293.003L58.958,293.049L59.352,293.093L59.746,293.135L60.14,293.173L60.536,293.21L60.932,293.244L61.329,293.275L61.727,293.304L62.125,293.331L62.524,293.355L62.924,293.377L63.324,293.396L63.726,293.412L64.127,293.426L64.53,293.438L64.933,293.447L65.337,293.453L65.741,293.457L66.146,293.458L66.551,293.457L66.955,293.453L67.359,293.447L67.762,293.438L68.164,293.426L68.566,293.412L68.967,293.396L69.368,293.377L69.767,293.355L70.166,293.331L70.565,293.304L70.962,293.275L71.359,293.244L71.756,293.21L72.151,293.173L72.546,293.135L72.94,293.093L73.333,293.049L73.726,293.003L74.118,292.955L74.509,292.904L74.899,292.85L75.289,292.794L75.677,292.736L76.065,292.676L76.453,292.613L76.839,292.547L77.224,292.48L77.609,292.409L77.993,292.337L78.376,292.262L78.758,292.185L79.14,292.106L79.52,292.024L79.9,291.94L80.279,291.854L80.657,291.765L81.034,291.675L81.41,291.581L81.785,291.486L82.159,291.388L82.533,291.288L82.905,291.186L83.277,291.082L83.647,290.975L84.017,290.866L84.386,290.755L84.754,290.642L85.121,290.527L85.486,290.409L85.851,290.289L86.215,290.167L86.578,290.043L86.94,289.917L87.301,289.788L87.661,289.658L88.02,289.525L88.377,289.39L88.734,289.253L89.09,289.114L89.445,288.973L89.798,288.829L90.151,288.684L90.502,288.537L90.853,288.387L91.202,288.235L91.55,288.082L91.897,287.926L92.243,287.768L92.588,287.608L92.932,287.446L93.274,287.282L93.616,287.117L93.956,286.949L94.295,286.779L94.633,286.607L94.97,286.433L95.306,286.257L95.64,286.079L95.973,285.899L96.305,285.718L96.636,285.534L96.966,285.348L97.294,285.161L97.621,284.971L97.947,284.78L98.271,284.586L98.595,284.391L98.917,284.194L99.238,283.995L99.557,283.794L99.875,283.592L100.192,283.387L100.508,283.18L100.822,282.972L101.135,282.762L101.447,282.55L101.757,282.336L102.066,282.121L102.374,281.903L102.68,281.684L102.985,281.463L103.288,281.24L103.59,281.016L103.891,280.789L104.19,280.561L104.488,280.331L104.785,280.1L105.08,279.866L105.373,279.631L105.665,279.394L105.956,279.156L106.246,278.916L106.533,278.674L106.82,278.43L107.104,278.185L107.388,277.938L107.67,277.689L107.95,277.439L108.229,277.187L108.506,276.933L108.782,276.678L109.056,276.421L109.329,276.163L109.6,275.903L109.87,275.641L110.138,275.378L110.404,275.113L110.669,274.846L110.933,274.578L111.194,274.309L111.454,274.037L111.713,273.765L111.97,273.49L112.225,273.215L112.479,272.937L112.731,272.658L112.981,272.378L113.23,272.096L113.476,271.813L113.722,271.528L113.965,271.242L114.207,270.954L114.448,270.665L114.686,270.374L114.923,270.082L115.158,269.788L115.391,269.493L115.623,269.197L115.853,268.899L116.081,268.599L116.307,268.299L116.532,267.997L116.755,267.693L116.976,267.388L117.195,267.082L117.412,266.774L117.628,266.465L117.842,266.155L118.054,265.843L118.264,265.531L118.472,265.216L118.679,264.901L118.883,264.584L119.086,264.265L119.287,263.946L119.486,263.625L119.683,263.303L119.878,262.98L120.071,262.655L120.263,262.329L120.452,262.002L120.64,261.674L120.826,261.344L121.009,261.014L121.191,260.682L121.371,260.348L121.549,260.014L121.725,259.678L121.898,259.342L122.07,259.004L122.24,258.664L122.408,258.324L122.574,257.983L122.738,257.64L122.9,257.296L123.06,256.952L123.217,256.606L123.373,256.258L123.527,255.91L123.679,255.561L123.828,255.211L123.976,254.859L124.121,254.507L124.264,254.153L124.406,253.798L124.545,253.443L124.682,253.086L124.817,252.728L124.949,252.369L125.08,252.009L125.208,251.648L125.335,251.286L125.459,250.923L125.581,250.56L125.701,250.195L125.818,249.829L125.934,249.462L126.047,249.094L126.158,248.726L126.267,248.356L126.374,247.985L126.478,247.614L126.58,247.241L126.68,246.868L126.778,246.493L126.873,246.118L126.966,245.742L127.057,245.365L127.146,244.987L127.232,244.608L127.316,244.229L127.398,243.848L127.477,243.467L127.554,243.084L127.629,242.701L127.701,242.317L127.771,241.933L127.839,241.547L127.904,241.161L127.967,240.774L128.028,240.386L128.086,239.997L128.142,239.608L128.195,239.217L128.246,238.826L128.295,238.434L128.341,238.042L128.385,237.648L128.426,237.254L128.465,236.859L128.502,236.464L128.535,236.068L128.567,235.671L128.596,235.273L128.623,234.875L128.647,234.476L128.668,234.076L128.687,233.676L128.704,233.274L128.718,232.873L128.729,232.47L128.738,232.067L128.745,231.664L128.748,231.259L128.75,230.854L128.748,230.449L128.745,230.045L128.738,229.641L128.729,229.238L128.718,228.836L128.704,228.434L128.687,228.033L128.668,227.632L128.647,227.233L128.623,226.834L128.596,226.435L128.567,226.038L128.535,225.641L128.502,225.244L128.465,224.849L128.426,224.454L128.385,224.06L128.341,223.667L128.295,223.274L128.246,222.882L128.195,222.491L128.142,222.101L128.086,221.711L128.028,221.323L127.967,220.935L127.904,220.547L127.839,220.161L127.771,219.776L127.701,219.391L127.629,219.007L127.554,218.624L127.477,218.242L127.398,217.86L127.316,217.48L127.232,217.1L127.146,216.721L127.057,216.343L126.966,215.966L126.873,215.59L126.778,215.215L126.68,214.841L126.58,214.467L126.478,214.095L126.374,213.723L126.267,213.353L126.158,212.983L126.047,212.614L125.934,212.246L125.818,211.879L125.701,211.514L125.581,211.149L125.459,210.785L125.335,210.422L125.208,210.06L125.08,209.699L124.949,209.339L124.817,208.98L124.682,208.623L124.545,208.266L124.406,207.91L124.264,207.555L124.121,207.202L123.976,206.849L123.828,206.498L123.679,206.147L123.527,205.798L123.373,205.45L123.217,205.103L123.06,204.757L122.9,204.412L122.738,204.068L122.574,203.726L122.408,203.384L122.24,203.044L122.07,202.705L121.898,202.367L121.725,202.03L121.549,201.694L121.371,201.36L121.191,201.027L121.009,200.695L120.826,200.364L120.64,200.034L120.452,199.706L120.263,199.379L120.071,199.053L119.878,198.729L119.683,198.405L119.486,198.083L119.287,197.762L119.086,197.443L118.883,197.125L118.679,196.808L118.472,196.492L118.264,196.178L118.054,195.865L117.842,195.553L117.628,195.243L117.412,194.934L117.195,194.626L116.976,194.32L116.755,194.015L116.532,193.712L116.307,193.41L116.081,193.109L115.853,192.81L115.623,192.512L115.391,192.215L115.158,191.92L114.923,191.627L114.686,191.334L114.448,191.044L114.207,190.755L113.965,190.467L113.722,190.18L113.476,189.896L113.23,189.612L112.981,189.33L112.731,189.05L112.479,188.771L112.225,188.494L111.97,188.218L111.713,187.944L111.454,187.671L111.194,187.4L110.933,187.13L110.669,186.862L110.404,186.596L110.138,186.331L109.87,186.067L109.6,185.806L109.329,185.546L109.056,185.287L108.782,185.03L108.506,184.775L108.229,184.521L107.95,184.269L107.67,184.019L107.388,183.77L107.104,183.524L106.82,183.278L106.533,183.035L106.246,182.793L105.956,182.552L105.666,182.314L105.373,182.077L105.08,181.842L104.785,181.609L104.488,181.377L104.19,181.147L103.891,180.919L103.59,180.693L103.288,180.468L102.985,180.245L102.68,180.024L102.374,179.805L102.066,179.588L101.757,179.372L101.447,179.158L101.135,178.946L100.822,178.736L100.508,178.528L100.192,178.321L99.875,178.117L99.557,177.914L99.238,177.713L98.917,177.514L98.595,177.317L98.271,177.122L97.947,176.929L97.621,176.737L97.294,176.548L96.966,176.36L96.636,176.174L96.305,175.991L95.973,175.809L95.64,175.629L95.306,175.451L94.97,175.275L94.633,175.102L94.295,174.93L93.956,174.76L93.616,174.592L93.274,174.426L92.932,174.262L92.588,174.1L92.243,173.94L91.897,173.783L91.55,173.627L91.202,173.473L90.853,173.321L90.502,173.172L90.151,173.024L89.798,172.879L89.445,172.736L89.09,172.594L88.734,172.455L88.377,172.318L88.02,172.183L87.661,172.051L87.301,171.92L86.94,171.792L86.578,171.665L86.215,171.541L85.851,171.419L85.486,171.299L85.121,171.182L84.754,171.066L84.386,170.953L84.017,170.842L83.647,170.733L83.277,170.626L82.905,170.522L82.533,170.42L82.159,170.32L81.785,170.222L81.41,170.127L81.034,170.034L80.657,169.943L80.279,169.854L79.9,169.768L79.52,169.684L79.14,169.602L78.758,169.523L78.376,169.446L77.993,169.371L77.609,169.299L77.224,169.229L76.839,169.161L76.453,169.096L76.065,169.033L75.677,168.972L75.289,168.914L74.899,168.858L74.509,168.805L74.118,168.754L73.726,168.705L73.333,168.659L72.94,168.615L72.546,168.574L72.151,168.535L71.756,168.498L71.359,168.465L70.962,168.433L70.565,168.404L70.166,168.377L69.767,168.353L69.368,168.332L68.967,168.313L68.566,168.296L68.164,168.282L67.762,168.271L67.359,168.262L66.955,168.255L66.551,168.252L66.146,168.25L65.741,168.252Z" style="fill:white;"/>
+ </g>
+ <g transform="matrix(1,0,0,1,-1.55155,8.75145)">
+ <g transform="matrix(1,0,0,1,-18.2398,144.929)">
+ <rect x="79.437" y="34.964" width="13" height="62.363" style="fill:white;"/>
+ </g>
+ <g transform="matrix(1,0,0,1.14583,0,156.831)">
+ <rect x="61.197" y="82.456" width="13" height="11.345" style="fill:white;"/>
+ </g>
+ </g>
+ </g>
+</svg>
diff --git a/Swift/resources/logo/logo-shaded-text.256.png b/Swift/resources/logo/logo-shaded-text.256.png
deleted file mode 100644
index 5605ad0..0000000
--- a/Swift/resources/logo/logo-shaded-text.256.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/logo/logo-shaded-text.png b/Swift/resources/logo/logo-shaded-text.png
new file mode 100644
index 0000000..8bc3bef
--- /dev/null
+++ b/Swift/resources/logo/logo-shaded-text.png
Binary files differ
diff --git a/Swift/resources/logo/logo-shaded-text.svg b/Swift/resources/logo/logo-shaded-text.svg
index 68192e9..deb8340 100644
--- a/Swift/resources/logo/logo-shaded-text.svg
+++ b/Swift/resources/logo/logo-shaded-text.svg
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
+
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
@@ -8,17 +9,18 @@
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
- width="744.09003"
- height="744"
+ width="175.8864mm"
+ height="175.8864mm"
id="svg2459"
sodipodi:version="0.32"
- inkscape:version="0.46"
- sodipodi:docname="logo-text.svg"
+ inkscape:version="0.91+devel+osxmenu r12922"
+ sodipodi:docname="logo-shaded-text.svg"
inkscape:output_extension="org.inkscape.output.svg.inkscape"
inkscape:export-xdpi="18.796354"
inkscape:export-ydpi="18.796354"
version="1.0"
- inkscape:export-filename="/Users/remko/src/swift/resources/logo/blog.png">
+ inkscape:export-filename="/Users/remko/src/swift/resources/logo/blog.png"
+ viewBox="0 0 664.77 664.76749">
<defs
id="defs2461">
<linearGradient
@@ -45,10 +47,10 @@
</linearGradient>
<inkscape:perspective
sodipodi:type="inkscape:persp3d"
- inkscape:vp_x="0 : 526.18109 : 1"
- inkscape:vp_y="0 : 1000 : 0"
- inkscape:vp_z="744.09448 : 526.18109 : 1"
- inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
+ inkscape:vp_x="0 : 526.18107 : 1"
+ inkscape:vp_y="0 : 999.99996 : 0"
+ inkscape:vp_z="744.09725 : 526.18107 : 1"
+ inkscape:persp3d-origin="372.04862 : 350.78737 : 1"
id="perspective2390" />
<filter
inkscape:collect="always"
@@ -70,15 +72,22 @@
inkscape:pageopacity="0.0"
inkscape:pageshadow="2"
inkscape:zoom="1.0074671"
- inkscape:cx="375"
- inkscape:cy="367.42652"
+ inkscape:cx="254.12047"
+ inkscape:cy="374.35139"
inkscape:document-units="px"
inkscape:current-layer="layer1"
showgrid="false"
- inkscape:window-width="1169"
- inkscape:window-height="990"
- inkscape:window-x="695"
- inkscape:window-y="75" />
+ inkscape:window-width="1680"
+ inkscape:window-height="1001"
+ inkscape:window-x="0"
+ inkscape:window-y="23"
+ inkscape:window-maximized="0"
+ borderlayer="false"
+ units="mm"
+ fit-margin-top="0"
+ fit-margin-left="0"
+ fit-margin-right="0"
+ fit-margin-bottom="0" />
<metadata
id="metadata2464">
<rdf:RDF>
@@ -87,33 +96,37 @@
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
+ <dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
- id="layer1">
+ id="layer1"
+ transform="translate(12.742622,-46.453819)">
<path
style="opacity:0.35820899;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:0.82541478px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;filter:url(#filter3237)"
- d="M 115.78906,165.28485 C 350.10074,221.97501 309.63531,304.49349 212.19531,373.84735 C 164.88631,390.51853 105.57186,410.97398 28.664058,434.5661 C 65.101978,429.72741 98.209468,426.47848 128.03906,424.8161 C 98.134688,440.73611 68.227048,455.00104 42.414058,466.8786 C 101.67266,450.07359 152.5607,435.94556 196.60156,424.0036 C 357.97622,430.8864 369.87302,508.77947 220.75781,659.0036 C 445.02711,532.63072 503.94812,439.58103 370.66406,379.59735 C 439.14989,363.96856 465.05721,361.86643 479.53906,363.2536 C 444.72231,339.57148 420.60352,327.54967 393.66406,325.3161 C 452.90693,238.96094 326.66051,184.93904 115.78906,165.28485 z M 396.16406,338.9411 C 400.59386,338.94111 404.19531,342.54255 404.19531,346.97235 C 404.1953,351.40217 400.59387,354.97235 396.16406,354.97235 C 391.73423,354.97236 388.13281,351.40217 388.13281,346.97235 C 388.1328,342.54255 391.73424,338.9411 396.16406,338.9411 z"
+ d="m 115.78906,165.28485 c 234.31168,56.69016 193.84625,139.20864 96.40625,208.5625 -47.309,16.67118 -106.62345,37.12663 -183.531252,60.71875 36.43792,-4.83869 69.54541,-8.08762 99.375002,-9.75 -29.904372,15.92001 -59.812012,30.18494 -85.625002,42.0625 59.258602,-16.80501 110.146642,-30.93304 154.187502,-42.875 161.37466,6.8828 173.27146,84.77587 24.15625,235 224.2693,-126.37288 283.19031,-219.42257 149.90625,-279.40625 68.48583,-15.62879 94.39315,-17.73092 108.875,-16.34375 -34.81675,-23.68212 -58.93554,-35.70393 -85.875,-37.9375 59.24287,-86.35516 -67.00355,-140.37706 -277.875,-160.03125 z m 280.375,173.65625 c 4.4298,10e-6 8.03125,3.60145 8.03125,8.03125 -1e-5,4.42982 -3.60144,8 -8.03125,8 -4.42983,10e-6 -8.03125,-3.57018 -8.03125,-8 -1e-5,-4.4298 3.60143,-8.03125 8.03125,-8.03125 z"
id="path2441"
- transform="matrix(1.2286617,0,0,1.2286617,7.4362342,-159.13251)" />
+ transform="matrix(1.2286617,0,0,1.2286617,7.4362425,-127.54827)"
+ inkscape:connector-curvature="0" />
<path
style="opacity:0.35820899;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:#000000;stroke-width:1.00333011px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
- d="M 193.43655,38.683901 C 481.36377,106.86408 431.64137,206.12084 311.88952,289.5279 C 253.76866,309.57308 180.85932,334.14392 86.387308,362.50752 C 131.16565,356.68778 171.8703,352.78146 208.52634,350.78268 C 171.78326,369.92726 135.03618,387.08152 103.32012,401.36485 C 176.12602,381.15723 238.61951,364.20345 292.72972,349.8432 C 491.00731,358.12042 505.62549,451.75302 322.41016,632.40439 C 597.96661,480.43489 670.40043,368.53822 506.63621,296.40496 C 590.78377,277.6106 622.61572,275.12026 640.40936,276.7884 C 597.63051,248.30952 567.9961,233.81513 534.89597,231.12916 C 607.68329,127.28416 452.52952,62.318851 193.43655,38.683901 z M 537.9677,247.51387 C 543.41055,247.51388 547.79717,251.84478 547.79717,257.17184 C 547.79718,262.49891 543.41054,266.8298 537.9677,266.8298 C 532.52484,266.8298 528.09981,262.49891 528.09981,257.17184 C 528.09981,251.84478 532.52483,247.51387 537.9677,247.51387 z"
- id="path2469" />
+ d="m 193.43656,70.268137 c 287.92722,68.180183 238.20482,167.436943 118.45297,250.844003 -58.12086,20.04518 -131.0302,44.61602 -225.502214,72.97962 44.778344,-5.81974 85.482994,-9.72606 122.139034,-11.72484 -36.74308,19.14458 -73.49016,36.29884 -105.20622,50.58217 72.8059,-20.20762 135.29939,-37.1614 189.4096,-51.52165 198.27759,8.27722 212.89577,101.90982 29.68044,282.56119 C 597.96662,512.01913 670.40044,400.12246 506.63622,327.9892 590.78378,309.19484 622.61573,306.7045 640.40937,308.37264 597.63052,279.89376 567.99611,265.39937 534.89598,262.7134 607.6833,158.8684 452.52953,93.903087 193.43656,70.268137 Z M 537.96771,279.09811 c 5.44285,10e-6 9.82947,4.33091 9.82947,9.65797 10e-6,5.32707 -4.38663,9.65796 -9.82947,9.65796 -5.44286,0 -9.86789,-4.33089 -9.86789,-9.65796 0,-5.32706 4.42502,-9.65797 9.86789,-9.65797 z"
+ id="path2469"
+ inkscape:connector-curvature="0" />
<text
xml:space="preserve"
- style="font-size:160.47987366px;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;text-align:start;line-height:125%;writing-mode:lr-tb;text-anchor:start;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bodoni SvtyTwo OS ITC TT;-inkscape-font-specification:Bodoni SvtyTwo OS ITC TT"
- x="22.41254"
- y="527.68341"
+ style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:160.48001099px;line-height:125%;font-family:'Bodoni 72 Oldstyle';-inkscape-font-specification:'Bodoni 72 Oldstyle, Normal';font-variant-ligatures:none;font-variant-caps:normal;font-variant-numeric:normal;text-align:start;writing-mode:lr-tb;text-anchor:start;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
+ x="22.412548"
+ y="557.24536"
id="text4727"
sodipodi:linespacing="125%"
- transform="scale(0.9359712,1.0684089)"><tspan
+ transform="scale(0.93597122,1.0684089)"><tspan
sodipodi:role="line"
id="tspan4729"
- x="22.41254"
- y="527.68341">Swift</tspan></text>
+ x="22.412548"
+ y="557.24536">Swift</tspan></text>
</g>
</svg>
diff --git a/Swift/resources/themes/Default/Demo.html b/Swift/resources/themes/Default/Demo.html
deleted file mode 100755
index cbe5bb1..0000000
--- a/Swift/resources/themes/Default/Demo.html
+++ /dev/null
@@ -1,91 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8" />
- <base href="%@">
-
- <style id="mainStyle" type="text/css" media="screen,print"> @import url( "Variants/Yellow on Green Alternating.css" ); </style>
-
-</head>
-<body style="background-color:#e3e3e3">
-<div id="Chat">
- <div class="chatItem incomingItem">
- <table width="100%">
- <tr>
- <td valign="top">
- <img src="images/DummyContact.png" alt="%sender%" title="%sender%" class="avatar">
- <div class="myBubble">
- <div class="indicator"></div>
- <table class="tableBubble" cellspacing="0" cellpadding="0">
- <tr>
- <td class="tl"></td>
- <td class="tr"></td>
- </tr>
- <tr>
- <td class="message">
- Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
- <div class="timeStamp">Torrey @ 4:55 am</div>
- <div class="followUp"></div>
- <div>
- testing 1
- <div class="timeStamp">%sender% @ %time%</div>
- </div>
- <div class="followUp"></div>
- <div class="followUpMessage">
- testing 123
- <div class="timeStamp">%sender% @ %time%</div>
- </div>
- <div class="followUp"></div>
- <div>
- testing 123testing 123testing 123testing 123
- testing 123testing 123
- <div class="timeStamp">%sender% @ %time%</div>
- </div>
- </td>
- <td class="messageRight"></td>
- </tr>
- <tr>
- <td class="bl"></td>
- <td class="br"></td>
- </tr>
- </table>
- </div>
- </td>
- </tr>
- </table>
- </div>
-
- <div class="chatItem outgoingItem">
- <table width="100%">
- <tr>
- <td valign="top">
- <img src="images/DummyContact.png" alt="%sender%" title="%sender%" class="avatar">
- <div class="myBubble">
- <div class="indicator"></div>
- <table class="tableBubble" cellspacing="0" cellpadding="0">
- <tr>
- <td class="tl"></td>
- <td class="tr"></td>
- </tr>
- <tr>
- <td class="message">
- Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas aliquam sapien. Aliquam sed erat eu leo bibendum egestas. Praesent mauris. Quisque eget eros et neque scelerisque convallis. Phasellus orci. Pellentesque interdum tellus a erat. venenatis tristique.
- <div class="timeStamp">Torrey @ 4:55 am</div>
- </td>
- <td class="messageRight"></td>
- </tr>
- <tr>
- <td class="bl"></td>
- <td class="br"></td>
- </tr>
- </table>
- </div>
- </td>
- </tr>
- </table>
- </div>
-
-</div>
-</body>
-</html>
diff --git a/Swift/resources/themes/Default/Header.html b/Swift/resources/themes/Default/Header.html
deleted file mode 100755
index 960dfa1..0000000
--- a/Swift/resources/themes/Default/Header.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<div id="heading">
- <div class="conversationIncomingIcon"><img src="%incomingIconPath%" /></div>
- <div class="conversationWith">%chatName%</div>
- <div class="conversationTime">Conversation began %timeOpened%</div>
-</div>
diff --git a/Swift/resources/themes/Default/Incoming/Content.html b/Swift/resources/themes/Default/Incoming/Content.html
index dc5f8b2..15bc088 100755..100644
--- a/Swift/resources/themes/Default/Incoming/Content.html
+++ b/Swift/resources/themes/Default/Incoming/Content.html
@@ -1,30 +1,19 @@
-<div class="chatItem incomingItem">
- <table width="100%">
- <tr>
- <td valign="top">
- <img src="%userIconPath%" class="avatar" title="%sender%" ondragstart="return false" />
- <div class="myBubble">
- <div class="indicator"></div>
- <table class="tableBubble" cellspacing="0" cellpadding="0">
- <tr>
- <td class="tl"></td>
- <td class="tr"></td>
- </tr>
- <tr>
- <td class="message" style="direction: %direction%">
- %message%
- <div class="timeStamp"><span class="name">%wrapped_sender% @</span> %time%</div>
- <span id="insert"></span>
- </td>
- <td class="messageRight"></td>
- </tr>
- <tr>
- <td class="bl"></td>
- <td class="br"></td>
- </tr>
- </table>
- </div>
- </td>
- </tr>
- </table>
+<!--OTHERS MESSAGE-->
+<div class="message" id="%id%">
+ <div class="user">
+ <div class="otheravatar">
+ <img src="%userIconPath%"/>
+ </div>
+ <div class="otherright">
+ <span class="swift_ack"></span>
+ <span class="swift_receipt"></span>
+ </div>
+ </div>
+ <div class="text">
+ <p class="otherusername username">%wrapped_sender%</p>
+ <div class="time">
+ %time%
+ </div>
+ <div class="message-content">%message%</div>
+ </div>
</div>
diff --git a/Swift/resources/themes/Default/Incoming/Context.html b/Swift/resources/themes/Default/Incoming/Context.html
deleted file mode 100755
index 1f0c528..0000000
--- a/Swift/resources/themes/Default/Incoming/Context.html
+++ /dev/null
@@ -1,30 +0,0 @@
-<div class="chatItem incomingItem">
- <table width="100%">
- <tr>
- <td valign="top">
- <img src="%userIconPath%" class="avatar" ondragstart="return false" />
- <div class="myBubble">
- <div class="indicator"></div>
- <table class="tableBubble" cellspacing="0" cellpadding="0">
- <tr>
- <td class="tl"></td>
- <td class="tr"></td>
- </tr>
- <tr>
- <td class="message" style="direction: %direction%">
- %message%
- <div class="timeStamp"><span class="name">%sender% @</span> %time%</div>
- <span id="insert"></span>
- </td>
- <td class="messageRight"></td>
- </tr>
- <tr>
- <td class="bl"></td>
- <td class="br"></td>
- </tr>
- </table>
- </div>
- </td>
- </tr>
- </table>
-</div>
diff --git a/Swift/resources/themes/Default/Incoming/NextContent.html b/Swift/resources/themes/Default/Incoming/NextContent.html
index aff669b..36fdaa3 100755..100644
--- a/Swift/resources/themes/Default/Incoming/NextContent.html
+++ b/Swift/resources/themes/Default/Incoming/NextContent.html
@@ -1,10 +1,18 @@
-<div>
- <div class="followUp"></div>
- <div style="direction: %direction%">
-
- %message%
- <div class="timeStamp">%time%</div>
- </div>
- <span id="insert"></span>
+<!--OTHERS MESSAGE ADDITIONAL-->
+<div class="message additional" id="%id%">
+ <div class="user">
+ <div class="systemavatar">
+ <img/>
+ </div>
+ <div class="systemright">
+ <span class="swift_ack"></span>
+ <span class="swift_receipt"></span>
+ </div>
+ </div>
+ <div class="text">
+ <div class="time">
+ %time%
+ </div>
+ <div class="message-content">%message%</div>
+ </div>
</div>
-
diff --git a/Swift/resources/themes/Default/Incoming/NextContext.html b/Swift/resources/themes/Default/Incoming/NextContext.html
deleted file mode 100755
index c0a8846..0000000
--- a/Swift/resources/themes/Default/Incoming/NextContext.html
+++ /dev/null
@@ -1,7 +0,0 @@
- <div class="followUp"></div>
- <div style="direction: %direction%">
-
- %message%
- <div class="timeStamp">%time%</div>
- </div><span id="insert"></span>
-
diff --git a/Swift/resources/themes/Default/Incoming/buddy_icon.png b/Swift/resources/themes/Default/Incoming/buddy_icon.png
deleted file mode 100644
index 0757aaa..0000000
--- a/Swift/resources/themes/Default/Incoming/buddy_icon.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/LICENSE.txt b/Swift/resources/themes/Default/LICENSE.txt
deleted file mode 100644
index 2eee1ee..0000000
--- a/Swift/resources/themes/Default/LICENSE.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-The images, css and html is dual licensed under the BSD and AFL license.
-The source files for the bubbles can be found at http://www.itorrey.com/adiumx/
-
-The fading javascript is not covered in this license. The code is fadomatic and is covered under its own license as set by its author.
-
-BSD LICENSE
-Copyright (c) 2007, Torrey Rice/Renkoo6¾3 All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Torrey Rice and Renkoo nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-Renkoo is a service mark of Renkoo, Inc.
-
-http://www.opensource.org/licenses/bsd-license.php
-
-
-
-# Larry Rosen has ceased to use or recommend any version # of the Academic Free License below version 2.1 The Academic Free License v. 2.1 This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following notice immediately following the copyright notice for the Original Work: Licensed under the Academic Free License version 2.1 1) Grant of Copyright License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license to do the following: a) to reproduce the Original Work in copies; b) to prepare derivative works ("Derivative Works") based upon the Original Work; c) to distribute copies of the Original Work and Derivative Works to the public; d) to perform the Original Work publicly; and e) to display the Original Work publicly. 2) Grant of Patent License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, to make, use, sell and offer for sale the Original Work and Derivative Works. 3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor hereby agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work, and by publishing the address of that information repository in a notice immediately following the copyright notice that applies to the Original Work. 4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior written permission of the Licensor. Nothing in this License shall be deemed to grant any rights to trademarks, copyrights, patents, trade secrets or any other intellectual property of Licensor except as expressly stated herein. No patent license is granted to make, use, sell or offer to sell embodiments of any patent claims other than the licensed claims defined in Section 2. No right is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under different terms from this License any Original Work that Licensor otherwise would have a right to license. 5) This section intentionally omitted. 6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. 7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately proceeding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to Original Work is granted hereunder except under this disclaimer. 8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to any person for any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to liability for death or personal injury resulting from Licensor's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. 9) Acceptance and Termination. If You distribute copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. Nothing else but this License (or another written agreement between Licensor and You) grants You permission to create Derivative Works based upon the Original Work or to exercise any of the rights granted in Section 1 herein, and any attempt to do so except under the terms of this License (or another written agreement between Licensor and You) is expressly prohibited by U.S. copyright law, the equivalent laws of other countries, and by international treaty. Therefore, by exercising any of the rights granted to You in Section 1 herein, You indicate Your acceptance of this License and all of its terms and conditions. 10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. 11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of the U.S. Copyright Act, 17 U.S.C. 0‡30¨¢0¡ă0ˆ3 101 et seq., the equivalent laws of other countries, and international treaty. This section shall survive the termination of this License. 12) Attorneys Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. 13) Miscellaneous. This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. 14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. This license is Copyright (C) 2003-2004 Lawrence E. Rosen. All rights reserved. Permission is hereby granted to copy and distribute this license without modification. This license may not be modified without the express written permission of its copyright owner. \ No newline at end of file
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-Black.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-Black.ttf
new file mode 100644
index 0000000..e2aeb6c
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-Black.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-BlackItalic.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-BlackItalic.ttf
new file mode 100644
index 0000000..8167388
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-BlackItalic.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-Bold.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-Bold.ttf
new file mode 100644
index 0000000..ef5ae3b
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-Bold.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-BoldItalic.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-BoldItalic.ttf
new file mode 100644
index 0000000..664cd02
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-BoldItalic.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-Hairline.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-Hairline.ttf
new file mode 100644
index 0000000..4c5a8fd
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-Hairline.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-HairlineItalic.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-HairlineItalic.ttf
new file mode 100644
index 0000000..af5ac3d
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-HairlineItalic.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-Heavy.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-Heavy.ttf
new file mode 100644
index 0000000..fc70ab7
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-Heavy.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-HeavyItalic.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-HeavyItalic.ttf
new file mode 100644
index 0000000..823188c
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-HeavyItalic.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-Italic.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-Italic.ttf
new file mode 100644
index 0000000..b23256f
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-Italic.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-Light.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-Light.ttf
new file mode 100644
index 0000000..0809b8e
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-Light.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-LightItalic.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-LightItalic.ttf
new file mode 100644
index 0000000..2d03739
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-LightItalic.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-Medium.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-Medium.ttf
new file mode 100644
index 0000000..2c612da
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-Medium.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-MediumItalic.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-MediumItalic.ttf
new file mode 100644
index 0000000..63ecd02
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-MediumItalic.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-Regular.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-Regular.ttf
new file mode 100644
index 0000000..adbfc46
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-Regular.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-Semibold.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-Semibold.ttf
new file mode 100644
index 0000000..60ac82d
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-Semibold.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-SemiboldItalic.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-SemiboldItalic.ttf
new file mode 100644
index 0000000..cc23390
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-SemiboldItalic.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-Thin.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-Thin.ttf
new file mode 100644
index 0000000..0f84dc1
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-Thin.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/Lato-ThinItalic.ttf b/Swift/resources/themes/Default/Lato2OFL/Lato-ThinItalic.ttf
new file mode 100644
index 0000000..7fbca2f
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/Lato-ThinItalic.ttf
Binary files differ
diff --git a/Swift/resources/themes/Default/Lato2OFL/OFL.txt b/Swift/resources/themes/Default/Lato2OFL/OFL.txt
new file mode 100755
index 0000000..8a7280e
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/OFL.txt
@@ -0,0 +1,94 @@
+Copyright (c) 2010-2015, Åukasz Dziedzic (dziedzic@typoland.com),
+with Reserved Font Name Lato.
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/Swift/resources/themes/Default/Lato2OFL/README.txt b/Swift/resources/themes/Default/Lato2OFL/README.txt
new file mode 100755
index 0000000..272db62
--- /dev/null
+++ b/Swift/resources/themes/Default/Lato2OFL/README.txt
@@ -0,0 +1,72 @@
+
+Lato font family (Desktop version)
+
+==================================
+
+Version 2.015; Latin+Cyrillic+Greek+IPA opensource
+
+Created by: tyPoland Lukasz Dziedzic
+Creation year: 2015
+
+Copyright (c) 2010-2015 by tyPoland Lukasz Dziedzic with Reserved Font Name "Lato". Licensed under the SIL Open Font License, Version 1.1.
+
+Lato is a trademark of tyPoland Lukasz Dziedzic.
+
+Source URL: http://www.latofonts.com/
+License URL: http://scripts.sil.org/OFL
+
+================
+
+Lato is a sanserif typeface family designed in the Summer 2010 and extended in the Summer 2013 by Warsaw-based designer Lukasz Dziedzic ("Lato" means "Summer" in Polish). It tries to carefully balance some potentially conflicting priorities: it should seem quite "transparent" when used in body text but would display some original traits when used in larger sizes. The classical proportions, particularly visible in the uppercase, give the letterforms familiar harmony and elegance. At the same time, its sleek sanserif look makes evident the fact that Lato was designed in the 2010s, even though it does not follow any current trend. The semi-rounded details of the letters give Lato a feeling of warmth, while the strong structure provides stability and seriousness. In 2013-2014, the family was greatly extended (with the help of Adam Twardoch and Botio Nikoltchev) to cover 3000+ glyphs over nine weights with italics. It now supports 100+ Latin-based languages, 50+ Cyrillic-based languages as well as Greek and IPA phonetics. The Lato fonts are available free of charge under the SIL Open Font License from http://www.latofonts.com/
+
+================
+
+CONTENTS:
+
+This folder contains 18 font files in OpenType TT (.ttf) format. You can install these fonts on your computer and use in any desktop applications (such as Word, InDesign, Illustrator, Photoshop, Keynote or Pages).
+
+================
+
+REVISION LOG:
+
+# Version 2.015 (2015-08-06)
+Initial implementation of mark positioning (should work for most glyphs)
+Autohinted using ttfautohint 1.3.
+
+# Version 2.010 (2014-09-01)
+Improved some contour bugs and diacritics positioning.
+Improved outline quality.
+Revised OTL features so that they work in browsers (ot-sanitise).
+Autohinted using ttfautohint 1.1.
+Interpolated the Medium weight differently so it provides more visual difference from Regular.
+
+# Version 2.007 (2014-02-27)
+Greatly expanded character set, revised metrics, four additional weights.
+
+# Version 1.104 (2011-11-08)
+Merged the distribution again
+Autohinted with updated ttfautohint 0.4 (which no longer causes Adobe and iOS problems)
+except the Hai and Lig weights which are hinted in FLS 5.1.
+
+# Version 1.102 (2011-10-28)
+Added OpenType Layout features
+Ssplit between desktop and web versions
+Desktop version: all weights autohinted with FontLab Studio
+Web version autohinted with ttfautohint 0.4 except the Hai and Lig weights
+
+# Version 1.101 (2011-09-30)
+Fixed OS/2 table Unicode and codepage entries
+
+# Version 1.100 (2011-09-12)
+Added Polish diacritics to the character set
+Weights Hai and Lig autohinted with FontLab Studio
+Other weights autohinted with ttfautohint 0.3
+
+# Version 1.011 (2010-12-29)
+Added the soft hyphen glyph
+
+# Version 1.010 (2010-12-13)
+Initial version released under SIL Open Font License
+Western character set
+
+================
diff --git a/Swift/resources/themes/Default/Outgoing/Content.html b/Swift/resources/themes/Default/Outgoing/Content.html
index b0475d2..e73e785 100755..100644
--- a/Swift/resources/themes/Default/Outgoing/Content.html
+++ b/Swift/resources/themes/Default/Outgoing/Content.html
@@ -1,30 +1,19 @@
-<div class="chatItem outgoingItem">
- <table width="100%">
- <tr>
- <td valign="top">
- <img src="%userIconPath%" class="avatar" title="%sender%" ondragstart="return false" />
- <div class="myBubble">
- <div class="indicator"></div>
- <table class="tableBubble" cellspacing="0" cellpadding="0">
- <tr>
- <td class="tl"></td>
- <td class="tr"></td>
- </tr>
- <tr>
- <td class="message" style="direction: %direction%">
- %message%
- <div class="timeStamp"><span class="name">%wrapped_sender% @</span> %time%</div>
- <span id="insert"></span>
- </td>
- <td class="messageRight"></td>
- </tr>
- <tr>
- <td class="bl"></td>
- <td class="br"></td>
- </tr>
- </table>
- </div>
- </td>
- </tr>
- </table>
+<!--MY MESSAGE-->
+<div class="message" id="%id%">
+ <div class="user">
+ <div class="myavatar">
+ <img src="%userIconPath%"/>
+ </div>
+ <div class="myright">
+ <span class="swift_ack"></span>
+ <span class="swift_receipt"></span>
+ </div>
+ </div>
+ <div class="text">
+ <p class="myusername username">%wrapped_sender%</p>
+ <div class="time">
+ %time%
+ </div>
+ <div class="message-content">%message%</div>
+ </div>
</div>
diff --git a/Swift/resources/themes/Default/Outgoing/Context.html b/Swift/resources/themes/Default/Outgoing/Context.html
deleted file mode 100755
index 679d786..0000000
--- a/Swift/resources/themes/Default/Outgoing/Context.html
+++ /dev/null
@@ -1,31 +0,0 @@
-<div class="chatItem outgoingItem">
- <table width="100%">
- <tr>
- <td valign="top">
- <img src="%userIconPath%" class="avatar" ondragstart="return false" />
- <div class="myBubble">
- <div class="indicator"></div>
- <table class="tableBubble" cellspacing="0" cellpadding="0">
- <tr>
- <td class="tl"></td>
- <td class="tr"></td>
- </tr>
- <tr>
- <td class="message" style="direction: %direction%">
-
- %message%
- <div class="timeStamp"><span class="name">%sender% @</span> %time%</div>
- <span id="insert"></span>
- </td>
- <td class="messageRight"></td>
- </tr>
- <tr>
- <td class="bl"></td>
- <td class="br"></td>
- </tr>
- </table>
- </div>
- </td>
- </tr>
- </table>
-</div>
diff --git a/Swift/resources/themes/Default/Outgoing/NextContent.html b/Swift/resources/themes/Default/Outgoing/NextContent.html
index fe6490e..f96f65a 100755..100644
--- a/Swift/resources/themes/Default/Outgoing/NextContent.html
+++ b/Swift/resources/themes/Default/Outgoing/NextContent.html
@@ -1,9 +1,19 @@
-<div>
- <div class="followUp"></div>
- <div style="direction: %direction%">
- %message%
- <div class="timeStamp">%time%</div>
- </div>
- <span id="insert"></span>
+<!--My MESSAGE ADDITIONAL-->
+<div class="message additional" id="%id%">
+ <div class="user">
+ <div class="systemavatar">
+ <img/>
+ </div>
+ <div class="systemright">
+ <span class="swift_ack"></span>
+ <span class="swift_receipt"></span>
+ </div>
+ </div>
+ <div class="text">
+ <div class="time">
+ %time%
+ </div>
+ <div class="message-content">%message%</div>
+ </div>
</div>
diff --git a/Swift/resources/themes/Default/Outgoing/NextContext.html b/Swift/resources/themes/Default/Outgoing/NextContext.html
deleted file mode 100755
index f66aeeb..0000000
--- a/Swift/resources/themes/Default/Outgoing/NextContext.html
+++ /dev/null
@@ -1,6 +0,0 @@
-<div class="followUp"></div>
-<div style="direction: %direction%">
- %message%
- <div class="timeStamp">%time%</div>
-</div><span id="insert"></span>
-
diff --git a/Swift/resources/themes/Default/Outgoing/buddy_icon.png b/Swift/resources/themes/Default/Outgoing/buddy_icon.png
deleted file mode 100644
index 0757aaa..0000000
--- a/Swift/resources/themes/Default/Outgoing/buddy_icon.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/Status.html b/Swift/resources/themes/Default/Status.html
index e7add89..0a0aaed 100755..100644
--- a/Swift/resources/themes/Default/Status.html
+++ b/Swift/resources/themes/Default/Status.html
@@ -1,27 +1,15 @@
-<div class="chatItem statusMessage">
- <table width="100%">
- <tr>
- <td valign="top">
- <div class="myBubble">
- <table class="tableBubble" cellspacing="0" cellpadding="0">
- <tr>
- <td class="tl"></td>
- <td class="tr"></td>
- </tr>
- <tr>
- <td class="message" style="direction: %direction%">
- %message%
- <div class="timeStamp">%time%</div>
- </td>
- <td class="messageRight"></td>
- </tr>
- <tr>
- <td class="bl"></td>
- <td class="br"></td>
- </tr>
- </table>
- </div>
- </td>
- </tr>
- </table>
+<!--SYSTEM MESSAGE-->
+<div class="message" id="%id%">
+ <div class="user">
+ <div class="systemavatar">
+ <img/>
+ </div>
+ <div class="systemright"></div>
+ </div>
+ <div class="text">
+ <div class="time">
+ %time%
+ </div>
+ <p class="system-message">%message%</p>
+ </div>
</div>
diff --git a/Swift/resources/themes/Default/Template.html b/Swift/resources/themes/Default/Template.html
index 9d5c3a0..74c5e46 100755..100644
--- a/Swift/resources/themes/Default/Template.html
+++ b/Swift/resources/themes/Default/Template.html
@@ -1,343 +1,20 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8" />
- <base href="%@">
-
- <script type="text/javascript">
- //<![CDATA[
-
- isDebug = false;
-
- // Fade interval in milliseconds
- // Make this larger if you experience performance issues
- Fadomatic.INTERVAL_MILLIS = 50;
-
- // Creates a fader
- // element - The element to fade
- // speed - The speed to fade at, from 0.0 to 100.0
- // initialOpacity (optional, default 100) - element's starting opacity, 0 to 100
- // minOpacity (optional, default 0) - element's minimum opacity, 0 to 100
- // maxOpacity (optional, default 0) - element's minimum opacity, 0 to 100
- function Fadomatic (element, rate, initialOpacity, minOpacity, maxOpacity) {
- this._element = element;
- this._intervalId = null;
- this._rate = rate;
- this._isFadeOut = true;
-
- // Set initial opacity and bounds
- // NB use 99 instead of 100 to avoid flicker at start of fade
- this._minOpacity = 0;
- this._maxOpacity = 99;
- this._opacity = 99;
-
- if (typeof minOpacity != 'undefined') {
- if (minOpacity < 0) {
- this._minOpacity = 0;
- } else if (minOpacity > 99) {
- this._minOpacity = 99;
- } else {
- this._minOpacity = minOpacity;
- }
- }
-
- if (typeof maxOpacity != 'undefined') {
- if (maxOpacity < 0) {
- this._maxOpacity = 0;
- } else if (maxOpacity > 99) {
- this._maxOpacity = 99;
- } else {
- this._maxOpacity = maxOpacity;
- }
-
- if (this._maxOpacity < this._minOpacity) {
- this._maxOpacity = this._minOpacity;
- }
- }
-
- if (typeof initialOpacity != 'undefined') {
- if (initialOpacity > this._maxOpacity) {
- this._opacity = this._maxOpacity;
- } else if (initialOpacity < this._minOpacity) {
- this._opacity = this._minOpacity;
- } else {
- this._opacity = initialOpacity;
- }
- }
-
- // See if we're using W3C opacity, MSIE filter, or just
- // toggling visiblity
- if(typeof element.style.opacity != 'undefined') {
-
- this._updateOpacity = this._updateOpacityW3c;
-
- } else if(typeof element.style.filter != 'undefined') {
-
- // If there's not an alpha filter on the element already,
- // add one
- if (element.style.filter.indexOf("alpha") == -1) {
-
- // Attempt to preserve existing filters
- var existingFilters="";
- if (element.style.filter) {
- existingFilters = element.style.filter+" ";
- }
- element.style.filter = existingFilters+"alpha(opacity="+this._opacity+")";
- }
-
- this._updateOpacity = this._updateOpacityMSIE;
-
- } else {
-
- this._updateOpacity = this._updateVisibility;
- }
-
- this._updateOpacity();
- }
-
- // Initiates a fade out
- Fadomatic.prototype.fadeOut = function () {
- this._isFadeOut = true;
- this._beginFade();
- }
-
- // Initiates a fade in
- Fadomatic.prototype.fadeIn = function () {
- this._isFadeOut = false;
- this._beginFade();
- }
-
- // Makes the element completely opaque, stops any fade in progress
- Fadomatic.prototype.show = function () {
- this.haltFade();
- this._opacity = this._maxOpacity;
- this._updateOpacity();
- }
-
- // Makes the element completely transparent, stops any fade in progress
- Fadomatic.prototype.hide = function () {
- this.haltFade();
- this._opacity = 0;
- this._updateOpacity();
- }
-
- // Halts any fade in progress
- Fadomatic.prototype.haltFade = function () {
-
- clearInterval(this._intervalId);
- }
-
- // Resumes a fade where it was halted
- Fadomatic.prototype.resumeFade = function () {
-
- this._beginFade();
- }
-
- // Pseudo-private members
-
- Fadomatic.prototype._beginFade = function () {
-
- this.haltFade();
- var objref = this;
- this._intervalId = setInterval(function() { objref._tickFade(); },Fadomatic.INTERVAL_MILLIS);
- }
-
- Fadomatic.prototype._tickFade = function () {
-
- if (this._isFadeOut) {
- this._opacity -= this._rate;
- if (this._opacity < this._minOpacity) {
- this._opacity = this._minOpacity;
- this.haltFade();
- }
- } else {
- this._opacity += this._rate;
- if (this._opacity > this._maxOpacity ) {
- this._opacity = this._maxOpacity;
- this.haltFade();
- }
- }
-
- this._updateOpacity();
- }
-
- Fadomatic.prototype._updateVisibility = function () {
-
- if (this._opacity > 0) {
- this._element.style.visibility = 'visible';
- } else {
- this._element.style.visibility = 'hidden';
- }
- }
-
- Fadomatic.prototype._updateOpacityW3c = function () {
-
- this._element.style.opacity = this._opacity/100;
- this._updateVisibility();
- }
-
- Fadomatic.prototype._updateOpacityMSIE = function () {
-
- this._element.filters.alpha.opacity = this._opacity;
- this._updateVisibility();
- }
-
- Fadomatic.prototype._updateOpacity = null;
-
-
-
- //Do this on load
- function initEvents() {
- if(document.getElementById("heading") == null){
- document.getElementById("bodyNode").style.marginTop = "5px";
- }
-
- if(isDebug == false) {
- document.getElementById("debug").style.display = "none";
- }
-
-
- alignChat(true);
- }
- //Debugging function
- function trace(msg) {
- var node = document.createElement("div");
- var debugCon = document.getElementById("debug");
- node.innerHTML = msg;
- debugCon.appendChild(node);
- }
-
-
- //Appending new content to the message view
- function appendMessage(html) {
- var shouldScroll = nearBottom();
-
- //Remove any existing insertion point
- var insert = document.getElementById("insert");
-
- if(insert) insert.parentNode.removeChild(insert);
-
- //Append the new message to the bottom of our chat block
- var chat = document.getElementById("Chat");
- var range = document.createRange();
- range.selectNode(chat);
- var documentFragment = range.createContextualFragment(html);
- var myFrag = chat.appendChild(documentFragment);
-
- // Don't do the fadomatic, it's too slow
- /*
- var frag1 = document.getElementById("insert");
- if (frag1) {
- var frag= frag1.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
-
- try {
- var fader = new Fadomatic(frag, 9, 0, 0, 95);
- } catch(e) {
- trace(e);
- }
- fader.fadeIn();
- }
- */
-
- alignChat(shouldScroll);
- }
-
-
- function appendNextMessage(html){
- var shouldScroll = nearBottom();
-
- //Locate the insertion point
- var insert = document.getElementById("insert");
-
- //make new node
- range = document.createRange();
- range.selectNode(insert.parentNode);
- newNode = range.createContextualFragment(html);
-
- //swap
- var pointer = insert.parentNode;
- insert.parentNode.replaceChild(newNode,insert);
- var els = pointer.getElementsByTagName("div");
-
- alignChat(shouldScroll);
- }
-
-
- //Auto-scroll to bottom. Use nearBottom to determine if a scrollToBottom is desired.
- function nearBottom() {
- return ( document.body.scrollTop >= ( document.body.offsetHeight - ( window.innerHeight * 1.2 ) ) );
- }
-
- var intervall_scroll;
- function scrollToBottom() {
- //document.body.scrollTop = (document.body.scrollHeight-window.innerHeight);
- //return;
- if( intervall_scroll ) clearInterval( intervall_scroll );
- intervall_scroll = setInterval( function() {
- var target_scroll = (document.body.scrollHeight-window.innerHeight) - 1;
- var scrolldiff = target_scroll - document.body.scrollTop;
- if ( document.body.scrollTop != target_scroll ) {
- var saved_scroll = document.body.scrollTop;
- document.body.scrollTop += scrolldiff / 5 + ( scrolldiff >= 0 ? (scrolldiff != 0 ) : -1 );
- } else {
- saved_scroll = -1;
- clearInterval( intervall_scroll );
- }
- } , 10 );
- return;
- }
-
-
- //Dynamically exchange the active stylesheet
- function setStylesheet( id, url ) {
- var code = "<style id=\"" + id + "\" type=\"text/css\" media=\"screen,print\">";
- if( url.length ) code += "@import url( \"" + url + "\" );";
- code += "</style>";
- var range = document.createRange();
- var head = document.getElementsByTagName( "head" ).item(0);
- range.selectNode( head );
- documentFragment = range.createContextualFragment( code );
- head.removeChild( document.getElementById( id ) );
- head.appendChild( documentFragment );
- }
-
- //Align our chat to the bottom of the window. If true is passed, view will also be scrolled down
- function alignChat(shouldScroll) {
-
- var windowHeight = window.innerHeight;
-
- if(windowHeight > 0) {
- var contentElement = document.getElementById('Chat');
- var contentHeight = contentElement.offsetHeight;
- if (windowHeight - contentHeight > 0) {
- contentElement.style.position = 'relative';
- contentElement.style.top = '0px';
- } else {
- contentElement.style.position = 'static';
- }
- }
-
- if(shouldScroll) scrollToBottom();
- }
-
- function windowDidResize() {
- alignChat(true/*nearBottom()*/); //nearBottom buggy with inavtive tabs
- }
-
- window.onresize = windowDidResize;
- //]]>
- </script>
-
- <style id="mainStyle" type="text/css" media="screen,print"> @import url( "%@" ); </style>
-
-</head>
-<body style="==bodyBackground==" id="bodyNode" onload="initEvents()">
-%@
-<div id="Chat">
-</div>
-%@
-<div id="debug"></div>
-</body>
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <link rel="stylesheet" href="qrc:///themes/Default/lato.css"/>
+ <link rel="stylesheet" href="qrc:///themes/Default/main.css"/>
+ <style id="text-resize-style">
+ </style>
+ </head>
+ <body>
+ <div class="container">
+ <div class="message-block">
+ <div id="insert">
+ <div class="user"></div><div class="text"></div>
+ </div>
+ </div>
+ </div>
+ </body>
</html>
diff --git a/Swift/resources/themes/Default/Unread.html b/Swift/resources/themes/Default/Unread.html
new file mode 100644
index 0000000..3e25431
--- /dev/null
+++ b/Swift/resources/themes/Default/Unread.html
@@ -0,0 +1 @@
+<div class='unread'><div class="user"></div><div class="text"><span class="swift_resizable"><p>Unread</p></span></div></div> \ No newline at end of file
diff --git a/Swift/resources/themes/Default/Variants/Blue on Green Alternating.css b/Swift/resources/themes/Default/Variants/Blue on Green Alternating.css
deleted file mode 100644
index 5b910eb..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Green Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Blue on Green.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/blueIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Blue on Green No Names Alt.css b/Swift/resources/themes/Default/Variants/Blue on Green No Names Alt.css
deleted file mode 100644
index ebad314..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Green No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Blue on Green Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Blue on Green No Names.css b/Swift/resources/themes/Default/Variants/Blue on Green No Names.css
deleted file mode 100644
index 2a0902c..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Green No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Blue on Green.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Blue on Green.css b/Swift/resources/themes/Default/Variants/Blue on Green.css
deleted file mode 100644
index 361c8c6..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Green.css
+++ /dev/null
@@ -1,90 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#7fc5f8;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/blueIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/blueCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/blueCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/blueCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/blueBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/blueBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/blueCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/blueCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#ddf0fe;
- border-bottom:1px solid #fff;
-}
-
-/*incoming */
-
-.incomingItem .myBubble .indicator {
- background:url("../images/greenIndicator.png") no-repeat top left;
-}
-
-.incomingItem .timeStamp {
- color:#9ecf35;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/greenCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/greenCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/greenCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/greenBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/greenBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/greenCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/greenCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#e2efc4;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Blue on Red Alternating.css b/Swift/resources/themes/Default/Variants/Blue on Red Alternating.css
deleted file mode 100644
index 5481c10..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Red Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Blue on Red.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/blueIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Blue on Red No Names Alt.css b/Swift/resources/themes/Default/Variants/Blue on Red No Names Alt.css
deleted file mode 100644
index 9818a6c..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Red No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Blue on Red Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Blue on Red No Names.css b/Swift/resources/themes/Default/Variants/Blue on Red No Names.css
deleted file mode 100644
index 3ac8c9a..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Red No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Blue on Red.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Blue on Red.css b/Swift/resources/themes/Default/Variants/Blue on Red.css
deleted file mode 100644
index 0717920..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Red.css
+++ /dev/null
@@ -1,89 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#7fc5f8;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/blueIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/blueCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/blueCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/blueCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/blueBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/blueBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/blueCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/blueCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#ddf0fe;
- border-bottom:1px solid #fff;
-}
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#f88f8f;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/redIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/redCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/redCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/redCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/redBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/redBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/redCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/redCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#ffdada;
- border-bottom:1px solid #fff;
-}
diff --git a/Swift/resources/themes/Default/Variants/Blue on Steel Alternating.css b/Swift/resources/themes/Default/Variants/Blue on Steel Alternating.css
deleted file mode 100644
index 8473d1f..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Steel Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Blue on Steel.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/blueIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Blue on Steel No Names Alt.css b/Swift/resources/themes/Default/Variants/Blue on Steel No Names Alt.css
deleted file mode 100644
index 1925d5c..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Steel No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Blue on Steel Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Blue on Steel No Names.css b/Swift/resources/themes/Default/Variants/Blue on Steel No Names.css
deleted file mode 100644
index 573aa58..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Steel No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Blue on Steel.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Blue on Steel.css b/Swift/resources/themes/Default/Variants/Blue on Steel.css
deleted file mode 100644
index 48ab03d..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Steel.css
+++ /dev/null
@@ -1,91 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#7fc5f8;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/blueIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/blueCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/blueCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/blueCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/blueBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/blueBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/blueCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/blueCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#ddf0fe;
- border-bottom:1px solid #fff;
-}
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#a9a9a9;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/steelIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/steelCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/steelCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/steelCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/steelBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/steelBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/steelCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/steelCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#ececec;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Blue on Yellow Alternating.css b/Swift/resources/themes/Default/Variants/Blue on Yellow Alternating.css
deleted file mode 100644
index d7927fc..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Yellow Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Blue on Yellow.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/blueIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Blue on Yellow No Names Alt.css b/Swift/resources/themes/Default/Variants/Blue on Yellow No Names Alt.css
deleted file mode 100644
index 38d374d..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Yellow No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Blue on Yellow Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Blue on Yellow No Names.css b/Swift/resources/themes/Default/Variants/Blue on Yellow No Names.css
deleted file mode 100644
index 3fdc8cd..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Yellow No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Blue on Yellow.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Blue on Yellow.css b/Swift/resources/themes/Default/Variants/Blue on Yellow.css
deleted file mode 100644
index b019b0b..0000000
--- a/Swift/resources/themes/Default/Variants/Blue on Yellow.css
+++ /dev/null
@@ -1,91 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#7fc5f8;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/blueIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/blueCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/blueCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/blueCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/blueBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/blueBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/blueCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/blueCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#ddf0fe;
- border-bottom:1px solid #fff;
-}
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#bdb410;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/yellowIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/yellowCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/yellowCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/yellowCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/yellowBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/yellowBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/yellowCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/yellowCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#f4f0a7;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Green on Blue Alternating.css b/Swift/resources/themes/Default/Variants/Green on Blue Alternating.css
deleted file mode 100644
index 272c0d0..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Blue Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Green on Blue.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/greenIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Green on Blue No Names Alt.css b/Swift/resources/themes/Default/Variants/Green on Blue No Names Alt.css
deleted file mode 100644
index 973f91a..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Blue No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Green on Blue Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Green on Blue No Names.css b/Swift/resources/themes/Default/Variants/Green on Blue No Names.css
deleted file mode 100644
index 0d92eb0..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Blue No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Green on Blue.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Green on Blue.css b/Swift/resources/themes/Default/Variants/Green on Blue.css
deleted file mode 100644
index 7185f4f..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Blue.css
+++ /dev/null
@@ -1,91 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#9ecf35;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/greenIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/greenCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/greenCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/greenCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/greenBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/greenBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/greenCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/greenCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#e2efc4;
- border-bottom:1px solid #fff;
-}
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#7fc5f8;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/blueIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/blueCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/blueCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/blueCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/blueBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/blueBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/blueCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/blueCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#ddf0fe;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Green on Red Alternating.css b/Swift/resources/themes/Default/Variants/Green on Red Alternating.css
deleted file mode 100644
index e656dc0..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Red Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Green on Red.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/greenIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Green on Red No Names Alt.css b/Swift/resources/themes/Default/Variants/Green on Red No Names Alt.css
deleted file mode 100644
index 5fd2482..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Red No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Green on Red Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Green on Red No Names.css b/Swift/resources/themes/Default/Variants/Green on Red No Names.css
deleted file mode 100644
index 23dae81..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Red No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Green on Red.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Green on Red.css b/Swift/resources/themes/Default/Variants/Green on Red.css
deleted file mode 100644
index cdf38b3..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Red.css
+++ /dev/null
@@ -1,91 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#9ecf35;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/greenIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/greenCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/greenCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/greenCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/greenBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/greenBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/greenCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/greenCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#e2efc4;
- border-bottom:1px solid #fff;
-}
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#f88f8f;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/redIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/redCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/redCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/redCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/redBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/redBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/redCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/redCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#ffdada;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Green on Steel Alternating.css b/Swift/resources/themes/Default/Variants/Green on Steel Alternating.css
deleted file mode 100644
index 3c14f7f..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Steel Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Green on Steel.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/greenIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Green on Steel No Names Alt.css b/Swift/resources/themes/Default/Variants/Green on Steel No Names Alt.css
deleted file mode 100644
index cfd6bb9..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Steel No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Green on Steel Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Green on Steel No Names.css b/Swift/resources/themes/Default/Variants/Green on Steel No Names.css
deleted file mode 100644
index 41bc9de..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Steel No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Green on Steel.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Green on Steel.css b/Swift/resources/themes/Default/Variants/Green on Steel.css
deleted file mode 100644
index 30a78a0..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Steel.css
+++ /dev/null
@@ -1,91 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#9ecf35;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/greenIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/greenCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/greenCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/greenCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/greenBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/greenBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/greenCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/greenCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#e2efc4;
- border-bottom:1px solid #fff;
-}
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#a9a9a9;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/steelIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/steelCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/steelCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/steelCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/steelBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/steelBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/steelCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/steelCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#ececec;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Green on Yellow Alternating.css b/Swift/resources/themes/Default/Variants/Green on Yellow Alternating.css
deleted file mode 100644
index d0553e8..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Yellow Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Green on Yellow.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/greenIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Green on Yellow No Names Alt.css b/Swift/resources/themes/Default/Variants/Green on Yellow No Names Alt.css
deleted file mode 100644
index 27adc33..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Yellow No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Green on Yellow Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Green on Yellow No Names.css b/Swift/resources/themes/Default/Variants/Green on Yellow No Names.css
deleted file mode 100644
index 8c8cb28..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Yellow No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Green on Yellow.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Green on Yellow.css b/Swift/resources/themes/Default/Variants/Green on Yellow.css
deleted file mode 100644
index d7f64d3..0000000
--- a/Swift/resources/themes/Default/Variants/Green on Yellow.css
+++ /dev/null
@@ -1,91 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#9ecf35;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/greenIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/greenCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/greenCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/greenCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/greenBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/greenBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/greenCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/greenCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#e2efc4;
- border-bottom:1px solid #fff;
-}
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#bdb410;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/yellowIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/yellowCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/yellowCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/yellowCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/yellowBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/yellowBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/yellowCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/yellowCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#f4f0a7;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Red on Blue Alternating.css b/Swift/resources/themes/Default/Variants/Red on Blue Alternating.css
deleted file mode 100644
index 5d241fb..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Blue Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Red on Blue.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/redIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Red on Blue No Names Alt.css b/Swift/resources/themes/Default/Variants/Red on Blue No Names Alt.css
deleted file mode 100644
index 2e80935..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Blue No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Red on Blue Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Red on Blue No Names.css b/Swift/resources/themes/Default/Variants/Red on Blue No Names.css
deleted file mode 100644
index da98b5c..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Blue No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Red on Blue.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Red on Blue.css b/Swift/resources/themes/Default/Variants/Red on Blue.css
deleted file mode 100644
index f6e646c..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Blue.css
+++ /dev/null
@@ -1,90 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#f88f8f;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/redIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/redCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/redCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/redCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/redBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/redBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/redCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/redCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#ffdada;
- border-bottom:1px solid #fff;
-}
-
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#7fc5f8;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/blueIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/blueCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/blueCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/blueCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/blueBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/blueBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/blueCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/blueCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#ddf0fe;
- border-bottom:1px solid #fff;
-}
diff --git a/Swift/resources/themes/Default/Variants/Red on Green Alternating.css b/Swift/resources/themes/Default/Variants/Red on Green Alternating.css
deleted file mode 100644
index db8effa..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Green Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Red on Green.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/redIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Red on Green No Names Alt.css b/Swift/resources/themes/Default/Variants/Red on Green No Names Alt.css
deleted file mode 100644
index 9a230f2..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Green No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Red on Green Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Red on Green No Names.css b/Swift/resources/themes/Default/Variants/Red on Green No Names.css
deleted file mode 100644
index 1bbc2a5..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Green No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Red on Green.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Red on Green.css b/Swift/resources/themes/Default/Variants/Red on Green.css
deleted file mode 100644
index 0e7c12b..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Green.css
+++ /dev/null
@@ -1,95 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#f88f8f;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/redIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/redCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/redCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/redCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/redBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/redBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/redCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/redCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#ffdada;
- border-bottom:1px solid #fff;
-}
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#9ecf35;
-}
-
-
-.incomingItem .myBubble .indicator {
- background:url("../images/greenIndicator.png") no-repeat top left;
-}
-
-.incomingItem .timeStamp {
- color:#9ecf35;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/greenCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/greenCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/greenCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/greenBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/greenBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/greenCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/greenCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#e2efc4;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Red on Steel Alternating.css b/Swift/resources/themes/Default/Variants/Red on Steel Alternating.css
deleted file mode 100644
index ad7eb15..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Steel Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Red on Steel.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/redIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Red on Steel No Names Alt.css b/Swift/resources/themes/Default/Variants/Red on Steel No Names Alt.css
deleted file mode 100644
index 9c6ab55..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Steel No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Red on Steel Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Red on Steel No Names.css b/Swift/resources/themes/Default/Variants/Red on Steel No Names.css
deleted file mode 100644
index aa2b60a..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Steel No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Red on Steel.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Red on Steel.css b/Swift/resources/themes/Default/Variants/Red on Steel.css
deleted file mode 100644
index 8a39df2..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Steel.css
+++ /dev/null
@@ -1,93 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#f88f8f;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/redIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/redCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/redCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/redCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/redBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/redBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/redCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/redCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#ffdada;
- border-bottom:1px solid #fff;
-}
-
-
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#a9a9a9;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/steelIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/steelCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/steelCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/steelCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/steelBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/steelBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/steelCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/steelCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#ececec;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Red on Yellow Alternating.css b/Swift/resources/themes/Default/Variants/Red on Yellow Alternating.css
deleted file mode 100644
index b264d7d..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Yellow Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Red on Yellow.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/redIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Red on Yellow No Names Alt.css b/Swift/resources/themes/Default/Variants/Red on Yellow No Names Alt.css
deleted file mode 100644
index dc4394e..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Yellow No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Red on Yellow Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Red on Yellow No Names.css b/Swift/resources/themes/Default/Variants/Red on Yellow No Names.css
deleted file mode 100644
index 9ca44ec..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Yellow No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Red on Yellow.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Red on Yellow.css b/Swift/resources/themes/Default/Variants/Red on Yellow.css
deleted file mode 100644
index f2dc5a0..0000000
--- a/Swift/resources/themes/Default/Variants/Red on Yellow.css
+++ /dev/null
@@ -1,91 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#f88f8f;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/redIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/redCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/redCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/redCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/redBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/redBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/redCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/redCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#ffdada;
- border-bottom:1px solid #fff;
-}
-
-
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#bdb410;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/yellowIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/yellowCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/yellowCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/yellowCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/yellowBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/yellowBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/yellowCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/yellowCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#f4f0a7;
- border-bottom:1px solid #fff;
-}
diff --git a/Swift/resources/themes/Default/Variants/Steel on Blue Alternating.css b/Swift/resources/themes/Default/Variants/Steel on Blue Alternating.css
deleted file mode 100644
index 8c15ec2..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Blue Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Steel on Blue.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/steelIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Steel on Blue No Names Alt.css b/Swift/resources/themes/Default/Variants/Steel on Blue No Names Alt.css
deleted file mode 100644
index 7edfcb1..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Blue No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Steel on Blue Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Steel on Blue No Names.css b/Swift/resources/themes/Default/Variants/Steel on Blue No Names.css
deleted file mode 100644
index f7058b9..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Blue No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Steel on Blue.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Steel on Blue.css b/Swift/resources/themes/Default/Variants/Steel on Blue.css
deleted file mode 100644
index 6203dc2..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Blue.css
+++ /dev/null
@@ -1,92 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#a9a9a9;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/steelIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/steelCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/steelCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/steelCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/steelBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/steelBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/steelCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/steelCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#ececec;
- border-bottom:1px solid #fff;
-}
-
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#7fc5f8;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/blueIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/blueCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/blueCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/blueCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/blueBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/blueBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/blueCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/blueCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#ddf0fe;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Steel on Green Alternating.css b/Swift/resources/themes/Default/Variants/Steel on Green Alternating.css
deleted file mode 100644
index 69474f0..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Green Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Steel on Green.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/steelIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Steel on Green No Names Alt.css b/Swift/resources/themes/Default/Variants/Steel on Green No Names Alt.css
deleted file mode 100644
index 6fc5606..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Green No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Steel on Green Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Steel on Green No Names.css b/Swift/resources/themes/Default/Variants/Steel on Green No Names.css
deleted file mode 100644
index f07264b..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Green No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Steel on Green.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Steel on Green.css b/Swift/resources/themes/Default/Variants/Steel on Green.css
deleted file mode 100644
index 800dc6b..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Green.css
+++ /dev/null
@@ -1,97 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#a9a9a9;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/steelIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/steelCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/steelCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/steelCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/steelBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/steelBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/steelCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/steelCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#ececec;
- border-bottom:1px solid #fff;
-}
-
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#9ecf35;
-}
-
-
-.incomingItem .myBubble .indicator {
- background:url("../images/greenIndicator.png") no-repeat top left;
-}
-
-.incomingItem .timeStamp {
- color:#9ecf35;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/greenCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/greenCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/greenCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/greenBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/greenBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/greenCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/greenCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#e2efc4;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Steel on Red Alternating.css b/Swift/resources/themes/Default/Variants/Steel on Red Alternating.css
deleted file mode 100644
index 64a783b..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Red Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Steel on Red.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/steelIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Steel on Red No Names Alt.css b/Swift/resources/themes/Default/Variants/Steel on Red No Names Alt.css
deleted file mode 100644
index 995f329..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Red No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Steel on Red Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Steel on Red No Names.css b/Swift/resources/themes/Default/Variants/Steel on Red No Names.css
deleted file mode 100644
index b5e622e..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Red No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Steel on Red.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Steel on Red.css b/Swift/resources/themes/Default/Variants/Steel on Red.css
deleted file mode 100644
index 922c6ef..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Red.css
+++ /dev/null
@@ -1,89 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#a9a9a9;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/steelIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/steelCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/steelCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/steelCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/steelBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/steelBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/steelCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/steelCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#ececec;
- border-bottom:1px solid #fff;
-}
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#f88f8f;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/redIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/redCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/redCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/redCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/redBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/redBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/redCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/redCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#ffdada;
- border-bottom:1px solid #fff;
-}
diff --git a/Swift/resources/themes/Default/Variants/Steel on Yellow Alternating.css b/Swift/resources/themes/Default/Variants/Steel on Yellow Alternating.css
deleted file mode 100644
index 0249230..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Yellow Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Steel on Yellow.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/steelIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Steel on Yellow No Names Alt.css b/Swift/resources/themes/Default/Variants/Steel on Yellow No Names Alt.css
deleted file mode 100644
index 9ab928c..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Yellow No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Steel on Yellow Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Steel on Yellow No Names.css b/Swift/resources/themes/Default/Variants/Steel on Yellow No Names.css
deleted file mode 100644
index ecf7861..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Yellow No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Steel on Yellow.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Steel on Yellow.css b/Swift/resources/themes/Default/Variants/Steel on Yellow.css
deleted file mode 100644
index 2d91510..0000000
--- a/Swift/resources/themes/Default/Variants/Steel on Yellow.css
+++ /dev/null
@@ -1,92 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#a9a9a9;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/steelIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/steelCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/steelCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/steelCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/steelBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/steelBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/steelCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/steelCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#ececec;
- border-bottom:1px solid #fff;
-}
-
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#bdb410;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/yellowIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/yellowCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/yellowCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/yellowCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/yellowBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/yellowBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/yellowCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/yellowCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#f4f0a7;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Blue Alternating.css b/Swift/resources/themes/Default/Variants/Yellow on Blue Alternating.css
deleted file mode 100644
index 361856d..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Blue Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Yellow on Blue.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/yellowIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Blue No Names Alt.css b/Swift/resources/themes/Default/Variants/Yellow on Blue No Names Alt.css
deleted file mode 100644
index 2e31a7c..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Blue No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Yellow on Blue Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Blue No Names.css b/Swift/resources/themes/Default/Variants/Yellow on Blue No Names.css
deleted file mode 100644
index 808377f..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Blue No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Yellow on Blue.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Blue.css b/Swift/resources/themes/Default/Variants/Yellow on Blue.css
deleted file mode 100644
index 7e745e9..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Blue.css
+++ /dev/null
@@ -1,91 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#bdb410;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/yellowIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/yellowCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/yellowCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/yellowCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/yellowBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/yellowBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/yellowCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/yellowCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#f4f0a7;
- border-bottom:1px solid #fff;
-}
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#7fc5f8;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/blueIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/blueCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/blueCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/blueCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/blueBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/blueBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/blueCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/blueCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#ddf0fe;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Green Alternating.css b/Swift/resources/themes/Default/Variants/Yellow on Green Alternating.css
deleted file mode 100644
index cb88dfb..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Green Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Yellow on Green.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/yellowIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Green No Names Alt.css b/Swift/resources/themes/Default/Variants/Yellow on Green No Names Alt.css
deleted file mode 100644
index 24fe8ef..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Green No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Yellow on Green Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Green No Names.css b/Swift/resources/themes/Default/Variants/Yellow on Green No Names.css
deleted file mode 100644
index 0c7d12b..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Green No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Yellow on Green.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Green.css b/Swift/resources/themes/Default/Variants/Yellow on Green.css
deleted file mode 100644
index de4afc6..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Green.css
+++ /dev/null
@@ -1,96 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#bdb410;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/yellowIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/yellowCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/yellowCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/yellowCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/yellowBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/yellowBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/yellowCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/yellowCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#f4f0a7;
- border-bottom:1px solid #fff;
-}
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#9ecf35;
-}
-
-
-.incomingItem .myBubble .indicator {
- background:url("../images/greenIndicator.png") no-repeat top left;
-}
-
-.incomingItem .timeStamp {
- color:#9ecf35;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/greenCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/greenCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/greenCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/greenBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/greenBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/greenCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/greenCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#e2efc4;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Red Alternating.css b/Swift/resources/themes/Default/Variants/Yellow on Red Alternating.css
deleted file mode 100644
index 592b8c4..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Red Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Yellow on Red.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/yellowIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Red No Names Alt.css b/Swift/resources/themes/Default/Variants/Yellow on Red No Names Alt.css
deleted file mode 100644
index fe464d9..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Red No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Yellow on Red Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Red No Names.css b/Swift/resources/themes/Default/Variants/Yellow on Red No Names.css
deleted file mode 100644
index f35c8a2..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Red No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Yellow on Red.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Red.css b/Swift/resources/themes/Default/Variants/Yellow on Red.css
deleted file mode 100644
index f73f0d0..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Red.css
+++ /dev/null
@@ -1,91 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#bdb410;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/yellowIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/yellowCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/yellowCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/yellowCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/yellowBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/yellowBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/yellowCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/yellowCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#f4f0a7;
- border-bottom:1px solid #fff;
-}
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#f88f8f;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/redIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/redCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/redCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/redCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/redBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/redBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/redCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/redCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#ffdada;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Steel Alternating.css b/Swift/resources/themes/Default/Variants/Yellow on Steel Alternating.css
deleted file mode 100644
index a019487..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Steel Alternating.css
+++ /dev/null
@@ -1,7 +0,0 @@
-@import url("Yellow on Steel.css");
-@import url("../alternating.css");
-
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/yellowIndicator2.png") no-repeat top left;
-}
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Steel No Names Alt.css b/Swift/resources/themes/Default/Variants/Yellow on Steel No Names Alt.css
deleted file mode 100644
index 273bcbb..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Steel No Names Alt.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Yellow on Steel Alternating.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Steel No Names.css b/Swift/resources/themes/Default/Variants/Yellow on Steel No Names.css
deleted file mode 100644
index 1f8d314..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Steel No Names.css
+++ /dev/null
@@ -1,2 +0,0 @@
-@import url("Yellow on Steel.css");
-@import url("../noname.css");
diff --git a/Swift/resources/themes/Default/Variants/Yellow on Steel.css b/Swift/resources/themes/Default/Variants/Yellow on Steel.css
deleted file mode 100644
index 680f0c8..0000000
--- a/Swift/resources/themes/Default/Variants/Yellow on Steel.css
+++ /dev/null
@@ -1,91 +0,0 @@
-@import url("../main.css");
-
-/* outgoing */
-
-
-.outgoingItem .timeStamp {
- color:#bdb410;
-}
-
-.outgoingItem .myBubble .indicator {
- background:url("../images/yellowIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("../images/yellowCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("../images/yellowCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("../images/yellowCurves.png") no-repeat -10px 0;
-}
-
-.outgoingItem .tableBubble .message {
- background:url("../images/yellowBackground.png") repeat-y top left;
-}
-
-.outgoingItem .tableBubble .messageRight {
- background:url("../images/yellowBackground.png") repeat-y top right;
-}
-
-.outgoingItem .tableBubble .bl {
- background:url("../images/yellowCurves.png") no-repeat bottom left;
-}
-
-.outgoingItem .tableBubble .br {
- background:url("../images/yellowCurves.png") no-repeat bottom right;
-}
-
-.outgoingItem .followUp {
- background-color:#f4f0a7;
- border-bottom:1px solid #fff;
-}
-
-
-/*incoming */
-
-.incomingItem .timeStamp {
- color:#a9a9a9;
-}
-
-.incomingItem .myBubble .indicator {
- background:url("../images/steelIndicator.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tl {
- background:url("../images/steelCurves.png") no-repeat top left;
-}
-
-.incomingItem .tableBubble .tr {
- background:url("../images/steelCurves.png") no-repeat top right;
-}
-
-.incomingItem .tableBubble .head {
- background:url("../images/steelCurves.png") no-repeat -10px 0;
-}
-
-.incomingItem .tableBubble .message {
- background:url("../images/steelBackground.png") repeat-y top left;
-}
-
-.incomingItem .tableBubble .messageRight {
- background:url("../images/steelBackground.png") repeat-y top right;
-}
-
-.incomingItem .tableBubble .bl {
- background:url("../images/steelCurves.png") no-repeat bottom left;
-}
-
-.incomingItem .tableBubble .br {
- background:url("../images/steelCurves.png") no-repeat bottom right;
-}
-
-.incomingItem .followUp {
- background-color:#ececec;
- border-bottom:1px solid #fff;
-}
-
-
diff --git a/Swift/resources/themes/Default/alternating.css b/Swift/resources/themes/Default/alternating.css
deleted file mode 100644
index 2b21147..0000000
--- a/Swift/resources/themes/Default/alternating.css
+++ /dev/null
@@ -1,16 +0,0 @@
-
-.outgoingItem .avatar {
- float:right;
-}
-
-.outgoingItem .indicator {
- float:right;
- position:relative;
- left:11px;
- top:8px;
-}
-
-.myBubble {
- margin-right:40px;
-}
-
diff --git a/Swift/resources/themes/Default/images/DummyContact.png b/Swift/resources/themes/Default/images/DummyContact.png
deleted file mode 100755
index 5149ea5..0000000
--- a/Swift/resources/themes/Default/images/DummyContact.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/alert.png b/Swift/resources/themes/Default/images/alert.png
deleted file mode 100755
index ad59ebc..0000000
--- a/Swift/resources/themes/Default/images/alert.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/blueBackground.gif b/Swift/resources/themes/Default/images/blueBackground.gif
deleted file mode 100755
index 1aad572..0000000
--- a/Swift/resources/themes/Default/images/blueBackground.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/blueBackground.png b/Swift/resources/themes/Default/images/blueBackground.png
deleted file mode 100644
index c3eecf5..0000000
--- a/Swift/resources/themes/Default/images/blueBackground.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/blueCurves.gif b/Swift/resources/themes/Default/images/blueCurves.gif
deleted file mode 100755
index 90e3823..0000000
--- a/Swift/resources/themes/Default/images/blueCurves.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/blueCurves.png b/Swift/resources/themes/Default/images/blueCurves.png
deleted file mode 100644
index 7a6afe1..0000000
--- a/Swift/resources/themes/Default/images/blueCurves.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/blueIndicator.gif b/Swift/resources/themes/Default/images/blueIndicator.gif
deleted file mode 100755
index 3a1b40a..0000000
--- a/Swift/resources/themes/Default/images/blueIndicator.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/blueIndicator.png b/Swift/resources/themes/Default/images/blueIndicator.png
deleted file mode 100644
index 29b65cb..0000000
--- a/Swift/resources/themes/Default/images/blueIndicator.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/blueIndicator2.png b/Swift/resources/themes/Default/images/blueIndicator2.png
deleted file mode 100644
index d7c3621..0000000
--- a/Swift/resources/themes/Default/images/blueIndicator2.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/blueIndicatorAlt.gif b/Swift/resources/themes/Default/images/blueIndicatorAlt.gif
deleted file mode 100644
index aaacb89..0000000
--- a/Swift/resources/themes/Default/images/blueIndicatorAlt.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/greenBackground.gif b/Swift/resources/themes/Default/images/greenBackground.gif
deleted file mode 100755
index a11a52d..0000000
--- a/Swift/resources/themes/Default/images/greenBackground.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/greenBackground.png b/Swift/resources/themes/Default/images/greenBackground.png
deleted file mode 100644
index dfeb36e..0000000
--- a/Swift/resources/themes/Default/images/greenBackground.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/greenCurves.gif b/Swift/resources/themes/Default/images/greenCurves.gif
deleted file mode 100755
index 165892a..0000000
--- a/Swift/resources/themes/Default/images/greenCurves.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/greenCurves.png b/Swift/resources/themes/Default/images/greenCurves.png
deleted file mode 100644
index 13fae75..0000000
--- a/Swift/resources/themes/Default/images/greenCurves.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/greenIndicator.gif b/Swift/resources/themes/Default/images/greenIndicator.gif
deleted file mode 100755
index b6409c7..0000000
--- a/Swift/resources/themes/Default/images/greenIndicator.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/greenIndicator.png b/Swift/resources/themes/Default/images/greenIndicator.png
deleted file mode 100644
index 381db82..0000000
--- a/Swift/resources/themes/Default/images/greenIndicator.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/greenIndicator2.png b/Swift/resources/themes/Default/images/greenIndicator2.png
deleted file mode 100644
index 1dedb31..0000000
--- a/Swift/resources/themes/Default/images/greenIndicator2.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/greenIndicatorAlt.gif b/Swift/resources/themes/Default/images/greenIndicatorAlt.gif
deleted file mode 100644
index 3ccbc23..0000000
--- a/Swift/resources/themes/Default/images/greenIndicatorAlt.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/redBackground.gif b/Swift/resources/themes/Default/images/redBackground.gif
deleted file mode 100755
index ce1443e..0000000
--- a/Swift/resources/themes/Default/images/redBackground.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/redBackground.png b/Swift/resources/themes/Default/images/redBackground.png
deleted file mode 100644
index bbacbc7..0000000
--- a/Swift/resources/themes/Default/images/redBackground.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/redCurves.gif b/Swift/resources/themes/Default/images/redCurves.gif
deleted file mode 100755
index 55e496d..0000000
--- a/Swift/resources/themes/Default/images/redCurves.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/redCurves.png b/Swift/resources/themes/Default/images/redCurves.png
deleted file mode 100644
index 3e7065a..0000000
--- a/Swift/resources/themes/Default/images/redCurves.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/redIndicator.gif b/Swift/resources/themes/Default/images/redIndicator.gif
deleted file mode 100755
index 58e189c..0000000
--- a/Swift/resources/themes/Default/images/redIndicator.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/redIndicator.png b/Swift/resources/themes/Default/images/redIndicator.png
deleted file mode 100644
index 9c906a9..0000000
--- a/Swift/resources/themes/Default/images/redIndicator.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/redIndicator2.png b/Swift/resources/themes/Default/images/redIndicator2.png
deleted file mode 100644
index 1f625a0..0000000
--- a/Swift/resources/themes/Default/images/redIndicator2.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/redIndicatorAlt.gif b/Swift/resources/themes/Default/images/redIndicatorAlt.gif
deleted file mode 100644
index 1f9c4f1..0000000
--- a/Swift/resources/themes/Default/images/redIndicatorAlt.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/silverBackground.gif b/Swift/resources/themes/Default/images/silverBackground.gif
deleted file mode 100755
index b2798a4..0000000
--- a/Swift/resources/themes/Default/images/silverBackground.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/silverCurves.gif b/Swift/resources/themes/Default/images/silverCurves.gif
deleted file mode 100755
index b7bca30..0000000
--- a/Swift/resources/themes/Default/images/silverCurves.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/steelBackground.gif b/Swift/resources/themes/Default/images/steelBackground.gif
deleted file mode 100755
index c292710..0000000
--- a/Swift/resources/themes/Default/images/steelBackground.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/steelBackground.png b/Swift/resources/themes/Default/images/steelBackground.png
deleted file mode 100644
index b1180d3..0000000
--- a/Swift/resources/themes/Default/images/steelBackground.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/steelCurves.gif b/Swift/resources/themes/Default/images/steelCurves.gif
deleted file mode 100755
index 663c5c3..0000000
--- a/Swift/resources/themes/Default/images/steelCurves.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/steelCurves.png b/Swift/resources/themes/Default/images/steelCurves.png
deleted file mode 100644
index e1ddeb0..0000000
--- a/Swift/resources/themes/Default/images/steelCurves.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/steelHeading.jpg b/Swift/resources/themes/Default/images/steelHeading.jpg
deleted file mode 100755
index a319c7e..0000000
--- a/Swift/resources/themes/Default/images/steelHeading.jpg
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/steelIndicator.gif b/Swift/resources/themes/Default/images/steelIndicator.gif
deleted file mode 100755
index 0d91eed..0000000
--- a/Swift/resources/themes/Default/images/steelIndicator.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/steelIndicator.png b/Swift/resources/themes/Default/images/steelIndicator.png
deleted file mode 100644
index 48a3af5..0000000
--- a/Swift/resources/themes/Default/images/steelIndicator.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/steelIndicator2.png b/Swift/resources/themes/Default/images/steelIndicator2.png
deleted file mode 100644
index 1a34ac7..0000000
--- a/Swift/resources/themes/Default/images/steelIndicator2.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/steelIndicatorAlt.gif b/Swift/resources/themes/Default/images/steelIndicatorAlt.gif
deleted file mode 100644
index 5d7686d..0000000
--- a/Swift/resources/themes/Default/images/steelIndicatorAlt.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/typing-left.png b/Swift/resources/themes/Default/images/typing-left.png
deleted file mode 100755
index e5448a5..0000000
--- a/Swift/resources/themes/Default/images/typing-left.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/typing-right.png b/Swift/resources/themes/Default/images/typing-right.png
deleted file mode 100755
index 1e997d4..0000000
--- a/Swift/resources/themes/Default/images/typing-right.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/yellowBackground.gif b/Swift/resources/themes/Default/images/yellowBackground.gif
deleted file mode 100755
index adcdb5d..0000000
--- a/Swift/resources/themes/Default/images/yellowBackground.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/yellowBackground.png b/Swift/resources/themes/Default/images/yellowBackground.png
deleted file mode 100644
index ea79d06..0000000
--- a/Swift/resources/themes/Default/images/yellowBackground.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/yellowCurves.gif b/Swift/resources/themes/Default/images/yellowCurves.gif
deleted file mode 100755
index c8bf931..0000000
--- a/Swift/resources/themes/Default/images/yellowCurves.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/yellowCurves.png b/Swift/resources/themes/Default/images/yellowCurves.png
deleted file mode 100644
index b4133ba..0000000
--- a/Swift/resources/themes/Default/images/yellowCurves.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/yellowHeading.jpg b/Swift/resources/themes/Default/images/yellowHeading.jpg
deleted file mode 100755
index bd6f049..0000000
--- a/Swift/resources/themes/Default/images/yellowHeading.jpg
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/yellowIndicator.gif b/Swift/resources/themes/Default/images/yellowIndicator.gif
deleted file mode 100755
index 537414c..0000000
--- a/Swift/resources/themes/Default/images/yellowIndicator.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/yellowIndicator.png b/Swift/resources/themes/Default/images/yellowIndicator.png
deleted file mode 100644
index bfaf230..0000000
--- a/Swift/resources/themes/Default/images/yellowIndicator.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/yellowIndicator2.png b/Swift/resources/themes/Default/images/yellowIndicator2.png
deleted file mode 100644
index c59fe2b..0000000
--- a/Swift/resources/themes/Default/images/yellowIndicator2.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/yellowIndicatorAlt.gif b/Swift/resources/themes/Default/images/yellowIndicatorAlt.gif
deleted file mode 100644
index f3cd7b0..0000000
--- a/Swift/resources/themes/Default/images/yellowIndicatorAlt.gif
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/yellowTL.png b/Swift/resources/themes/Default/images/yellowTL.png
deleted file mode 100644
index 2bdfa65..0000000
--- a/Swift/resources/themes/Default/images/yellowTL.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/images/yellowTR.png b/Swift/resources/themes/Default/images/yellowTR.png
deleted file mode 100644
index 1aff191..0000000
--- a/Swift/resources/themes/Default/images/yellowTR.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/incoming_icon.png b/Swift/resources/themes/Default/incoming_icon.png
deleted file mode 100755
index 7080fd6..0000000
--- a/Swift/resources/themes/Default/incoming_icon.png
+++ /dev/null
Binary files differ
diff --git a/Swift/resources/themes/Default/lato.css b/Swift/resources/themes/Default/lato.css
new file mode 100644
index 0000000..c8bc47a
--- /dev/null
+++ b/Swift/resources/themes/Default/lato.css
@@ -0,0 +1,143 @@
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-Hairline.ttf') format('truetype');
+ font-style: normal;
+ font-weight: 100;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-HairlineItalic.ttf') format('truetype');
+ font-style: italic;
+ font-weight: 100;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-Thin.ttf') format('truetype');
+ font-style: normal;
+ font-weight: 200;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-ThinItalic.ttf') format('truetype');
+ font-style: italic;
+ font-weight: 200;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-Light.ttf') format('truetype');
+ font-style: normal;
+ font-weight: 300;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-LightItalic.ttf') format('truetype');
+ font-style: italic;
+ font-weight: 300;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-Regular.ttf') format('truetype');
+ font-style: normal;
+ font-weight: 400;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-Italic.ttf') format('truetype');
+ font-style: italic;
+ font-weight: 400;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-Medium.ttf') format('truetype');
+ font-style: normal;
+ font-weight: 500;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-MediumItalic.ttf') format('truetype');
+ font-style: italic;
+ font-weight: 500;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-Semibold.ttf') format('truetype');
+ font-style: normal;
+ font-weight: 600;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-SemiboldItalic.ttf') format('truetype');
+ font-style: italic;
+ font-weight: 600;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-Bold.ttf') format('truetype');
+ font-style: normal;
+ font-weight: 700;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-BoldItalic.ttf') format('truetype');
+ font-style: italic;
+ font-weight: 700;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-Heavy.ttf') format('truetype');
+ font-style: normal;
+ font-weight: 800;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-HeavyItalic.ttf') format('truetype');
+ font-style: italic;
+ font-weight: 800;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-Black.ttf') format('truetype');
+ font-style: normal;
+ font-weight: 900;
+ text-rendering: optimizeLegibility;
+}
+
+@font-face {
+ font-family: 'Lato';
+ src: url('qrc:///themes/Default/Lato2OFL/Lato-BlackItalic.ttf') format('truetype');
+ font-style: italic;
+ font-weight: 900;
+ text-rendering: optimizeLegibility;
+}
diff --git a/Swift/resources/themes/Default/main.css b/Swift/resources/themes/Default/main.css
index afca281..bd69596 100755..100644
--- a/Swift/resources/themes/Default/main.css
+++ b/Swift/resources/themes/Default/main.css
@@ -1,293 +1,232 @@
-* {
- word-wrap: break-word;
- word-break:break-word;
-}
-
-#header1 {
- position: fixed;
- top: 0px;
- left: 0px;
- right: 0px;
- margin: 0;
- padding: 10px;
- overflow: auto;
- color: white;
- text-align: center;
- font-size: 10px;
- font-weight: regular;
- background: rgba(0,0,0,.65);
- z-index: 999;
-}
-
-#heading {
- position: fixed;
- top: 0px;
- left: 0px;
- margin: 0;
- padding: 5px;
- font-weight: regular;
- background-color:#fbfbed;
- z-index: 999;
- width:100%;
- height:45px;
- border-bottom:2px solid #d5d5d5;
- background:url("images/steelHeading.jpg") repeat-x top left;
-
-}
-
-#heading .conversationIncomingIcon {
- position:absolute;
- left:5px;
- top:5px;
-}
-
-#heading .conversationIncomingIcon img {
- width:48px;
- height:48px;
-}
-
-#heading .conversationWith {
- position:relative;
- left:60px;
- margin:5px 0 0 0;
- overflow:hide;
-}
-
-#heading .conversationTime {
- position:relative;
- left:60px;
- color:#6d6d6d;
-}
-
-body {
- margin-top: 65px;
- background-color: white;
- color: black;
-}
-
-.status_container {
-}
-
+/* Chat Window Container */
body {
- font-family: "DejaVu Sans", "Myriad Pro", Myriad, "Lucida Grande", "Trebuchet MS", Arial, "Droid Sans", sans-serif;
+ font-family: 'Lato', sans-serif;
+ margin: 0;
+ padding: 0;
}
-.followUp {
- clear:right;
- height:1px;
- font-size:1px;
- line-height:1px;
- margin:4px 0 4px 0;
+/* This turns the insert marker element into a vertical fill.
+ * This way the colored side bar is expanded to the full height of the view. */
+#insert {
+ display: table-row;
+ height: 100%;
}
-.chatItem {
- /*Removing opacity, because this causes Qt's WebKit to draw low-quality images */
- /*opacity:0.96;*/
+.container {
+ height: 100%;
+ width: 100%;
+ background-color: #fff;
+ position: absolute;
+ display: table;
}
+/* Holds all user and message content */
-.tableBubble {
- width:100%;
+.message-block {
+ display: table;
+ border: 0px solid black;
+ border-spacing: 0;
+ height: 100%;
+ width: 100%;
+ z-index: 10;
+ top: 0;
+ left: 0;
+ overflow-wrap: break-word; /* Allow breaking of long words (e.g. URLs) to prevent overflow. */
}
-.tableBubble .tl {
- height:8px;
-}
-
-.tableBubble .tr {
- width:8px;
- height:8px;
-}
+/* Individual message */
.message {
- padding:0 1em 0 1.25em;
- word-wrap: break-word;
-}
-
-.tableBubble .message {
- font-size:11px;
-}
-
-.tableBubble .message img {
- vertical-align:middle;
-}
-
-.tableBubble .messageRight {
- width:1px;
-}
-
-.tableBubble .bl {
- height:10px;
+ display: table-row;
+ border: inherit;
+ width: 100%;
+ margin-top: 10px;
+ border-top: 0.2em solid transparent;
+}
+
+.additional {
+ margin-top: -12px;
+}
+
+.unread {
+ height: 30px;
+ display: table-row;
+ border: inherit;
+ /*width: 100%;*/
+ margin-top: -6px;
+ margin-bottom: -15px;
+ margin-left: 190px;
+ margin-right: 20px;
+ text-align: right;
}
-.tableBubble .br {
- width:8px;
- height:10px;
+.unread p {
+ margin-top: 0px;
+ font-size: 75%;
+ text-transform: uppercase;
+ color: #ffd180;
+ border-top: solid 1px #ffd180;
+ margin-left: 20px;
+ margin-right: 20px;
}
-.tableBubble .timeStamp {
- margin-left:7px;
- text-align:right;
- float:right;
-}
-
-.myBubble .indicator {
- position:absolute;
- top:8px;
- left:0;
- width:13px;
- height:11px;
-}
-
-.myBubble {
- position:relative;
- padding-left:10px;
- margin-left:33px;
- margin-right:10px;
-}
-
-.chatItem .avatar {
- max-width:32px;
- max-height:32px;
- float:left;
-}
-
-/****** STatus ******/
-
-.statusMessage {
- opacity:0.8;
- color:#676767;
-}
-
-.statusMessage .myBubble .indicator {
- background:url("images/steelIndicator.png") no-repeat top left;
-}
-
-.statusMessage .tableBubble .tl {
- background:url("images/steelCurves.png") no-repeat top left;
-}
-
-.statusMessage .tableBubble .tr {
- background:url("images/steelCurves.png") no-repeat top right;
-}
-
-.statusMessage .tableBubble .head {
- background:url("images/steelCurves.png") no-repeat -10px 0;
-}
+/* Left column content */
-.statusMessage .tableBubble .message {
- background:url("images/steelBackground.png") repeat-y top left;
+:not(.additional) > .user {
+ height: 2.5em;
}
-.statusMessage .tableBubble .messageRight {
- background:url("images/steelBackground.png") repeat-y top right;
+.user {
+ display: table-cell;
+ border: inherit;
+ margin-top: 2px;
+ text-align: right;
+ width: 4.6em;
+ max-width: 4.6em;
+ min-width: 4.6em;
+ background-color: #595959;
}
-.statusMessage .tableBubble .bl {
- background:url("images/steelCurves.png") no-repeat bottom left;
-}
+div.time {
+ color: #ffffff;
+ font-size: 80%;
+ font-weight: 300;
-.statusMessage .tableBubble .br {
- background:url("images/steelCurves.png") no-repeat bottom right;
+ float: right;
+ background-color: #595959;
+ border-top-left-radius: 3ex 3ex;
+ border-bottom-left-radius: 3ex 3ex;
+ /* min-width: 50px; */
+ text-align: right;
+ padding-left: 0.5em;
+ padding-right: 0.5em;
+ padding-top: 0.05ex;
+ padding-bottom: 0.05ex;
+ margin-left: 0.5em;
}
-.statusMessage .followUp {
- background-color:#f4f0a7;
- border-bottom:1px solid #fff;
+.myavatar {
+ height: 2.5em;
+ width: 2.5em;
+ display: inline-block;
+ margin: 0 auto;
+ background-color: #92c47e;
+ border-top-left-radius: 50%;
+ border-bottom-left-radius: 50%;
}
-.statusMessage .timeStamp {
- color:#676767;
+.otheravatar {
+ height: 2.5em;
+ width: 2.5em;
+ display: inline-block;
+ margin: 0 auto;
+ background-color: #6eb6ce;
+ border-top-left-radius: 50%;
+ border-bottom-left-radius: 50%;
}
-
-/*incoming */
-
-.incomingItem .myBubble .indicator {
- background:url("images/yellowIndicator.png") no-repeat top left;
+.myavatar img {
+ border-radius: 50%;
+ height: 2.5em;
+ position: relative;
+ left: -1px;
}
-.incomingItem .tableBubble .tl {
- background:url("images/yellowCurves.png") no-repeat top left;
+.otheravatar img {
+ border-radius: 50%;
+ height: 2.5em;
+ position: relative;
+ left: -1px;
}
-.incomingItem .tableBubble .tr {
- background:url("images/yellowCurves.png") no-repeat top right;
+.myright {
+ float: right;
+ width: 1.05em; /* myuser width/2 - ( other avatar width/2) = 1.05em*/
+ height: 2.5em;
+ background: #92c47e;
}
-.incomingItem .tableBubble .head {
- background:url("images/yellowCurves.png") no-repeat -10px 0;
+.otherright {
+ float: right;
+ width: 1.05em; /* myuser width/2 - ( other avatar width/2) = 1.05em*/
+ height: 2.5em;
+ background: #6eb6ce;
}
-.incomingItem .tableBubble .message {
- background:url("images/yellowBackground.png") repeat-y top left;
+:not(.additional) > div > .systemavatar {
+ height: 2.5em;
}
-.incomingItem .tableBubble .messageRight {
- background:url("images/yellowBackground.png") repeat-y top right;
+.systemavatar {
+ width: 2.5em;
+ display: inline-block;
+ margin: 0 auto;
+ background-color: #595959;
+ border-top-left-radius: 50%;
+ border-bottom-left-radius: 50%;
}
-.incomingItem .tableBubble .bl {
- background:url("images/yellowCurves.png") no-repeat bottom left;
+:not(.additional) > div > .systemright {
+ height: 2.5em;
}
-.incomingItem .tableBubble .br {
- background:url("images/yellowCurves.png") no-repeat bottom right;
+.systemright {
+ float: right;
+ width: 1.05em; /* myuser width/2 - ( other avatar width/2) = 1.05em*/
+ background: #595959;
}
-.incomingItem .followUp {
- background-color:#f4f0a7;
- border-bottom:1px solid #fff;
+/* Right column content */
+.message:not(.additional) {
+ border-top: 1.2em solid transparent; /* Workaround for table rows not having a padding. */
}
-.incomingItem .timeStamp {
- color:#bdb410;
+.message:not(.additional) .text {
+ min-height: 2.5em;
}
-/* outgoing */
-
-
-.outgoingItem .myBubble .indicator {
- background:url("images/greenIndicator.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tl {
- background:url("images/greenCurves.png") no-repeat top left;
-}
-
-.outgoingItem .tableBubble .tr {
- background:url("images/greenCurves.png") no-repeat top right;
-}
-
-.outgoingItem .tableBubble .head {
- background:url("images/greenCurves.png") no-repeat -10px 0;
-}
+.text {
+ display: table-cell;
+ border: inherit;
+ color: #595959;
+ vertical-align: top;
-.outgoingItem .tableBubble .message {
- background:url("images/greenBackground.png") repeat-y top left;
+ /* Break long URLs at any point. */
+ word-break: break-word;
+ word-wrap: break-word;
+ hyphens: auto;
}
-.outgoingItem .tableBubble .messageRight {
- background:url("images/greenBackground.png") repeat-y top right;
+.username {
+ margin-left: 20px;
+ font-weight: 700;
+ margin-top: 0px;
+ margin-bottom: 0.2em;
}
-.outgoingItem .tableBubble .bl {
- background:url("images/greenCurves.png") no-repeat bottom left;
+.myusername {
+ color: #92c47e;
}
-.outgoingItem .tableBubble .br {
- background:url("images/greenCurves.png") no-repeat bottom right;
+.otherusername {
+ color: #6eb6ce;
}
-.outgoingItem .followUp {
- background-color:#e2efc4;
- border-bottom:1px solid #fff;
+.message-content {
+ margin-left: 20px;
+ margin-right: 20px;
}
-.outgoingItem .timeStamp {
- color:#9ecf35;
+.system-message {
+ margin-left: 20px;
+ margin-right: 20px;
+ margin-top: 0px;
+ margin-bottom: 0px;
+ color: #aaa;
+ font-style: italic;
}
-html {
- height: 101%;
+/* receipt */
+span.swift_receipt > img {
+ height: 12px;
}
diff --git a/Swift/resources/themes/Default/noname.css b/Swift/resources/themes/Default/noname.css
deleted file mode 100644
index 9d905a9..0000000
--- a/Swift/resources/themes/Default/noname.css
+++ /dev/null
@@ -1,3 +0,0 @@
-.name {
- display:none;
-}
diff --git a/Swift/resources/themes/Default/outgoing_icon.png b/Swift/resources/themes/Default/outgoing_icon.png
deleted file mode 100755
index 7080fd6..0000000
--- a/Swift/resources/themes/Default/outgoing_icon.png
+++ /dev/null
Binary files differ
diff --git a/Swiften/AdHoc/OutgoingAdHocCommandSession.cpp b/Swiften/AdHoc/OutgoingAdHocCommandSession.cpp
index 4a006ad..22c478d 100644
--- a/Swiften/AdHoc/OutgoingAdHocCommandSession.cpp
+++ b/Swiften/AdHoc/OutgoingAdHocCommandSession.cpp
@@ -1,16 +1,17 @@
/*
- * Copyright (c) 2010-2011 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/AdHoc/OutgoingAdHocCommandSession.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Base/Algorithm.h>
+#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
OutgoingAdHocCommandSession::OutgoingAdHocCommandSession(const JID& to, const std::string& commandNode, IQRouter* iqRouter) : to_(to), commandNode_(commandNode), iqRouter_(iqRouter), isMultiStage_(false) {
@@ -18,83 +19,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);
- }
+void OutgoingAdHocCommandSession::handleResponse(std::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);
+ }
}
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();
+ std::shared_ptr<GenericRequest<Command> > commandRequest = std::make_shared< GenericRequest<Command> >(IQ::Set, to_, std::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();
+ std::shared_ptr<Command> command(std::make_shared<Command>(commandNode_, sessionID_, action));
+ command->setForm(form);
+ std::shared_ptr<GenericRequest<Command> > commandRequest = std::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 19b4b7e..9a97ed0 100644
--- a/Swiften/AdHoc/OutgoingAdHocCommandSession.h
+++ b/Swiften/AdHoc/OutgoingAdHocCommandSession.h
@@ -1,99 +1,99 @@
/*
- * Copyright (c) 2010-2011 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <string>
#include <map>
+#include <memory>
+#include <string>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Elements/Command.h>
#include <Swiften/Elements/ErrorPayload.h>
-#include <boost/signals/connection.hpp>
+#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::signals2::signal<void (Command::ref)> onNextStageReceived;
- /**
- * Emitted on error.
- */
- boost::signal<void (ErrorPayload::ref)> onError;
+ /**
+ * Emitted on error.
+ */
+ boost::signals2::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(std::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::signals2::connection connection_;
+ };
}
diff --git a/Swiften/AdHoc/SConscript b/Swiften/AdHoc/SConscript
index 69c9083..6d3f176 100644
--- a/Swiften/AdHoc/SConscript
+++ b/Swiften/AdHoc/SConscript
@@ -1,6 +1,6 @@
Import("swiften_env")
objects = swiften_env.SwiftenObject([
- "OutgoingAdHocCommandSession.cpp",
- ])
+ "OutgoingAdHocCommandSession.cpp",
+ ])
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
diff --git a/Swiften/Avatars/AvatarManager.h b/Swiften/Avatars/AvatarManager.h
index b717959..a71d323 100644
--- a/Swiften/Avatars/AvatarManager.h
+++ b/Swiften/Avatars/AvatarManager.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,21 +7,21 @@
#pragma once
#include <boost/filesystem/path.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Base/ByteArray.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::signals2::signal<void (const JID&)> onAvatarChanged;
+ };
}
diff --git a/Swiften/Avatars/AvatarManagerImpl.cpp b/Swiften/Avatars/AvatarManagerImpl.cpp
index fb924c6..6e98b1b 100644
--- a/Swiften/Avatars/AvatarManagerImpl.cpp
+++ b/Swiften/Avatars/AvatarManagerImpl.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,59 +8,59 @@
#include <boost/bind.hpp>
-#include <Swiften/Avatars/VCardUpdateAvatarManager.h>
-#include <Swiften/Avatars/VCardAvatarManager.h>
#include <Swiften/Avatars/AvatarStorage.h>
#include <Swiften/Avatars/OfflineAvatarManager.h>
+#include <Swiften/Avatars/VCardAvatarManager.h>
+#include <Swiften/Avatars/VCardUpdateAvatarManager.h>
#include <Swiften/Base/ByteArray.h>
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..d58e09f 100644
--- a/Swiften/Avatars/AvatarManagerImpl.h
+++ b/Swiften/Avatars/AvatarManagerImpl.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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* = nullptr);
+ 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 bd67e74..bc40a26 100644
--- a/Swiften/Avatars/AvatarMemoryStorage.h
+++ b/Swiften/Avatars/AvatarMemoryStorage.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,36 +9,36 @@
#include <map>
#include <string>
-#include <Swiften/Base/ByteArray.h>
#include <Swiften/Avatars/AvatarStorage.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/ByteArray.h>
+#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..a92418f 100644
--- a/Swiften/Avatars/AvatarProvider.h
+++ b/Swiften/Avatars/AvatarProvider.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,18 +8,19 @@
#include <string>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#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::signals2::signal<void (const JID&)> onAvatarChanged;
+ };
}
diff --git a/Swiften/Avatars/AvatarStorage.h b/Swiften/Avatars/AvatarStorage.h
index 01151c2..dc3eb34 100644
--- a/Swiften/Avatars/AvatarStorage.h
+++ b/Swiften/Avatars/AvatarStorage.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/filesystem/path.hpp>
#include <string>
+#include <boost/filesystem/path.hpp>
+
#include <Swiften/Base/API.h>
#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 4fa4c2b..465512f 100644
--- a/Swiften/Avatars/CombinedAvatarProvider.cpp
+++ b/Swiften/Avatars/CombinedAvatarProvider.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,6 +7,7 @@
#include <Swiften/Avatars/CombinedAvatarProvider.h>
#include <algorithm>
+
#include <boost/bind.hpp>
#include <Swiften/Base/Log.h>
@@ -14,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 d8c045c..f667ad2 100644
--- a/Swiften/Avatars/CombinedAvatarProvider.h
+++ b/Swiften/Avatars/CombinedAvatarProvider.h
@@ -1,32 +1,32 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <map>
+#include <vector>
-#include <Swiften/Base/API.h>
#include <Swiften/Avatars/AvatarProvider.h>
+#include <Swiften/Base/API.h>
#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 f6f075f..f079be1 100644
--- a/Swiften/Avatars/DummyAvatarManager.h
+++ b/Swiften/Avatars/DummyAvatarManager.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,26 +8,26 @@
#include <map>
-#include <Swiften/JID/JID.h>
#include <Swiften/Avatars/AvatarManager.h>
+#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/SConscript b/Swiften/Avatars/SConscript
index 9c219a4..0cd419d 100644
--- a/Swiften/Avatars/SConscript
+++ b/Swiften/Avatars/SConscript
@@ -1,13 +1,13 @@
Import("swiften_env")
objects = swiften_env.SwiftenObject([
- "VCardUpdateAvatarManager.cpp",
- "VCardAvatarManager.cpp",
- "OfflineAvatarManager.cpp",
- "AvatarManager.cpp",
- "AvatarManagerImpl.cpp",
- "AvatarStorage.cpp",
- "AvatarProvider.cpp",
- "CombinedAvatarProvider.cpp",
- ])
+ "VCardUpdateAvatarManager.cpp",
+ "VCardAvatarManager.cpp",
+ "OfflineAvatarManager.cpp",
+ "AvatarManager.cpp",
+ "AvatarManagerImpl.cpp",
+ "AvatarStorage.cpp",
+ "AvatarProvider.cpp",
+ "CombinedAvatarProvider.cpp",
+ ])
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
diff --git a/Swiften/Avatars/UnitTest/AvatarManagerImplTest.cpp b/Swiften/Avatars/UnitTest/AvatarManagerImplTest.cpp
index 146676a..241f375 100644
--- a/Swiften/Avatars/UnitTest/AvatarManagerImplTest.cpp
+++ b/Swiften/Avatars/UnitTest/AvatarManagerImplTest.cpp
@@ -1,141 +1,143 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <string>
+
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/bind.hpp>
-#include <Swiften/JID/JID.h>
-#include <string>
#include <Swiften/Avatars/AvatarManagerImpl.h>
+#include <Swiften/Avatars/AvatarMemoryStorage.h>
#include <Swiften/Avatars/CombinedAvatarProvider.h>
-#include <Swiften/Avatars/VCardAvatarManager.h>
#include <Swiften/Avatars/OfflineAvatarManager.h>
-#include <Swiften/Elements/VCardUpdate.h>
-#include <Swiften/MUC/MUCRegistry.h>
+#include <Swiften/Avatars/VCardAvatarManager.h>
+#include <Swiften/Avatars/VCardUpdateAvatarManager.h>
#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/Elements/VCardUpdate.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/MUC/MUCRegistry.h>
#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/Avatars/AvatarMemoryStorage.h>
-#include <Swiften/VCards/VCardMemoryStorage.h>
-#include <Swiften/VCards/VCardManager.h>
-#include <Swiften/Avatars/VCardUpdateAvatarManager.h>
#include <Swiften/StringCodecs/Hexify.h>
+#include <Swiften/VCards/VCardManager.h>
+#include <Swiften/VCards/VCardMemoryStorage.h>
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 = std::make_shared<DummyStanzaChannel>();
+ iqRouter = std::make_shared<IQRouter>(stanzaChannel.get());
+ crypto = std::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ vcardStorage = std::make_shared<VCardMemoryStorage>(crypto.get());
+ vcardManager = std::make_shared<VCardManager>(ownerJID, iqRouter.get(), vcardStorage.get());
+ avatarStorage = std::make_shared<AvatarMemoryStorage>();
+ mucRegistry = std::make_shared<DummyMUCRegistry>();
+ avatarManager = std::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");
+ std::shared_ptr<VCardUpdate> vcardUpdate = std::make_shared<VCardUpdate>();
+ vcardUpdate->setPhotoHash(Hexify::hexify(crypto->getSHA1Hash(fullAvatar)));
+ std::shared_ptr<Presence> presence = std::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());
+ std::shared_ptr<IQ> request = std::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas[0]);
+ stanzaChannel->sentStanzas.pop_back();
+ CPPUNIT_ASSERT(!!request);
+ std::shared_ptr<VCard> vcard = request->getPayload<VCard>();
+ CPPUNIT_ASSERT(!!vcard);
+
+ std::shared_ptr<IQ> reply = std::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 = std::make_shared<VCardUpdate>();
+ presence = std::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 = std::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 = std::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;
+ std::shared_ptr<DummyStanzaChannel> stanzaChannel;
+ std::shared_ptr<IQRouter> iqRouter;
+ std::shared_ptr<CryptoProvider> crypto;
+ std::shared_ptr<VCardMemoryStorage> vcardStorage;
+ std::shared_ptr<VCardManager> vcardManager;
+ std::shared_ptr<AvatarMemoryStorage> avatarStorage;
+ std::shared_ptr<DummyMUCRegistry> mucRegistry;
+ std::shared_ptr<AvatarManagerImpl> avatarManager;
};
diff --git a/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp b/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp
index 58bf6fd..8aca98e 100644
--- a/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp
+++ b/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp
@@ -1,377 +1,375 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+#include <string>
+
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/bind.hpp>
-#include <Swiften/JID/JID.h>
-#include <string>
+#include <Swiften/Avatars/AvatarMemoryStorage.h>
#include <Swiften/Avatars/CombinedAvatarProvider.h>
-#include <Swiften/Avatars/VCardAvatarManager.h>
#include <Swiften/Avatars/OfflineAvatarManager.h>
-#include <Swiften/MUC/MUCRegistry.h>
+#include <Swiften/Avatars/VCardAvatarManager.h>
+#include <Swiften/Avatars/VCardUpdateAvatarManager.h>
#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/MUC/MUCRegistry.h>
#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/Avatars/AvatarMemoryStorage.h>
-#include <Swiften/VCards/VCardMemoryStorage.h>
-#include <Swiften/VCards/VCardManager.h>
-#include <Swiften/Avatars/VCardUpdateAvatarManager.h>
#include <Swiften/StringCodecs/Hexify.h>
+#include <Swiften/VCards/VCardManager.h>
+#include <Swiften/VCards/VCardMemoryStorage.h>
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 = std::unique_ptr<DummyAvatarProvider>(new DummyAvatarProvider());
+ avatarProvider2 = std::unique_ptr<DummyAvatarProvider>(new DummyAvatarProvider());
+ user1 = JID("user1@bar.com/bla");
+ user2 = JID("user2@foo.com/baz");
+ avatarHash1 = "ABCDEFG";
+ avatarHash2 = "XYZU";
+ avatarHash3 = "IDGH";
+ }
+
+ void testGetAvatarWithNoAvatarProviderReturnsEmpty() {
+ std::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+
+ boost::optional<std::string> hash = testling->getAvatarHash(user1);
+ CPPUNIT_ASSERT(!hash);
+ }
+
+ void testGetAvatarWithSingleAvatarProvider() {
+ std::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ avatarProvider1->avatars[user1] = avatarHash1;
+ testling->addProvider(avatarProvider1.get());
+
+ boost::optional<std::string> hash = testling->getAvatarHash(user1);
+ CPPUNIT_ASSERT(hash);
+ CPPUNIT_ASSERT_EQUAL(avatarHash1, *hash);
+ }
+
+ void testGetAvatarWithMultipleAvatarProviderReturnsFirstAvatar() {
+ std::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ avatarProvider1->avatars[user1] = avatarHash1;
+ avatarProvider2->avatars[user1] = avatarHash2;
+ testling->addProvider(avatarProvider1.get());
+ testling->addProvider(avatarProvider2.get());
+
+ boost::optional<std::string> hash = testling->getAvatarHash(user1);
+ CPPUNIT_ASSERT(hash);
+ CPPUNIT_ASSERT_EQUAL(avatarHash1, *hash);
+ }
+
+ void testGetAvatarWithMultipleAvatarProviderAndFailingFirstProviderReturnsSecondAvatar() {
+ std::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ avatarProvider2->avatars[user1] = avatarHash2;
+ testling->addProvider(avatarProvider1.get());
+ testling->addProvider(avatarProvider2.get());
+
+ boost::optional<std::string> hash = testling->getAvatarHash(user1);
+ CPPUNIT_ASSERT(hash);
+ CPPUNIT_ASSERT_EQUAL(avatarHash2, *hash);
+ }
+
+ void testProviderUpdateTriggersChange() {
+ std::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ testling->addProvider(avatarProvider1.get());
+ avatarProvider1->avatars[user1] = avatarHash1;
+ avatarProvider1->onAvatarChanged(user1);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
+ }
+
+ void testProviderUpdateWithoutChangeDoesNotTriggerChange() {
+ std::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ testling->addProvider(avatarProvider1.get());
+ testling->addProvider(avatarProvider2.get());
+ 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() {
+ std::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ testling->addProvider(avatarProvider1.get());
+ 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() {
+ std::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ testling->addProvider(avatarProvider1.get());
+ 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() {
+ std::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ testling->addProvider(avatarProvider1.get());
+ 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() {
+ std::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ testling->addProvider(avatarProvider1.get());
+ avatarProvider1->avatars[user1] = avatarHash1;
+
+ testling->getAvatarHash(user1);
+ avatarProvider1->onAvatarChanged(user1);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
+ }
+
+ void testRemoveProviderDisconnectsUpdates() {
+ std::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ testling->addProvider(avatarProvider1.get());
+ testling->addProvider(avatarProvider2.get());
+ testling->removeProvider(avatarProvider1.get());
+ avatarProvider1->avatars[user1] = avatarHash1;
+ avatarProvider2->avatars[user1] = avatarHash2;
+ avatarProvider1->onAvatarChanged(user1);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
+ }
+
+ void testProviderUpdateBareJIDAfterGetFullJID() {
+ std::shared_ptr<CombinedAvatarProvider> testling(createProvider());
+ avatarProvider1->useBare = true;
+ testling->addProvider(avatarProvider1.get());
+
+ 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");
+
+ std::shared_ptr<CryptoProvider> crypto = std::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);
+
+ std::shared_ptr<VCardUpdateAvatarManager> updateManager(new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, crypto.get(), mucRegistry));
+ updateManager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1));
+
+ std::shared_ptr<VCardAvatarManager> manager(new VCardAvatarManager(vcardManager, avatarStorage, crypto.get(), mucRegistry));
+ manager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1));
+
+ std::shared_ptr<OfflineAvatarManager> offlineManager(new OfflineAvatarManager(avatarStorage));
+ offlineManager->onAvatarChanged.connect(boost::bind(&CombinedAvatarProviderTest::handleAvatarChanged, this, _1));
+
+ std::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 = std::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 = std::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 = std::dynamic_pointer_cast<IQ>(stanzaChannel->sentStanzas.back());
+ payload = request->getPayload<VCard>();
+ CPPUNIT_ASSERT(!!payload);
+ stanzaChannel->sentStanzas.pop_back();
+
+ VCard::ref vcard3(new VCard());
+ reply = std::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:
+ std::shared_ptr<CombinedAvatarProvider> createProvider() {
+ std::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_;
+ };
+
+ std::unique_ptr<DummyAvatarProvider> avatarProvider1;
+ std::unique_ptr<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 0ac0b70..2ca9c1a 100644
--- a/Swiften/Avatars/UnitTest/VCardAvatarManagerTest.cpp
+++ b/Swiften/Avatars/UnitTest/VCardAvatarManagerTest.cpp
@@ -1,175 +1,176 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/ByteArray.h>
+#include <boost/bind.hpp>
+
#include <QA/Checker/IO.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/bind.hpp>
-#include <Swiften/Elements/VCard.h>
-#include <Swiften/Avatars/VCardAvatarManager.h>
-#include <Swiften/VCards/VCardMemoryStorage.h>
#include <Swiften/Avatars/AvatarMemoryStorage.h>
-#include <Swiften/VCards/VCardManager.h>
-#include <Swiften/MUC/MUCRegistry.h>
-#include <Swiften/Queries/IQRouter.h>
+#include <Swiften/Avatars/VCardAvatarManager.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/Elements/VCard.h>
+#include <Swiften/MUC/MUCRegistry.h>
+#include <Swiften/Queries/IQRouter.h>
#include <Swiften/StringCodecs/Hexify.h>
+#include <Swiften/VCards/VCardManager.h>
+#include <Swiften/VCards/VCardMemoryStorage.h>
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 = std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::shared_ptr<VCardAvatarManager> testling = createManager();
+
+ boost::optional<std::string> result = testling->getAvatarHash(user1);
+
+ CPPUNIT_ASSERT(result);
+ CPPUNIT_ASSERT_EQUAL(std::string(), *result);
+ }
+
+ void testGetAvatarHashKnownAvatarUnknownVCard() {
+ std::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() {
+ std::shared_ptr<VCardAvatarManager> testling = createManager();
+ vcardManager->requestVCard(user1);
+ sendVCardResult();
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
+ }
+
+ private:
+ std::shared_ptr<VCardAvatarManager> createManager() {
+ std::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;
+ std::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(VCardAvatarManagerTest);
diff --git a/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp b/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp
index 80b5718..bfa13cd 100644
--- a/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp
+++ b/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp
@@ -1,211 +1,212 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/ByteArray.h>
+#include <boost/bind.hpp>
+
#include <QA/Checker/IO.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/bind.hpp>
-#include <Swiften/Elements/VCardUpdate.h>
-#include <Swiften/Avatars/VCardUpdateAvatarManager.h>
#include <Swiften/Avatars/AvatarMemoryStorage.h>
-#include <Swiften/VCards/VCardMemoryStorage.h>
-#include <Swiften/VCards/VCardManager.h>
-#include <Swiften/MUC/MUCRegistry.h>
-#include <Swiften/Queries/IQRouter.h>
+#include <Swiften/Avatars/VCardUpdateAvatarManager.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/Client/DummyStanzaChannel.h>
-#include <Swiften/StringCodecs/Hexify.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/Elements/VCardUpdate.h>
+#include <Swiften/MUC/MUCRegistry.h>
+#include <Swiften/Queries/IQRouter.h>
+#include <Swiften/StringCodecs/Hexify.h>
+#include <Swiften/VCards/VCardManager.h>
+#include <Swiften/VCards/VCardMemoryStorage.h>
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 = std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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:
+ std::shared_ptr<VCardUpdateAvatarManager> createManager() {
+ std::shared_ptr<VCardUpdateAvatarManager> result(new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, crypto.get(), mucRegistry));
+ result->onAvatarChanged.connect(boost::bind(&VCardUpdateAvatarManagerTest::handleAvatarChanged, this, _1));
+ return result;
+ }
+
+ std::shared_ptr<Presence> createPresenceWithPhotoHash(const JID& jid, const std::string& hash) {
+ std::shared_ptr<Presence> presence(new Presence());
+ presence->setFrom(jid);
+ presence->addPayload(std::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;
+ std::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(VCardUpdateAvatarManagerTest);
diff --git a/Swiften/Avatars/VCardAvatarManager.cpp b/Swiften/Avatars/VCardAvatarManager.cpp
index 4960900..919d833 100644
--- a/Swiften/Avatars/VCardAvatarManager.cpp
+++ b/Swiften/Avatars/VCardAvatarManager.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,55 +8,55 @@
#include <boost/bind.hpp>
-#include <Swiften/Elements/VCard.h>
-#include <Swiften/Crypto/CryptoProvider.h>
-#include <Swiften/StringCodecs/Hexify.h>
#include <Swiften/Avatars/AvatarStorage.h>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Crypto/CryptoProvider.h>
+#include <Swiften/Elements/VCard.h>
#include <Swiften/MUC/MUCRegistry.h>
+#include <Swiften/StringCodecs/Hexify.h>
#include <Swiften/VCards/VCardManager.h>
-#include <Swiften/Base/Log.h>
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 74f36a1..70df6a8 100644
--- a/Swiften/Avatars/VCardAvatarManager.h
+++ b/Swiften/Avatars/VCardAvatarManager.h
@@ -1,35 +1,35 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/API.h>
#include <Swiften/Avatars/AvatarProvider.h>
+#include <Swiften/Base/API.h>
#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* = nullptr);
- 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 a21cd41..3e8d87b 100644
--- a/Swiften/Avatars/VCardUpdateAvatarManager.cpp
+++ b/Swiften/Avatars/VCardUpdateAvatarManager.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,97 +8,97 @@
#include <boost/bind.hpp>
+#include <Swiften/Avatars/AvatarStorage.h>
+#include <Swiften/Base/Log.h>
#include <Swiften/Client/StanzaChannel.h>
-#include <Swiften/Elements/VCardUpdate.h>
-#include <Swiften/VCards/GetVCardRequest.h>
#include <Swiften/Crypto/CryptoProvider.h>
-#include <Swiften/StringCodecs/Hexify.h>
-#include <Swiften/Avatars/AvatarStorage.h>
+#include <Swiften/Elements/VCardUpdate.h>
#include <Swiften/MUC/MUCRegistry.h>
+#include <Swiften/StringCodecs/Hexify.h>
+#include <Swiften/VCards/GetVCardRequest.h>
#include <Swiften/VCards/VCardManager.h>
-#include <Swiften/Base/Log.h>
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);
- }
+void VCardUpdateAvatarManager::handlePresenceReceived(std::shared_ptr<Presence> presence) {
+ std::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 3d6d73a..19ed672 100644
--- a/Swiften/Avatars/VCardUpdateAvatarManager.h
+++ b/Swiften/Avatars/VCardUpdateAvatarManager.h
@@ -1,46 +1,46 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
#include <map>
+#include <memory>
-#include <Swiften/Base/API.h>
#include <Swiften/Avatars/AvatarProvider.h>
-#include <Swiften/JID/JID.h>
+#include <Swiften/Base/API.h>
+#include <Swiften/Elements/ErrorPayload.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/VCard.h>
-#include <Swiften/Elements/ErrorPayload.h>
+#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::signals2::trackable {
+ public:
+ VCardUpdateAvatarManager(VCardManager*, StanzaChannel*, AvatarStorage*, CryptoProvider* crypto, MUCRegistry* = nullptr);
+
+ boost::optional<std::string> getAvatarHash(const JID&) const;
+
+ private:
+ void handlePresenceReceived(std::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..ae065d4 100644
--- a/Swiften/Base/Atomic.h
+++ b/Swiften/Base/Atomic.h
@@ -1,45 +1,44 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/thread.hpp>
-#include <boost/thread/locks.hpp>
+#include <mutex>
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) {
+ std::lock_guard<std::mutex> lock(valueMutex_);
+ value_ = newValue;
+ return *this;
+ }
+
+ /**
+ * Synchronized read access.
+ */
+ operator ValueType() {
+ std::lock_guard<std::mutex> lock(valueMutex_);
+ return value_;
+ }
+
+ private:
+ std::mutex valueMutex_;
+ ValueType value_;
};
}
diff --git a/Swiften/Base/BoostRandomGenerator.cpp b/Swiften/Base/BoostRandomGenerator.cpp
index 16b164b..d893d4d 100644
--- a/Swiften/Base/BoostRandomGenerator.cpp
+++ b/Swiften/Base/BoostRandomGenerator.cpp
@@ -1,26 +1,27 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Base/BoostRandomGenerator.h>
+#include <ctime>
#include <numeric>
+
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
-#include <ctime>
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(nullptr)));
}
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 055c65f..ff715c3 100644
--- a/Swiften/Base/BoostRandomGenerator.h
+++ b/Swiften/Base/BoostRandomGenerator.h
@@ -1,25 +1,25 @@
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/RandomGenerator.h>
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-
#include <boost/random/mersenne_twister.hpp>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#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 b137590..882421d 100644
--- a/Swiften/Base/ByteArray.cpp
+++ b/Swiften/Base/ByteArray.cpp
@@ -1,50 +1,50 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Base/ByteArray.h>
-#include <boost/numeric/conversion/cast.hpp>
#include <boost/filesystem/fstream.hpp>
+#include <boost/numeric/conversion/cast.hpp>
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 4a5d4e9..b567b5a 100644
--- a/Swiften/Base/ByteArray.h
+++ b/Swiften/Base/ByteArray.h
@@ -1,47 +1,48 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <string>
+#include <vector>
-#include <Swiften/Base/API.h>
#include <boost/filesystem/path.hpp>
+#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() ? nullptr : &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() ? nullptr : &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);
+ SWIFTEN_API std::string byteArrayToString(const ByteArray& b);
- SWIFTEN_API void readByteArrayFromFile(ByteArray&, const boost::filesystem::path& file);
+ 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 d19e9c7..4443566 100644
--- a/Swiften/Base/DateTime.cpp
+++ b/Swiften/Base/DateTime.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,41 +7,42 @@
#include <Swiften/Base/DateTime.h>
#include <locale>
-#include <boost/date_time/time_facet.hpp>
+
+#include <boost/date_time/c_local_time_adjustor.hpp>
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
-#include <boost/date_time/c_local_time_adjustor.hpp>
+#include <boost/date_time/time_facet.hpp>
-#include <Swiften/Base/String.h>
#include <Swiften/Base/Log.h>
+#include <Swiften/Base/String.h>
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 dc729f0..36cff65 100644
--- a/Swiften/Base/DateTime.h
+++ b/Swiften/Base/DateTime.h
@@ -1,28 +1,29 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/API.h>
#include <boost/date_time/posix_time/ptime.hpp>
+#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..b4245c3 100644
--- a/Swiften/Base/Debug.cpp
+++ b/Swiften/Base/Debug.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,135 +7,184 @@
#include <Swiften/Base/Debug.h>
#include <iostream>
-
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Client/ClientError.h>
+#include <Swiften/Client/ClientSession.h>
#include <Swiften/Serializer/PayloadSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
#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;
+
+ std::shared_ptr<Element> element = std::shared_ptr<Element>(ele);
- boost::shared_ptr<Element> element = boost::shared_ptr<Element>(ele);
+ std::shared_ptr<Payload> payload = std::dynamic_pointer_cast<Payload>(element);
+ if (payload) {
+ FullPayloadSerializerCollection payloadSerializerCollection;
+ PayloadSerializer *serializer = payloadSerializerCollection.getPayloadSerializer(payload);
+ os << "Payload(" << serializer->serialize(payload) << ")";
+ return os;
+ }
+ std::shared_ptr<ToplevelElement> topLevelElement = std::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;
+std::ostream& operator<<(std::ostream& os, Swift::ClientSession::State state) {
+ using CS = Swift::ClientSession;
+ switch (state) {
+ case CS::State::Initial:
+ os << "ClientSession::State::Initial";
+ break;
+ case CS::State::WaitingForStreamStart:
+ os << "ClientSession::State::WaitingForStreamStart";
+ break;
+ case CS::State::Negotiating:
+ os << "ClientSession::State::Negotiating";
+ break;
+ case CS::State::Compressing:
+ os << "ClientSession::State::Compressing";
+ break;
+ case CS::State::WaitingForEncrypt:
+ os << "ClientSession::State::WaitingForEncrypt";
+ break;
+ case CS::State::Encrypting:
+ os << "ClientSession::State::Encrypting";
+ break;
+ case CS::State::WaitingForCredentials:
+ os << "ClientSession::State::WaitingForCredentials";
+ break;
+ case CS::State::Authenticating:
+ os << "ClientSession::State::Authenticating";
+ break;
+ case CS::State::EnablingSessionManagement:
+ os << "ClientSession::State::EnablingSessionManagement";
+ break;
+ case CS::State::BindingResource:
+ os << "ClientSession::State::BindingResource";
+ break;
+ case CS::State::StartingSession:
+ os << "ClientSession::State::StartingSession";
+ break;
+ case CS::State::Initialized:
+ os << "ClientSession::State::Initialized";
+ break;
+ case CS::State::Finishing:
+ os << "ClientSession::State::Finishing";
+ break;
+ case CS::State::Finished:
+ os << "ClientSession::State::Finished";
+ break;
+ }
+ return os;
}
diff --git a/Swiften/Base/Debug.h b/Swiften/Base/Debug.h
index 33d439e..9dde74c 100644
--- a/Swiften/Base/Debug.h
+++ b/Swiften/Base/Debug.h
@@ -1,20 +1,26 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#pragma once
+
#include <iosfwd>
+#include <Swiften/Client/ClientSession.h>
+
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);
std::ostream& operator<<(std::ostream& os, Swift::Element* ele);
+
+std::ostream& operator<<(std::ostream& os, Swift::ClientSession::State state);
diff --git a/Swiften/Base/Error.h b/Swiften/Base/Error.h
index 3589bf0..af4f27e 100644
--- a/Swiften/Base/Error.h
+++ b/Swiften/Base/Error.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,10 +9,11 @@
#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)
+ SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(Error)
+ virtual ~Error();
+ };
}
diff --git a/Swiften/Base/FileSize.cpp b/Swiften/Base/FileSize.cpp
index 9b1fbba..a335337 100644
--- a/Swiften/Base/FileSize.cpp
+++ b/Swiften/Base/FileSize.cpp
@@ -1,23 +1,24 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Base/FileSize.h>
+
#include <boost/format.hpp>
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", nullptr};
+ 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/FileSize.h b/Swiften/Base/FileSize.h
index 1482c1e..af303cc 100644
--- a/Swiften/Base/FileSize.h
+++ b/Swiften/Base/FileSize.h
@@ -1,15 +1,17 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/API.h>
-#include <boost/cstdint.hpp>
#include <string>
+#include <boost/cstdint.hpp>
+
+#include <Swiften/Base/API.h>
+
namespace Swift {
SWIFTEN_API std::string formatSize(const boost::uintmax_t bytes);
diff --git a/Swiften/Base/IDGenerator.cpp b/Swiften/Base/IDGenerator.cpp
index 881d588..b59a39c 100644
--- a/Swiften/Base/IDGenerator.cpp
+++ b/Swiften/Base/IDGenerator.cpp
@@ -1,24 +1,27 @@
/*
- * Copyright (c) 2010-2011 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Base/IDGenerator.h>
+#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid.hpp>
-#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
-#include <boost/lexical_cast.hpp>
+#include <boost/uuid/uuid_io.hpp>
namespace Swift {
IDGenerator::IDGenerator() {
}
+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..6b53994 100644
--- a/Swiften/Base/IDGenerator.h
+++ b/Swiften/Base/IDGenerator.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -11,10 +11,11 @@
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API IDGenerator {
- public:
- IDGenerator();
+ class SWIFTEN_API IDGenerator {
+ public:
+ IDGenerator();
+ virtual ~IDGenerator();
- std::string generateID();
- };
+ virtual 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/LogSerializers.cpp b/Swiften/Base/LogSerializers.cpp
new file mode 100644
index 0000000..ccc8437
--- /dev/null
+++ b/Swiften/Base/LogSerializers.cpp
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swiften/Base/LogSerializers.h>
+
+#include <Swiften/Elements/Presence.h>
+
+namespace Swift {
+
+std::ostream& operator<<(std::ostream& stream, const Presence& presence) {
+ std::string typeString;
+ switch (presence.getType()) {
+ case Presence::Available:
+ typeString = "Available";
+ break;
+ case Presence::Error:
+ typeString = "Error";
+ break;
+ case Presence::Probe:
+ typeString = "Probe";
+ break;
+ case Presence::Subscribe:
+ typeString = "Subscribe";
+ break;
+ case Presence::Subscribed:
+ typeString = "Subscribed";
+ break;
+ case Presence::Unavailable:
+ typeString = "Unavailable";
+ break;
+ case Presence::Unsubscribe:
+ typeString = "Unsubscribe";
+ break;
+ case Presence::Unsubscribed:
+ typeString = "Unsubscribed";
+ break;
+ }
+
+ std::string showTypeString;
+ switch (presence.getShow()) {
+ case StatusShow::Online:
+ showTypeString = "Online";
+ break;
+ case StatusShow::Away:
+ showTypeString = "Away";
+ break;
+ case StatusShow::FFC:
+ showTypeString = "FFC";
+ break;
+ case StatusShow::DND:
+ showTypeString = "DND";
+ break;
+ case StatusShow::XA:
+ showTypeString = "XA";
+ break;
+ case StatusShow::None:
+ showTypeString = "None";
+ break;
+ }
+
+ stream << "Presence(" << "from: " << presence.getFrom() << ", to: " << presence.getTo() << ", type: " << typeString << ", status: " << showTypeString << ", priority: " << presence.getPriority() << ", '" << presence.getStatus() << "'" << " )";
+ return stream;
+}
+
+};
diff --git a/Swiften/Base/LogSerializers.h b/Swiften/Base/LogSerializers.h
new file mode 100644
index 0000000..3d60426
--- /dev/null
+++ b/Swiften/Base/LogSerializers.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#pragma once
+
+#include <memory>
+#include <ostream>
+#include <string>
+#include <vector>
+
+namespace Swift {
+
+class Presence;
+
+template <typename T>
+std::ostream& operator<<(std::ostream& stream, const std::shared_ptr<T>& ptr) {
+ if (ptr) {
+ stream << *ptr;
+ }
+ else {
+ stream << "nullptr";
+ }
+ return stream;
+}
+
+template <typename T>
+std::ostream& operator<<(std::ostream& stream, const std::vector<T>& vec) {
+ stream << "[";
+ if (!vec.empty()) {
+ auto it = std::begin(vec);
+ stream << *it;
+
+ ++it;
+ for (auto end = std::end(vec); it != end; ++it) {
+ stream << ", " << *it;
+ }
+ }
+ stream << "]";
+ return stream;
+}
+
+std::ostream& operator<<(std::ostream& stream, const Presence& presence);
+
+};
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 172f4bd..40141b5 100644
--- a/Swiften/Base/Path.h
+++ b/Swiften/Base/Path.h
@@ -1,27 +1,29 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/API.h>
-#include <boost/filesystem/path.hpp>
#include <string>
+#include <boost/filesystem/path.hpp>
+
+#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 cb1b9f7..06677ec 100644
--- a/Swiften/Base/RandomGenerator.h
+++ b/Swiften/Base/RandomGenerator.h
@@ -1,23 +1,24 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/API.h>
#include <vector>
+#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/SConscript b/Swiften/Base/SConscript
index d7fd7cc..de502c2 100644
--- a/Swiften/Base/SConscript
+++ b/Swiften/Base/SConscript
@@ -1,22 +1,23 @@
Import("swiften_env")
objects = swiften_env.SwiftenObject([
- "ByteArray.cpp",
- "DateTime.cpp",
- "SafeByteArray.cpp",
- "SafeAllocator.cpp",
- "Error.cpp",
- "Log.cpp",
- "Path.cpp",
- "Paths.cpp",
- "String.cpp",
- "IDGenerator.cpp",
- "SimpleIDGenerator.cpp",
- "RandomGenerator.cpp",
- "BoostRandomGenerator.cpp",
- "sleep.cpp",
- "URL.cpp",
- "Regex.cpp",
- "FileSize.cpp"
- ])
+ "BoostRandomGenerator.cpp",
+ "ByteArray.cpp",
+ "DateTime.cpp",
+ "Error.cpp",
+ "FileSize.cpp",
+ "IDGenerator.cpp",
+ "Log.cpp",
+ "LogSerializers.cpp",
+ "Path.cpp",
+ "Paths.cpp",
+ "RandomGenerator.cpp",
+ "Regex.cpp",
+ "SafeAllocator.cpp",
+ "SafeByteArray.cpp",
+ "SimpleIDGenerator.cpp",
+ "String.cpp",
+ "URL.cpp",
+ "sleep.cpp",
+ ])
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
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 5f9ac70..0369ec4 100644
--- a/Swiften/Base/SafeAllocator.h
+++ b/Swiften/Base/SafeAllocator.h
@@ -1,36 +1,36 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <algorithm>
+#include <vector>
#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 e523dcd..342c185 100644
--- a/Swiften/Base/SafeByteArray.h
+++ b/Swiften/Base/SafeByteArray.h
@@ -1,59 +1,59 @@
/*
- * Copyright (c) 2011-2013 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <vector>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/SafeAllocator.h>
#include <Swiften/Base/ByteArray.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#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 std::shared_ptr<SafeByteArray> createSafeByteArrayRef(const std::string& s) {
+ return std::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 std::shared_ptr<SafeByteArray> createSafeByteArrayRef(const char* c, size_t n) {
+ return std::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 std::shared_ptr<SafeByteArray> createSafeByteArrayRef(const unsigned char* c, size_t n) {
+ return std::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 65d49d1..5e54537 100644
--- a/Swiften/Base/SafeString.h
+++ b/Swiften/Base/SafeString.h
@@ -1,33 +1,33 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/SafeByteArray.h>
#include <Swiften/Base/API.h>
+#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 c9ea38b..e6d72b3 100644
--- a/Swiften/Base/SimpleIDGenerator.cpp
+++ b/Swiften/Base/SimpleIDGenerator.cpp
@@ -1,34 +1,37 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swiften/Base/SimpleIDGenerator.h"
+#include <Swiften/Base/SimpleIDGenerator.h>
namespace Swift {
SimpleIDGenerator::SimpleIDGenerator() {
}
+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..ff645b1 100644
--- a/Swiften/Base/SimpleIDGenerator.h
+++ b/Swiften/Base/SimpleIDGenerator.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -10,21 +10,23 @@
#include <Swiften/Base/API.h>
#include <Swiften/Base/IDGenerator.h>
+#include <Swiften/Base/Override.h>
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();
+ ~SimpleIDGenerator();
- std::string generateID();
+ std::string generateID() SWIFTEN_OVERRIDE;
- 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..4a5e4c9 100644
--- a/Swiften/Base/String.cpp
+++ b/Swiften/Base/String.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 (char i : s) {
+ if (i == c) {
+ result.push_back(accumulator);
+ accumulator = "";
+ }
+ else {
+ accumulator += 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 c7584ab..f19dca5 100644
--- a/Swiften/Base/String.h
+++ b/Swiften/Base/String.h
@@ -1,58 +1,57 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <sstream>
#include <string>
#include <vector>
-#include <sstream>
#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..4a47a11 100644
--- a/Swiften/Base/URL.cpp
+++ b/Swiften/Base/URL.cpp
@@ -1,114 +1,141 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Base/URL.h>
+#include <algorithm>
#include <iostream>
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;
+ if (hostAndPort[0] == '[') {
+ // handle IPv6 address literals
+ size_t addressEndIndex = hostAndPort.find(']');
+ if (addressEndIndex != std::string::npos) {
+ host = hostAndPort.substr(1, addressEndIndex - 1);
+ colonIndex = hostAndPort.find(':', addressEndIndex);
+ if (colonIndex != std::string::npos) {
+ try {
+ port = boost::lexical_cast<int>(hostAndPort.substr(colonIndex + 1));
+ }
+ catch (const boost::bad_lexical_cast&) {
+ return URL();
+ }
+ }
+ }
+ else {
+ return URL();
+ }
+ }
+ else {
+ 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 += "@";
+ }
+ if (host.find(':') != std::string::npos) {
+ result += "[" + host + "]";
+ }
+ else {
+ 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 +145,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 9d436f5..1a03efe 100644
--- a/Swiften/Base/URL.h
+++ b/Swiften/Base/URL.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,73 +7,75 @@
#pragma once
#include <string>
+
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
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 8852b78..2eb601b 100644
--- a/Swiften/Base/UnitTest/ByteArrayTest.cpp
+++ b/Swiften/Base/UnitTest/ByteArrayTest.cpp
@@ -1,56 +1,57 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <boost/lexical_cast.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <Swiften/Base/ByteArray.h>
-#include <boost/lexical_cast.hpp>
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 a9350fa..6a82d96 100644
--- a/Swiften/Base/UnitTest/DateTimeTest.cpp
+++ b/Swiften/Base/UnitTest/DateTimeTest.cpp
@@ -1,50 +1,52 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
#include <string>
+
#include <boost/date_time/posix_time/posix_time.hpp>
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
#include <Swiften/Base/DateTime.h>
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 06be9ca..08bd48b 100644
--- a/Swiften/Base/UnitTest/IDGeneratorTest.cpp
+++ b/Swiften/Base/UnitTest/IDGeneratorTest.cpp
@@ -1,12 +1,13 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <set>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <set>
#include <Swiften/Base/IDGenerator.h>
@@ -14,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 e9dcece..9b49c0a 100644
--- a/Swiften/Base/UnitTest/SimpleIDGeneratorTest.cpp
+++ b/Swiften/Base/UnitTest/SimpleIDGeneratorTest.cpp
@@ -1,40 +1,41 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <set>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <set>
-#include "Swiften/Base/SimpleIDGenerator.h"
+#include <Swiften/Base/SimpleIDGenerator.h>
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 5317326..e2e1665 100644
--- a/Swiften/Base/UnitTest/StringTest.cpp
+++ b/Swiften/Base/UnitTest/StringTest.cpp
@@ -1,128 +1,129 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <string>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <string>
-#include <Swiften/Base/String.h>
#include <Swiften/Base/Platform.h>
+#include <Swiften/Base/String.h>
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);
+
+ 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");
+
+ 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);
+ }
- public:
- void testGetUnicodeCodePoints() {
- std::string testling("$\xc2\xa2\xe2\x82\xac\xf4\x8a\xaf\x8d");
- std::vector<unsigned int> points = String::getUnicodeCodePoints(testling);
+ void testGetSplittedAtFirst_CharacterAtBegin() {
+ std::string testling(" ab");
- CPPUNIT_ASSERT_EQUAL(0x24U, points[0]);
- CPPUNIT_ASSERT_EQUAL(0xA2U, points[1]);
- CPPUNIT_ASSERT_EQUAL(0x20ACU, points[2]);
- CPPUNIT_ASSERT_EQUAL(0x10ABCDU, points[3]);
- }
+ 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() {
- std::string testling("ab@cd@ef");
+ 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_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(result.second.empty());
+ }
- void testGetSplittedAtFirst_CharacterAtBegin() {
- std::string testling(" ab");
+ void testGetSplittedAtFirst_NoSuchCharacter() {
+ 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_EQUAL(std::string("ab"), result.first);
+ CPPUNIT_ASSERT(result.second.empty());
+ }
- void testGetSplittedAtFirst_CharacterAtEnd() {
- std::string testling("ab@");
+ void testReplaceAll() {
+ std::string testling("abcbd");
- std::pair<std::string,std::string> result = String::getSplittedAtFirst(testling, '@');
- CPPUNIT_ASSERT_EQUAL(std::string("ab"), result.first);
- CPPUNIT_ASSERT(result.second.empty());
- }
+ String::replaceAll(testling, 'b', "xyz");
- void testGetSplittedAtFirst_NoSuchCharacter() {
- std::string testling("ab");
+ CPPUNIT_ASSERT_EQUAL(std::string("axyzcxyzd"), testling);
+ }
- 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_LastChar() {
+ std::string testling("abc");
- void testReplaceAll() {
- std::string testling("abcbd");
+ String::replaceAll(testling, 'c', "xyz");
- String::replaceAll(testling, 'b', "xyz");
-
- CPPUNIT_ASSERT_EQUAL(std::string("axyzcxyzd"), testling);
- }
+ 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");
-
- CPPUNIT_ASSERT_EQUAL(std::string("abxyz"), testling);
- }
+ String::replaceAll(testling, 'b',"xyz");
- void testReplaceAll_ConsecutiveChars() {
- std::string testling("abbc");
+ CPPUNIT_ASSERT_EQUAL(std::string("axyzxyzc"), testling);
+ }
- String::replaceAll(testling, 'b',"xyz");
-
- CPPUNIT_ASSERT_EQUAL(std::string("axyzxyzc"), testling);
- }
+ void testReplaceAll_MatchingReplace() {
+ std::string testling("abc");
- void testReplaceAll_MatchingReplace() {
- std::string testling("abc");
+ String::replaceAll(testling, 'b',"bbb");
- String::replaceAll(testling, 'b',"bbb");
-
- CPPUNIT_ASSERT_EQUAL(std::string("abbbc"), testling);
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("abbbc"), testling);
+ }
- void testSplit() {
- std::vector<std::string> result = String::split("abc def ghi", ' ');
+ 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]);
- }
+ 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 b20d21e..c38398a 100644
--- a/Swiften/Base/UnitTest/URLTest.cpp
+++ b/Swiften/Base/UnitTest/URLTest.cpp
@@ -1,114 +1,238 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <boost/lexical_cast.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <Swiften/Base/URL.h>
-#include <boost/lexical_cast.hpp>
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(testFromString_IPv4Address);
+ CPPUNIT_TEST(testFromString_IPv4AddressWithPort);
+ CPPUNIT_TEST(testFromString_IPv6Address);
+ CPPUNIT_TEST(testFromString_IPv6AddressWithPort);
+ CPPUNIT_TEST(testToString);
+ CPPUNIT_TEST(testToString_WithPort);
+ CPPUNIT_TEST(test_FromString_ToString_IPv6RFC2732);
+ 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 testFromString_IPv4Address() {
+ URL url = URL::fromString("http://127.0.0.1/foobar");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("127.0.0.1"), url.getHost());
+ CPPUNIT_ASSERT_EQUAL(std::string("/foobar"), url.getPath());
+ }
+
+ void testFromString_IPv4AddressWithPort() {
+ URL url = URL::fromString("http://127.0.0.1:12345/foobar");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("127.0.0.1"), url.getHost());
+ CPPUNIT_ASSERT_EQUAL(12345, url.getPort().get_value_or(0));
+ CPPUNIT_ASSERT_EQUAL(std::string("/foobar"), url.getPath());
+ }
+
+ void testFromString_IPv6Address() {
+ URL url = URL::fromString("http://[fdf8:f53b:82e4::53]/foobar");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("fdf8:f53b:82e4::53"), url.getHost());
+ }
+
+ void testFromString_IPv6AddressWithPort() {
+ URL url = URL::fromString("http://[fdf8:f53b:82e4::53]:12435/foobar");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("fdf8:f53b:82e4::53"), url.getHost());
+ CPPUNIT_ASSERT_EQUAL(12435, url.getPort().get_value_or(0));
+ }
+
+ void test_FromString_ToString_IPv6RFC2732() {
+ {
+ const char* testVector = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html";
+ URL url = URL::fromString(testVector);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("FEDC:BA98:7654:3210:FEDC:BA98:7654:3210"), url.getHost());
+ CPPUNIT_ASSERT_EQUAL(80, url.getPort().get_value_or(2));
+ CPPUNIT_ASSERT_EQUAL(std::string("/index.html"), url.getPath());
+
+ CPPUNIT_ASSERT_EQUAL(std::string(testVector), url.toString());
+ }
+
+ {
+ const char* testVector = "http://[1080:0:0:0:8:800:200C:417A]/index.html";
+ URL url = URL::fromString(testVector);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("1080:0:0:0:8:800:200C:417A"), url.getHost());
+ CPPUNIT_ASSERT_EQUAL(2, url.getPort().get_value_or(2));
+ CPPUNIT_ASSERT_EQUAL(std::string("/index.html"), url.getPath());
+
+ CPPUNIT_ASSERT_EQUAL(std::string(testVector), url.toString());
+ }
+
+ {
+ const char* testVector = "http://[3ffe:2a00:100:7031::1]";
+ URL url = URL::fromString(testVector);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("3ffe:2a00:100:7031::1"), url.getHost());
+ CPPUNIT_ASSERT_EQUAL(2, url.getPort().get_value_or(2));
+ CPPUNIT_ASSERT_EQUAL(std::string(""), url.getPath());
+
+ CPPUNIT_ASSERT_EQUAL(std::string(testVector), url.toString());
+ }
+
+ {
+ const char* testVector = "http://[1080::8:800:200C:417A]/foo";
+ URL url = URL::fromString(testVector);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("1080::8:800:200C:417A"), url.getHost());
+ CPPUNIT_ASSERT_EQUAL(2, url.getPort().get_value_or(2));
+ CPPUNIT_ASSERT_EQUAL(std::string("/foo"), url.getPath());
+
+ CPPUNIT_ASSERT_EQUAL(std::string(testVector), url.toString());
+ }
+
+ {
+ const char* testVector = "http://[::192.9.5.5]/ipng";
+ URL url = URL::fromString(testVector);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("::192.9.5.5"), url.getHost());
+ CPPUNIT_ASSERT_EQUAL(2, url.getPort().get_value_or(2));
+ CPPUNIT_ASSERT_EQUAL(std::string("/ipng"), url.getPath());
+
+ CPPUNIT_ASSERT_EQUAL(std::string(testVector), url.toString());
+ }
+
+ {
+ const char* testVector = "http://[::FFFF:129.144.52.38]:80/index.html";
+ URL url = URL::fromString(testVector);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("::FFFF:129.144.52.38"), url.getHost());
+ CPPUNIT_ASSERT_EQUAL(80, url.getPort().get_value_or(2));
+ CPPUNIT_ASSERT_EQUAL(std::string("/index.html"), url.getPath());
+
+ CPPUNIT_ASSERT_EQUAL(std::string(testVector), url.toString());
+ }
+
+ {
+ const char* testVector = "http://[2010:836B:4179::836B:4179]";
+ URL url = URL::fromString(testVector);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme());
+ CPPUNIT_ASSERT_EQUAL(std::string("2010:836B:4179::836B:4179"), url.getHost());
+ CPPUNIT_ASSERT_EQUAL(2, url.getPort().get_value_or(2));
+ CPPUNIT_ASSERT_EQUAL(std::string(), url.getPath());
+
+ CPPUNIT_ASSERT_EQUAL(std::string(testVector), url.toString());
+ }
+ }
+
+ 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
deleted file mode 100644
index 005c7dc..0000000
--- a/Swiften/Base/boost_bsignals.h
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (c) 2010 Isode Limited.
- * All rights reserved.
- * See the COPYING file for more information.
- */
-
-// Work around for the boost::signals / Qt signals keyword clash.
-// Based on an example from Frank Hess, improved by Niels Dekker
-
-#pragma once
-
-#if defined(signals) && defined(Q_SIGNALS) && !defined(QT_MOC_CPP)
-#undef signals
-#define signals signals
-#endif
-
-#include <boost/signal.hpp>
-
-namespace boost {
- namespace bsignals = signals;
-}
-
-#if defined(signals) && defined(Q_SIGNALS) && !defined(QT_MOC_CPP)
-#undef signals
-#define signals Q_SIGNALS
-#endif
diff --git a/Swiften/Base/foreach.h b/Swiften/Base/foreach.h
deleted file mode 100644
index 3e8ec43..0000000
--- a/Swiften/Base/foreach.h
+++ /dev/null
@@ -1,13 +0,0 @@
-/*
- * Copyright (c) 2010 Isode Limited.
- * All rights reserved.
- * See the COPYING file for more information.
- */
-
-#pragma once
-
-#include <boost/foreach.hpp>
-
-#undef foreach
-#define foreach BOOST_FOREACH
-#define reverse_foreach BOOST_REVERSE_FOREACH
diff --git a/Swiften/Base/format.h b/Swiften/Base/format.h
index a10ce2e..e5696b0 100644
--- a/Swiften/Base/format.h
+++ b/Swiften/Base/format.h
@@ -1,25 +1,26 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/format.hpp>
#include <iostream>
+#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..48eae51 100644
--- a/Swiften/Base/sleep.cpp
+++ b/Swiften/Base/sleep.cpp
@@ -1,25 +1,18 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Base/sleep.h>
-#include <boost/thread.hpp>
-#include <boost/version.hpp>
+#include <chrono>
+#include <thread>
namespace Swift {
void sleep(unsigned int msecs) {
- boost::xtime xt;
-#if BOOST_VERSION >= 105000
- boost::xtime_get(&xt, boost::TIME_UTC_);
-#else
- boost::xtime_get(&xt, boost::TIME_UTC);
-#endif
- xt.nsec += msecs*1000000;
- boost::thread::sleep(xt);
+ std::this_thread::sleep_for(std::chrono::milliseconds(msecs));
}
}
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/ChangeLog.md b/Swiften/ChangeLog.md
new file mode 100644
index 0000000..62cea5e
--- /dev/null
+++ b/Swiften/ChangeLog.md
@@ -0,0 +1,17 @@
+4.0-in-progress
+---------------
+- Handle sessions being closed by the server
+
+4.0-beta1 ( 2016-07-15 )
+------------------------
+- Moved code-base to C++11
+ - Use C++11 threading instead of Boost.Thread library
+ - Use C++11 smart pointers instead of Boost's
+- Migrated from Boost.Signals to Boost.Signals2
+- Build without warnings on our CI platforms
+- General cleanup like remove of superflous files and #include statements. This means header files that previously were included implictly need to be explicitly included now
+- Support IPv6 addresses in URLs
+- Changed source code style to use soft tabs (4 spaces wide) instead of hard tabs. Custom patches for Swiften will need to be reformatted accordingly
+- Require a TLS backend for building
+- Update 3rdParty/lcov to version 1.12
+- Fix several possible race conditions and other small bugs \ No newline at end of file
diff --git a/Swiften/Chat/ChatStateNotifier.cpp b/Swiften/Chat/ChatStateNotifier.cpp
index 9ff9e5a..cbb9b0b 100644
--- a/Swiften/Chat/ChatStateNotifier.cpp
+++ b/Swiften/Chat/ChatStateNotifier.cpp
@@ -1,93 +1,94 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Chat/ChatStateNotifier.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Elements/Message.h>
-#include <Swiften/Elements/ChatState.h>
#include <Swiften/Client/StanzaChannel.h>
#include <Swiften/Disco/EntityCapsProvider.h>
+#include <Swiften/Elements/ChatState.h>
+#include <Swiften/Elements/Message.h>
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);
+ std::shared_ptr<Message> message(std::make_shared<Message>());
+ message->setTo(contact_);
+ message->addPayload(std::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(std::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 d832680..a7af9e4 100644
--- a/Swiften/Chat/ChatStateNotifier.h
+++ b/Swiften/Chat/ChatStateNotifier.h
@@ -1,51 +1,52 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/ChatState.h>
+#include <Swiften/Elements/Message.h>
#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..25ecd1c 100644
--- a/Swiften/Chat/ChatStateTracker.cpp
+++ b/Swiften/Chat/ChatStateTracker.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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());;
- }
+void ChatStateTracker::handleMessageReceived(std::shared_ptr<Message> message) {
+ if (message->getType() == Message::Error) {
+ return;
+ }
+ std::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);
- }
+void ChatStateTracker::handlePresenceChange(std::shared_ptr<Presence> newPresence) {
+ 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 01e7155..c903e3a 100644
--- a/Swiften/Chat/ChatStateTracker.h
+++ b/Swiften/Chat/ChatStateTracker.h
@@ -1,28 +1,29 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/API.h>
+#include <memory>
+
+#include <boost/signals2.hpp>
+#include <Swiften/Base/API.h>
+#include <Swiften/Elements/ChatState.h>
#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Presence.h>
-#include <Swiften/Elements/ChatState.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(std::shared_ptr<Message> message);
+ void handlePresenceChange(std::shared_ptr<Presence> newPresence);
+ boost::signals2::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 11586a4..7eeb531 100644
--- a/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp
+++ b/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp
@@ -1,14 +1,14 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Chat/ChatStateNotifier.h>
#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/Disco/DummyEntityCapsProvider.h>
@@ -16,153 +16,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();
+ std::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() {
+ std::shared_ptr<Message> message(new Message());
+ notifier_->addChatStateRequest(message);
+ CPPUNIT_ASSERT(!message->getPayload<ChatState>());
+ }
+
+ void testContactShouldReceiveStates_ActiveOverrideOn() {
+ notifier_->receivedMessageFromContact(true);
+ std::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.
+ */
+ std::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;
+ for (auto&& stanza : stanzaChannel->sentStanzas) {
+ if (stanza->getPayload<ChatState>() && stanza->getPayload<ChatState>()->getChatState() == ChatState::Composing) {
+ result++;
+ }
+ }
+ return result;
+ }
+
+ int getActiveCount() const {
+ int result = 0;
+ for (auto&& stanza : stanzaChannel->sentStanzas) {
+ if (stanza->getPayload<ChatState>() && stanza->getPayload<ChatState>()->getChatState() == ChatState::Active) {
+ result++;
+ }
+ }
+ return result;
+ }
+
+ private:
+ DummyStanzaChannel* stanzaChannel;
+ DummyEntityCapsProvider* entityCapsProvider;
+ ChatStateNotifier* notifier_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ChatStateNotifierTest);
diff --git a/Swiften/Client/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 eeb6c10..7a54626 100644
--- a/Swiften/Client/BlockList.h
+++ b/Swiften/Client/BlockList.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,30 +8,31 @@
#include <vector>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
+#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::signals2::signal<void ()> onStateChanged;
+ boost::signals2::signal<void (const JID&)> onItemAdded;
+ boost::signals2::signal<void (const JID&)> onItemRemoved;
+ };
}
diff --git a/Swiften/Client/BlockListImpl.cpp b/Swiften/Client/BlockListImpl.cpp
index 4abaa37..54dcdf5 100644
--- a/Swiften/Client/BlockListImpl.cpp
+++ b/Swiften/Client/BlockListImpl.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,8 +8,6 @@
#include <algorithm>
-#include <Swiften/Base/foreach.h>
-
using namespace Swift;
BlockListImpl::BlockListImpl() : state(Init) {
@@ -17,58 +15,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.
+ for (const auto& jid : items) {
+ if (std::find(newItems.begin(), newItems.end(), jid) == newItems.end()) {
+ onItemRemoved(jid);
+ }
+ }
- // JIDs which are in the new list but not in the current list, are added.
- foreach (const JID& jid, newItems) {
- 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.
+ for (const auto& jid : newItems) {
+ if (std::find(items.begin(), items.end(), jid) == items.end()) {
+ onItemAdded(jid);
+ }
+ }
+ items = newItems;
}
void BlockListImpl::addItem(const JID& item) {
- if (std::find(items.begin(), items.end(), item) == items.end()) {
- items.push_back(item);
- onItemAdded(item);
- }
+ 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);
- }
+ for (const auto& item : items) {
+ addItem(item);
+ }
}
void BlockListImpl::removeItems(const std::vector<JID>& items) {
- std::vector<JID> itemsToRemove = items;
- foreach (const JID& item, itemsToRemove) {
- removeItem(item);
- }
+ std::vector<JID> itemsToRemove = items;
+ for (const auto& 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..8642a4e 100644
--- a/Swiften/Client/Client.cpp
+++ b/Swiften/Client/Client.cpp
@@ -1,37 +1,39 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Client/Client.h>
-#include <Swiften/Queries/Responders/SoftwareVersionResponder.h>
-#include <Swiften/Roster/XMPPRosterImpl.h>
-#include <Swiften/Roster/XMPPRosterController.h>
-#include <Swiften/Presence/PresenceOracle.h>
-#include <Swiften/Presence/StanzaChannelPresenceSender.h>
-#include <Swiften/Presence/DirectedPresenceSender.h>
-#include <Swiften/MUC/MUCRegistry.h>
-#include <Swiften/MUC/MUCManager.h>
-#include <Swiften/PubSub/PubSubManagerImpl.h>
-#include <Swiften/Client/MemoryStorages.h>
-#include <Swiften/VCards/VCardManager.h>
-#include <Swiften/VCards/VCardManager.h>
#include <Swiften/Avatars/AvatarManagerImpl.h>
+#include <Swiften/Base/SafeString.h>
+#include <Swiften/Client/ClientBlockListManager.h>
+#include <Swiften/Client/ClientSession.h>
+#include <Swiften/Client/MemoryStorages.h>
+#include <Swiften/Client/NickManagerImpl.h>
+#include <Swiften/Client/NickResolver.h>
#include <Swiften/Disco/CapsManager.h>
-#include <Swiften/Disco/EntityCapsManager.h>
#include <Swiften/Disco/ClientDiscoManager.h>
-#include <Swiften/Client/NickResolver.h>
-#include <Swiften/Presence/SubscriptionManager.h>
-#include <Swiften/TLS/BlindCertificateTrustChecker.h>
-#include <Swiften/Client/NickManagerImpl.h>
-#include <Swiften/Client/ClientSession.h>
+#include <Swiften/Disco/EntityCapsManager.h>
+#include <Swiften/FileTransfer/FileTransferManagerImpl.h>
#include <Swiften/Jingle/JingleSessionManager.h>
+#include <Swiften/MUC/MUCManager.h>
+#include <Swiften/MUC/MUCRegistry.h>
#include <Swiften/Network/NetworkFactories.h>
-#include <Swiften/FileTransfer/FileTransferManagerImpl.h>
+#include <Swiften/Presence/DirectedPresenceSender.h>
+#include <Swiften/Presence/PresenceOracle.h>
+#include <Swiften/Presence/StanzaChannelPresenceSender.h>
+#include <Swiften/Presence/SubscriptionManager.h>
+#include <Swiften/PubSub/PubSubManagerImpl.h>
+#include <Swiften/Queries/Responders/SoftwareVersionResponder.h>
+#include <Swiften/Roster/XMPPRosterController.h>
+#include <Swiften/Roster/XMPPRosterImpl.h>
+#include <Swiften/TLS/BlindCertificateTrustChecker.h>
+#include <Swiften/VCards/VCardManager.h>
+#include <Swiften/VCards/VCardManager.h>
#include <Swiften/Whiteboard/WhiteboardSessionManager.h>
-#include <Swiften/Client/ClientBlockListManager.h>
+
#ifndef SWIFT_EXPERIMENTAL_FT
#include <Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h>
#endif
@@ -39,160 +41,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 = nullptr;
#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 bd05345..5b11688 100644
--- a/Swiften/Client/Client.h
+++ b/Swiften/Client/Client.h
@@ -6,202 +6,206 @@
#pragma once
-#include <Swiften/Client/CoreClient.h>
-
#include <Swiften/Base/API.h>
-#include <Swiften/Base/SafeString.h>
+#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 AvatarManager;
+ class BlindCertificateTrustChecker;
+ class CapsManager;
+ class ClientBlockListManager;
+ class ClientDiscoManager;
+ class DirectedPresenceSender;
+ class EntityCapsManager;
+ class EntityCapsProvider;
+ class FileTransferManager;
+ class FileTransferManager;
+ class JingleSessionManager;
+ class MUCManager;
+ class MUCRegistry;
+ class MemoryStorages;
+ class NickManager;
+ class NickResolver;
+ class PresenceOracle;
+ class PresenceSender;
+ class PubSubManager;
+ class SafeString;
+ class SoftwareVersionResponder;
+ class StanzaChannelPresenceSender;
+ class Storages;
+ class SubscriptionManager;
+ class VCardManager;
+ class WhiteboardSessionManager;
+ class XMPPRoster;
+ class XMPPRosterController;
+ class XMPPRosterImpl;
+
+ /**
+ * 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 jid The JID to be used for the login. If only a bare
+ * JID is give the server will be asked to generate a resource.
+ * \param password The password used for login given as a \ref SafeString.
+ * \param networkFactories The network factories that are used
+ * to handle any network related tasks.
+ * \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 = nullptr);
+ 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.
+ */
+ std::shared_ptr<Presence> getLastPresence(const JID& jid) const;
+
+ /**
+ * Returns the presence with the highest priority received for the given JID.
+ */
+ std::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::signals2::signal<void (std::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 9cf349f..bfdec30 100644
--- a/Swiften/Client/ClientBlockListManager.cpp
+++ b/Swiften/Client/ClientBlockListManager.cpp
@@ -1,68 +1,69 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Client/ClientBlockListManager.h>
-#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <cassert>
+#include <memory>
+
+#include <boost/bind.hpp>
#include <Swiften/Client/BlockListImpl.h>
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(std::shared_ptr<BlockListImpl> blockList, IQRouter* iqRouter) : SetResponder<BlockPayload>(iqRouter), blockList(blockList) {
+ }
+
+ virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, std::shared_ptr<BlockPayload> payload) {
+ if (getIQRouter()->isAccountJID(from)) {
+ if (payload) {
+ blockList->addItems(payload->getItems());
+ }
+ sendResponse(from, id, std::shared_ptr<BlockPayload>());
+ }
+ else {
+ sendError(from, id, ErrorPayload::NotAuthorized, ErrorPayload::Cancel);
+ }
+ return true;
+ }
+
+ private:
+ std::shared_ptr<BlockListImpl> blockList;
+ };
+
+ class UnblockResponder : public SetResponder<UnblockPayload> {
+ public:
+ UnblockResponder(std::shared_ptr<BlockListImpl> blockList, IQRouter* iqRouter) : SetResponder<UnblockPayload>(iqRouter), blockList(blockList) {
+ }
+
+ virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, std::shared_ptr<UnblockPayload> payload) {
+ if (getIQRouter()->isAccountJID(from)) {
+ if (payload) {
+ if (payload->getItems().empty()) {
+ blockList->removeAllItems();
+ }
+ else {
+ blockList->removeItems(payload->getItems());
+ }
+ }
+ sendResponse(from, id, std::shared_ptr<UnblockPayload>());
+ }
+ else {
+ sendError(from, id, ErrorPayload::NotAuthorized, ErrorPayload::Cancel);
+ }
+ return true;
+ }
+
+ private:
+ std::shared_ptr<BlockListImpl> blockList;
+ };
}
ClientBlockListManager::ClientBlockListManager(IQRouter* iqRouter) : iqRouter(iqRouter) {
@@ -70,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;
+std::shared_ptr<BlockList> ClientBlockListManager::getBlockList() {
+ if (!blockList) {
+ blockList = std::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;
+std::shared_ptr<BlockList> ClientBlockListManager::requestBlockList() {
+ if (!blockList) {
+ blockList = std::make_shared<BlockListImpl>();
+ }
+ blockList->setState(BlockList::Requesting);
+ std::shared_ptr<GenericRequest<BlockListPayload> > getRequest = std::make_shared< GenericRequest<BlockListPayload> >(IQ::Get, JID(), std::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);
+ std::shared_ptr<BlockPayload> payload = std::make_shared<BlockPayload>(jids);
+ return std::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);
+ std::shared_ptr<UnblockPayload> payload = std::make_shared<UnblockPayload>(jids);
+ return std::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();
- }
- }
+void ClientBlockListManager::handleBlockListReceived(std::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 = std::make_shared<BlockResponder>(blockList, iqRouter);
+ blockResponder->start();
+ }
+ if (!unblockResponder) {
+ unblockResponder = std::make_shared<UnblockResponder>(blockList, iqRouter);
+ unblockResponder->start();
+ }
+ }
}
diff --git a/Swiften/Client/ClientBlockListManager.h b/Swiften/Client/ClientBlockListManager.h
index fb30eee..5fc1335 100644
--- a/Swiften/Client/ClientBlockListManager.h
+++ b/Swiften/Client/ClientBlockListManager.h
@@ -1,57 +1,58 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/Elements/BlockPayload.h>
+#include <Swiften/Client/BlockList.h>
+#include <Swiften/Client/BlockListImpl.h>
#include <Swiften/Elements/BlockListPayload.h>
-#include <Swiften/Elements/UnblockPayload.h>
+#include <Swiften/Elements/BlockPayload.h>
#include <Swiften/Elements/DiscoInfo.h>
-#include <Swiften/Queries/SetResponder.h>
+#include <Swiften/Elements/UnblockPayload.h>
#include <Swiften/Queries/GenericRequest.h>
-#include <Swiften/Client/BlockList.h>
-#include <Swiften/Client/BlockListImpl.h>
+#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.
+ */
+ std::shared_ptr<BlockList> getBlockList();
+
+ /**
+ * Get the blocklist from the server.
+ */
+ std::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(std::shared_ptr<BlockListPayload> payload, ErrorPayload::ref);
+
+ private:
+ IQRouter* iqRouter;
+ std::shared_ptr<SetResponder<BlockPayload> > blockResponder;
+ std::shared_ptr<SetResponder<UnblockPayload> > unblockResponder;
+ std::shared_ptr<BlockListImpl> blockList;
+ };
}
diff --git a/Swiften/Client/ClientError.h b/Swiften/Client/ClientError.h
index 19de42b..3453611 100644
--- a/Swiften/Client/ClientError.h
+++ b/Swiften/Client/ClientError.h
@@ -1,65 +1,66 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#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(std::shared_ptr<boost::system::error_code> errorCode) { errorCode_ = errorCode; }
- boost::shared_ptr<boost::system::error_code> getErrorCode() const { return errorCode_; }
+ std::shared_ptr<boost::system::error_code> getErrorCode() const { return errorCode_; }
- private:
- Type type_;
- boost::shared_ptr<boost::system::error_code> errorCode_;
- };
+ private:
+ Type type_;
+ std::shared_ptr<boost::system::error_code> errorCode_;
+ };
}
diff --git a/Swiften/Client/ClientOptions.h b/Swiften/Client/ClientOptions.h
index c09b987..1a337b6 100644
--- a/Swiften/Client/ClientOptions.h
+++ b/Swiften/Client/ClientOptions.h
@@ -1,163 +1,154 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/URL.h>
#include <Swiften/Base/SafeString.h>
+#include <Swiften/Base/URL.h>
#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() {
+ }
+
+ /**
+ * Whether ZLib stream compression should be used when available.
+ *
+ * Default: true
+ */
+ bool useStreamCompression = true;
+
+ /**
+ * Sets whether TLS encryption should be used.
+ *
+ * Default: UseTLSWhenAvailable
+ */
+ UseTLS useTLS = UseTLSWhenAvailable;
+
+ /**
+ * Sets whether plaintext authentication is
+ * allowed over non-TLS-encrypted connections.
+ *
+ * Default: false
+ */
+ bool allowPLAINWithoutTLS = false;
+
+ /**
+ * Use XEP-196 stream resumption when available.
+ *
+ * Default: false
+ */
+ bool useStreamResumption = false;
+
+ /**
+ * 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 = false;
+
+ /**
+ * Use XEP-0198 acks in the stream when available.
+ * Default: true
+ */
+ bool useAcks = true;
+
+ /**
+ * Use Single Sign On.
+ * Default: false
+ */
+ bool singleSignOn = false;
+
+ /**
+ * 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 = -1;
+
+ /**
+ * The type of proxy to use for connecting to the XMPP
+ * server.
+ */
+ ProxyType proxyType = SystemConfiguredProxy;
+
+ /**
+ * Override the system-configured proxy hostname.
+ */
+ std::string manualProxyHostname = "";
+
+ /**
+ * Override the system-configured proxy port.
+ */
+ int manualProxyPort = -1;
+
+ /**
+ * If non-empty, use BOSH instead of direct TCP, with the given URL.
+ * Default: empty (no BOSH)
+ */
+ URL boshURL = URL();
+
+ /**
+ * If non-empty, BOSH connections will try to connect over this HTTP CONNECT
+ * proxy instead of directly.
+ * Default: empty (no proxy)
+ */
+ URL boshHTTPConnectProxyURL = URL();
+
+ /**
+ * 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("");
+ SafeString boshHTTPConnectProxyAuthPassword = SafeString("");
+
+ /**
+ * This can be initialized with a custom HTTPTrafficFilter, which allows HTTP CONNECT
+ * proxy initialization to be customized.
+ */
+ std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter;
+
+ /**
+ * Options passed to the TLS stack
+ */
+ TLSOptions tlsOptions;
+
+ /**
+ * Session shutdown timeout in milliseconds. This is the maximum time Swiften
+ * waits from a session close to the socket close.
+ */
+ int sessionShutdownTimeoutInMilliseconds = 10000;
+ };
}
diff --git a/Swiften/Client/ClientSession.cpp b/Swiften/Client/ClientSession.cpp
index 52b8cfb..bcfb004 100644
--- a/Swiften/Client/ClientSession.cpp
+++ b/Swiften/Client/ClientSession.cpp
@@ -1,47 +1,52 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Client/ClientSession.h>
+#include <memory>
+
#include <boost/bind.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Base/Platform.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Elements/ProtocolHeader.h>
-#include <Swiften/Elements/StreamFeatures.h>
-#include <Swiften/Elements/StreamError.h>
-#include <Swiften/Elements/StartTLSRequest.h>
-#include <Swiften/Elements/StartTLSFailure.h>
-#include <Swiften/Elements/TLSProceed.h>
-#include <Swiften/Elements/AuthRequest.h>
-#include <Swiften/Elements/AuthSuccess.h>
-#include <Swiften/Elements/AuthFailure.h>
+#include <Swiften/Base/Platform.h>
+#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Elements/AuthChallenge.h>
+#include <Swiften/Elements/AuthFailure.h>
+#include <Swiften/Elements/AuthRequest.h>
#include <Swiften/Elements/AuthResponse.h>
-#include <Swiften/Elements/Compressed.h>
+#include <Swiften/Elements/AuthSuccess.h>
#include <Swiften/Elements/CompressFailure.h>
#include <Swiften/Elements/CompressRequest.h>
+#include <Swiften/Elements/Compressed.h>
#include <Swiften/Elements/EnableStreamManagement.h>
-#include <Swiften/Elements/StreamManagementEnabled.h>
-#include <Swiften/Elements/StreamManagementFailed.h>
-#include <Swiften/Elements/StartSession.h>
-#include <Swiften/Elements/StanzaAck.h>
-#include <Swiften/Elements/StanzaAckRequest.h>
#include <Swiften/Elements/IQ.h>
+#include <Swiften/Elements/ProtocolHeader.h>
#include <Swiften/Elements/ResourceBind.h>
-#include <Swiften/SASL/PLAINClientAuthenticator.h>
+#include <Swiften/Elements/StanzaAck.h>
+#include <Swiften/Elements/StanzaAckRequest.h>
+#include <Swiften/Elements/StartSession.h>
+#include <Swiften/Elements/StartTLSFailure.h>
+#include <Swiften/Elements/StartTLSRequest.h>
+#include <Swiften/Elements/StreamError.h>
+#include <Swiften/Elements/StreamFeatures.h>
+#include <Swiften/Elements/StreamManagementEnabled.h>
+#include <Swiften/Elements/StreamManagementFailed.h>
+#include <Swiften/Elements/TLSProceed.h>
+#include <Swiften/Network/Timer.h>
+#include <Swiften/Network/TimerFactory.h>
+#include <Swiften/SASL/DIGESTMD5ClientAuthenticator.h>
#include <Swiften/SASL/EXTERNALClientAuthenticator.h>
+#include <Swiften/SASL/PLAINClientAuthenticator.h>
#include <Swiften/SASL/SCRAMSHA1ClientAuthenticator.h>
-#include <Swiften/SASL/DIGESTMD5ClientAuthenticator.h>
-#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Session/SessionStream.h>
+#include <Swiften/StreamManagement/StanzaAckRequester.h>
+#include <Swiften/StreamManagement/StanzaAckResponder.h>
#include <Swiften/TLS/CertificateTrustChecker.h>
#include <Swiften/TLS/ServerIdentityVerifier.h>
@@ -51,35 +56,37 @@
#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,
+ std::shared_ptr<SessionStream> stream,
+ IDNConverter* idnConverter,
+ CryptoProvider* crypto,
+ TimerFactory* timerFactory) :
+ localJID(jid),
+ state(State::Initial),
+ stream(stream),
+ idnConverter(idnConverter),
+ crypto(crypto),
+ timerFactory(timerFactory),
+ allowPLAINOverNonTLS(false),
+ useStreamCompression(true),
+ useTLS(UseTLSWhenAvailable),
+ useAcks(true),
+ needSessionStart(false),
+ needResourceBind(false),
+ needAcking(false),
+ rosterVersioningSupported(false),
+ authenticator(nullptr),
+ certificateTrustChecker(nullptr),
+ 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 +95,482 @@ 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->onStreamEndReceived.connect(boost::bind(&ClientSession::handleStreamEnd, shared_from_this()));
+ 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 == State::Initial);
+ state = 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);
- }
+void ClientSession::sendStanza(std::shared_ptr<Stanza> 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(State::WaitingForStreamStart);
+ state = 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()) {
+void ClientSession::handleStreamEnd() {
+ if (state == State::Finishing) {
+ // We are already in finishing state if we iniated the close of the session.
+ stream->close();
+ }
+ else {
+ state = State::Finishing;
+ initiateShutdown(true);
+ }
+}
+
+void ClientSession::handleElement(std::shared_ptr<ToplevelElement> element) {
+ if (std::shared_ptr<Stanza> stanza = std::dynamic_pointer_cast<Stanza>(element)) {
+ if (stanzaAckResponder_) {
+ stanzaAckResponder_->handleStanzaReceived();
+ }
+ if (getState() == State::Initialized) {
+ onStanzaReceived(stanza);
+ }
+ else if (std::shared_ptr<IQ> iq = std::dynamic_pointer_cast<IQ>(element)) {
+ if (state == State::BindingResource) {
+ std::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 == 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 (std::dynamic_pointer_cast<StanzaAckRequest>(element)) {
+ if (stanzaAckResponder_) {
+ stanzaAckResponder_->handleAckRequestReceived();
+ }
+ }
+ else if (std::shared_ptr<StanzaAck> ack = std::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 = std::dynamic_pointer_cast<StreamError>(element)) {
+ finishSession(Error::StreamError);
+ }
+ else if (getState() == State::Initialized) {
+ std::shared_ptr<Stanza> stanza = std::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(State::Negotiating);
+
+ if (streamFeatures->hasStartTLS() && stream->supportsTLSEncryption() && useTLS != NeverUseTLS) {
+ state = State::WaitingForEncrypt;
+ stream->writeElement(std::make_shared<StartTLSRequest>());
+ }
+ else if (useTLS == RequireTLS && !stream->isTLSEncrypted()) {
+ finishSession(Error::NoSupportedAuthMechanismsError);
+ }
+ else if (useStreamCompression && stream->supportsZLibCompression() && streamFeatures->hasCompressionMethod("zlib")) {
+ state = State::Compressing;
+ stream->writeElement(std::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);
+ std::shared_ptr<Error> error = std::make_shared<Error>(Error::AuthenticationFailedError);
+
+ authenticator = gssapiAuthenticator;
+
+ if (!gssapiAuthenticator->isError()) {
+ state = State::Authenticating;
+ stream->writeElement(std::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 = State::Authenticating;
+ stream->writeElement(std::make_shared<AuthRequest>("EXTERNAL", createSafeByteArray("")));
+ }
+ else {
+ finishSession(Error::TLSClientCertificateError);
+ }
+ }
+ else if (streamFeatures->hasAuthenticationMechanism("EXTERNAL")) {
+ authenticator = new EXTERNALClientAuthenticator();
+ state = State::Authenticating;
+ stream->writeElement(std::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 = State::WaitingForCredentials;
+ onNeedCredentials();
+ }
+ else if ((stream->isTLSEncrypted() || allowPLAINOverNonTLS) && streamFeatures->hasAuthenticationMechanism("PLAIN")) {
+ authenticator = new PLAINClientAuthenticator();
+ state = 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 = 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 (std::dynamic_pointer_cast<Compressed>(element)) {
+ CHECK_STATE_OR_RETURN(State::Compressing);
+ state = State::WaitingForStreamStart;
+ stream->addZLibCompression();
+ stream->resetXMPPParser();
+ sendStreamHeader();
+ }
+ else if (std::dynamic_pointer_cast<CompressFailure>(element)) {
+ finishSession(Error::CompressionFailedError);
+ }
+ else if (std::dynamic_pointer_cast<StreamManagementEnabled>(element)) {
+ stanzaAckRequester_ = std::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_ = std::make_shared<StanzaAckResponder>();
+ stanzaAckResponder_->onAck.connect(boost::bind(&ClientSession::ack, shared_from_this(), _1));
+ needAcking = false;
+ continueSessionInitialization();
+ }
+ else if (std::dynamic_pointer_cast<StreamManagementFailed>(element)) {
+ needAcking = false;
+ continueSessionInitialization();
+ }
+ else if (AuthChallenge* challenge = dynamic_cast<AuthChallenge*>(element.get())) {
+ CHECK_STATE_OR_RETURN(State::Authenticating);
+ assert(authenticator);
+ if (authenticator->setChallenge(challenge->getValue())) {
+ stream->writeElement(std::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)) {
+ std::shared_ptr<Error> error = std::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(State::Authenticating);
+ assert(authenticator);
+ if (!authenticator->setChallenge(authSuccess->getValue())) {
+ finishSession(Error::ServerVerificationFailedError);
+ }
+ else {
+ state = State::WaitingForStreamStart;
+ delete authenticator;
+ authenticator = nullptr;
+ stream->resetXMPPParser();
+ sendStreamHeader();
+ }
+ }
+ else if (dynamic_cast<AuthFailure*>(element.get())) {
+ finishSession(Error::AuthenticationFailedError);
+ }
+ else if (dynamic_cast<TLSProceed*>(element.get())) {
+ CHECK_STATE_OR_RETURN(State::WaitingForEncrypt);
+ state = State::Encrypting;
+ stream->addTLSEncryption();
+ }
+ else if (dynamic_cast<StartTLSFailure*>(element.get())) {
+ finishSession(Error::TLSError);
+ }
+ else {
+ // FIXME Not correct?
+ state = 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 = State::BindingResource;
+ std::shared_ptr<ResourceBind> resourceBind(std::make_shared<ResourceBind>());
+ if (!localJID.getResource().empty()) {
+ resourceBind->setResource(localJID.getResource());
+ }
+ sendStanza(IQ::createRequest(IQ::Set, JID(), "session-bind", resourceBind));
+ }
+ else if (needAcking) {
+ state = State::EnablingSessionManagement;
+ stream->writeElement(std::make_shared<EnableStreamManagement>());
+ }
+ else if (needSessionStart) {
+ state = State::StartingSession;
+ sendStanza(IQ::createRequest(IQ::Set, JID(), "session-start", std::make_shared<StartSession>()));
+ }
+ else {
+ state = 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(state == State::WaitingForCredentials);
+ assert(authenticator);
+ state = State::Authenticating;
+ authenticator->setCredentials(localJID.getNode(), password);
+ stream->writeElement(std::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(State::Encrypting);
+
+ std::vector<Certificate::ref> certificateChain = stream->getPeerCertificateChain();
+ std::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, std::make_shared<CertificateVerificationError>(CertificateVerificationError::InvalidServerIdentity));
+ }
+ }
+}
+
+void ClientSession::checkTrustOrFinish(const std::vector<Certificate::ref>& certificateChain, std::shared_ptr<CertificateVerificationError> error) {
+ if (certificateTrustChecker && certificateTrustChecker->isCertificateTrusted(certificateChain)) {
+ continueAfterTLSEncrypted();
+ }
+ else {
+ finishSession(error);
+ }
}
-void ClientSession::checkTrustOrFinish(const std::vector<Certificate::ref>& certificateChain, boost::shared_ptr<CertificateVerificationError> error) {
- if (certificateTrustChecker && certificateTrustChecker->isCertificateTrusted(certificateChain)) {
- continueAfterTLSEncrypted();
- }
- else {
- finishSession(error);
- }
+void ClientSession::initiateShutdown(bool sendFooter) {
+ if (!streamShutdownTimeout) {
+ streamShutdownTimeout = timerFactory->createTimer(sessionShutdownTimeoutInMilliseconds);
+ streamShutdownTimeout->onTick.connect(boost::bind(&ClientSession::handleStreamShutdownTimeout, shared_from_this()));
+ streamShutdownTimeout->start();
+ }
+ if (sendFooter) {
+ stream->writeFooter();
+ }
+ if (state == State::Finishing) {
+ // The other side already send </stream>; we can close the socket.
+ stream->close();
+ }
+ else {
+ state = State::Finishing;
+ }
}
void ClientSession::continueAfterTLSEncrypted() {
- state = WaitingForStreamStart;
- stream->resetXMPPParser();
- sendStreamHeader();
+ state = State::WaitingForStreamStart;
+ stream->resetXMPPParser();
+ sendStreamHeader();
+}
+
+void ClientSession::handleStreamClosed(std::shared_ptr<Swift::Error> streamError) {
+ State previousState = state;
+ state = State::Finished;
+
+ if (streamShutdownTimeout) {
+ streamShutdownTimeout->stop();
+ streamShutdownTimeout.reset();
+ }
+
+ 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->onStreamEndReceived.disconnect(boost::bind(&ClientSession::handleStreamEnd, shared_from_this()));
+ 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 == State::Finishing) {
+ onFinished(error_);
+ }
+ else {
+ onFinished(streamError);
+ }
}
-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);
- }
+void ClientSession::handleStreamShutdownTimeout() {
+ handleStreamClosed(std::shared_ptr<Swift::Error>());
}
void ClientSession::finish() {
- finishSession(boost::shared_ptr<Error>());
+ if (state != State::Finishing && state != State::Finished) {
+ finishSession(std::shared_ptr<Error>());
+ }
+ else {
+ SWIFT_LOG(warning) << "Session already finished or finishing." << std::endl;
+ }
}
void ClientSession::finishSession(Error::Type error) {
- finishSession(boost::make_shared<Swift::ClientSession::Error>(error));
+ finishSession(std::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();
+void ClientSession::finishSession(std::shared_ptr<Swift::Error> error) {
+ if (!error_) {
+ error_ = error;
+ }
+ else {
+ SWIFT_LOG(warning) << "Session finished twice";
+ }
+ assert(stream->isOpen());
+ if (stanzaAckResponder_) {
+ stanzaAckResponder_->handleAckRequestReceived();
+ }
+ if (authenticator) {
+ delete authenticator;
+ authenticator = nullptr;
+ }
+ // Immidiately close TCP connection without stream closure.
+ if (std::dynamic_pointer_cast<CertificateVerificationError>(error)) {
+ state = State::Finishing;
+ initiateShutdown(false);
+ }
+ else {
+ if (state == State::Finishing) {
+ initiateShutdown(true);
+ }
+ else if (state != State::Finished) {
+ initiateShutdown(true);
+ }
+ }
}
void ClientSession::requestAck() {
- stream->writeElement(boost::make_shared<StanzaAckRequest>());
+ stream->writeElement(std::make_shared<StanzaAckRequest>());
}
-void ClientSession::handleStanzaAcked(boost::shared_ptr<Stanza> stanza) {
- onStanzaAcked(stanza);
+void ClientSession::handleStanzaAcked(std::shared_ptr<Stanza> stanza) {
+ onStanzaAcked(stanza);
}
void ClientSession::ack(unsigned int handledStanzasCount) {
- stream->writeElement(boost::make_shared<StanzaAck>(handledStanzasCount));
+ stream->writeElement(std::make_shared<StanzaAck>(handledStanzasCount));
}
}
diff --git a/Swiften/Client/ClientSession.h b/Swiften/Client/ClientSession.h
index c4b6abe..c7b3658 100644
--- a/Swiften/Client/ClientSession.h
+++ b/Swiften/Client/ClientSession.h
@@ -1,201 +1,215 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/enable_shared_from_this.hpp>
+#include <memory>
+#include <string>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/Error.h>
-#include <Swiften/Session/SessionStream.h>
-#include <string>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/ToplevelElement.h>
-#include <Swiften/StreamManagement/StanzaAckRequester.h>
-#include <Swiften/StreamManagement/StanzaAckResponder.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/Session/SessionStream.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 CertificateTrustChecker;
+ class ClientAuthenticator;
+ class CryptoProvider;
+ class IDNConverter;
+ class Stanza;
+ class StanzaAckRequester;
+ class StanzaAckResponder;
+ class TimerFactory;
+ class Timer;
+
+ class SWIFTEN_API ClientSession : public std::enable_shared_from_this<ClientSession> {
+ public:
+ enum class 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,
+ StreamEndError, // The server send a closing stream tag.
+ } type;
+ std::shared_ptr<boost::system::error_code> errorCode;
+ Error(Type type) : type(type) {}
+ };
+
+ enum UseTLS {
+ NeverUseTLS,
+ UseTLSWhenAvailable,
+ RequireTLS
+ };
+
+ ~ClientSession();
+
+ static std::shared_ptr<ClientSession> create(const JID& jid, std::shared_ptr<SessionStream> stream, IDNConverter* idnConverter, CryptoProvider* crypto, TimerFactory* timerFactory) {
+ return std::shared_ptr<ClientSession>(new ClientSession(jid, stream, idnConverter, crypto, timerFactory));
+ }
+
+ 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() == State::Finished;
+ }
+
+ void sendCredentials(const SafeByteArray& password);
+ void sendStanza(std::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;
+ }
+
+ void setSessionShutdownTimeout(int timeoutInMilliseconds) {
+ sessionShutdownTimeoutInMilliseconds = timeoutInMilliseconds;
+ }
+
+ public:
+ boost::signals2::signal<void ()> onNeedCredentials;
+ boost::signals2::signal<void ()> onInitialized;
+ boost::signals2::signal<void (std::shared_ptr<Swift::Error>)> onFinished;
+ boost::signals2::signal<void (std::shared_ptr<Stanza>)> onStanzaReceived;
+ boost::signals2::signal<void (std::shared_ptr<Stanza>)> onStanzaAcked;
+
+ private:
+ ClientSession(
+ const JID& jid,
+ std::shared_ptr<SessionStream>,
+ IDNConverter* idnConverter,
+ CryptoProvider* crypto,
+ TimerFactory* timerFactory);
+
+ void finishSession(Error::Type error);
+ void finishSession(std::shared_ptr<Swift::Error> error);
+
+ JID getRemoteJID() const {
+ return JID("", localJID.getDomain());
+ }
+
+ void sendStreamHeader();
+
+ void handleElement(std::shared_ptr<ToplevelElement>);
+ void handleStreamStart(const ProtocolHeader&);
+ void handleStreamEnd();
+ void handleStreamClosed(std::shared_ptr<Swift::Error>);
+ void handleStreamShutdownTimeout();
+
+ void handleTLSEncrypted();
+
+ bool checkState(State);
+ void continueSessionInitialization();
+
+ void requestAck();
+ void handleStanzaAcked(std::shared_ptr<Stanza> stanza);
+ void ack(unsigned int handledStanzasCount);
+ void continueAfterTLSEncrypted();
+ void checkTrustOrFinish(const std::vector<Certificate::ref>& certificateChain, std::shared_ptr<CertificateVerificationError> error);
+ void initiateShutdown(bool sendFooter);
+
+ private:
+ JID localJID;
+ State state;
+ std::shared_ptr<SessionStream> stream;
+ IDNConverter* idnConverter = nullptr;
+ CryptoProvider* crypto = nullptr;
+ TimerFactory* timerFactory = nullptr;
+ std::shared_ptr<Timer> streamShutdownTimeout;
+ int sessionShutdownTimeoutInMilliseconds = 10000;
+ bool allowPLAINOverNonTLS;
+ bool useStreamCompression;
+ UseTLS useTLS;
+ bool useAcks;
+ bool needSessionStart;
+ bool needResourceBind;
+ bool needAcking;
+ bool rosterVersioningSupported;
+ ClientAuthenticator* authenticator;
+ std::shared_ptr<StanzaAckRequester> stanzaAckRequester_;
+ std::shared_ptr<StanzaAckResponder> stanzaAckResponder_;
+ std::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..f48b306 100644
--- a/Swiften/Client/ClientSessionStanzaChannel.cpp
+++ b/Swiften/Client/ClientSessionStanzaChannel.cpp
@@ -1,112 +1,112 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Client/ClientSessionStanzaChannel.h>
-#include <iostream>
-
#include <boost/bind.hpp>
+#include <Swiften/Base/Log.h>
+
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));
+void ClientSessionStanzaChannel::setSession(std::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));
}
-void ClientSessionStanzaChannel::sendIQ(boost::shared_ptr<IQ> iq) {
- send(iq);
+void ClientSessionStanzaChannel::sendIQ(std::shared_ptr<IQ> iq) {
+ send(iq);
}
-void ClientSessionStanzaChannel::sendMessage(boost::shared_ptr<Message> message) {
- send(message);
+void ClientSessionStanzaChannel::sendMessage(std::shared_ptr<Message> message) {
+ send(message);
}
-void ClientSessionStanzaChannel::sendPresence(boost::shared_ptr<Presence> presence) {
- send(presence);
+void ClientSessionStanzaChannel::sendPresence(std::shared_ptr<Presence> 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);
+void ClientSessionStanzaChannel::send(std::shared_ptr<Stanza> stanza) {
+ if (!isAvailable()) {
+ SWIFT_LOG(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();
+void ClientSessionStanzaChannel::handleSessionFinished(std::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();
- 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;
- }
+void ClientSessionStanzaChannel::handleStanza(std::shared_ptr<Stanza> stanza) {
+ std::shared_ptr<Message> message = std::dynamic_pointer_cast<Message>(stanza);
+ if (message) {
+ onMessageReceived(message);
+ return;
+ }
+
+ std::shared_ptr<Presence> presence = std::dynamic_pointer_cast<Presence>(stanza);
+ if (presence) {
+ onPresenceReceived(presence);
+ return;
+ }
+
+ std::shared_ptr<IQ> iq = std::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);
+void ClientSessionStanzaChannel::handleStanzaAcked(std::shared_ptr<Stanza> stanza) {
+ onStanzaAcked(stanza);
}
void ClientSessionStanzaChannel::handleSessionInitialized() {
- onAvailableChanged(true);
+ onAvailableChanged(true);
}
}
diff --git a/Swiften/Client/ClientSessionStanzaChannel.h b/Swiften/Client/ClientSessionStanzaChannel.h
index 0ffcd9d..c4ee393 100644
--- a/Swiften/Client/ClientSessionStanzaChannel.h
+++ b/Swiften/Client/ClientSessionStanzaChannel.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Base/IDGenerator.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(std::shared_ptr<ClientSession> session);
+
+ void sendIQ(std::shared_ptr<IQ> iq);
+ void sendMessage(std::shared_ptr<Message> message);
+ void sendPresence(std::shared_ptr<Presence> presence);
+ bool getStreamManagementEnabled() const;
+ virtual std::vector<Certificate::ref> getPeerCertificateChain() const;
+
+ bool isAvailable() const {
+ return session && session->getState() == ClientSession::State::Initialized;
+ }
+
+ private:
+ std::string getNewIQID();
+ void send(std::shared_ptr<Stanza> stanza);
+ void handleSessionFinished(std::shared_ptr<Error> error);
+ void handleStanza(std::shared_ptr<Stanza> stanza);
+ void handleStanzaAcked(std::shared_ptr<Stanza> stanza);
+ void handleSessionInitialized();
+
+ private:
+ IDGenerator idGenerator;
+ std::shared_ptr<ClientSession> session;
+ };
}
diff --git a/Swiften/Client/ClientXMLTracer.cpp b/Swiften/Client/ClientXMLTracer.cpp
index e197042..4852aa1 100644
--- a/Swiften/Client/ClientXMLTracer.cpp
+++ b/Swiften/Client/ClientXMLTracer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,6 +7,7 @@
#include <Swiften/Client/ClientXMLTracer.h>
#include <iostream>
+
#include <boost/bind.hpp>
#include <Swiften/Base/Platform.h>
@@ -15,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 2275487..ad28fe2 100644
--- a/Swiften/Client/ClientXMLTracer.h
+++ b/Swiften/Client/ClientXMLTracer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,24 +7,24 @@
#pragma once
#include <Swiften/Base/API.h>
+#include <Swiften/Base/SafeByteArray.h>
#include <Swiften/Client/CoreClient.h>
#include <Swiften/Client/XMLBeautifier.h>
-#include <Swiften/Base/SafeByteArray.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::signals2::scoped_connection onDataReadConnection;
+ boost::signals2::scoped_connection onDataWrittenConnection;
+ };
}
diff --git a/Swiften/Client/CoreClient.cpp b/Swiften/Client/CoreClient.cpp
index 6fc491c..3c7902e 100644
--- a/Swiften/Client/CoreClient.cpp
+++ b/Swiften/Client/CoreClient.cpp
@@ -1,19 +1,19 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Client/CoreClient.h>
+#include <memory>
+
#include <boost/bind.hpp>
#include <boost/optional.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/Algorithm.h>
#include <Swiften/Base/IDGenerator.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/ClientSession.h>
#include <Swiften/Client/ClientSessionStanzaChannel.h>
#include <Swiften/Network/ChainedConnector.h>
@@ -31,449 +31,453 @@
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));
+CoreClient::CoreClient(const JID& jid, const SafeByteArray& password, NetworkFactories* networkFactories) : jid_(jid), password_(password), networkFactories(networkFactories), disconnectRequested_(false), certificateTrustChecker(nullptr) {
+ stanzaChannel_ = new ClientSessionStanzaChannel();
+ stanzaChannel_->onMessageReceived.connect(boost::bind(&CoreClient::handleMessageReceived, this, _1));
+ stanzaChannel_->onPresenceReceived.connect(boost::bind(&CoreClient::handlePresenceReceived, this, _1));
+ stanzaChannel_->onStanzaAcked.connect(boost::bind(&CoreClient::handleStanzaAcked, this, _1));
+ stanzaChannel_->onAvailableChanged.connect(boost::bind(&CoreClient::handleStanzaChannelAvailableChanged, this, _1));
- iqRouter_ = new IQRouter(stanzaChannel_);
- iqRouter_->setJID(jid);
+ 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_ = std::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.
+ */
+ std::shared_ptr<BOSHSessionStream> boshSessionStream_ = std::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(), networkFactories->getTimerFactory());
+ session_->setCertificateTrustChecker(certificateTrustChecker);
+ session_->setUseStreamCompression(options.useStreamCompression);
+ session_->setAllowPLAINOverNonTLS(options.allowPLAINWithoutTLS);
+ session_->setSingleSignOn(options.singleSignOn);
+ session_->setAuthenticationPort(options.manualPort);
+ session_->setSessionShutdownTimeout(options.sessionShutdownTimeoutInMilliseconds);
+ 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();
- }
+void CoreClient::handleConnectorFinished(std::shared_ptr<Connection> connection, std::shared_ptr<Error> error) {
+ resetConnector();
+ if (!connection) {
+ if (options.forgetPassword) {
+ purgePassword();
+ }
+ boost::optional<ClientError> clientError;
+ if (!disconnectRequested_) {
+ clientError = std::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_ = std::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);
+void CoreClient::handleSessionFinished(std::shared_ptr<Error> error) {
+ if (options.forgetPassword) {
+ purgePassword();
+ }
+ resetSession();
+
+ boost::optional<ClientError> actualError;
+ if (error) {
+ ClientError clientError;
+ if (std::shared_ptr<ClientSession::Error> actualError = std::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;
+ case ClientSession::Error::StreamEndError:
+ clientError = ClientError(ClientError::StreamError);
+ break;
+ }
+ clientError.setErrorCode(actualError->errorCode);
+ }
+ else if (std::shared_ptr<TLSError> actualError = std::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 (std::shared_ptr<SessionStream::SessionStreamError> actualError = std::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 (std::shared_ptr<CertificateVerificationError> verificationError = std::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);
+void CoreClient::sendMessage(std::shared_ptr<Message> message) {
+ stanzaChannel_->sendMessage(message);
}
-void CoreClient::sendPresence(boost::shared_ptr<Presence> presence) {
- stanzaChannel_->sendPresence(presence);
+void CoreClient::sendPresence(std::shared_ptr<Presence> 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();
+ for (auto f : proxyConnectionFactories) {
+ delete f;
+ }
+ proxyConnectionFactories.clear();
}
void CoreClient::resetSession() {
- session_->onFinished.disconnect(boost::bind(&CoreClient::handleSessionFinished, this, _1));
- session_->onNeedCredentials.disconnect(boost::bind(&CoreClient::handleNeedCredentials, this));
-
- sessionStream_->onDataRead.disconnect(boost::bind(&CoreClient::handleDataRead, this, _1));
- sessionStream_->onDataWritten.disconnect(boost::bind(&CoreClient::handleDataWritten, this, _1));
-
- if (connection_) {
- connection_->disconnect();
- }
- else if (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 (std::dynamic_pointer_cast<BOSHSessionStream>(sessionStream_)) {
+ sessionStream_->close();
+ }
+ sessionStream_.reset();
+ connection_.reset();
}
void CoreClient::forceReset() {
- if (connector_) {
- SWIFT_LOG(warning) << "Client not disconnected properly: Connector still active" << std::endl;
- resetConnector();
- }
- if (sessionStream_ || connection_) {
- SWIFT_LOG(warning) << "Client not disconnected properly: Session still active" << std::endl;
- resetSession();
- }
+ 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..27031c0 100644
--- a/Swiften/Client/CoreClient.h
+++ b/Swiften/Client/CoreClient.h
@@ -6,13 +6,13 @@
#pragma once
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/SafeByteArray.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Client/ClientError.h>
#include <Swiften/Client/ClientOptions.h>
#include <Swiften/Entity/Entity.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(std::shared_ptr<Message>);
+
+ /**
+ * Sends a presence stanza.
+ */
+ void sendPresence(std::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::signals2::signal<void (const boost::optional<ClientError>&)> onDisconnected;
+
+ /**
+ * Emitted when the client is connected and authenticated,
+ * and stanzas can be sent.
+ */
+ boost::signals2::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::signals2::signal<void (const SafeByteArray&)> onDataRead;
+
+ /**
+ * Emitted when the client sends data.
+ *
+ * This signal is emitted after the XML was serialized, and
+ * is unformatted.
+ */
+ boost::signals2::signal<void (const SafeByteArray&)> onDataWritten;
+
+ /**
+ * Emitted when a message is received.
+ */
+ boost::signals2::signal<void (std::shared_ptr<Message>)> onMessageReceived;
+
+ /**
+ * Emitted when a presence stanza is received.
+ */
+ boost::signals2::signal<void (std::shared_ptr<Presence>) > onPresenceReceived;
+
+ /**
+ * Emitted when the server acknowledges receipt of a
+ * stanza (if acknowledgements are available).
+ *
+ * \see getStreamManagementEnabled()
+ */
+ boost::signals2::signal<void (std::shared_ptr<Stanza>)> onStanzaAcked;
+
+ protected:
+ std::shared_ptr<ClientSession> getSession() const {
+ return session_;
+ }
+
+ NetworkFactories* getNetworkFactories() const {
+ return networkFactories;
+ }
+
+ /**
+ * Called before onConnected signal is emmitted.
+ */
+ virtual void handleConnected() {}
+
+ private:
+ void handleConnectorFinished(std::shared_ptr<Connection>, std::shared_ptr<Error> error);
+ void handleStanzaChannelAvailableChanged(bool available);
+ void handleSessionFinished(std::shared_ptr<Error>);
+ void handleNeedCredentials();
+ void handleDataRead(const SafeByteArray&);
+ void handleDataWritten(const SafeByteArray&);
+ void handlePresenceReceived(std::shared_ptr<Presence>);
+ void handleMessageReceived(std::shared_ptr<Message>);
+ void handleStanzaAcked(std::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;
+ std::shared_ptr<ChainedConnector> connector_;
+ std::vector<ConnectionFactory*> proxyConnectionFactories;
+ std::shared_ptr<Connection> connection_;
+ std::shared_ptr<SessionStream> sessionStream_;
+ std::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..fc2f05b 100644
--- a/Swiften/Client/DummyStanzaChannel.h
+++ b/Swiften/Client/DummyStanzaChannel.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -11,79 +11,89 @@
#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(std::shared_ptr<Stanza> stanza) {
+ sentStanzas.push_back(stanza);
+ }
+
+ void setAvailable(bool available) {
+ available_ = available;
+ onAvailableChanged(available);
+ }
+
+ virtual void sendIQ(std::shared_ptr<IQ> iq) {
+ sentStanzas.push_back(iq);
+ }
+
+ virtual void sendMessage(std::shared_ptr<Message> message) {
+ sentStanzas.push_back(message);
+ }
+
+ virtual void sendPresence(std::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;
+ }
+ std::shared_ptr<IQ> iqStanza = std::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;
+ }
+ std::shared_ptr<IQ> iqStanza = std::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;
+ }
+ std::shared_ptr<IQ> iqStanza = std::dynamic_pointer_cast<IQ>(sentStanzas[index]);
+ return iqStanza && iqStanza->getType() == IQ::Error && iqStanza->getID() == id;
+ }
+
+ template<typename T> std::shared_ptr<T> getStanzaAtIndex(size_t index) {
+ if (sentStanzas.size() <= index) {
+ return std::shared_ptr<T>();
+ }
+ return std::dynamic_pointer_cast<T>(sentStanzas[index]);
+ }
+
+ template<typename T> size_t countSentStanzaOfType() {
+ size_t count = 0;
+ for (auto& stanza : sentStanzas) {
+ if (std::dynamic_pointer_cast<T>(stanza)) {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ std::vector<Certificate::ref> getPeerCertificateChain() const {
+ return std::vector<Certificate::ref>();
+ }
+
+ std::vector<std::shared_ptr<Stanza> > sentStanzas;
+ bool available_;
+ };
}
diff --git a/Swiften/Client/MemoryStorages.cpp b/Swiften/Client/MemoryStorages.cpp
index 8825fa2..5e52799 100644
--- a/Swiften/Client/MemoryStorages.cpp
+++ b/Swiften/Client/MemoryStorages.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 = nullptr;
#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 nullptr;
#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 ffc147a..c5f0e58 100644
--- a/Swiften/Client/NickManager.h
+++ b/Swiften/Client/NickManager.h
@@ -1,23 +1,25 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <string>
+#include <boost/signals2.hpp>
+
+#include <Swiften/Base/API.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::signals2::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 249b44e..394d490 100644
--- a/Swiften/Client/NickResolver.cpp
+++ b/Swiften/Client/NickResolver.cpp
@@ -1,12 +1,13 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Client/NickResolver.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/bind.hpp>
#include <Swiften/MUC/MUCRegistry.h>
@@ -21,59 +22,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 (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);
- }
-
- return jid.toBare();
+ 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 (xmppRoster_->containsJID(jid) && !xmppRoster_->getNameForJID(jid).empty()) {
+ return xmppRoster_->getNameForJID(jid);
+ }
+
+ 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 4b6cc3e..a19c244 100644
--- a/Swiften/Client/NickResolver.h
+++ b/Swiften/Client/NickResolver.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,37 +7,38 @@
#pragma once
#include <map>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/VCard.h>
+#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::signals2::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 c7c0971..930bae1 100644
--- a/Swiften/Client/StanzaChannel.h
+++ b/Swiften/Client/StanzaChannel.h
@@ -1,32 +1,33 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/IQChannel.h>
#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Presence.h>
+#include <Swiften/Queries/IQChannel.h>
#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(std::shared_ptr<Message>) = 0;
+ virtual void sendPresence(std::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::signals2::signal<void (bool /* isAvailable */)> onAvailableChanged;
+ boost::signals2::signal<void (std::shared_ptr<Message>)> onMessageReceived;
+ boost::signals2::signal<void (std::shared_ptr<Presence>) > onPresenceReceived;
+ boost::signals2::signal<void (std::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..b2e45e2 100644
--- a/Swiften/Client/UnitTest/BlockListImplTest.cpp
+++ b/Swiften/Client/UnitTest/BlockListImplTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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_ = std::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:
+ std::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 dd6c95d..5d22cac 100644
--- a/Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp
+++ b/Swiften/Client/UnitTest/ClientBlockListManagerTest.cpp
@@ -4,186 +4,190 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
#include <algorithm>
-#include <Swiften/Base/foreach.h>
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Client/StanzaChannel.h>
-#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/Client/ClientBlockListManager.h>
-#include <Swiften/Queries/IQRouter.h>
+#include <Swiften/Client/DummyStanzaChannel.h>
+#include <Swiften/Client/StanzaChannel.h>
#include <Swiften/Elements/IQ.h>
+#include <Swiften/Queries/IQRouter.h>
using namespace Swift;
class ClientBlockListManagerTest : public CppUnit::TestFixture {
- CPPUNIT_TEST_SUITE(ClientBlockListManagerTest);
- CPPUNIT_TEST(testFetchBlockList);
- CPPUNIT_TEST(testBlockCommand);
- CPPUNIT_TEST(testUnblockCommand);
- CPPUNIT_TEST(testUnblockAllCommand);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- void setUp() {
- ownJID_ = JID("kev@wonderland.lit");
- stanzaChannel_ = new DummyStanzaChannel();
- iqRouter_ = new IQRouter(stanzaChannel_);
- iqRouter_->setJID(ownJID_);
- clientBlockListManager_ = new ClientBlockListManager(iqRouter_);
- }
-
- void testFetchBlockList() {
- std::vector<JID> blockJids;
- blockJids.push_back(JID("romeo@montague.net"));
- blockJids.push_back(JID("iago@shakespeare.lit"));
- helperInitialBlockListFetch(blockJids);
-
- 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() != nullptr);
+ std::shared_ptr<BlockPayload> blockPayload = request->getPayload<BlockPayload>();
+ CPPUNIT_ASSERT(blockPayload.get() != nullptr);
+ 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
+ std::shared_ptr<BlockPayload> pushPayload = std::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() != nullptr);
+ std::shared_ptr<UnblockPayload> unblockPayload = request->getPayload<UnblockPayload>();
+ CPPUNIT_ASSERT(unblockPayload.get() != nullptr);
+ 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
+ std::shared_ptr<UnblockPayload> pushPayload = std::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() != nullptr);
+ std::shared_ptr<UnblockPayload> unblockPayload = request->getPayload<UnblockPayload>();
+ CPPUNIT_ASSERT(unblockPayload.get() != nullptr);
+ 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
+ std::shared_ptr<UnblockPayload> pushPayload = std::make_shared<UnblockPayload>();
+ IQ::ref unblockPush = IQ::createRequest(IQ::Set, ownJID_, "push1", pushPayload);
+ stanzaChannel_->sendIQ(unblockPush);
+ stanzaChannel_->onIQReceived(unblockPush);
+
+ CPPUNIT_ASSERT_EQUAL(true, clientBlockListManager_->getBlockList()->getItems().empty());
+ }
+
+ void tearDown() {
+ delete clientBlockListManager_;
+ delete iqRouter_;
+ delete stanzaChannel_;
+ }
+
+ private:
+ void helperInitialBlockListFetch(const std::vector<JID>& blockedJids) {
+ std::shared_ptr<BlockList> blockList = clientBlockListManager_->requestBlockList();
+ CPPUNIT_ASSERT(blockList);
+
+ // check for IQ request
+ IQ::ref request = stanzaChannel_->getStanzaAtIndex<IQ>(0);
+ CPPUNIT_ASSERT(request.get() != nullptr);
+ std::shared_ptr<BlockListPayload> requestPayload = request->getPayload<BlockListPayload>();
+ CPPUNIT_ASSERT(requestPayload.get() != nullptr);
+
+ CPPUNIT_ASSERT_EQUAL(BlockList::Requesting, blockList->getState());
+ CPPUNIT_ASSERT_EQUAL(BlockList::Requesting, clientBlockListManager_->getBlockList()->getState());
+
+ // build IQ response
+ std::shared_ptr<BlockListPayload> responsePayload = std::make_shared<BlockListPayload>();
+ for (const auto& jid : blockedJids) {
+ responsePayload->addItem(jid);
+ }
+
+ IQ::ref response = IQ::createResult(ownJID_, JID(), request->getID(), responsePayload);
+ stanzaChannel_->sendIQ(response);
+ stanzaChannel_->onIQReceived(response);
+
+ CPPUNIT_ASSERT_EQUAL(BlockList::Available, clientBlockListManager_->getBlockList()->getState());
+ CPPUNIT_ASSERT(responsePayload->getItems() == clientBlockListManager_->getBlockList()->getItems());
+ }
+
+
+ private:
+ JID ownJID_;
+ IQRouter* iqRouter_;
+ DummyStanzaChannel* stanzaChannel_;
+ ClientBlockListManager* clientBlockListManager_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ClientBlockListManagerTest);
diff --git a/Swiften/Client/UnitTest/ClientSessionTest.cpp b/Swiften/Client/UnitTest/ClientSessionTest.cpp
index 624bac5..44df961 100644
--- a/Swiften/Client/UnitTest/ClientSessionTest.cpp
+++ b/Swiften/Client/UnitTest/ClientSessionTest.cpp
@@ -1,827 +1,908 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
#include <deque>
+#include <memory>
+
#include <boost/bind.hpp>
#include <boost/optional.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/IDN/IDNConverter.h>
-#include <Swiften/IDN/PlatformIDNConverter.h>
-#include <Swiften/Session/SessionStream.h>
+#include <Swiften/Base/Debug.h>
+
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
#include <Swiften/Client/ClientSession.h>
-#include <Swiften/Elements/Message.h>
+#include <Swiften/Crypto/CryptoProvider.h>
+#include <Swiften/Crypto/PlatformCryptoProvider.h>
#include <Swiften/Elements/AuthChallenge.h>
-#include <Swiften/Elements/StartTLSRequest.h>
-#include <Swiften/Elements/StreamFeatures.h>
-#include <Swiften/Elements/StreamError.h>
-#include <Swiften/Elements/TLSProceed.h>
-#include <Swiften/Elements/StartTLSFailure.h>
+#include <Swiften/Elements/AuthFailure.h>
#include <Swiften/Elements/AuthRequest.h>
#include <Swiften/Elements/AuthSuccess.h>
-#include <Swiften/Elements/AuthFailure.h>
-#include <Swiften/Elements/StreamManagementEnabled.h>
-#include <Swiften/Elements/StreamManagementFailed.h>
-#include <Swiften/Elements/StanzaAck.h>
#include <Swiften/Elements/EnableStreamManagement.h>
#include <Swiften/Elements/IQ.h>
+#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/ResourceBind.h>
-#include <Swiften/TLS/SimpleCertificate.h>
+#include <Swiften/Elements/StanzaAck.h>
+#include <Swiften/Elements/StartTLSFailure.h>
+#include <Swiften/Elements/StartTLSRequest.h>
+#include <Swiften/Elements/StreamError.h>
+#include <Swiften/Elements/StreamFeatures.h>
+#include <Swiften/Elements/StreamManagementEnabled.h>
+#include <Swiften/Elements/StreamManagementFailed.h>
+#include <Swiften/Elements/TLSProceed.h>
+#include <Swiften/IDN/IDNConverter.h>
+#include <Swiften/IDN/PlatformIDNConverter.h>
+#include <Swiften/Network/DummyTimerFactory.h>
+#include <Swiften/Session/SessionStream.h>
#include <Swiften/TLS/BlindCertificateTrustChecker.h>
-#include <Swiften/Crypto/CryptoProvider.h>
-#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/TLS/SimpleCertificate.h>
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(testServerInitiatedSessionClose);
+ CPPUNIT_TEST(testClientInitiatedSessionClose);
+ CPPUNIT_TEST(testTimeoutOnShutdown);
+
+ /*
+ 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 = std::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ idnConverter = std::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
+ timerFactory = std::make_shared<DummyTimerFactory>();
+ server = std::make_shared<MockSessionStream>();
+ sessionFinishedReceived = false;
+ needCredentials = false;
+ blindCertificateTrustChecker = new BlindCertificateTrustChecker();
+ }
+
+ void tearDown() {
+ delete blindCertificateTrustChecker;
+ }
+
+ void testStart_Error() {
+ std::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->breakConnection();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testStart_StreamError() {
+ std::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->sendStreamStart();
+ server->sendStreamError();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finishing, session->getState());
+ CPPUNIT_ASSERT_EQUAL(true, server->receivedEvents.back().footer);
+
+ server->onStreamEndReceived();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testStartTLS() {
+ std::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() {
+ std::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::State::Finishing, session->getState());
+ CPPUNIT_ASSERT_EQUAL(true, server->receivedEvents.back().footer);
+
+ server->onStreamEndReceived();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testStartTLS_ConnectError() {
+ std::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithStartTLS();
+ server->receiveStartTLS();
+ server->sendTLSProceed();
+ server->breakTLS();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testStartTLS_InvalidIdentity() {
+ std::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();
+ server->close();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finished, session->getState());
+
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ CPPUNIT_ASSERT(std::dynamic_pointer_cast<CertificateVerificationError>(sessionFinishedError));
+ CPPUNIT_ASSERT_EQUAL(CertificateVerificationError::InvalidServerIdentity, std::dynamic_pointer_cast<CertificateVerificationError>(sessionFinishedError)->getType());
+ }
+
+ void testStart_StreamFeaturesWithoutResourceBindingFails() {
+ std::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendEmptyStreamFeatures();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finishing, session->getState());
+ CPPUNIT_ASSERT_EQUAL(true, server->receivedEvents.back().footer);
+
+ server->onStreamEndReceived();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testAuthenticate() {
+ std::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithPLAINAuthentication();
+ CPPUNIT_ASSERT(needCredentials);
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::WaitingForCredentials, session->getState());
+ session->sendCredentials(createSafeByteArray("mypass"));
+ server->receiveAuthRequest("PLAIN");
+ server->sendAuthSuccess();
+ server->receiveStreamStart();
+
+ session->finish();
+ }
+
+ void testAuthenticate_Unauthorized() {
+ std::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithPLAINAuthentication();
+ CPPUNIT_ASSERT(needCredentials);
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::WaitingForCredentials, session->getState());
+ session->sendCredentials(createSafeByteArray("mypass"));
+ server->receiveAuthRequest("PLAIN");
+ server->sendAuthFailure();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finishing, session->getState());
+ CPPUNIT_ASSERT_EQUAL(true, server->receivedEvents.back().footer);
+
+ server->onStreamEndReceived();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testAuthenticate_PLAINOverNonTLS() {
+ std::shared_ptr<ClientSession> session(createSession());
+ session->setAllowPLAINOverNonTLS(false);
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithPLAINAuthentication();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finishing, session->getState());
+ CPPUNIT_ASSERT_EQUAL(true, server->receivedEvents.back().footer);
+
+ server->onStreamEndReceived();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testAuthenticate_RequireTLS() {
+ std::shared_ptr<ClientSession> session(createSession());
+ session->setUseTLS(ClientSession::RequireTLS);
+ session->setAllowPLAINOverNonTLS(true);
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithMultipleAuthentication();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finishing, session->getState());
+ CPPUNIT_ASSERT_EQUAL(true, server->receivedEvents.back().footer);
+
+ server->onStreamEndReceived();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testAuthenticate_NoValidAuthMechanisms() {
+ std::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithUnknownAuthentication();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finishing, session->getState());
+ CPPUNIT_ASSERT_EQUAL(true, server->receivedEvents.back().footer);
+
+ server->onStreamEndReceived();
+ server->close();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testAuthenticate_EXTERNAL() {
+ std::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithEXTERNALAuthentication();
+ server->receiveAuthRequest("EXTERNAL");
+ server->sendAuthSuccess();
+ server->receiveStreamStart();
+
+ session->finish();
+ }
+
+ void testUnexpectedChallenge() {
+ std::shared_ptr<ClientSession> session(createSession());
+ session->start();
+ server->receiveStreamStart();
+ server->sendStreamStart();
+ server->sendStreamFeaturesWithEXTERNALAuthentication();
+ server->receiveAuthRequest("EXTERNAL");
+ server->sendChallenge();
+ server->sendChallenge();
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finishing, session->getState());
+ CPPUNIT_ASSERT_EQUAL(true, server->receivedEvents.back().footer);
+
+ server->onStreamEndReceived();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ CPPUNIT_ASSERT(sessionFinishedError);
+ }
+
+ void testStreamManagement() {
+ std::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::State::Initialized, session->getState());
+
+ session->finish();
+ }
+
+ void testStreamManagement_Failed() {
+ std::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::State::Initialized, session->getState());
+
+ session->finish();
+ }
+
+ void testFinishAcksStanzas() {
+ std::shared_ptr<ClientSession> session(createSession());
+ initializeSession(session);
+ server->sendMessage();
+ server->sendMessage();
+ server->sendMessage();
+
+ session->finish();
+
+ server->receiveAck(3);
+ }
+
+ void testServerInitiatedSessionClose() {
+ std::shared_ptr<ClientSession> session(createSession());
+ initializeSession(session);
+
+ server->onStreamEndReceived();
+ server->close();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finished, session->getState());
+ CPPUNIT_ASSERT_EQUAL(true, server->receivedEvents.back().footer);
+ }
+
+ void testClientInitiatedSessionClose() {
+ std::shared_ptr<ClientSession> session(createSession());
+ initializeSession(session);
+
+ session->finish();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finishing, session->getState());
+ CPPUNIT_ASSERT_EQUAL(true, server->receivedEvents.back().footer);
+
+ server->onStreamEndReceived();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finished, session->getState());
+ }
+
+ void testTimeoutOnShutdown() {
+ std::shared_ptr<ClientSession> session(createSession());
+ initializeSession(session);
+
+ session->finish();
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finishing, session->getState());
+ CPPUNIT_ASSERT_EQUAL(true, server->receivedEvents.back().footer);
+ timerFactory->setTime(60000);
+
+ CPPUNIT_ASSERT_EQUAL(ClientSession::State::Finished, session->getState());
+ CPPUNIT_ASSERT(sessionFinishedReceived);
+ }
+
+ private:
+ std::shared_ptr<ClientSession> createSession() {
+ std::shared_ptr<ClientSession> session = ClientSession::create(JID("me@foo.com"), server, idnConverter.get(), crypto.get(), timerFactory.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(std::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(std::shared_ptr<Error> error) {
+ sessionFinishedReceived = true;
+ sessionFinishedError = error;
+ }
+
+ void handleSessionNeedCredentials() {
+ needCredentials = true;
+ }
+
+ class MockSessionStream : public SessionStream {
+ public:
+ struct Event {
+ Event(std::shared_ptr<ToplevelElement> element) : element(element), footer(false) {}
+ Event(const ProtocolHeader& header) : header(header), footer(false) {}
+ Event() : footer(true) {}
+
+ std::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(std::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(std::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 std::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const {
+ return std::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(std::make_shared<SessionStream::SessionStreamError>(SessionStream::SessionStreamError::ConnectionReadError));
+ }
+
+ void breakTLS() {
+ onClosed(std::make_shared<SessionStream::SessionStreamError>(SessionStream::SessionStreamError::TLSError));
+ }
+
+
+ void sendStreamStart() {
+ ProtocolHeader header;
+ header.setTo("foo.com");
+ return onStreamStartReceived(header);
+ }
+
+ void sendStreamFeaturesWithStartTLS() {
+ std::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
+ streamFeatures->setHasStartTLS();
+ onElementReceived(streamFeatures);
+ }
+
+ void sendChallenge() {
+ onElementReceived(std::make_shared<AuthChallenge>());
+ }
+
+ void sendStreamError() {
+ onElementReceived(std::make_shared<StreamError>());
+ }
+
+ void sendTLSProceed() {
+ onElementReceived(std::make_shared<TLSProceed>());
+ }
+
+ void sendTLSFailure() {
+ onElementReceived(std::make_shared<StartTLSFailure>());
+ }
+
+ void sendStreamFeaturesWithMultipleAuthentication() {
+ std::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
+ streamFeatures->addAuthenticationMechanism("PLAIN");
+ streamFeatures->addAuthenticationMechanism("DIGEST-MD5");
+ streamFeatures->addAuthenticationMechanism("SCRAM-SHA1");
+ onElementReceived(streamFeatures);
+ }
+
+ void sendStreamFeaturesWithPLAINAuthentication() {
+ std::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
+ streamFeatures->addAuthenticationMechanism("PLAIN");
+ onElementReceived(streamFeatures);
+ }
+
+ void sendStreamFeaturesWithEXTERNALAuthentication() {
+ std::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
+ streamFeatures->addAuthenticationMechanism("EXTERNAL");
+ onElementReceived(streamFeatures);
+ }
+
+ void sendStreamFeaturesWithUnknownAuthentication() {
+ std::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
+ streamFeatures->addAuthenticationMechanism("UNKNOWN");
+ onElementReceived(streamFeatures);
+ }
+
+ void sendStreamFeaturesWithBindAndStreamManagement() {
+ std::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
+ streamFeatures->setHasResourceBind();
+ streamFeatures->setHasStreamManagement();
+ onElementReceived(streamFeatures);
+ }
+
+ void sendEmptyStreamFeatures() {
+ onElementReceived(std::make_shared<StreamFeatures>());
+ }
+
+ void sendAuthSuccess() {
+ onElementReceived(std::make_shared<AuthSuccess>());
+ }
+
+ void sendAuthFailure() {
+ onElementReceived(std::make_shared<AuthFailure>());
+ }
+
+ void sendStreamManagementEnabled() {
+ onElementReceived(std::make_shared<StreamManagementEnabled>());
+ }
+
+ void sendStreamManagementFailed() {
+ onElementReceived(std::make_shared<StreamManagementFailed>());
+ }
+
+ void sendBindResult() {
+ std::shared_ptr<ResourceBind> resourceBind(new ResourceBind());
+ resourceBind->setJID(JID("foo@bar.com/bla"));
+ std::shared_ptr<IQ> iq = IQ::createResult(JID("foo@bar.com"), bindID, resourceBind);
+ onElementReceived(iq);
+ }
+
+ void sendMessage() {
+ std::shared_ptr<Message> message = std::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(std::dynamic_pointer_cast<StartTLSRequest>(event.element));
+ }
+
+ void receiveAuthRequest(const std::string& mech) {
+ Event event = popEvent();
+ CPPUNIT_ASSERT(event.element);
+ std::shared_ptr<AuthRequest> request(std::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(std::dynamic_pointer_cast<EnableStreamManagement>(event.element));
+ }
+
+ void receiveBind() {
+ Event event = popEvent();
+ CPPUNIT_ASSERT(event.element);
+ std::shared_ptr<IQ> iq = std::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);
+ std::shared_ptr<StanzaAck> ack = std::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;
+ };
+
+ std::shared_ptr<IDNConverter> idnConverter;
+ std::shared_ptr<MockSessionStream> server;
+ bool sessionFinishedReceived;
+ bool needCredentials;
+ std::shared_ptr<Error> sessionFinishedError;
+ BlindCertificateTrustChecker* blindCertificateTrustChecker;
+ std::shared_ptr<CryptoProvider> crypto;
+ std::shared_ptr<DummyTimerFactory> timerFactory;
};
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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeatures();
+ session->startSession();
+ processEvents();
+ CPPUNIT_ASSERT(session->getWhitespacePingLayer());
+ }
+
+ void testReceiveElementAfterSessionStarted() {
+ std::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
+ getMockServer()->expectStreamStart();
+ getMockServer()->sendStreamStart();
+ getMockServer()->sendStreamFeatures();
+ session->startSession();
+ processEvents();
+
+ getMockServer()->expectMessage();
+ session->sendElement(std::make_shared<Message>()));
+ }
+
+ void testSendElement() {
+ std::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(std::dynamic_pointer_cast<Message>(receivedElements_[0]));
+ }
#endif
diff --git a/Swiften/Client/UnitTest/NickResolverTest.cpp b/Swiften/Client/UnitTest/NickResolverTest.cpp
index 20ec35f..2846173 100644
--- a/Swiften/Client/UnitTest/NickResolverTest.cpp
+++ b/Swiften/Client/UnitTest/NickResolverTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All right reserved.
* See the COPYING file for more information.
*/
@@ -7,147 +7,147 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/Client/NickResolver.h>
+#include <Swiften/Crypto/CryptoProvider.h>
+#include <Swiften/Crypto/PlatformCryptoProvider.h>
#include <Swiften/MUC/MUCRegistry.h>
+#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Roster/XMPPRosterImpl.h>
#include <Swiften/VCards/VCardManager.h>
#include <Swiften/VCards/VCardMemoryStorage.h>
-#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/Client/DummyStanzaChannel.h>
-#include <Swiften/Crypto/CryptoProvider.h>
-#include <Swiften/Crypto/PlatformCryptoProvider.h>
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 = std::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_;
+ std::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(NickResolverTest);
diff --git a/Swiften/Client/XMLBeautifier.cpp b/Swiften/Client/XMLBeautifier.cpp
index 95970cb..e2cd58e 100644
--- a/Swiften/Client/XMLBeautifier.cpp
+++ b/Swiften/Client/XMLBeautifier.cpp
@@ -5,42 +5,42 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swiften/Client/XMLBeautifier.h>
+
#include <sstream>
#include <stack>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Client/XMLBeautifier.h>
#include <Swiften/Parser/PlatformXMLParserFactory.h>
namespace Swift {
-XMLBeautifier::XMLBeautifier(bool indention, bool coloring) : doIndention(indention), doColoring(coloring), intLevel(0), parser(NULL), lastWasStepDown(false) {
- factory = new PlatformXMLParserFactory();
+XMLBeautifier::XMLBeautifier(bool indention, bool coloring) : doIndention(indention), doColoring(coloring), intLevel(0), parser(nullptr), lastWasStepDown(false) {
+ 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
@@ -55,78 +55,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()) {
+ for (const auto& entry : attributes.getEntries()) {
+ buffer << " ";
+ buffer << (doColoring ? styleAttribute(entry.getAttribute().getName()) : entry.getAttribute().getName());
+ buffer << "=";
+ buffer << "\"" << (doColoring ? styleValue(entry.getValue()) : entry.getValue()) << "\"";
+ }
+ }
+ buffer << ">";
+ ++intLevel;
+ lastWasStepDown = false;
+ parentNSs.push(ns);
}
void XMLBeautifier::handleEndElement(const std::string& element, const std::string& /* ns */) {
- --intLevel;
- parentNSs.pop();
- if (/*hadCDATA.top() ||*/ lastWasStepDown) {
- if (doIndention) {
- buffer << std::endl;
- }
- indent();
- }
- buffer << "</" << (doColoring ? styleTag(element) : element) << ">";
- lastWasStepDown = true;
+ --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 f8dccc5..8da935a 100644
--- a/Swiften/Client/XMLBeautifier.h
+++ b/Swiften/Client/XMLBeautifier.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,49 +13,50 @@
#pragma once
#include <sstream>
-#include <string>
#include <stack>
+#include <string>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/Parser/XMLParserFactory.h>
-#include <Swiften/Parser/XMLParserClient.h>
#include <Swiften/Parser/XMLParser.h>
+#include <Swiften/Parser/XMLParserClient.h>
+#include <Swiften/Parser/XMLParserFactory.h>
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 9d8b5d3..a7ef621 100644
--- a/Swiften/Component/Component.h
+++ b/Swiften/Component/Component.h
@@ -6,32 +6,31 @@
#pragma once
-#include <Swiften/Component/CoreComponent.h>
-
#include <Swiften/Base/API.h>
+#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 072fd73..a7375a7 100644
--- a/Swiften/Component/ComponentConnector.cpp
+++ b/Swiften/Component/ComponentConnector.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,11 +7,10 @@
#include <Swiften/Component/ComponentConnector.h>
#include <boost/bind.hpp>
-#include <iostream>
#include <Swiften/Network/ConnectionFactory.h>
-#include <Swiften/Network/DomainNameResolver.h>
#include <Swiften/Network/DomainNameAddressQuery.h>
+#include <Swiften/Network/DomainNameResolver.h>
#include <Swiften/Network/TimerFactory.h>
namespace Swift {
@@ -20,88 +19,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(std::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(std::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(std::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);
+void ComponentConnector::finish(std::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);
}
void ComponentConnector::handleTimeout() {
- finish(boost::shared_ptr<Connection>());
+ finish(std::shared_ptr<Connection>());
}
}
diff --git a/Swiften/Component/ComponentConnector.h b/Swiften/Component/ComponentConnector.h
index e5acdb0..ab36901 100644
--- a/Swiften/Component/ComponentConnector.h
+++ b/Swiften/Component/ComponentConnector.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,59 +7,60 @@
#pragma once
#include <deque>
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <string>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Network/Connection.h>
-#include <Swiften/Network/Timer.h>
-#include <Swiften/Network/HostAddressPort.h>
-#include <string>
#include <Swiften/Network/DomainNameResolveError.h>
+#include <Swiften/Network/HostAddressPort.h>
+#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::signals2::trackable, public std::enable_shared_from_this<ComponentConnector> {
+ public:
+ typedef std::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::signals2::signal<void (std::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(std::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;
+ std::shared_ptr<Timer> timer;
+ std::shared_ptr<DomainNameAddressQuery> addressQuery;
+ std::deque<HostAddress> addressQueryResults;
+ std::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 8914686..647b3da 100644
--- a/Swiften/Component/ComponentHandshakeGenerator.cpp
+++ b/Swiften/Component/ComponentHandshakeGenerator.cpp
@@ -1,24 +1,25 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Component/ComponentHandshakeGenerator.h>
-#include <Swiften/StringCodecs/Hexify.h>
+
#include <Swiften/Base/String.h>
#include <Swiften/Crypto/CryptoProvider.h>
+#include <Swiften/StringCodecs/Hexify.h>
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 d69790f..0805ac1 100644
--- a/Swiften/Component/ComponentSession.cpp
+++ b/Swiften/Component/ComponentSession.cpp
@@ -1,122 +1,123 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Component/ComponentSession.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <Swiften/Component/ComponentHandshakeGenerator.h>
+#include <Swiften/Elements/ComponentHandshake.h>
#include <Swiften/Elements/ProtocolHeader.h>
#include <Swiften/Elements/StreamFeatures.h>
-#include <Swiften/Elements/ComponentHandshake.h>
#include <Swiften/Session/SessionStream.h>
-#include <Swiften/Component/ComponentHandshakeGenerator.h>
namespace Swift {
-ComponentSession::ComponentSession(const JID& jid, const std::string& secret, boost::shared_ptr<SessionStream> stream, CryptoProvider* crypto) : jid(jid), secret(secret), stream(stream), crypto(crypto), state(Initial) {
+ComponentSession::ComponentSession(const JID& jid, const std::string& secret, std::shared_ptr<SessionStream> stream, CryptoProvider* crypto) : jid(jid), secret(secret), stream(stream), crypto(crypto), state(Initial) {
}
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);
+void ComponentSession::sendStanza(std::shared_ptr<Stanza> 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);
- }
+void ComponentSession::handleElement(std::shared_ptr<ToplevelElement> element) {
+ if (std::shared_ptr<Stanza> stanza = std::dynamic_pointer_cast<Stanza>(element)) {
+ if (getState() == Initialized) {
+ onStanzaReceived(stanza);
+ }
+ else {
+ finishSession(Error::UnexpectedElementError);
+ }
+ }
+ else if (std::dynamic_pointer_cast<ComponentHandshake>(element)) {
+ if (!checkState(Authenticating)) {
+ return;
+ }
+ stream->setWhitespacePingEnabled(true);
+ state = Initialized;
+ onInitialized();
+ }
+ else if (getState() == Authenticating) {
+ if (std::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);
- }
+void ComponentSession::handleStreamClosed(std::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);
+ }
}
void ComponentSession::finish() {
- finishSession(boost::shared_ptr<Error>());
+ finishSession(std::shared_ptr<Error>());
}
void ComponentSession::finishSession(Error::Type error) {
- finishSession(boost::make_shared<Swift::ComponentSession::Error>(error));
+ finishSession(std::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();
+void ComponentSession::finishSession(std::shared_ptr<Swift::Error> finishError) {
+ state = Finishing;
+ error = finishError;
+ assert(stream->isOpen());
+ stream->writeFooter();
+ stream->close();
}
}
diff --git a/Swiften/Component/ComponentSession.h b/Swiften/Component/ComponentSession.h
index 0b8c55c..9d963a1 100644
--- a/Swiften/Component/ComponentSession.h
+++ b/Swiften/Component/ComponentSession.h
@@ -1,86 +1,86 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/enable_shared_from_this.hpp>
+#include <memory>
+#include <string>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Base/Error.h>
-#include <string>
-#include <Swiften/Elements/ToplevelElement.h>
#include <Swiften/Elements/Stanza.h>
+#include <Swiften/Elements/ToplevelElement.h>
+#include <Swiften/JID/JID.h>
#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 std::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 std::shared_ptr<ComponentSession> create(const JID& jid, const std::string& secret, std::shared_ptr<SessionStream> stream, CryptoProvider* crypto) {
+ return std::shared_ptr<ComponentSession>(new ComponentSession(jid, secret, stream, crypto));
+ }
+
+ State getState() const {
+ return state;
+ }
+
+ void start();
+ void finish();
+
+ void sendStanza(std::shared_ptr<Stanza>);
+
+ public:
+ boost::signals2::signal<void ()> onInitialized;
+ boost::signals2::signal<void (std::shared_ptr<Swift::Error>)> onFinished;
+ boost::signals2::signal<void (std::shared_ptr<Stanza>)> onStanzaReceived;
+
+ private:
+ ComponentSession(const JID& jid, const std::string& secret, std::shared_ptr<SessionStream>, CryptoProvider*);
+
+ void finishSession(Error::Type error);
+ void finishSession(std::shared_ptr<Swift::Error> error);
+
+ void sendStreamHeader();
+
+ void handleElement(std::shared_ptr<ToplevelElement>);
+ void handleStreamStart(const ProtocolHeader&);
+ void handleStreamClosed(std::shared_ptr<Swift::Error>);
+
+ bool checkState(State);
+
+ private:
+ JID jid;
+ std::string secret;
+ std::shared_ptr<SessionStream> stream;
+ CryptoProvider* crypto;
+ std::shared_ptr<Swift::Error> error;
+ State state;
+ };
}
diff --git a/Swiften/Component/ComponentSessionStanzaChannel.cpp b/Swiften/Component/ComponentSessionStanzaChannel.cpp
index fa58d4b..fd61594 100644
--- a/Swiften/Component/ComponentSessionStanzaChannel.cpp
+++ b/Swiften/Component/ComponentSessionStanzaChannel.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,73 +7,74 @@
#include <Swiften/Component/ComponentSessionStanzaChannel.h>
#include <boost/bind.hpp>
-#include <iostream>
+
+#include <Swiften/Base/Log.h>
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));
+void ComponentSessionStanzaChannel::setSession(std::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));
}
-void ComponentSessionStanzaChannel::sendIQ(boost::shared_ptr<IQ> iq) {
- send(iq);
+void ComponentSessionStanzaChannel::sendIQ(std::shared_ptr<IQ> iq) {
+ send(iq);
}
-void ComponentSessionStanzaChannel::sendMessage(boost::shared_ptr<Message> message) {
- send(message);
+void ComponentSessionStanzaChannel::sendMessage(std::shared_ptr<Message> message) {
+ send(message);
}
-void ComponentSessionStanzaChannel::sendPresence(boost::shared_ptr<Presence> presence) {
- send(presence);
+void ComponentSessionStanzaChannel::sendPresence(std::shared_ptr<Presence> 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);
+void ComponentSessionStanzaChannel::send(std::shared_ptr<Stanza> stanza) {
+ if (!isAvailable()) {
+ SWIFT_LOG(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();
+void ComponentSessionStanzaChannel::handleSessionFinished(std::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();
- 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;
- }
+void ComponentSessionStanzaChannel::handleStanza(std::shared_ptr<Stanza> stanza) {
+ std::shared_ptr<Message> message = std::dynamic_pointer_cast<Message>(stanza);
+ if (message) {
+ onMessageReceived(message);
+ return;
+ }
+
+ std::shared_ptr<Presence> presence = std::dynamic_pointer_cast<Presence>(stanza);
+ if (presence) {
+ onPresenceReceived(presence);
+ return;
+ }
+
+ std::shared_ptr<IQ> iq = std::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 f0f4abd..ad38edc 100644
--- a/Swiften/Component/ComponentSessionStanzaChannel.h
+++ b/Swiften/Component/ComponentSessionStanzaChannel.h
@@ -1,56 +1,56 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Base/IDGenerator.h>
-#include <Swiften/Component/ComponentSession.h>
#include <Swiften/Client/StanzaChannel.h>
-#include <Swiften/Elements/Message.h>
+#include <Swiften/Component/ComponentSession.h>
#include <Swiften/Elements/IQ.h>
+#include <Swiften/Elements/Message.h>
#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(std::shared_ptr<ComponentSession> session);
+
+ void sendIQ(std::shared_ptr<IQ> iq);
+ void sendMessage(std::shared_ptr<Message> message);
+ void sendPresence(std::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(std::shared_ptr<Stanza> stanza);
+ void handleSessionFinished(std::shared_ptr<Error> error);
+ void handleStanza(std::shared_ptr<Stanza> stanza);
+ void handleSessionInitialized();
+
+ private:
+ IDGenerator idGenerator;
+ std::shared_ptr<ComponentSession> session;
+ };
}
diff --git a/Swiften/Component/ComponentXMLTracer.cpp b/Swiften/Component/ComponentXMLTracer.cpp
index 8efc774..94d4ec2 100644
--- a/Swiften/Component/ComponentXMLTracer.cpp
+++ b/Swiften/Component/ComponentXMLTracer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,25 +7,26 @@
#include <Swiften/Component/ComponentXMLTracer.h>
#include <iostream>
+
#include <boost/bind.hpp>
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 358b0c6..3896bdd 100644
--- a/Swiften/Component/CoreComponent.cpp
+++ b/Swiften/Component/CoreComponent.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,9 +7,9 @@
#include <Swiften/Component/CoreComponent.h>
#include <boost/bind.hpp>
-#include <iostream>
#include <Swiften/Base/IDGenerator.h>
+#include <Swiften/Base/Log.h>
#include <Swiften/Component/ComponentSession.h>
#include <Swiften/Component/ComponentSessionStanzaChannel.h>
#include <Swiften/Network/Connector.h>
@@ -19,152 +19,151 @@
#include <Swiften/TLS/PKCS12Certificate.h>
#include <Swiften/TLS/TLSOptions.h>
-
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_) {
+ SWIFT_LOG(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();
- }
+void CoreComponent::handleConnectorFinished(std::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_ = std::make_shared<BasicSessionStream>(ComponentStreamType, connection_, getPayloadParserFactories(), getPayloadSerializers(), nullptr, 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);
- }
+void CoreComponent::handleSessionFinished(std::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 (std::shared_ptr<ComponentSession::Error> actualError = std::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 (std::shared_ptr<SessionStream::SessionStreamError> actualError = std::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);
+void CoreComponent::sendMessage(std::shared_ptr<Message> message) {
+ stanzaChannel_->sendMessage(message);
}
-void CoreComponent::sendPresence(boost::shared_ptr<Presence> presence) {
- stanzaChannel_->sendPresence(presence);
+void CoreComponent::sendPresence(std::shared_ptr<Presence> 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..669be97 100644
--- a/Swiften/Component/CoreComponent.h
+++ b/Swiften/Component/CoreComponent.h
@@ -6,14 +6,14 @@
#pragma once
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/Error.h>
#include <Swiften/Base/SafeByteArray.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Component/ComponentConnector.h>
#include <Swiften/Component/ComponentError.h>
#include <Swiften/Component/ComponentSession.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(std::shared_ptr<Message>);
+ void sendPresence(std::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::signals2::signal<void (const ComponentError&)> onError;
+ boost::signals2::signal<void ()> onConnected;
+ boost::signals2::signal<void (const SafeByteArray&)> onDataRead;
+ boost::signals2::signal<void (const SafeByteArray&)> onDataWritten;
+
+ boost::signals2::signal<void (std::shared_ptr<Message>)> onMessageReceived;
+ boost::signals2::signal<void (std::shared_ptr<Presence>) > onPresenceReceived;
+
+ private:
+ void handleConnectorFinished(std::shared_ptr<Connection>);
+ void handleStanzaChannelAvailableChanged(bool available);
+ void handleSessionFinished(std::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_;
+ std::shared_ptr<Connection> connection_;
+ std::shared_ptr<BasicSessionStream> sessionStream_;
+ std::shared_ptr<ComponentSession> session_;
+ bool disconnectRequested_;
+ };
}
diff --git a/Swiften/Component/SConscript b/Swiften/Component/SConscript
index ef5700c..2553ac6 100644
--- a/Swiften/Component/SConscript
+++ b/Swiften/Component/SConscript
@@ -1,13 +1,13 @@
Import("swiften_env")
sources = [
- "ComponentHandshakeGenerator.cpp",
- "ComponentConnector.cpp",
- "ComponentSession.cpp",
- "ComponentSessionStanzaChannel.cpp",
- "CoreComponent.cpp",
- "Component.cpp",
- "ComponentXMLTracer.cpp",
- ]
+ "ComponentHandshakeGenerator.cpp",
+ "ComponentConnector.cpp",
+ "ComponentSession.cpp",
+ "ComponentSessionStanzaChannel.cpp",
+ "CoreComponent.cpp",
+ "Component.cpp",
+ "ComponentXMLTracer.cpp",
+ ]
swiften_env.Append(SWIFTEN_OBJECTS = swiften_env.SwiftenObject(sources))
diff --git a/Swiften/Component/UnitTest/ComponentConnectorTest.cpp b/Swiften/Component/UnitTest/ComponentConnectorTest.cpp
index 3968c2c..3b4fa83 100644
--- a/Swiften/Component/UnitTest/ComponentConnectorTest.cpp
+++ b/Swiften/Component/UnitTest/ComponentConnectorTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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::fromString("1.1.1.1").get();
+ host2 = HostAddress::fromString("2.2.2.2").get();
+ 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(std::shared_ptr<Connection> connection) {
+ std::shared_ptr<MockConnection> c(std::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) {
+ }
+
+ std::shared_ptr<Connection> createConnection() {
+ return std::make_shared<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< std::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..ce8eaa4 100644
--- a/Swiften/Component/UnitTest/ComponentHandshakeGeneratorTest.cpp
+++ b/Swiften/Component/UnitTest/ComponentHandshakeGeneratorTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 = std::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:
+ std::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ComponentHandshakeGeneratorTest);
diff --git a/Swiften/Component/UnitTest/ComponentSessionTest.cpp b/Swiften/Component/UnitTest/ComponentSessionTest.cpp
index 8d5d700..48c6d8d 100644
--- a/Swiften/Component/UnitTest/ComponentSessionTest.cpp
+++ b/Swiften/Component/UnitTest/ComponentSessionTest.cpp
@@ -1,220 +1,222 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
#include <deque>
+
#include <boost/bind.hpp>
#include <boost/optional.hpp>
-#include <Swiften/Session/SessionStream.h>
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
#include <Swiften/Component/ComponentSession.h>
-#include <Swiften/Elements/ComponentHandshake.h>
-#include <Swiften/Elements/AuthFailure.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/Elements/AuthFailure.h>
+#include <Swiften/Elements/ComponentHandshake.h>
+#include <Swiften/Session/SessionStream.h>
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 = std::make_shared<MockSessionStream>();
+ sessionFinishedReceived = false;
+ crypto = std::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ }
+
+ void testStart() {
+ std::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() {
+ std::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() {
+ std::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:
+ std::shared_ptr<ComponentSession> createSession() {
+ std::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(std::shared_ptr<Error> error) {
+ sessionFinishedReceived = true;
+ sessionFinishedError = error;
+ }
+
+ class MockSessionStream : public SessionStream {
+ public:
+ struct Event {
+ Event(std::shared_ptr<ToplevelElement> element) : element(element), footer(false) {}
+ Event(const ProtocolHeader& header) : header(header), footer(false) {}
+ Event() : footer(true) {}
+
+ std::shared_ptr<ToplevelElement> element;
+ boost::optional<ProtocolHeader> header;
+ bool footer;
+ };
+
+ MockSessionStream() : available(true), whitespacePingEnabled(false), resetCount(0) {
+ }
+
+ virtual void close() {
+ onClosed(std::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(std::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 std::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const {
+ return std::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(std::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(std::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;
+ };
+
+ std::shared_ptr<MockSessionStream> server;
+ bool sessionFinishedReceived = false;
+ std::shared_ptr<Error> sessionFinishedError;
+ std::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ComponentSessionTest);
diff --git a/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp b/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp
index 69ceb56..ca99201 100644
--- a/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp
+++ b/Swiften/Compress/UnitTest/ZLibCompressorTest.cpp
@@ -1,15 +1,15 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/SafeByteArray.h>
#include <QA/Checker/IO.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <Swiften/Base/SafeByteArray.h>
#include <Swiften/Compress/ZLibCompressor.h>
using namespace Swift;
@@ -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 d11ac4a..5873c0e 100644
--- a/Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp
+++ b/Swiften/Compress/UnitTest/ZLibDecompressorTest.cpp
@@ -1,17 +1,17 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/ByteArray.h>
#include <QA/Checker/IO.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Compress/ZLibDecompressor.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/Compress/ZLibCompressor.h>
+#include <Swiften/Compress/ZLibDecompressor.h>
#include <Swiften/Compress/ZLibException.h>
using namespace Swift;
@@ -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 fdfce78..344e6b7 100644
--- a/Swiften/Compress/ZLibCodecompressor.cpp
+++ b/Swiften/Compress/ZLibCodecompressor.cpp
@@ -1,55 +1,58 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Compress/ZLibCodecompressor.h>
-#include <cassert>
#include <string.h>
-#include <zlib.h>
+
+#include <cassert>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/Compress/ZLibException.h>
+#include <zlib.h>
+
#include <Swiften/Compress/ZLibCodecompressor_Private.h>
+#include <Swiften/Compress/ZLibException.h>
namespace Swift {
static const size_t CHUNK_SIZE = 1024; // If you change this, also change the unittest
-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;
+ZLibCodecompressor::ZLibCodecompressor() : p(new Private()) {
+ 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..8bc5d88 100644
--- a/Swiften/Compress/ZLibCodecompressor.h
+++ b/Swiften/Compress/ZLibCodecompressor.h
@@ -1,25 +1,27 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#include <Swiften/Base/API.h>
#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;
+ const std::unique_ptr<Private> p;
+ };
}
diff --git a/Swiften/Compress/ZLibCodecompressor_Private.h b/Swiften/Compress/ZLibCodecompressor_Private.h
index 451bc50..2adc4b6 100644
--- a/Swiften/Compress/ZLibCodecompressor_Private.h
+++ b/Swiften/Compress/ZLibCodecompressor_Private.h
@@ -1,17 +1,17 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Compress/ZLibCodecompressor.h>
-
#include <zlib.h>
+#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 5fbac6d..2201e62 100644
--- a/Swiften/Compress/ZLibException.h
+++ b/Swiften/Compress/ZLibException.h
@@ -1,15 +1,14 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-
namespace Swift {
- class ZLibException {
- public:
- ZLibException() {}
- };
+ class ZLibException {
+ public:
+ ZLibException() {}
+ };
}
diff --git a/Swiften/Config/SConscript b/Swiften/Config/SConscript
index 837884b..dd06d61 100644
--- a/Swiften/Config/SConscript
+++ b/Swiften/Config/SConscript
@@ -3,16 +3,16 @@ import os.path
Import("env")
def replaceSwiftenPath(input) :
- return input.replace(env.Dir("#").abspath, "#")
+ return input.replace(env.Dir("#").abspath, "#")
def cStringVariable(env, cVar, sconsVar) :
- result = "static const char* " + cVar + "[] = {\n"
- # FIXME: Probably not very robust
- for var in sconsVar.split(" ") :
- result += "\t\"" + env.subst(var).replace("\\", "\\\\") + "\",\n"
- result += "\t0\n"
- result += "};\n"
- return result
+ result = "static const char* " + cVar + "[] = {\n"
+ # FIXME: Probably not very robust
+ for var in sconsVar.split(" ") :
+ result += "\t\"" + env.subst(var).replace("\\", "\\\\") + "\",\n"
+ result += "\t0\n"
+ result += "};\n"
+ return result
config_flags = ""
@@ -21,36 +21,38 @@ swiften_env.UseFlags(swiften_env["SWIFTEN_FLAGS"])
swiften_env.UseFlags(swiften_env["SWIFTEN_DEP_FLAGS"])
cppflags = replaceSwiftenPath(" ".join([
- swiften_env.subst("$CPPFLAGS").replace("-isystem ","-I"),
- swiften_env.subst("$_CPPDEFFLAGS"),
- swiften_env.subst("$_CPPINCFLAGS")]))
+ swiften_env.subst("$CPPFLAGS").replace("-isystem ","-I"),
+ swiften_env.subst("$_CPPDEFFLAGS"),
+ swiften_env.subst("$_CPPINCFLAGS")]))
config_flags += cStringVariable(swiften_env, "CPPFLAGS", cppflags)
libflags = replaceSwiftenPath(" ".join([
- swiften_env.subst("$_LIBDIRFLAGS"),
- swiften_env.subst("$_LIBFLAGS"),
- swiften_env.subst("$_FRAMEWORKPATH"),
- swiften_env.subst("$_FRAMEWORKS"),
- swiften_env.subst("$_FRAMEWORKSFLAGS")
- ]))
+ swiften_env.subst("$_LIBDIRFLAGS"),
+ swiften_env.subst("$_LIBFLAGS"),
+ swiften_env.subst("$_FRAMEWORKPATH"),
+ swiften_env.subst("$_FRAMEWORKS"),
+ swiften_env.subst("$_FRAMEWORKSFLAGS")
+ ]))
config_flags += cStringVariable(swiften_env, "LIBFLAGS", libflags)
config_env = env.Clone()
+config_env.Append(CPPDEFINES = ["SWIFTEN_STATIC"])
+
# Create a local copy of Paths.cpp to avoid a Swiften dependency
config_env.Install(".", [
- "#/Swiften/Base/Paths.cpp",
- "#/Swiften/Base/Path.cpp",
- "#/Swiften/Base/String.cpp",
+ "#/Swiften/Base/Paths.cpp",
+ "#/Swiften/Base/Path.cpp",
+ "#/Swiften/Base/String.cpp",
])
config_env.UseFlags(config_env["BOOST_FLAGS"])
config_env.UseFlags(config_env["PLATFORM_FLAGS"])
config_env.WriteVal("swiften-config.h", config_env.Value(config_flags))
swiften_config = config_env.Program("swiften-config", [
- "Paths.cpp",
- "Path.cpp",
- "String.cpp",
- "swiften-config.cpp"
- ])
+ "Paths.cpp",
+ "Path.cpp",
+ "String.cpp",
+ "swiften-config.cpp"
+ ])
if swiften_env.get("SWIFTEN_INSTALLDIR", "") :
- swiften_env.Install(os.path.join(swiften_env["SWIFTEN_INSTALLDIR"], "bin"), swiften_config)
+ swiften_env.Install(os.path.join(swiften_env["SWIFTEN_INSTALLDIR"], "bin"), swiften_config)
diff --git a/Swiften/Config/swiften-config.cpp b/Swiften/Config/swiften-config.cpp
index be94c25..2b66989 100644
--- a/Swiften/Config/swiften-config.cpp
+++ b/Swiften/Config/swiften-config.cpp
@@ -1,126 +1,126 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swiften/Config/swiften-config.h>
+
#include <iostream>
+#include <string>
#include <boost/algorithm/string.hpp>
+#include <boost/filesystem.hpp>
+#include <boost/program_options.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
-#include <boost/program_options.hpp>
#include <boost/version.hpp>
-#include <boost/filesystem.hpp>
-#include <string>
-#include <Swiften/Base/Platform.h>
-#include <Swiften/Base/Paths.h>
#include <Swiften/Base/Path.h>
+#include <Swiften/Base/Paths.h>
+#include <Swiften/Base/Platform.h>
#include <Swiften/Version.h>
-#include "swiften-config.h"
-
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(auto & i : libs) {
+ if (inPlace) {
+ std::string lib = i;
+ boost::replace_all(lib, "#", pathToString(topSourcePath));
+ i = lib;
+ }
+ else {
+ std::string lib = i;
+ boost::replace_all(lib, "#", pathToString(topInstallPath / "lib"));
+ boost::erase_all(lib, "/Swiften");
+ i = lib;
+ }
+ }
+ for(auto & i : cflags) {
+ if (inPlace) {
+ std::string cflag = i;
+ boost::replace_all(cflag, "#", pathToString(topSourcePath));
+ i = cflag;
+ }
+ else {
+ std::string cflag = i;
+ boost::replace_all(cflag, "#", pathToString(topInstallPath / "include"));
+ 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 35ae901..9fbdb2a 100644
--- a/Swiften/Crypto/CommonCryptoCryptoProvider.cpp
+++ b/Swiften/Crypto/CommonCryptoCryptoProvider.cpp
@@ -1,110 +1,112 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Crypto/CommonCryptoCryptoProvider.h>
+#include <cassert>
+
+#include <boost/numeric/conversion/cast.hpp>
+
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
-#include <cassert>
-#include <Swiften/Crypto/Hash.h>
#include <Swiften/Base/ByteArray.h>
-#include <boost/numeric/conversion/cast.hpp>
+#include <Swiften/Crypto/Hash.h>
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() {
@@ -114,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 5c9cbe6..8fa7fa6 100644
--- a/Swiften/Crypto/CommonCryptoCryptoProvider.h
+++ b/Swiften/Crypto/CommonCryptoCryptoProvider.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,19 +7,19 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Base/Override.h>
+#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.cpp b/Swiften/Crypto/CryptoProvider.cpp
index 04b0b16..9c7c637 100644
--- a/Swiften/Crypto/CryptoProvider.cpp
+++ b/Swiften/Crypto/CryptoProvider.cpp
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Crypto/CryptoProvider.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
using namespace Swift;
diff --git a/Swiften/Crypto/CryptoProvider.h b/Swiften/Crypto/CryptoProvider.h
index 1fe2b2c..3eaeeb3 100644
--- a/Swiften/Crypto/CryptoProvider.h
+++ b/Swiften/Crypto/CryptoProvider.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::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 std::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 2b565eb..6e0c01b 100644
--- a/Swiften/Crypto/OpenSSLCryptoProvider.h
+++ b/Swiften/Crypto/OpenSSLCryptoProvider.h
@@ -1,24 +1,24 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Base/Override.h>
+#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..a72bf8e 100644
--- a/Swiften/Crypto/PlatformCryptoProvider.cpp
+++ b/Swiften/Crypto/PlatformCryptoProvider.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 nullptr;
}
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/SConscript b/Swiften/Crypto/SConscript
index ce4bdae..d5532fd 100644
--- a/Swiften/Crypto/SConscript
+++ b/Swiften/Crypto/SConscript
@@ -2,27 +2,27 @@ Import("swiften_env", "env")
objects = swiften_env.SwiftenObject([
- "CryptoProvider.cpp",
- "Hash.cpp"
+ "CryptoProvider.cpp",
+ "Hash.cpp"
])
myenv = swiften_env.Clone()
if myenv["PLATFORM"] == "win32" :
- objects += myenv.SwiftenObject(["WindowsCryptoProvider.cpp"])
+ objects += myenv.SwiftenObject(["WindowsCryptoProvider.cpp"])
if myenv.get("HAVE_OPENSSL", False) :
- myenv.Append(CPPDEFINES = ["HAVE_OPENSSL_CRYPTO_PROVIDER"])
- objects += myenv.SwiftenObject(["OpenSSLCryptoProvider.cpp"])
+ myenv.Append(CPPDEFINES = ["HAVE_OPENSSL_CRYPTO_PROVIDER"])
+ objects += myenv.SwiftenObject(["OpenSSLCryptoProvider.cpp"])
if myenv["PLATFORM"] == "darwin" and myenv["target"] == "native" :
- myenv.Append(CPPDEFINES = ["HAVE_COMMONCRYPTO_CRYPTO_PROVIDER"])
- objects += myenv.SwiftenObject(["CommonCryptoCryptoProvider.cpp"])
+ myenv.Append(CPPDEFINES = ["HAVE_COMMONCRYPTO_CRYPTO_PROVIDER"])
+ objects += myenv.SwiftenObject(["CommonCryptoCryptoProvider.cpp"])
objects += myenv.SwiftenObject(["PlatformCryptoProvider.cpp"])
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
if env["TEST"] :
- test_env = myenv.Clone()
- test_env.UseFlags(swiften_env["CPPUNIT_FLAGS"])
- env.Append(UNITTEST_OBJECTS = test_env.SwiftenObject([
- File("UnitTest/CryptoProviderTest.cpp"),
- ]))
+ test_env = myenv.Clone()
+ test_env.UseFlags(swiften_env["CPPUNIT_FLAGS"])
+ env.Append(UNITTEST_OBJECTS = test_env.SwiftenObject([
+ File("UnitTest/CryptoProviderTest.cpp"),
+ ]))
diff --git a/Swiften/Crypto/UnitTest/CryptoProviderTest.cpp b/Swiften/Crypto/UnitTest/CryptoProviderTest.cpp
index 3e40ecf..72eb81d 100644
--- a/Swiften/Crypto/UnitTest/CryptoProviderTest.cpp
+++ b/Swiften/Crypto/UnitTest/CryptoProviderTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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() {
+ std::shared_ptr<Hash> sha = std::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() {
+ std::shared_ptr<Hash> sha = std::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() {
+ std::shared_ptr<Hash> sha = std::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() {
+ std::shared_ptr<Hash> testling = std::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..513941f 100644
--- a/Swiften/Crypto/WindowsCryptoProvider.cpp
+++ b/Swiften/Crypto/WindowsCryptoProvider.cpp
@@ -17,7 +17,7 @@
#include <security.h>
#include <Wincrypt.h>
#include <cassert>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Crypto/Hash.h>
#include <Swiften/Base/ByteArray.h>
@@ -27,196 +27,195 @@
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);
- }
+WindowsCryptoProvider::WindowsCryptoProvider() : p(new 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..f446027 100644
--- a/Swiften/Crypto/WindowsCryptoProvider.h
+++ b/Swiften/Crypto/WindowsCryptoProvider.h
@@ -6,26 +6,27 @@
#pragma once
+#include <memory>
+
#include <boost/noncopyable.hpp>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Base/Override.h>
#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;
+ const std::unique_ptr<Private> p;
+ };
}
diff --git a/Swiften/Disco/CapsInfoGenerator.cpp b/Swiften/Disco/CapsInfoGenerator.cpp
index d2354ea..961ef43 100644
--- a/Swiften/Disco/CapsInfoGenerator.cpp
+++ b/Swiften/Disco/CapsInfoGenerator.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,16 +8,15 @@
#include <algorithm>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/FormField.h>
-#include <Swiften/Crypto/CryptoProvider.h>
#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 +25,39 @@ CapsInfoGenerator::CapsInfoGenerator(const std::string& node, CryptoProvider* cr
}
CapsInfo CapsInfoGenerator::generateCapsInfo(const DiscoInfo& discoInfo) const {
- std::string serializedCaps;
-
- std::vector<DiscoInfo::Identity> identities(discoInfo.getIdentities());
- std::sort(identities.begin(), identities.end());
- foreach (const DiscoInfo::Identity& identity, identities) {
- 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 + "<";
- }
-
- 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 serializedCaps;
+
+ std::vector<DiscoInfo::Identity> identities(discoInfo.getIdentities());
+ std::sort(identities.begin(), identities.end());
+ for (const auto& identity : identities) {
+ serializedCaps += identity.getCategory() + "/" + identity.getType() + "/" + identity.getLanguage() + "/" + identity.getName() + "<";
+ }
+
+ std::vector<std::string> features(discoInfo.getFeatures());
+ std::sort(features.begin(), features.end());
+ for (const auto& feature : features) {
+ serializedCaps += feature + "<";
+ }
+
+ for (const auto& extension : discoInfo.getExtensions()) {
+ serializedCaps += extension->getFormType() + "<";
+ std::vector<FormField::ref> fields(extension->getFields());
+ std::sort(fields.begin(), fields.end(), &compareFields);
+ for (const auto& field : fields) {
+ if (field->getName() == "FORM_TYPE") {
+ continue;
+ }
+ serializedCaps += field->getName() + "<";
+ std::vector<std::string> values(field->getValues());
+ std::sort(values.begin(), values.end());
+ for (const auto& value : values) {
+ serializedCaps += value + "<";
+ }
+ }
+ }
+
+ std::string version(Base64::encode(crypto_->getSHA1Hash(createByteArray(serializedCaps))));
+ return CapsInfo(node_, version, "sha-1");
}
}
diff --git a/Swiften/Disco/CapsInfoGenerator.h b/Swiften/Disco/CapsInfoGenerator.h
index ebcb8fa..ed1b1bd 100644
--- a/Swiften/Disco/CapsInfoGenerator.h
+++ b/Swiften/Disco/CapsInfoGenerator.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,21 +7,22 @@
#pragma once
#include <string>
+
#include <Swiften/Base/API.h>
#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 2f2f909..794cf74 100644
--- a/Swiften/Disco/CapsManager.cpp
+++ b/Swiften/Disco/CapsManager.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,77 +7,77 @@
#include <Swiften/Disco/CapsManager.h>
#include <boost/bind.hpp>
-#include <iostream>
+#include <Swiften/Base/Log.h>
#include <Swiften/Client/StanzaChannel.h>
-#include <Swiften/Disco/CapsStorage.h>
#include <Swiften/Disco/CapsInfoGenerator.h>
-#include <Swiften/Elements/CapsInfo.h>
+#include <Swiften/Disco/CapsStorage.h>
#include <Swiften/Disco/GetDiscoInfoRequest.h>
+#include <Swiften/Elements/CapsInfo.h>
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);
+void CapsManager::handlePresenceReceived(std::shared_ptr<Presence> presence) {
+ std::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) {
+ SWIFT_LOG(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 095fe1f..e57730e 100644
--- a/Swiften/Disco/CapsManager.h
+++ b/Swiften/Disco/CapsManager.h
@@ -1,53 +1,54 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <set>
#include <map>
+#include <set>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/Elements/Presence.h>
-#include <Swiften/Elements/DiscoInfo.h>
+#include <Swiften/Disco/CapsProvider.h>
#include <Swiften/Elements/CapsInfo.h>
+#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/ErrorPayload.h>
-#include <Swiften/Disco/CapsProvider.h>
+#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::signals2::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(std::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 2a81554..15a1fd3 100644
--- a/Swiften/Disco/CapsMemoryStorage.h
+++ b/Swiften/Disco/CapsMemoryStorage.h
@@ -1,39 +1,39 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
#include <map>
-
+#include <memory>
#include <string>
+
#include <Swiften/Base/API.h>
#include <Swiften/Disco/CapsStorage.h>
namespace Swift {
- class SWIFTEN_API CapsMemoryStorage : public CapsStorage {
- public:
- CapsMemoryStorage() {}
+ 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 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;
- }
+ virtual void setDiscoInfo(const std::string& hash, DiscoInfo::ref discoInfo) {
+ caps[hash] = discoInfo;
+ }
- private:
- typedef std::map<std::string, DiscoInfo::ref> CapsMap;
- CapsMap caps;
- };
+ private:
+ typedef std::map<std::string, DiscoInfo::ref> CapsMap;
+ CapsMap caps;
+ };
}
diff --git a/Swiften/Disco/CapsProvider.h b/Swiften/Disco/CapsProvider.h
index 08202a7..b9e2d21 100644
--- a/Swiften/Disco/CapsProvider.h
+++ b/Swiften/Disco/CapsProvider.h
@@ -1,25 +1,26 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/CapsInfo.h>
+#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() {}
+
+ virtual DiscoInfo::ref getCaps(const std::string&) const = 0;
- boost::signal<void (const std::string&)> onCapsAvailable;
- };
+ boost::signals2::signal<void (const std::string&)> onCapsAvailable;
+ };
}
diff --git a/Swiften/Disco/CapsStorage.h b/Swiften/Disco/CapsStorage.h
index 85b8d5d..ebfd3f3 100644
--- a/Swiften/Disco/CapsStorage.h
+++ b/Swiften/Disco/CapsStorage.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Base/API.h>
+#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 74336a5..8c90d2d 100644
--- a/Swiften/Disco/ClientDiscoManager.cpp
+++ b/Swiften/Disco/ClientDiscoManager.cpp
@@ -1,43 +1,43 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Disco/ClientDiscoManager.h>
-#include <Swiften/Disco/DiscoInfoResponder.h>
#include <Swiften/Disco/CapsInfoGenerator.h>
+#include <Swiften/Disco/DiscoInfoResponder.h>
#include <Swiften/Presence/PayloadAddingPresenceSender.h>
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..595beeb 100644
--- a/Swiften/Disco/ClientDiscoManager.h
+++ b/Swiften/Disco/ClientDiscoManager.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -12,66 +12,67 @@
#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.
+ * \param crypto the crypto provider used for cryptographic hash computations.
+ */
+ 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 3c477c3..c94d299 100644
--- a/Swiften/Disco/DiscoInfoResponder.cpp
+++ b/Swiften/Disco/DiscoInfoResponder.cpp
@@ -1,14 +1,15 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
-
#include <Swiften/Disco/DiscoInfoResponder.h>
-#include <Swiften/Queries/IQRouter.h>
+
+#include <memory>
+
#include <Swiften/Elements/DiscoInfo.h>
+#include <Swiften/Queries/IQRouter.h>
namespace Swift {
@@ -16,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;
+bool DiscoInfoResponder::handleGetRequest(const JID& from, const JID&, const std::string& id, std::shared_ptr<DiscoInfo> info) {
+ if (info->getNode().empty()) {
+ sendResponse(from, id, std::make_shared<DiscoInfo>(info_));
+ }
+ else {
+ std::map<std::string,DiscoInfo>::const_iterator i = nodeInfo_.find(info->getNode());
+ if (i != nodeInfo_.end()) {
+ sendResponse(from, id, std::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 0ca6336..9995695 100644
--- a/Swiften/Disco/DiscoInfoResponder.h
+++ b/Swiften/Disco/DiscoInfoResponder.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,25 +9,25 @@
#include <map>
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/GetResponder.h>
#include <Swiften/Elements/DiscoInfo.h>
+#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, std::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..a3f95d2 100644
--- a/Swiften/Disco/DiscoServiceWalker.cpp
+++ b/Swiften/Disco/DiscoServiceWalker.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,7 +9,6 @@
#include <boost/bind.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
@@ -18,118 +17,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;
+ for (auto&& request : pendingDiscoInfoRequests_) {
+ request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, request));
+ }
+ for (auto&& request : pendingDiscoItemsRequests_) {
+ request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoItemsResponse, this, _1, _2, request));
+ }
+ active_ = false;
+ onWalkAborted();
+ }
}
void DiscoServiceWalker::walkNode(const JID& jid) {
- SWIFT_LOG(debug) << "Walking node " << jid << std::endl;
- servicesBeingSearched_.insert(jid);
- searchedServices_.insert(jid);
- GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(jid, iqRouter_);
- discoInfoRequest->onResponse.connect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, discoInfoRequest));
- pendingDiscoInfoRequests_.insert(discoInfoRequest);
- discoInfoRequest->send();
+ 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());
- }
+void DiscoServiceWalker::handleDiscoInfoResponse(std::shared_ptr<DiscoInfo> info, ErrorPayload::ref error, GetDiscoInfoRequest::ref request) {
+ /* If we got canceled, don't do anything */
+ if (!active_) {
+ return;
+ }
+
+ SWIFT_LOG(debug) << "Disco info response from " << request->getReceiver() << std::endl;
+
+ request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, request));
+ pendingDiscoInfoRequests_.erase(request);
+ if (error) {
+ handleDiscoError(request->getReceiver(), error);
+ return;
+ }
+
+ bool couldContainServices = false;
+ for (const auto& identity : info->getIdentities()) {
+ if (identity.getCategory() == "server") {
+ couldContainServices = true;
+ }
+ }
+ bool completed = false;
+ if (couldContainServices) {
+ GetDiscoItemsRequest::ref discoItemsRequest = GetDiscoItemsRequest::create(request->getReceiver(), iqRouter_);
+ discoItemsRequest->onResponse.connect(boost::bind(&DiscoServiceWalker::handleDiscoItemsResponse, this, _1, _2, discoItemsRequest));
+ pendingDiscoItemsRequests_.insert(discoItemsRequest);
+ discoItemsRequest->send();
+ } else {
+ completed = true;
+ }
+ onServiceFound(request->getReceiver(), info);
+ if (completed) {
+ markNodeCompleted(request->getReceiver());
+ }
}
-void DiscoServiceWalker::handleDiscoItemsResponse(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());
+void DiscoServiceWalker::handleDiscoItemsResponse(std::shared_ptr<DiscoItems> items, ErrorPayload::ref error, GetDiscoItemsRequest::ref request) {
+ /* If we got canceled, don't do anything */
+ if (!active_) {
+ return;
+ }
+
+ SWIFT_LOG(debug) << "Received disco items from " << request->getReceiver() << std::endl;
+ request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoItemsResponse, this, _1, _2, request));
+ pendingDiscoItemsRequests_.erase(request);
+ if (error) {
+ handleDiscoError(request->getReceiver(), error);
+ return;
+ }
+ for (auto&& item : items->getItems()) {
+ if (item.getNode().empty()) {
+ /* Don't look at noded items. It's possible that this will exclude some services,
+ * but I've never seen one in the wild, and it's an easy fix for not looping.
+ */
+ if (std::find(searchedServices_.begin(), searchedServices_.end(), item.getJID()) == searchedServices_.end()) { /* Don't recurse infinitely */
+ SWIFT_LOG(debug) << "Received disco item " << item.getJID() << std::endl;
+ walkNode(item.getJID());
+ }
+ }
+ }
+ markNodeCompleted(request->getReceiver());
}
void DiscoServiceWalker::handleDiscoError(const JID& jid, ErrorPayload::ref /*error*/) {
- SWIFT_LOG(debug) << "Disco error from " << jid << std::endl;
- markNodeCompleted(jid);
+ 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 643096d..f7e1e6d 100644
--- a/Swiften/Disco/DiscoServiceWalker.h
+++ b/Swiften/Disco/DiscoServiceWalker.h
@@ -1,75 +1,76 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
+#include <memory>
#include <set>
+#include <string>
+#include <vector>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/boost_bsignals.h>
-#include <string>
-#include <Swiften/JID/JID.h>
+#include <Swiften/Disco/GetDiscoInfoRequest.h>
+#include <Swiften/Disco/GetDiscoItemsRequest.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/DiscoItems.h>
#include <Swiften/Elements/ErrorPayload.h>
-#include <Swiften/Disco/GetDiscoInfoRequest.h>
-#include <Swiften/Disco/GetDiscoItemsRequest.h>
+#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::signals2::signal<void(const JID&, std::shared_ptr<DiscoInfo>)> onServiceFound;
- /** Emitted when walking is aborted. */
- boost::signal<void()> onWalkAborted;
+ /** Emitted when walking is aborted. */
+ boost::signals2::signal<void()> onWalkAborted;
- /** Emitted when walking is complete.*/
- boost::signal<void()> onWalkComplete;
+ /** Emitted when walking is complete.*/
+ boost::signals2::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(std::shared_ptr<DiscoInfo> info, ErrorPayload::ref error, GetDiscoInfoRequest::ref request);
+ void handleDiscoItemsResponse(std::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..fce38fe 100644
--- a/Swiften/Disco/DummyEntityCapsProvider.cpp
+++ b/Swiften/Disco/DummyEntityCapsProvider.cpp
@@ -1,21 +1,19 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Disco/DummyEntityCapsProvider.h>
-#include <iostream>
-
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 09519ba..64d90be 100644
--- a/Swiften/Disco/EntityCapsManager.cpp
+++ b/Swiften/Disco/EntityCapsManager.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,72 +8,72 @@
#include <boost/bind.hpp>
-#include <Swiften/Disco/CapsProvider.h>
#include <Swiften/Client/StanzaChannel.h>
+#include <Swiften/Disco/CapsProvider.h>
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);
- }
- }
+void EntityCapsManager::handlePresenceReceived(std::shared_ptr<Presence> presence) {
+ JID from = presence->getFrom();
+ if (presence->isAvailable()) {
+ std::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 2f6982f..4236326 100644
--- a/Swiften/Disco/EntityCapsManager.h
+++ b/Swiften/Disco/EntityCapsManager.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,39 +8,40 @@
#include <map>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/Elements/Presence.h>
+#include <Swiften/Disco/EntityCapsProvider.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Elements/ErrorPayload.h>
-#include <Swiften/Disco/EntityCapsProvider.h>
+#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::signals2::trackable {
+ public:
+ EntityCapsManager(CapsProvider*, StanzaChannel*);
+
+ /**
+ * Returns the service discovery information of the given JID.
+ */
+ DiscoInfo::ref getCaps(const JID&) const;
+
+ private:
+ void handlePresenceReceived(std::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 0e34f02..5f4af18 100644
--- a/Swiften/Disco/EntityCapsProvider.h
+++ b/Swiften/Disco/EntityCapsProvider.h
@@ -1,34 +1,35 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/DiscoInfo.h>
+#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::signals2::signal<void (const JID&)> onCapsChanged;
+ };
}
diff --git a/Swiften/Disco/FeatureOracle.cpp b/Swiften/Disco/FeatureOracle.cpp
index 4e61aa9..2baf87c 100644
--- a/Swiften/Disco/FeatureOracle.cpp
+++ b/Swiften/Disco/FeatureOracle.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,10 +8,12 @@
#include <algorithm>
#include <iterator>
+#include <unordered_set>
#include <vector>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Base/Log.h>
#include <Swiften/Disco/EntityCapsProvider.h>
+#include <Swiften/Elements/Idle.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/FileTransfer/FileTransferManager.h>
#include <Swiften/JID/JID.h>
@@ -20,78 +22,178 @@
namespace Swift {
FeatureOracle::FeatureOracle(EntityCapsProvider* capsProvider, PresenceOracle* presenceOracle) : capsProvider_(capsProvider), presenceOracle_(presenceOracle) {
-
}
Tristate FeatureOracle::isFileTransferSupported(const JID& jid) {
- DiscoInfo::ref discoInfo = getDiscoResultForJID(jid);
- if (discoInfo) {
- return FileTransferManager::isSupportedBy(discoInfo) ? Yes : No;
- }
- else {
- return Maybe;
- }
+ Tristate fileTransferSupported = No;
+
+ auto isYesOrMaybe = [](Tristate tristate) { return tristate == Yes || tristate == Maybe; };
+ auto isYes = [](Tristate tristate) { return tristate == Yes; };
+
+ auto supportedFeatures = getFeaturesForJID(jid);
+
+ auto jingleSupported = isFeatureSupported(supportedFeatures, DiscoInfo::JingleFeature);
+ auto jingleFTSupported = isFeatureSupported(supportedFeatures, DiscoInfo::JingleFTFeature);
+ auto jingleTransportIBBSupported = isFeatureSupported(supportedFeatures, DiscoInfo::JingleTransportsIBBFeature);
+ auto jingleTransportS5BSupported = isFeatureSupported(supportedFeatures, DiscoInfo::JingleTransportsS5BFeature);
+
+ if (isYes(jingleSupported) && isYes(jingleFTSupported) && (isYes(jingleTransportIBBSupported) || isYes(jingleTransportS5BSupported))) {
+ fileTransferSupported = Yes;
+ }
+ else if (isYesOrMaybe(jingleSupported) && isYesOrMaybe(jingleFTSupported) && (isYesOrMaybe(jingleTransportIBBSupported) || isYesOrMaybe(jingleTransportS5BSupported))) {
+ fileTransferSupported = Maybe;
+ }
+
+ return fileTransferSupported;
}
Tristate FeatureOracle::isMessageReceiptsSupported(const JID& jid) {
- return isFeatureSupported(jid, DiscoInfo::MessageDeliveryReceiptsFeature);
+ return isFeatureSupported(getFeaturesForJID(jid), DiscoInfo::MessageDeliveryReceiptsFeature);
}
Tristate FeatureOracle::isMessageCorrectionSupported(const JID& jid) {
- return isFeatureSupported(jid, DiscoInfo::MessageCorrectionFeature);
+ return isFeatureSupported(getFeaturesForJID(jid), DiscoInfo::MessageCorrectionFeature);
+}
+
+Tristate FeatureOracle::isWhiteboardSupported(const JID& jid) {
+ return isFeatureSupported(getFeaturesForJID(jid), DiscoInfo::WhiteboardFeature);
+}
+
+class PresenceFeatureAvailablityComparator {
+ public:
+ 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;
+ }
+
+ static int compareWithoutResource(const Presence::ref& a, const Presence::ref& b) {
+ int aPreference = preferenceFromStatusShow(a->getShow());
+ int bPreference = preferenceFromStatusShow(b->getShow());
+
+ if (aPreference != bPreference) {
+ return aPreference < bPreference ? 1 : -1;
+ }
+
+ Idle::ref aIdle = a->getPayload<Idle>();
+ Idle::ref bIdle = b->getPayload<Idle>();
+
+ if (aIdle && !bIdle) {
+ return -1;
+ }
+ else if (!aIdle && bIdle) {
+ return 1;
+ }
+
+ if (a->getPriority() != b->getPriority()) {
+ return a->getPriority() < b->getPriority() ? 1 : -1;
+ }
+
+ return 0;
+ }
+
+ /*
+ * This method returns true, if \ref Presence \p b is more available than
+ * \ref Presence \p a.
+ * Going by \ref StatusShow::Type first, then by idle state, then by
+ * presence priority and finally by resource name.
+ */
+ bool operator()(const Presence::ref& a, const Presence::ref& b) {
+ int aMoreAvailableThanB = compareWithoutResource(a, b);
+ if (aMoreAvailableThanB < 0) {
+ return true;
+ }
+ else if (aMoreAvailableThanB > 0) {
+ return false;
+ }
+
+ return a->getFrom().getResource() < b->getFrom().getResource();
+ }
+};
+
+JID FeatureOracle::getMostAvailableClientForFileTrasfer(const JID& bareJID) {
+ JID fullJID;
+ assert(bareJID.isBare());
+
+ std::vector<Presence::ref> allPresences = presenceOracle_->getAllPresence(bareJID);
+ std::sort(allPresences.begin(), allPresences.end(), PresenceFeatureAvailablityComparator());
+
+ for (const auto& presence : allPresences) {
+ if (presence->isAvailable()) {
+ if (isFileTransferSupported(presence->getFrom()) == Yes) {
+ fullJID = presence->getFrom();
+ break;
+ }
+ }
+ }
+
+ SWIFT_LOG_ASSERT(!fullJID.isBare(), error);
+ return fullJID;
}
-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;
+std::unordered_map<std::string, Tristate> FeatureOracle::getFeaturesForJID(const JID& jid) {
+ std::unordered_map<std::string, Tristate> supportedFeatures;
+ if (jid.isBare()) {
+ // Calculate the union of disco features of all most available results and return that.
+ std::vector<DiscoInfo::ref> onlineDiscoInfos;
+ std::unordered_set<std::string> features;
+
+ // Collect relevant disco info results and the set of features.
+ for (auto&& presence : presenceOracle_->getAllPresence(jid)) {
+ if (presence->getType() == Presence::Available) {
+ DiscoInfo::ref presenceDiscoInfo = capsProvider_->getCaps(presence->getFrom());
+ if (presenceDiscoInfo) {
+ onlineDiscoInfos.push_back(presenceDiscoInfo);
+ features.insert(presenceDiscoInfo->getFeatures().begin(), presenceDiscoInfo->getFeatures().end());
+ }
+ }
+ }
+
+ // Calculate supportedFeaturesMap.
+ for (auto&& feature : features) {
+ Tristate supported = Yes;
+ for (auto&& discoInfo : onlineDiscoInfos) {
+ if (!discoInfo->hasFeature(feature)) {
+ supported = Maybe;
+ break;
+ }
+ }
+ supportedFeatures[feature] = supported;
+ }
+ }
+ else {
+ // Return the disco result of the full JID.
+ auto discoInfo = capsProvider_->getCaps(jid);
+ if (discoInfo) {
+ for (auto&& feature : discoInfo->getFeatures()) {
+ supportedFeatures[feature] = Yes;
+ }
+ }
+ }
+
+ return supportedFeatures;
}
-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;
- }
+Tristate FeatureOracle::isFeatureSupported(const std::unordered_map<std::string, Tristate>& supportedFeatures, const std::string& feature) {
+ Tristate supported = No;
+ auto lookupResult = supportedFeatures.find(feature);
+ if (lookupResult != supportedFeatures.end()) {
+ supported = lookupResult->second;
+ }
+ return supported;
}
}
diff --git a/Swiften/Disco/FeatureOracle.h b/Swiften/Disco/FeatureOracle.h
index d579e5a..be0cd6f 100644
--- a/Swiften/Disco/FeatureOracle.h
+++ b/Swiften/Disco/FeatureOracle.h
@@ -1,11 +1,14 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <unordered_map>
+#include <unordered_set>
+
#include <Swiften/Base/API.h>
#include <Swiften/Base/Tristate.h>
#include <Swiften/Elements/DiscoInfo.h>
@@ -20,27 +23,30 @@ 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);
+ Tristate isWhiteboardSupported(const JID& jid);
+
+ JID getMostAvailableClientForFileTrasfer(const JID& bareJID);
+
+ private:
+ /**
+ * @brief getDiscoResultForJID returns a shared reference to a DiscoInfo representing features supported by the jid.
+ * @param jid The JID to return an std::unordered_map<std::string, Tristate> for.
+ * @return std::unordered_map<std::string, Tristate>
+ */
+ std::unordered_map<std::string, Tristate> getFeaturesForJID(const JID& jid);
+
+ Tristate isFeatureSupported(const std::unordered_map<std::string, Tristate>& supportedFeatures, const std::string& feature);
+
+ private:
+ EntityCapsProvider* capsProvider_;
+ PresenceOracle* presenceOracle_;
};
}
diff --git a/Swiften/Disco/GetDiscoInfoRequest.h b/Swiften/Disco/GetDiscoInfoRequest.h
index a3c1415..1d86c14 100644
--- a/Swiften/Disco/GetDiscoInfoRequest.h
+++ b/Swiften/Disco/GetDiscoInfoRequest.h
@@ -1,38 +1,38 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/DiscoInfo.h>
+#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 std::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, std::make_shared<DiscoInfo>(), router) {
+ }
+
+ GetDiscoInfoRequest(const JID& jid, const std::string& node, IQRouter* router) :
+ GenericRequest<DiscoInfo>(IQ::Get, jid, std::make_shared<DiscoInfo>(), router) {
+ getPayloadGeneric()->setNode(node);
+ }
+ };
}
diff --git a/Swiften/Disco/GetDiscoItemsRequest.h b/Swiften/Disco/GetDiscoItemsRequest.h
index a9cf38b..5b1ccf2 100644
--- a/Swiften/Disco/GetDiscoItemsRequest.h
+++ b/Swiften/Disco/GetDiscoItemsRequest.h
@@ -1,38 +1,38 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/DiscoItems.h>
+#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 std::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, std::make_shared<DiscoItems>(), router) {
+ }
+
+ GetDiscoItemsRequest(const JID& jid, const std::string& node, IQRouter* router) :
+ GenericRequest<DiscoItems>(IQ::Get, jid, std::make_shared<DiscoItems>(), router) {
+ getPayloadGeneric()->setNode(node);
+ }
+ };
}
diff --git a/Swiften/Disco/JIDDiscoInfoResponder.cpp b/Swiften/Disco/JIDDiscoInfoResponder.cpp
index 6a632cf..8802bce 100644
--- a/Swiften/Disco/JIDDiscoInfoResponder.cpp
+++ b/Swiften/Disco/JIDDiscoInfoResponder.cpp
@@ -1,14 +1,15 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
-
#include <Swiften/Disco/JIDDiscoInfoResponder.h>
-#include <Swiften/Queries/IQRouter.h>
+
+#include <memory>
+
#include <Swiften/Elements/DiscoInfo.h>
+#include <Swiften/Queries/IQRouter.h>
namespace Swift {
@@ -16,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;
+bool JIDDiscoInfoResponder::handleGetRequest(const JID& from, const JID& to, const std::string& id, std::shared_ptr<DiscoInfo> discoInfo) {
+ JIDDiscoInfoMap::const_iterator i = info.find(to);
+ if (i != info.end()) {
+ if (discoInfo->getNode().empty()) {
+ sendResponse(from, to, id, std::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, std::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 2f184bf..1eb6228 100644
--- a/Swiften/Disco/JIDDiscoInfoResponder.h
+++ b/Swiften/Disco/JIDDiscoInfoResponder.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,30 +9,30 @@
#include <map>
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/GetResponder.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/JID/JID.h>
+#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, std::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/SConscript b/Swiften/Disco/SConscript
index 1779e26..15137ae 100644
--- a/Swiften/Disco/SConscript
+++ b/Swiften/Disco/SConscript
@@ -1,16 +1,16 @@
Import("swiften_env")
objects = swiften_env.SwiftenObject([
- "CapsInfoGenerator.cpp",
- "CapsManager.cpp",
- "EntityCapsManager.cpp",
- "EntityCapsProvider.cpp",
- "DummyEntityCapsProvider.cpp",
- "CapsStorage.cpp",
- "ClientDiscoManager.cpp",
- "DiscoInfoResponder.cpp",
- "JIDDiscoInfoResponder.cpp",
- "DiscoServiceWalker.cpp",
- "FeatureOracle.cpp",
- ])
+ "CapsInfoGenerator.cpp",
+ "CapsManager.cpp",
+ "EntityCapsManager.cpp",
+ "EntityCapsProvider.cpp",
+ "DummyEntityCapsProvider.cpp",
+ "CapsStorage.cpp",
+ "ClientDiscoManager.cpp",
+ "DiscoInfoResponder.cpp",
+ "JIDDiscoInfoResponder.cpp",
+ "DiscoServiceWalker.cpp",
+ "FeatureOracle.cpp",
+ ])
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
diff --git a/Swiften/Disco/UnitTest/CapsInfoGeneratorTest.cpp b/Swiften/Disco/UnitTest/CapsInfoGeneratorTest.cpp
index 328c367..8d27ec5 100644
--- a/Swiften/Disco/UnitTest/CapsInfoGeneratorTest.cpp
+++ b/Swiften/Disco/UnitTest/CapsInfoGeneratorTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,80 +7,80 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Elements/DiscoInfo.h>
-#include <Swiften/Disco/CapsInfoGenerator.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/Disco/CapsInfoGenerator.h>
+#include <Swiften/Elements/DiscoInfo.h>
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 = std::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 = std::make_shared<FormField>(FormField::HiddenType, "urn:xmpp:dataforms:softwareinfo");
+ field->setName("FORM_TYPE");
+ extension->addField(field);
+ field = std::make_shared<FormField>(FormField::ListMultiType);
+ field->addValue("ipv6");
+ field->addValue("ipv4");
+ field->setName("ip_version");
+ extension->addField(field);
+ field = std::make_shared<FormField>(FormField::TextSingleType, "Psi");
+ field->setName("software");
+ extension->addField(field);
+ field = std::make_shared<FormField>(FormField::TextSingleType, "0.11");
+ field->setName("software_version");
+ extension->addField(field);
+ field = std::make_shared<FormField>(FormField::TextSingleType, "Mac");
+ field->setName("os");
+ extension->addField(field);
+ field = std::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());
+ }
- CPPUNIT_ASSERT_EQUAL(std::string("q07IKJEyjvHSyhy//CH0CxmKi8w="), result.getVersion());
- }
-
- private:
- boost::shared_ptr<CryptoProvider> crypto;
+ private:
+ std::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(CapsInfoGeneratorTest);
diff --git a/Swiften/Disco/UnitTest/CapsManagerTest.cpp b/Swiften/Disco/UnitTest/CapsManagerTest.cpp
index 5841ef4..153e821 100644
--- a/Swiften/Disco/UnitTest/CapsManagerTest.cpp
+++ b/Swiften/Disco/UnitTest/CapsManagerTest.cpp
@@ -1,290 +1,291 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <memory>
#include <vector>
+
#include <boost/bind.hpp>
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
+#include <Swiften/Client/DummyStanzaChannel.h>
+#include <Swiften/Crypto/CryptoProvider.h>
+#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/Disco/CapsInfoGenerator.h>
#include <Swiften/Disco/CapsManager.h>
#include <Swiften/Disco/CapsMemoryStorage.h>
-#include <Swiften/Disco/CapsInfoGenerator.h>
-#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Elements/CapsInfo.h>
#include <Swiften/Elements/DiscoInfo.h>
-#include <Swiften/Client/DummyStanzaChannel.h>
-#include <Swiften/Crypto/CryptoProvider.h>
-#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/Queries/IQRouter.h>
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 = std::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ stanzaChannel = std::unique_ptr<DummyStanzaChannel>(new DummyStanzaChannel());
+ iqRouter = std::unique_ptr<IQRouter>(new IQRouter(stanzaChannel.get()));
+ storage = std::unique_ptr<CapsMemoryStorage>(new CapsMemoryStorage());
+ user1 = JID("user1@bar.com/bla");
+ discoInfo1 = std::make_shared<DiscoInfo>();
+ discoInfo1->addFeature("http://swift.im/feature1");
+ capsInfo1 = std::make_shared<CapsInfo>(CapsInfoGenerator("http://node1.im", crypto.get()).generateCapsInfo(*discoInfo1.get()));
+ capsInfo1alt = std::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo1.get()));
+ user2 = JID("user2@foo.com/baz");
+ discoInfo2 = std::make_shared<DiscoInfo>();
+ discoInfo2->addFeature("http://swift.im/feature2");
+ capsInfo2 = std::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo2.get()));
+ user3 = JID("user3@foo.com/baz");
+ legacyCapsInfo = std::make_shared<CapsInfo>("http://swift.im", "ver1", "");
+ }
+
+ void tearDown() {
+ iqRouter.reset();
+ }
+
+ void testReceiveNewHashRequestsDisco() {
+ std::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get));
+ std::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[0]->getPayload<DiscoInfo>());
+ CPPUNIT_ASSERT(discoInfo);
+ CPPUNIT_ASSERT_EQUAL("http://node1.im#" + capsInfo1->getVersion(), discoInfo->getNode());
+ }
+
+ void testReceiveSameHashDoesNotRequestDisco() {
+ std::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() {
+ std::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, legacyCapsInfo);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
+ }
+
+ void testReceiveSameHashAfterSuccesfulDiscoDoesNotRequestDisco() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ sendDiscoInfoResult(discoInfo1);
+
+ std::shared_ptr<DiscoInfo> discoInfo(storage->getDiscoInfo(capsInfo1->getVersion()));
+ CPPUNIT_ASSERT(discoInfo);
+ CPPUNIT_ASSERT(discoInfo->hasFeature("http://swift.im/feature1"));
+ }
+
+ void testReceiveIncorrectVerificationDiscoDoesNotStoreCaps() {
+ std::shared_ptr<CapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+ sendDiscoInfoResult(discoInfo2);
+
+ std::shared_ptr<DiscoInfo> discoInfo(storage->getDiscoInfo(capsInfo1->getVersion()));
+ CPPUNIT_ASSERT(!discoInfo);
+ }
+
+ void testReceiveFailingDiscoFallsBack() {
+ std::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));
+ std::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[1]->getPayload<DiscoInfo>());
+ CPPUNIT_ASSERT(discoInfo);
+ CPPUNIT_ASSERT_EQUAL("http://node2.im#" + capsInfo1alt->getVersion(), discoInfo->getNode());
+ }
+
+ void testReceiveNoDiscoFallsBack() {
+ std::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(), std::shared_ptr<DiscoInfo>()));
+
+ CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(1, user2, IQ::Get));
+ std::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[1]->getPayload<DiscoInfo>());
+ CPPUNIT_ASSERT(discoInfo);
+ CPPUNIT_ASSERT_EQUAL("http://node2.im#" + capsInfo1alt->getVersion(), discoInfo->getNode());
+ }
+
+ void testReceiveFailingFallbackDiscoFallsBack() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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:
+ std::shared_ptr<CapsManager> createManager() {
+ std::shared_ptr<CapsManager> manager(new CapsManager(storage.get(), stanzaChannel.get(), iqRouter.get(), 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, std::shared_ptr<CapsInfo> caps) {
+ std::shared_ptr<Presence> presence(new Presence());
+ presence->setFrom(jid);
+ presence->addPayload(caps);
+ stanzaChannel->onPresenceReceived(presence);
+ }
+
+ void sendDiscoInfoResult(std::shared_ptr<DiscoInfo> discoInfo) {
+ stanzaChannel->onIQReceived(IQ::createResult(JID("baz@fum.com/dum"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), discoInfo));
+ }
+
+ private:
+ std::unique_ptr<DummyStanzaChannel> stanzaChannel;
+ std::unique_ptr<IQRouter> iqRouter;
+ std::unique_ptr<CapsStorage> storage;
+ std::vector<JID> changes;
+ JID user1;
+ std::shared_ptr<DiscoInfo> discoInfo1;
+ std::shared_ptr<CapsInfo> capsInfo1;
+ std::shared_ptr<CapsInfo> capsInfo1alt;
+ JID user2;
+ std::shared_ptr<DiscoInfo> discoInfo2;
+ std::shared_ptr<CapsInfo> capsInfo2;
+ std::shared_ptr<CapsInfo> legacyCapsInfo;
+ JID user3;
+ std::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(CapsManagerTest);
diff --git a/Swiften/Disco/UnitTest/DiscoInfoResponderTest.cpp b/Swiften/Disco/UnitTest/DiscoInfoResponderTest.cpp
index 62760f0..45dc959 100644
--- a/Swiften/Disco/UnitTest/DiscoInfoResponderTest.cpp
+++ b/Swiften/Disco/UnitTest/DiscoInfoResponderTest.cpp
@@ -1,96 +1,97 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <typeinfo>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <typeinfo>
#include <Swiften/Disco/DiscoInfoResponder.h>
-#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Queries/DummyIQChannel.h>
+#include <Swiften/Queries/IQRouter.h>
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);
+
+ std::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()));
+ std::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);
+
+ std::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()));
+ std::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_);
+ std::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()));
+ std::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 d5ad27a..8c59741 100644
--- a/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp
+++ b/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp
@@ -1,193 +1,191 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <memory>
#include <vector>
+
#include <boost/bind.hpp>
-#include <Swiften/Disco/EntityCapsManager.h>
-#include <Swiften/Disco/CapsProvider.h>
-#include <Swiften/Elements/CapsInfo.h>
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
#include <Swiften/Client/DummyStanzaChannel.h>
-#include <Swiften/Disco/CapsInfoGenerator.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/Disco/CapsInfoGenerator.h>
+#include <Swiften/Disco/CapsProvider.h>
+#include <Swiften/Disco/EntityCapsManager.h>
+#include <Swiften/Elements/CapsInfo.h>
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 = std::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+
+ stanzaChannel = std::unique_ptr<DummyStanzaChannel>(new DummyStanzaChannel());
+ capsProvider = std::unique_ptr<DummyCapsProvider>(new DummyCapsProvider());
+
+ user1 = JID("user1@bar.com/bla");
+ discoInfo1 = std::make_shared<DiscoInfo>();
+ discoInfo1->addFeature("http://swift.im/feature1");
+ capsInfo1 = std::make_shared<CapsInfo>(CapsInfoGenerator("http://node1.im", crypto.get()).generateCapsInfo(*discoInfo1.get()));
+ capsInfo1alt = std::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo1.get()));
+ user2 = JID("user2@foo.com/baz");
+ discoInfo2 = std::make_shared<DiscoInfo>();
+ discoInfo2->addFeature("http://swift.im/feature2");
+ capsInfo2 = std::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo2.get()));
+ user3 = JID("user3@foo.com/baz");
+ legacyCapsInfo = std::make_shared<CapsInfo>("http://swift.im", "ver1", "");
+ }
+
+ void testReceiveKnownHash() {
+ std::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() {
+ std::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() {
+ std::shared_ptr<EntityCapsManager> testling = createManager();
+ sendPresenceWithCaps(user1, capsInfo1);
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
+ }
+
+ void testHashAvailable() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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:
+ std::shared_ptr<EntityCapsManager> createManager() {
+ std::shared_ptr<EntityCapsManager> manager(new EntityCapsManager(capsProvider.get(), stanzaChannel.get()));
+ 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, std::shared_ptr<CapsInfo> caps) {
+ std::shared_ptr<Presence> presence(new Presence());
+ presence->setFrom(jid);
+ presence->addPayload(caps);
+ stanzaChannel->onPresenceReceived(presence);
+ }
+
+ void sendUnavailablePresence(const JID& jid) {
+ std::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:
+ std::unique_ptr<DummyStanzaChannel> stanzaChannel;
+ std::unique_ptr<DummyCapsProvider> capsProvider;
+ JID user1;
+ std::shared_ptr<DiscoInfo> discoInfo1;
+ std::shared_ptr<CapsInfo> capsInfo1;
+ std::shared_ptr<CapsInfo> capsInfo1alt;
+ JID user2;
+ std::shared_ptr<DiscoInfo> discoInfo2;
+ std::shared_ptr<CapsInfo> capsInfo2;
+ std::shared_ptr<CapsInfo> legacyCapsInfo;
+ JID user3;
+ std::vector<JID> changes;
+ std::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(EntityCapsManagerTest);
diff --git a/Swiften/Disco/UnitTest/FeatureOracleTest.cpp b/Swiften/Disco/UnitTest/FeatureOracleTest.cpp
new file mode 100644
index 0000000..e5ff09b
--- /dev/null
+++ b/Swiften/Disco/UnitTest/FeatureOracleTest.cpp
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <vector>
+
+#include <boost/bind.hpp>
+
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
+#include <Swiften/Base/Tristate.h>
+#include <Swiften/Client/DummyStanzaChannel.h>
+#include <Swiften/Crypto/CryptoProvider.h>
+#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/Disco/CapsInfoGenerator.h>
+#include <Swiften/Disco/CapsProvider.h>
+#include <Swiften/Disco/EntityCapsManager.h>
+#include <Swiften/Disco/FeatureOracle.h>
+#include <Swiften/Elements/CapsInfo.h>
+#include <Swiften/Presence/PresenceOracle.h>
+#include <Swiften/Roster/XMPPRosterImpl.h>
+
+using namespace Swift;
+
+class FeatureOracleTest : public CppUnit::TestFixture {
+ CPPUNIT_TEST_SUITE(FeatureOracleTest);
+ CPPUNIT_TEST(testMergeAvailableResourcesForFeatures);
+ CPPUNIT_TEST(testMostAvailableFileTransferClient);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void setUp() {
+ crypto_ = std::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ dummyStanzaChannel_ = new DummyStanzaChannel();
+ xmppRosterImpl_ = new XMPPRosterImpl();
+ dummyCapsProvider_ = new DummyCapsProvider();
+ entityCapsManager_ = new EntityCapsManager(dummyCapsProvider_, dummyStanzaChannel_);
+ presenceOracle_ = new PresenceOracle(dummyStanzaChannel_, xmppRosterImpl_);
+ featureOracle_ = new FeatureOracle(entityCapsManager_, presenceOracle_);
+ }
+
+ void tearDown() {
+ delete featureOracle_;
+ delete presenceOracle_;
+ delete entityCapsManager_;
+ delete dummyCapsProvider_;
+ delete xmppRosterImpl_;
+ delete dummyStanzaChannel_;
+ }
+
+ void simulateIncomingPresence(const JID& from, Presence::Type type, StatusShow::Type status, const DiscoInfo::ref& disco, const std::vector<Payload::ref>& additionalPayloads = {}) {
+ auto capsInfo = std::make_shared<CapsInfo>(CapsInfoGenerator("http://example.com", crypto_.get()).generateCapsInfo(*disco.get()));
+ dummyCapsProvider_->caps[capsInfo->getVersion()] = disco;
+
+ Presence::ref capsNotifyPresence = std::make_shared<Presence>();
+ capsNotifyPresence->setType(type);
+ capsNotifyPresence->setFrom(from);
+ capsNotifyPresence->setShow(status);
+ capsNotifyPresence->addPayload(capsInfo);
+
+ capsNotifyPresence->addPayloads(additionalPayloads);
+
+ xmppRosterImpl_->addContact(from, "Foo", {}, RosterItemPayload::Both);
+ dummyStanzaChannel_->onPresenceReceived(capsNotifyPresence);
+ }
+
+ DiscoInfo::ref fileTransferSupportingDisco() {
+ DiscoInfo::ref discoInfo = std::make_shared<DiscoInfo>();
+ discoInfo->addFeature(DiscoInfo::JingleFeature);
+ discoInfo->addFeature(DiscoInfo::JingleFTFeature);
+ discoInfo->addFeature(DiscoInfo::JingleTransportsS5BFeature);
+ discoInfo->addFeature(DiscoInfo::JingleTransportsIBBFeature);
+ return discoInfo;
+ }
+
+ DiscoInfo::ref noFileTransferSupportingDisco() {
+ DiscoInfo::ref discoInfo = std::make_shared<DiscoInfo>();
+ discoInfo->addFeature(DiscoInfo::JingleFeature);
+ return discoInfo;
+ }
+
+ void testMergeAvailableResourcesForFeatures() {
+ CPPUNIT_ASSERT_EQUAL(No, featureOracle_->isFileTransferSupported(baseJID));
+
+ simulateIncomingPresence(noFileTransferJID, Presence::Available, StatusShow::Online, noFileTransferSupportingDisco());
+
+ CPPUNIT_ASSERT_EQUAL(size_t(1), presenceOracle_->getAllPresence(baseJID).size());
+ CPPUNIT_ASSERT_EQUAL(No, featureOracle_->isFileTransferSupported(baseJID));
+
+ simulateIncomingPresence(fileTransferJID, Presence::Available, StatusShow::Online, fileTransferSupportingDisco());
+
+ CPPUNIT_ASSERT_EQUAL(size_t(2), presenceOracle_->getAllPresence(baseJID).size());
+ CPPUNIT_ASSERT_EQUAL(Maybe, featureOracle_->isFileTransferSupported(baseJID));
+
+ simulateIncomingPresence(noFileTransferJID, Presence::Unavailable, StatusShow::None, noFileTransferSupportingDisco());
+
+ CPPUNIT_ASSERT_EQUAL(size_t(1), presenceOracle_->getAllPresence(baseJID).size());
+ CPPUNIT_ASSERT_EQUAL(Yes, featureOracle_->isFileTransferSupported(baseJID));
+
+ simulateIncomingPresence(fileTransferJID, Presence::Unavailable, StatusShow::None, fileTransferSupportingDisco());
+
+ CPPUNIT_ASSERT_EQUAL(size_t(1), presenceOracle_->getAllPresence(baseJID).size());
+ CPPUNIT_ASSERT_EQUAL(No, featureOracle_->isFileTransferSupported(baseJID));
+ }
+
+ void testMostAvailableFileTransferClient() {
+ simulateIncomingPresence(fileTransferJID, Presence::Available, StatusShow::DND, fileTransferSupportingDisco());
+
+ CPPUNIT_ASSERT_EQUAL(fileTransferJID, featureOracle_->getMostAvailableClientForFileTrasfer(baseJID));
+
+ simulateIncomingPresence(noFileTransferJID, Presence::Available, StatusShow::Online, noFileTransferSupportingDisco());
+
+ CPPUNIT_ASSERT_EQUAL(fileTransferJID, featureOracle_->getMostAvailableClientForFileTrasfer(baseJID));
+
+ auto moreAvailableJID = baseJID.withResource("moreAvailableFt");
+ simulateIncomingPresence(moreAvailableJID, Presence::Available, StatusShow::Online, fileTransferSupportingDisco());
+
+ CPPUNIT_ASSERT_EQUAL(moreAvailableJID, featureOracle_->getMostAvailableClientForFileTrasfer(baseJID));
+ }
+
+ 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:
+ JID baseJID = "test@example.com";
+ JID fileTransferJID = baseJID.withResource("fileTransfer");
+ JID noFileTransferJID = baseJID.withResource("noFileTransfer");
+
+ std::shared_ptr<CryptoProvider> crypto_;
+ DummyCapsProvider* dummyCapsProvider_;
+ DummyStanzaChannel* dummyStanzaChannel_;
+ EntityCapsManager* entityCapsManager_;
+ FeatureOracle* featureOracle_;
+ PresenceOracle* presenceOracle_;
+ XMPPRosterImpl* xmppRosterImpl_;
+};
+
+CPPUNIT_TEST_SUITE_REGISTRATION(FeatureOracleTest);
diff --git a/Swiften/Disco/UnitTest/JIDDiscoInfoResponderTest.cpp b/Swiften/Disco/UnitTest/JIDDiscoInfoResponderTest.cpp
index adf709e..9369a04 100644
--- a/Swiften/Disco/UnitTest/JIDDiscoInfoResponderTest.cpp
+++ b/Swiften/Disco/UnitTest/JIDDiscoInfoResponderTest.cpp
@@ -1,118 +1,119 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <typeinfo>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <typeinfo>
#include <Swiften/Disco/JIDDiscoInfoResponder.h>
-#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Queries/DummyIQChannel.h>
+#include <Swiften/Queries/IQRouter.h>
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);
+
+ std::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()));
+ std::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);
+
+ std::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()));
+ std::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();
+
+ std::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()));
+ std::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();
+
+ std::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()));
+ std::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 8cfba19..0c43980 100644
--- a/Swiften/Elements/AuthChallenge.h
+++ b/Swiften/Elements/AuthChallenge.h
@@ -1,35 +1,36 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/optional.hpp>
#include <vector>
+#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
#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..9546b0d 100644
--- a/Swiften/Elements/AuthFailure.h
+++ b/Swiften/Elements/AuthFailure.h
@@ -1,21 +1,21 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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 std::shared_ptr<AuthFailure> ref;
- AuthFailure() {}
- };
+ AuthFailure() {}
+ };
}
diff --git a/Swiften/Elements/AuthRequest.h b/Swiften/Elements/AuthRequest.h
index 939a95a..33b25b4 100644
--- a/Swiften/Elements/AuthRequest.h
+++ b/Swiften/Elements/AuthRequest.h
@@ -1,51 +1,52 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <string>
+#include <vector>
+
#include <boost/optional.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/ToplevelElement.h>
#include <Swiften/Base/SafeByteArray.h>
+#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 b1f4419..a88e8d0 100644
--- a/Swiften/Elements/AuthResponse.h
+++ b/Swiften/Elements/AuthResponse.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,33 +7,34 @@
#pragma once
#include <vector>
+
#include <boost/optional.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/ToplevelElement.h>
#include <Swiften/Base/SafeByteArray.h>
+#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 22c259d..860702c 100644
--- a/Swiften/Elements/AuthSuccess.h
+++ b/Swiften/Elements/AuthSuccess.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,25 +7,26 @@
#pragma once
#include <vector>
+
#include <boost/optional.hpp>
#include <Swiften/Base/API.h>
#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 93e738d..acc9df4 100644
--- a/Swiften/Elements/BlockListPayload.h
+++ b/Swiften/Elements/BlockListPayload.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,24 +9,24 @@
#include <vector>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/Payload.h>
+#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 495c79b..df8d150 100644
--- a/Swiften/Elements/BlockPayload.h
+++ b/Swiften/Elements/BlockPayload.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,24 +9,24 @@
#include <vector>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/Payload.h>
+#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 bc114a2..ca30922 100644
--- a/Swiften/Elements/Bytestreams.h
+++ b/Swiften/Elements/Bytestreams.h
@@ -1,62 +1,63 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+#include <string>
#include <vector>
+
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
-#include <string>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/Payload.h>
+#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 std::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 bdfe342..d1e5103 100644
--- a/Swiften/Elements/CapsInfo.h
+++ b/Swiften/Elements/CapsInfo.h
@@ -1,60 +1,60 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <Swiften/Base/API.h>
#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 std::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..9526061 100644
--- a/Swiften/Elements/CarbonsDisable.h
+++ b/Swiften/Elements/CarbonsDisable.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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 std::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..bcb27a2 100644
--- a/Swiften/Elements/CarbonsEnable.h
+++ b/Swiften/Elements/CarbonsEnable.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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 std::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..5cc25ff 100644
--- a/Swiften/Elements/CarbonsPrivate.h
+++ b/Swiften/Elements/CarbonsPrivate.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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 std::shared_ptr<CarbonsPrivate> ref;
- public:
- virtual ~CarbonsPrivate();
- };
+ public:
+ virtual ~CarbonsPrivate();
+ };
}
diff --git a/Swiften/Elements/CarbonsReceived.cpp b/Swiften/Elements/CarbonsReceived.cpp
index d906f8e..7c233a3 100644
--- a/Swiften/Elements/CarbonsReceived.cpp
+++ b/Swiften/Elements/CarbonsReceived.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::shared_ptr<Forwarded> forwarded) {
+ forwarded_ = forwarded;
+ }
- boost::shared_ptr<Forwarded> CarbonsReceived::getForwarded() const {
- return forwarded_;
- }
+ std::shared_ptr<Forwarded> CarbonsReceived::getForwarded() const {
+ return forwarded_;
+ }
}
diff --git a/Swiften/Elements/CarbonsReceived.h b/Swiften/Elements/CarbonsReceived.h
index b057893..c33b600 100644
--- a/Swiften/Elements/CarbonsReceived.h
+++ b/Swiften/Elements/CarbonsReceived.h
@@ -1,28 +1,28 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Forwarded.h>
#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 std::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(std::shared_ptr<Forwarded> forwarded);
+ std::shared_ptr<Forwarded> getForwarded() const;
- private:
- boost::shared_ptr<Forwarded> forwarded_;
- };
+ private:
+ std::shared_ptr<Forwarded> forwarded_;
+ };
}
diff --git a/Swiften/Elements/CarbonsSent.cpp b/Swiften/Elements/CarbonsSent.cpp
index 08b2e13..a026871 100644
--- a/Swiften/Elements/CarbonsSent.cpp
+++ b/Swiften/Elements/CarbonsSent.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::shared_ptr<Forwarded> forwarded) {
+ forwarded_ = forwarded;
+ }
+
+ std::shared_ptr<Forwarded> CarbonsSent::getForwarded() const {
+ return forwarded_;
+ }
}
diff --git a/Swiften/Elements/CarbonsSent.h b/Swiften/Elements/CarbonsSent.h
index f6b2b53..89739de 100644
--- a/Swiften/Elements/CarbonsSent.h
+++ b/Swiften/Elements/CarbonsSent.h
@@ -1,28 +1,28 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Forwarded.h>
#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 std::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(std::shared_ptr<Forwarded> forwarded);
+ std::shared_ptr<Forwarded> getForwarded() const;
- private:
- boost::shared_ptr<Forwarded> forwarded_;
- };
+ private:
+ std::shared_ptr<Forwarded> forwarded_;
+ };
}
diff --git a/Swiften/Elements/ChatState.h b/Swiften/Elements/ChatState.h
index 5f0bb9b..4288398 100644
--- a/Swiften/Elements/ChatState.h
+++ b/Swiften/Elements/ChatState.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::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 060037d..33aadd5 100644
--- a/Swiften/Elements/Command.h
+++ b/Swiften/Elements/Command.h
@@ -1,82 +1,82 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/Form.h>
+#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 std::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 f19c488..4d6d059 100644
--- a/Swiften/Elements/ComponentHandshake.h
+++ b/Swiften/Elements/ComponentHandshake.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <Swiften/Base/API.h>
#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 std::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 0ca073c..3da04b7 100644
--- a/Swiften/Elements/ContainerPayload.h
+++ b/Swiften/Elements/ContainerPayload.h
@@ -1,33 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+#include <vector>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
-#include <vector>
namespace Swift {
- template<typename T>
- class SWIFTEN_API ContainerPayload : public Payload {
- public:
- ContainerPayload() {}
- ContainerPayload(boost::shared_ptr<T> payload) : payload(payload) {}
+ template<typename T>
+ class SWIFTEN_API ContainerPayload : public Payload {
+ public:
+ ContainerPayload() {}
+ ContainerPayload(std::shared_ptr<T> payload) : payload(payload) {}
+
+ void setPayload(std::shared_ptr<T> payload) {
+ this->payload = payload;
+ }
- void setPayload(boost::shared_ptr<T> payload) {
- this->payload = payload;
- }
-
- boost::shared_ptr<T> getPayload() const {
- return payload;
- }
+ std::shared_ptr<T> getPayload() const {
+ return payload;
+ }
- private:
- boost::shared_ptr<T> payload;
- };
+ private:
+ std::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..238485d 100644
--- a/Swiften/Elements/DeliveryReceipt.h
+++ b/Swiften/Elements/DeliveryReceipt.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -20,24 +20,24 @@
namespace Swift {
class SWIFTEN_API DeliveryReceipt : public Payload {
- public:
- typedef boost::shared_ptr<DeliveryReceipt> ref;
+ public:
+ typedef std::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..9a7d478 100644
--- a/Swiften/Elements/DeliveryReceiptRequest.h
+++ b/Swiften/Elements/DeliveryReceiptRequest.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -18,11 +18,11 @@
namespace Swift {
class SWIFTEN_API DeliveryReceiptRequest : public Payload {
- public:
- typedef boost::shared_ptr<DeliveryReceiptRequest> ref;
+ public:
+ typedef std::shared_ptr<DeliveryReceiptRequest> ref;
- public:
- DeliveryReceiptRequest() {}
+ public:
+ DeliveryReceiptRequest() {}
};
}
diff --git a/Swiften/Elements/DiscoInfo.cpp b/Swiften/Elements/DiscoInfo.cpp
index 84f5ed3..51a4450 100644
--- a/Swiften/Elements/DiscoInfo.cpp
+++ b/Swiften/Elements/DiscoInfo.cpp
@@ -24,28 +24,29 @@ const std::string DiscoInfo::Bytestream = std::string("http://jabber.org/protoco
const std::string DiscoInfo::MessageDeliveryReceiptsFeature = std::string("urn:xmpp:receipts");
const std::string DiscoInfo::WhiteboardFeature = std::string("http://swift.im/whiteboard");
const std::string DiscoInfo::BlockingCommandFeature = std::string("urn:xmpp:blocking");
+const std::string DiscoInfo::MessageCarbonsFeature = std::string("urn:xmpp:carbons:2");
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 4019b2e..ebc598c 100644
--- a/Swiften/Elements/DiscoInfo.h
+++ b/Swiften/Elements/DiscoInfo.h
@@ -1,113 +1,114 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <string>
+#include <vector>
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/Form.h>
+#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 std::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;
+ static const std::string MessageCarbonsFeature;
+
+ 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 1084f2b..9c06b8d 100644
--- a/Swiften/Elements/DiscoItems.h
+++ b/Swiften/Elements/DiscoItems.h
@@ -1,71 +1,71 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <string>
+#include <vector>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Payload.h>
#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 ef09f79..bf867e2 100644
--- a/Swiften/Elements/EnableStreamManagement.h
+++ b/Swiften/Elements/EnableStreamManagement.h
@@ -1,17 +1,17 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Elements/ToplevelElement.h>
#include <Swiften/Base/API.h>
+#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 27f4249..0269e4d 100644
--- a/Swiften/Elements/ErrorPayload.h
+++ b/Swiften/Elements/ErrorPayload.h
@@ -1,87 +1,87 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <Swiften/Base/API.h>
#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 std::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(std::shared_ptr<Payload> payload) {
+ payload_ = payload;
+ }
+
+ std::shared_ptr<Payload> getPayload() const {
+ return payload_;
+ }
+
+ private:
+ Type type_;
+ Condition condition_;
+ std::string text_;
+ std::shared_ptr<Payload> payload_;
+ };
}
diff --git a/Swiften/Elements/Form.cpp b/Swiften/Elements/Form.cpp
index b24afea..dc4bd72 100644
--- a/Swiften/Elements/Form.cpp
+++ b/Swiften/Elements/Form.cpp
@@ -1,65 +1,64 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Elements/Form.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
std::string Form::getFormType() const {
- FormField::ref field = getField("FORM_TYPE");
- if (field && field->getType() == FormField::HiddenType) {
- return field->getValues().empty() ? "" : field->getValues()[0];
- }
- return "";
+ FormField::ref 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();
+ for (const auto& 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;
+ for (const auto& field : fields_) {
+ if (field->getType() == FormField::TextSingleType) {
+ if (!field->getTextSingleValue().empty()) {
+ populatedFields.push_back(field);
+ }
+ }
+ else if (field->getType() == FormField::TextMultiType) {
+ if (!field->getTextMultiValue().empty()) {
+ populatedFields.push_back(field);
+ }
+ }
+ else {
+ populatedFields.push_back(field);
+ }
+ }
+ fields_ = populatedFields;
}
}
diff --git a/Swiften/Elements/Form.h b/Swiften/Elements/Form.h
index c1d7a5b..899fb93 100644
--- a/Swiften/Elements/Form.h
+++ b/Swiften/Elements/Form.h
@@ -1,123 +1,124 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
+#include <cassert>
#include <string>
+#include <vector>
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
+#include <Swiften/Elements/FormField.h>
#include <Swiften/Elements/FormPage.h>
#include <Swiften/Elements/FormSection.h>
-#include <Swiften/Elements/FormField.h>
+#include <Swiften/Elements/Payload.h>
#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 std::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(std::shared_ptr<FormPage> page) {
+ assert(page);
+ pages_.push_back(page);
+ }
+
+ const std::vector<std::shared_ptr<FormPage> >& getPages() const {
+ return pages_;
+ }
+
+ void addField(std::shared_ptr<FormField> field) {
+ assert(field);
+ fields_.push_back(field);
+ }
+
+ const std::vector<std::shared_ptr<FormField> >& getFields() const {
+ return fields_;
+ }
+
+ void clearFields() {
+ fields_.clear();
+ }
+
+ void addTextElement(std::shared_ptr<FormText> text) {
+ assert(text);
+ textElements_.push_back(text);
+ }
+
+ const std::vector<std::shared_ptr<FormText> >& getTextElements() const {
+ return textElements_;
+ }
+
+ void addReportedRef(std::shared_ptr<FormReportedRef> reportedRef) {
+ assert(reportedRef);
+ reportedRefs_.push_back(reportedRef);
+ }
+
+ const std::vector<std::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<std::shared_ptr<FormReportedRef> >reportedRefs_;
+ std::vector<std::shared_ptr<FormText> > textElements_;
+ std::vector<std::shared_ptr<FormPage> > pages_;
+ std::vector<std::shared_ptr<FormField> > fields_;
+ std::vector<std::shared_ptr<FormField> > reportedFields_;
+ std::vector<FormItem> items_;
+ std::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 870672c..d4bc9f4 100644
--- a/Swiften/Elements/FormField.cpp
+++ b/Swiften/Elements/FormField.cpp
@@ -1,14 +1,14 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Elements/FormField.h>
-#include <boost/algorithm/string/split.hpp>
-#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/classification.hpp>
+#include <boost/algorithm/string/join.hpp>
+#include <boost/algorithm/string/split.hpp>
using namespace Swift;
@@ -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 a8649fb..194589c 100644
--- a/Swiften/Elements/FormField.h
+++ b/Swiften/Elements/FormField.h
@@ -1,139 +1,140 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
-#include <boost/shared_ptr.hpp>
+#include <cassert>
+#include <memory>
#include <string>
+#include <vector>
#include <Swiften/Base/API.h>
#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 std::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 1a9bd32..0afa112 100644
--- a/Swiften/Elements/FormPage.cpp
+++ b/Swiften/Elements/FormPage.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,62 +7,58 @@
namespace Swift {
-FormPage::FormPage() : xmlns_("http://jabber.org/protocol/xdata-layout") {
+FormPage::FormPage() {
}
FormPage::~FormPage() {
}
void FormPage::setLabel(const std::string& label) {
- label_ = label;
+ label_ = label;
}
const std::string& FormPage::getLabel() const {
- return label_;
+ return label_;
}
-const std::string& FormPage::getXMLNS() const {
- return xmlns_;
+void FormPage::addChildSection(std::shared_ptr<FormSection> section) {
+ childSections_.push_back(section);
}
-void FormPage::addChildSection(boost::shared_ptr<FormSection>& section) {
- childSections_.push_back(section);
+const std::vector<std::shared_ptr<FormSection> >& FormPage::getChildSections() const {
+ return childSections_;
}
-const std::vector<boost::shared_ptr<FormSection> >& FormPage::getChildSections() const {
- return childSections_;
+void FormPage::addTextElement(std::shared_ptr<FormText> textElement) {
+ textElements_.push_back(textElement);
}
-void FormPage::addTextElement(boost::shared_ptr<FormText>& textElement) {
- textElements_.push_back(textElement);
+const std::vector<std::shared_ptr<FormText> >& FormPage::getTextElements() const {
+ return textElements_;
}
-const std::vector<boost::shared_ptr<FormText> >& FormPage::getTextElements() const {
- return textElements_;
+void FormPage::addReportedRef(std::shared_ptr<FormReportedRef> reportedRef) {
+ reportedRefs_.push_back(reportedRef);
}
-void FormPage::addReportedRef(boost::shared_ptr<FormReportedRef>& reportedRef) {
- reportedRefs_.push_back(reportedRef);
+const std::vector<std::shared_ptr<FormReportedRef> >& FormPage::getReportedRefs() const {
+ return reportedRefs_;
}
-const std::vector<boost::shared_ptr<FormReportedRef> >& FormPage::getReportedRefs() const {
- return reportedRefs_;
+void FormPage::addField(std::shared_ptr<FormField> field) {
+ fields_.push_back(field);
}
-void FormPage::addField(boost::shared_ptr<FormField>& field) {
- fields_.push_back(field);
-}
-
-const std::vector<boost::shared_ptr<FormField> >& FormPage::getFields() const {
- return fields_;
+const std::vector<std::shared_ptr<FormField> >& FormPage::getFields() const {
+ 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 e5ecda2..8412d9e 100644
--- a/Swiften/Elements/FormPage.h
+++ b/Swiften/Elements/FormPage.h
@@ -1,13 +1,14 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
#include <vector>
-#include <boost/shared_ptr.hpp>
+
#include <Swiften/Base/API.h>
#include <Swiften/Elements/FormField.h>
#include <Swiften/Elements/FormReportedRef.h>
@@ -16,32 +17,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;
- const std::string& getXMLNS() 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 std::shared_ptr<FormPage> page;
+ FormPage ();
+ ~FormPage();
+ void setLabel(const std::string& label);
+ const std::string& getLabel() const;
+ void addChildSection(std::shared_ptr<FormSection> section);
+ const std::vector<std::shared_ptr<FormSection> >& getChildSections() const;
+ void addTextElement(std::shared_ptr<FormText> textElement);
+ const std::vector<std::shared_ptr<FormText> >& getTextElements() const;
+ void addReportedRef(std::shared_ptr<FormReportedRef> reportedRef);
+ const std::vector<std::shared_ptr<FormReportedRef> >& getReportedRefs() const;
+ void addField(std::shared_ptr<FormField> field);
+ const std::vector<std::shared_ptr<FormField> >& getFields() const;
+ void addFieldRef(std::string ref);
+ const std::vector<std::string> getFieldRefs() const;
- private:
- std::string xmlns_;
- 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<std::shared_ptr<FormText> > textElements_;
+ std::vector<std::shared_ptr<FormSection> > childSections_;
+ std::vector<std::shared_ptr<FormReportedRef> > reportedRefs_;
+ std::vector<std::shared_ptr<FormField> > fields_;
+ std::vector<std::string> fieldRefs_;
+ };
}
diff --git a/Swiften/Elements/FormReportedRef.h b/Swiften/Elements/FormReportedRef.h
index 03a89d1..d6dc718 100644
--- a/Swiften/Elements/FormReportedRef.h
+++ b/Swiften/Elements/FormReportedRef.h
@@ -1,19 +1,19 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
namespace Swift {
- class SWIFTEN_API FormReportedRef {
+ class SWIFTEN_API FormReportedRef {
- public:
- typedef boost::shared_ptr<FormReportedRef> ref;
- };
+ public:
+ typedef std::shared_ptr<FormReportedRef> ref;
+ };
}
diff --git a/Swiften/Elements/FormSection.cpp b/Swiften/Elements/FormSection.cpp
index 46005a0..9ca3b4d 100644
--- a/Swiften/Elements/FormSection.cpp
+++ b/Swiften/Elements/FormSection.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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);
+void FormSection::addTextElement(std::shared_ptr<FormText> textElement) {
+ textElements_.push_back(textElement);
}
-const std::vector<boost::shared_ptr<FormText> >& FormSection::getTextElements() const {
- return textElements_;
+const std::vector<std::shared_ptr<FormText> >& FormSection::getTextElements() const {
+ return textElements_;
}
-void FormSection::addReportedRef(boost::shared_ptr<FormReportedRef>& reportedRef) {
- reportedRefs_.push_back(reportedRef);
+void FormSection::addReportedRef(std::shared_ptr<FormReportedRef> reportedRef) {
+ reportedRefs_.push_back(reportedRef);
}
-const std::vector<boost::shared_ptr<FormReportedRef> >& FormSection::getReportedRefs() const {
- return reportedRefs_;
+const std::vector<std::shared_ptr<FormReportedRef> >& FormSection::getReportedRefs() const {
+ return reportedRefs_;
}
-void FormSection::addChildSection(boost::shared_ptr<FormSection>& childSection) {
- childSections_.push_back(childSection);
+void FormSection::addChildSection(std::shared_ptr<FormSection> childSection) {
+ childSections_.push_back(childSection);
}
-const std::vector<boost::shared_ptr<FormSection> >& FormSection::getChildSections() const {
- return childSections_;
+const std::vector<std::shared_ptr<FormSection> >& FormSection::getChildSections() const {
+ return childSections_;
}
-void FormSection::addField(boost::shared_ptr<FormField>& field) {
- fields_.push_back(field);
+void FormSection::addField(std::shared_ptr<FormField> field) {
+ fields_.push_back(field);
}
-const std::vector<boost::shared_ptr<FormField> >& FormSection::getFields() const {
- return fields_;
+const std::vector<std::shared_ptr<FormField> >& FormSection::getFields() const {
+ 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 f799062..b1d60bc 100644
--- a/Swiften/Elements/FormSection.h
+++ b/Swiften/Elements/FormSection.h
@@ -1,13 +1,14 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
#include <vector>
-#include <boost/shared_ptr.hpp>
+
#include <Swiften/Base/API.h>
#include <Swiften/Elements/FormField.h>
#include <Swiften/Elements/FormReportedRef.h>
@@ -15,30 +16,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 std::shared_ptr<FormSection> section;
+ FormSection();
+ ~FormSection();
+ void setLabel(const std::string& label);
+ const std::string& getLabel() const;
+ void addTextElement(std::shared_ptr<FormText> textElement);
+ const std::vector<std::shared_ptr<FormText> >& getTextElements() const;
+ void addReportedRef(std::shared_ptr<FormReportedRef> reportedRef);
+ const std::vector<std::shared_ptr<FormReportedRef> >& getReportedRefs() const;
+ void addChildSection(std::shared_ptr<FormSection> childSection);
+ const std::vector<std::shared_ptr<FormSection> >& getChildSections() const;
+ void addField(std::shared_ptr<FormField> field);
+ const std::vector<std::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<std::shared_ptr<FormText> > textElements_;
+ std::vector<std::shared_ptr<FormReportedRef> > reportedRefs_;
+ std::vector<std::shared_ptr<FormSection> > childSections_;
+ std::vector<std::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 501af11..a0c8d56 100644
--- a/Swiften/Elements/FormText.h
+++ b/Swiften/Elements/FormText.h
@@ -1,26 +1,27 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
+
#include <Swiften/Base/API.h>
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 std::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 60f0e8c..a7eb492 100644
--- a/Swiften/Elements/Forwarded.h
+++ b/Swiften/Elements/Forwarded.h
@@ -1,32 +1,35 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/optional.hpp>
-#include <boost/date_time/posix_time/posix_time.hpp>
+#include <memory>
+
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class Delay;
- class Stanza;
+ class Delay;
+ class Stanza;
+
+ class SWIFTEN_API Forwarded : public Payload {
+ public:
+ typedef std::shared_ptr<Forwarded> ref;
- class SWIFTEN_API Forwarded : public Payload {
- public:
- virtual ~Forwarded();
+ public:
+ virtual ~Forwarded();
- void setDelay(boost::shared_ptr<Delay> delay) { delay_ = delay; }
- const boost::shared_ptr<Delay>& getDelay() const { return delay_; }
+ void setDelay(std::shared_ptr<Delay> delay) { delay_ = delay; }
+ const std::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(std::shared_ptr<Stanza> stanza) { stanza_ = stanza; }
+ const std::shared_ptr<Stanza>& getStanza() const { return stanza_; }
- private:
- boost::shared_ptr<Delay> delay_;
- boost::shared_ptr<Stanza> stanza_;
- };
+ private:
+ std::shared_ptr<Delay> delay_;
+ std::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 58194b9..bd0b661 100644
--- a/Swiften/Elements/IBB.h
+++ b/Swiften/Elements/IBB.h
@@ -1,108 +1,107 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
#include <vector>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/API.h>
#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 std::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 = std::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 = std::make_shared<IBB>(Data, streamID);
+ result->setSequenceNumber(sequenceNumber);
+ result->setData(data);
+ return result;
+ }
+
+ static IBB::ref createIBBClose(const std::string& streamID) {
+ return std::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..31a654f 100644
--- a/Swiften/Elements/IQ.cpp
+++ b/Swiften/Elements/IQ.cpp
@@ -1,68 +1,68 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Elements/IQ.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
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;
+std::shared_ptr<IQ> IQ::createRequest(
+ Type type, const JID& to, const std::string& id, std::shared_ptr<Payload> payload) {
+ std::shared_ptr<IQ> iq = std::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;
+std::shared_ptr<IQ> IQ::createResult(const JID& to, const std::string& id, std::shared_ptr<Payload> payload) {
+ std::shared_ptr<IQ> iq = std::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;
+std::shared_ptr<IQ> IQ::createResult(const JID& to, const JID& from, const std::string& id, std::shared_ptr<Payload> payload) {
+ std::shared_ptr<IQ> iq = std::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;
+std::shared_ptr<IQ> IQ::createError(const JID& to, const std::string& id, ErrorPayload::Condition condition, ErrorPayload::Type type, std::shared_ptr<Payload> payload) {
+ std::shared_ptr<IQ> iq = std::make_shared<IQ>(IQ::Error);
+ iq->setTo(to);
+ iq->setID(id);
+ std::shared_ptr<ErrorPayload> errorPayload = std::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;
+std::shared_ptr<IQ> IQ::createError(const JID& to, const JID& from, const std::string& id, ErrorPayload::Condition condition, ErrorPayload::Type type, std::shared_ptr<Payload> payload) {
+ std::shared_ptr<IQ> iq = std::make_shared<IQ>(IQ::Error);
+ iq->setTo(to);
+ iq->setFrom(from);
+ iq->setID(id);
+ std::shared_ptr<ErrorPayload> errorPayload = std::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 a44f790..00ed848 100644
--- a/Swiften/Elements/IQ.h
+++ b/Swiften/Elements/IQ.h
@@ -1,58 +1,58 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Stanza.h>
#include <Swiften/Elements/ErrorPayload.h>
+#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 std::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 std::shared_ptr<IQ> createRequest(
+ Type type,
+ const JID& to,
+ const std::string& id,
+ std::shared_ptr<Payload> payload);
+ static std::shared_ptr<IQ> createResult(
+ const JID& to,
+ const std::string& id,
+ std::shared_ptr<Payload> payload = std::shared_ptr<Payload>());
+ static std::shared_ptr<IQ> createResult(
+ const JID& to,
+ const JID& from,
+ const std::string& id,
+ std::shared_ptr<Payload> payload = std::shared_ptr<Payload>());
+ static std::shared_ptr<IQ> createError(
+ const JID& to,
+ const std::string& id,
+ ErrorPayload::Condition condition = ErrorPayload::BadRequest,
+ ErrorPayload::Type type = ErrorPayload::Cancel,
+ std::shared_ptr<Payload> payload = std::shared_ptr<Payload>());
+ static std::shared_ptr<IQ> createError(
+ const JID& to,
+ const JID& from,
+ const std::string& id,
+ ErrorPayload::Condition condition = ErrorPayload::BadRequest,
+ ErrorPayload::Type type = ErrorPayload::Cancel,
+ std::shared_ptr<Payload> payload = std::shared_ptr<Payload>());
+
+ private:
+ Type type_;
+ };
}
diff --git a/Swiften/Elements/Idle.h b/Swiften/Elements/Idle.h
index d30120c..9f721aa 100644
--- a/Swiften/Elements/Idle.h
+++ b/Swiften/Elements/Idle.h
@@ -5,14 +5,15 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <Swiften/Base/API.h>
@@ -20,25 +21,25 @@
namespace Swift {
- class SWIFTEN_API Idle : public Payload {
- public:
- typedef boost::shared_ptr<Idle> ref;
+ class SWIFTEN_API Idle : public Payload {
+ public:
+ typedef std::shared_ptr<Idle> ref;
- public:
- Idle() {}
- Idle(boost::posix_time::ptime since) : since_(since) {
- }
+ public:
+ Idle() {}
+ Idle(boost::posix_time::ptime since) : since_(since) {
+ }
- void setSince(boost::posix_time::ptime since) {
- since_ = since;
- }
+ void setSince(boost::posix_time::ptime since) {
+ since_ = since;
+ }
- boost::posix_time::ptime getSince() const {
- return since_;
- }
+ boost::posix_time::ptime getSince() const {
+ return since_;
+ }
- private:
- boost::posix_time::ptime since_;
- };
+ private:
+ boost::posix_time::ptime since_;
+ };
}
diff --git a/Swiften/Elements/InBandRegistrationPayload.h b/Swiften/Elements/InBandRegistrationPayload.h
index 4089bf7..4fad248 100644
--- a/Swiften/Elements/InBandRegistrationPayload.h
+++ b/Swiften/Elements/InBandRegistrationPayload.h
@@ -1,210 +1,211 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/optional.hpp>
+#include <memory>
#include <string>
+#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/Form.h>
+#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 std::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 c1b2987..39655ce 100644
--- a/Swiften/Elements/IsodeIQDelegation.h
+++ b/Swiften/Elements/IsodeIQDelegation.h
@@ -1,36 +1,36 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Forwarded.h>
+#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API IsodeIQDelegation : public Payload {
- public:
-
- IsodeIQDelegation();
-
- virtual ~IsodeIQDelegation();
+ class SWIFTEN_API IsodeIQDelegation : public Payload {
+ public:
+
+ IsodeIQDelegation();
+
+ virtual ~IsodeIQDelegation();
- boost::shared_ptr<Forwarded> getForward() const {
- return forward;
- }
+ std::shared_ptr<Forwarded> getForward() const {
+ return forward;
+ }
- void setForward(boost::shared_ptr<Forwarded> value) {
- this->forward = value ;
- }
+ void setForward(std::shared_ptr<Forwarded> value) {
+ this->forward = value ;
+ }
- private:
- boost::shared_ptr<Forwarded> forward;
- };
+ private:
+ std::shared_ptr<Forwarded> forward;
+ };
}
diff --git a/Swiften/Elements/JingleContentPayload.h b/Swiften/Elements/JingleContentPayload.h
index f908053..744ac09 100644
--- a/Swiften/Elements/JingleContentPayload.h
+++ b/Swiften/Elements/JingleContentPayload.h
@@ -1,101 +1,102 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
#include <vector>
+
#include <boost/optional.hpp>
-#include <string>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/JingleDescription.h>
#include <Swiften/Elements/JingleTransportPayload.h>
+#include <Swiften/Elements/Payload.h>
+#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 std::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<std::shared_ptr<JingleTransportPayload> >& getTransports() const {
+ return transports;
+ }
+
+ void addTransport(std::shared_ptr<JingleTransportPayload> transport) {
+ transports.push_back(transport);
+ }
+
+ template<typename T>
+ std::shared_ptr<T> getDescription() const {
+ for (const auto& description : descriptions) {
+ std::shared_ptr<T> result(std::dynamic_pointer_cast<T>(description));
+ if (result) {
+ return result;
+ }
+ }
+ return std::shared_ptr<T>();
+ }
+
+ template<typename T>
+ std::shared_ptr<T> getTransport() const {
+ for (const auto& transport : transports) {
+ std::shared_ptr<T> result(std::dynamic_pointer_cast<T>(transport));
+ if (result) {
+ return result;
+ }
+ }
+ return std::shared_ptr<T>();
+ }
+
+ private:
+ Creator creator;
+ std::string name;
+ //Senders senders;
+ std::vector<JingleDescription::ref> descriptions;
+ std::vector<std::shared_ptr<JingleTransportPayload> > transports;
+ };
}
diff --git a/Swiften/Elements/JingleDescription.h b/Swiften/Elements/JingleDescription.h
index 7577383..ee3dcae 100644
--- a/Swiften/Elements/JingleDescription.h
+++ b/Swiften/Elements/JingleDescription.h
@@ -1,19 +1,19 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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 std::shared_ptr<JingleDescription> ref;
+ };
}
diff --git a/Swiften/Elements/JingleFileTransferDescription.h b/Swiften/Elements/JingleFileTransferDescription.h
index 39f10b9..2418f3b 100644
--- a/Swiften/Elements/JingleFileTransferDescription.h
+++ b/Swiften/Elements/JingleFileTransferDescription.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <vector>
#include <Swiften/Base/API.h>
@@ -14,19 +14,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 std::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 92929a0..9fd8756 100644
--- a/Swiften/Elements/JingleFileTransferFileInfo.h
+++ b/Swiften/Elements/JingleFileTransferFileInfo.h
@@ -1,18 +1,18 @@
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <map>
+#include <memory>
#include <string>
#include <vector>
-#include <map>
-#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
+#include <boost/optional.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/HashElement.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 std::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 3f3c3f0..4669e1c 100644
--- a/Swiften/Elements/JingleFileTransferHash.h
+++ b/Swiften/Elements/JingleFileTransferHash.h
@@ -5,15 +5,15 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
#include <map>
+#include <memory>
#include <string>
#include <Swiften/Base/API.h>
@@ -24,18 +24,18 @@ namespace Swift {
class SWIFTEN_API JingleFileTransferHash : public Payload {
public:
- typedef boost::shared_ptr<JingleFileTransferHash> ref;
+ typedef std::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 d87570d..8f0a369 100644
--- a/Swiften/Elements/JingleIBBTransportPayload.h
+++ b/Swiften/Elements/JingleIBBTransportPayload.h
@@ -1,49 +1,50 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/optional.hpp>
+#include <memory>
#include <string>
+#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
#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 std::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 86e3747..a1e8500 100644
--- a/Swiften/Elements/JinglePayload.h
+++ b/Swiften/Elements/JinglePayload.h
@@ -1,166 +1,167 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+#include <string>
#include <vector>
-#include <boost/shared_ptr.hpp>
+
#include <boost/optional.hpp>
-#include <string>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/JingleContentPayload.h>
+#include <Swiften/Elements/Payload.h>
+#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 std::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(std::shared_ptr<Payload> payload) {
+ this->payloads.push_back(payload);
+ }
+
+ const std::vector<JingleContentPayload::ref> getContents() const {
+ return getPayloads<JingleContentPayload>();
+ }
+
+ const std::vector<std::shared_ptr<Payload> > getPayloads() const {
+ return payloads;
+ }
+
+ template<typename T>
+ const std::vector<std::shared_ptr<T> > getPayloads() const {
+ std::vector<std::shared_ptr<T> > matched_payloads;
+ for (const auto& payload : payloads) {
+ std::shared_ptr<T> result = std::dynamic_pointer_cast<T>(payload);
+ if (result) {
+ matched_payloads.push_back(result);
+ }
+ }
+
+ return matched_payloads;
+
+ }
+
+ template<typename T>
+ const std::shared_ptr<T> getPayload() const {
+ std::shared_ptr<T> result;
+ for (const auto& payload : payloads) {
+ result = std::dynamic_pointer_cast<T>(payload);
+ 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<std::shared_ptr<Payload> > payloads;
+ boost::optional<Reason> reason;
+ };
}
diff --git a/Swiften/Elements/JingleS5BTransportPayload.h b/Swiften/Elements/JingleS5BTransportPayload.h
index 313e51a..5e16243 100644
--- a/Swiften/Elements/JingleS5BTransportPayload.h
+++ b/Swiften/Elements/JingleS5BTransportPayload.h
@@ -1,122 +1,120 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <vector>
-#include <boost/shared_ptr.hpp>
-
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/JingleTransportPayload.h>
#include <Swiften/Elements/Bytestreams.h>
+#include <Swiften/Elements/JingleTransportPayload.h>
#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 std::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..dfd9d22 100644
--- a/Swiften/Elements/JingleTransportPayload.h
+++ b/Swiften/Elements/JingleTransportPayload.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <string>
#include <Swiften/Base/API.h>
#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 std::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 30a3f05..e5e719b 100644
--- a/Swiften/Elements/MAMFin.h
+++ b/Swiften/Elements/MAMFin.h
@@ -1,14 +1,14 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>
#include <Swiften/Base/API.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(std::shared_ptr<ResultSet> resultSet) {
+ resultSet_ = resultSet;
+ }
+
+ std::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_;
+ std::shared_ptr<ResultSet> resultSet_;
+ boost::optional<std::string> queryID_;
+ };
}
diff --git a/Swiften/Elements/MAMQuery.h b/Swiften/Elements/MAMQuery.h
index 33902ae..764c238 100644
--- a/Swiften/Elements/MAMQuery.h
+++ b/Swiften/Elements/MAMQuery.h
@@ -1,14 +1,14 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>
#include <Swiften/Base/API.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(std::shared_ptr<Form> form) { form_ = form; }
+ const std::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(std::shared_ptr<ResultSet> resultSet) { resultSet_ = resultSet; }
+ const std::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_;
+ std::shared_ptr<Form> form_;
+ std::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 b271f06..3f78cc8 100644
--- a/Swiften/Elements/MUCAdminPayload.h
+++ b/Swiften/Elements/MUCAdminPayload.h
@@ -1,36 +1,37 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
+#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Elements/Payload.h>
-#include <Swiften/Elements/MUCOccupant.h>
#include <Swiften/Elements/MUCItem.h>
+#include <Swiften/Elements/MUCOccupant.h>
+#include <Swiften/Elements/Payload.h>
+#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 std::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..ad1bda2 100644
--- a/Swiften/Elements/MUCDestroyPayload.h
+++ b/Swiften/Elements/MUCDestroyPayload.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::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..545e60f 100644
--- a/Swiften/Elements/MUCInvitationPayload.h
+++ b/Swiften/Elements/MUCInvitationPayload.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::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..3c89e68 100644
--- a/Swiften/Elements/MUCItem.h
+++ b/Swiften/Elements/MUCItem.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,14 +8,17 @@
#include <Swiften/Elements/MUCOccupant.h>
#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() {}
+ MUCItem(MUCOccupant::Affiliation affiliation, const JID& jid, MUCOccupant::Role role) : realJID(jid), affiliation(affiliation), role(role) {}
+ MUCItem(MUCOccupant::Affiliation affiliation, MUCOccupant::Role role) : affiliation(affiliation), role(role) {}
+ 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..65fb8c2 100644
--- a/Swiften/Elements/MUCOccupant.cpp
+++ b/Swiften/Elements/MUCOccupant.cpp
@@ -1,11 +1,13 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Elements/MUCOccupant.h>
+#include <utility>
+
namespace Swift {
MUCOccupant::MUCOccupant(const std::string &nick, Role role, Affiliation affiliation) : nick_(nick), role_(role), affiliation_(affiliation) {
@@ -18,29 +20,37 @@ MUCOccupant::MUCOccupant(const MUCOccupant& other) : nick_(other.getNick()), rol
}
+MUCOccupant& MUCOccupant::operator=(MUCOccupant other) {
+ std::swap(nick_, other.nick_);
+ std::swap(role_, other.role_);
+ std::swap(affiliation_, other.affiliation_);
+ std::swap(realJID_, other.realJID_);
+ return *this;
+}
+
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 4526229..c345a49 100644
--- a/Swiften/Elements/MUCOccupant.h
+++ b/Swiften/Elements/MUCOccupant.h
@@ -1,42 +1,45 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/optional.hpp>
#include <string>
+#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
#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();
+
+ MUCOccupant& operator=(MUCOccupant other);
+
+ 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 09166b6..5f3c633 100644
--- a/Swiften/Elements/MUCOwnerPayload.h
+++ b/Swiften/Elements/MUCOwnerPayload.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,30 +9,30 @@
#include <boost/optional.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/Form.h>
+#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 std::shared_ptr<MUCOwnerPayload> ref;
- MUCOwnerPayload() {
- }
+ MUCOwnerPayload() {
+ }
- boost::shared_ptr<Payload> getPayload() const {
- return payload;
- }
+ std::shared_ptr<Payload> getPayload() const {
+ return payload;
+ }
- void setPayload(boost::shared_ptr<Payload> p) {
- payload = p;
- }
+ void setPayload(std::shared_ptr<Payload> p) {
+ payload = p;
+ }
- Form::ref getForm() {
- return boost::dynamic_pointer_cast<Form>(payload);
- }
+ Form::ref getForm() {
+ return std::dynamic_pointer_cast<Form>(payload);
+ }
- private:
- boost::shared_ptr<Payload> payload;
- };
+ private:
+ std::shared_ptr<Payload> payload;
+ };
}
diff --git a/Swiften/Elements/MUCPayload.h b/Swiften/Elements/MUCPayload.h
index dadfc6a..6e199e5 100644
--- a/Swiften/Elements/MUCPayload.h
+++ b/Swiften/Elements/MUCPayload.h
@@ -1,75 +1,76 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/optional.hpp>
+#include <string>
+
#include <boost/date_time/posix_time/posix_time_types.hpp>
+#include <boost/optional.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
-#include <string>
#include <Swiften/Elements/Payload.h>
+#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 std::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 ed31816..dd57376 100644
--- a/Swiften/Elements/MUCUserPayload.h
+++ b/Swiften/Elements/MUCUserPayload.h
@@ -1,96 +1,97 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
+#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Elements/Payload.h>
-#include <Swiften/Elements/MUCOccupant.h>
#include <Swiften/Elements/MUCItem.h>
+#include <Swiften/Elements/MUCOccupant.h>
+#include <Swiften/Elements/Payload.h>
+#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 std::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 addItem(const MUCItem& item) {items_.push_back(item);}
-
- void addStatusCode(StatusCode code) {statusCodes_.push_back(code);}
+ void addStatusCode(StatusCode code) {statusCodes_.push_back(code);}
- const std::vector<MUCItem>& getItems() const {return items_;}
+ const std::vector<MUCItem>& getItems() const {return items_;}
- const std::vector<StatusCode>& getStatusCodes() const {return statusCodes_;}
+ const std::vector<StatusCode>& getStatusCodes() const {return statusCodes_;}
- boost::shared_ptr<Payload> getPayload() const {
- return payload_;
- }
+ std::shared_ptr<Payload> getPayload() const {
+ return payload_;
+ }
- void setPayload(boost::shared_ptr<Payload> p) {
- payload_ = p;
- }
+ void setPayload(std::shared_ptr<Payload> p) {
+ payload_ = p;
+ }
- const boost::optional<std::string>& getPassword() const {
- return password_;
- }
+ const boost::optional<std::string>& getPassword() const {
+ return password_;
+ }
- void setPassword(const std::string& password) {
- password_ = password;
- }
+ void setPassword(const std::string& password) {
+ password_ = password;
+ }
- const boost::optional<Invite>& getInvite() const {
- return invite_;
- }
+ const boost::optional<Invite>& getInvite() const {
+ return invite_;
+ }
- void setInvite(const Invite& invite) {
- invite_ = 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_;
+ std::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..c357cd4 100644
--- a/Swiften/Elements/Message.h
+++ b/Swiften/Elements/Message.h
@@ -6,11 +6,10 @@
#pragma once
+#include <memory>
#include <string>
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Body.h>
@@ -20,63 +19,61 @@
#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 std::shared_ptr<Message> ref;
+
+ enum Type { Normal, Chat, Error, Groupchat, Headline };
+
+ Message() : type_(Chat) { }
+
+ std::string getSubject() const {
+ std::shared_ptr<Subject> subject(getPayload<Subject>());
+ if (subject) {
+ return subject->getText();
+ }
+ return "";
+ }
+
+ void setSubject(const std::string& subject) {
+ updatePayload(std::make_shared<Subject>(subject));
+ }
+
+ bool hasSubject() {
+ return getPayload<Subject>() != nullptr;
+ }
+
+ boost::optional<std::string> getBody() const {
+ std::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(std::make_shared<Body>(body.get()));
+ }
+ else {
+ removePayloadOfSameType(std::make_shared<Body>());
+ }
+ }
+
+ bool isError() {
+ std::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 2c62720..123c156 100644
--- a/Swiften/Elements/Nickname.h
+++ b/Swiften/Elements/Nickname.h
@@ -1,30 +1,31 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Payload.h>
-#include <string>
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..9923f0b 100644
--- a/Swiften/Elements/Payload.h
+++ b/Swiften/Elements/Payload.h
@@ -1,25 +1,25 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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 std::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..f75f3be 100644
--- a/Swiften/Elements/Presence.cpp
+++ b/Swiften/Elements/Presence.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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);
+ std::shared_ptr<Priority> priority(getPayload<Priority>());
+ return (priority ? priority->getPriority() : 0);
}
void Presence::setPriority(int priority) {
- updatePayload(boost::make_shared<Priority>(priority));
+ updatePayload(std::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 {
+ std::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(std::make_shared<Status>(status));
}
}
diff --git a/Swiften/Elements/Presence.h b/Swiften/Elements/Presence.h
index 53b77cf..e658606 100644
--- a/Swiften/Elements/Presence.h
+++ b/Swiften/Elements/Presence.h
@@ -1,72 +1,71 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Stanza.h>
#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 std::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 std::make_shared<Presence>();
+ }
- static ref create(const std::string& status) {
- return boost::make_shared<Presence>(status);
- }
+ static ref create(const std::string& status) {
+ return std::make_shared<Presence>(status);
+ }
- static ref create(Presence::ref presence) {
- return boost::make_shared<Presence>(*presence);
- }
+ static ref create(Presence::ref presence) {
+ return std::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 {
+ std::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(std::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);
- }
+ std::shared_ptr<Presence> clone() const {
+ return std::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..dfae34c 100644
--- a/Swiften/Elements/PrivateStorage.h
+++ b/Swiften/Elements/PrivateStorage.h
@@ -1,31 +1,31 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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(std::shared_ptr<Payload> payload = std::shared_ptr<Payload>()) : payload(payload) {
+ }
- boost::shared_ptr<Payload> getPayload() const {
- return payload;
- }
+ std::shared_ptr<Payload> getPayload() const {
+ return payload;
+ }
- void setPayload(boost::shared_ptr<Payload> p) {
- payload = p;
- }
+ void setPayload(std::shared_ptr<Payload> p) {
+ payload = p;
+ }
- private:
- boost::shared_ptr<Payload> payload;
- };
+ private:
+ std::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 a1b2075..d62c54e 100644
--- a/Swiften/Elements/PubSub.h
+++ b/Swiften/Elements/PubSub.h
@@ -1,21 +1,20 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/ContainerPayload.h>
-
#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 fb96160..b19e84b 100644
--- a/Swiften/Elements/PubSubAffiliation.h
+++ b/Swiften/Elements/PubSubAffiliation.h
@@ -1,53 +1,52 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
#include <string>
-
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#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 4fe6896..c7e22ce 100644
--- a/Swiften/Elements/PubSubAffiliations.h
+++ b/Swiften/Elements/PubSubAffiliations.h
@@ -1,53 +1,54 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
+#include <boost/optional.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubAffiliation.h>
#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< std::shared_ptr<PubSubAffiliation> >& getAffiliations() const {
+ return affiliations;
+ }
+
+ void setAffiliations(const std::vector< std::shared_ptr<PubSubAffiliation> >& value) {
+ this->affiliations = value ;
+ }
+
+ void addAffiliation(std::shared_ptr<PubSubAffiliation> value) {
+ this->affiliations.push_back(value);
+ }
+
+
+ private:
+ boost::optional< std::string > node;
+ std::vector< std::shared_ptr<PubSubAffiliation> > affiliations;
+ };
}
diff --git a/Swiften/Elements/PubSubConfigure.h b/Swiften/Elements/PubSubConfigure.h
index 125ef60..8442198 100644
--- a/Swiften/Elements/PubSubConfigure.h
+++ b/Swiften/Elements/PubSubConfigure.h
@@ -1,36 +1,36 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Form.h>
+#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API PubSubConfigure : public Payload {
- public:
-
- PubSubConfigure();
-
- virtual ~PubSubConfigure();
+ class SWIFTEN_API PubSubConfigure : public Payload {
+ public:
+
+ PubSubConfigure();
+
+ virtual ~PubSubConfigure();
- boost::shared_ptr<Form> getData() const {
- return data;
- }
+ std::shared_ptr<Form> getData() const {
+ return data;
+ }
- void setData(boost::shared_ptr<Form> value) {
- this->data = value ;
- }
+ void setData(std::shared_ptr<Form> value) {
+ this->data = value ;
+ }
- private:
- boost::shared_ptr<Form> data;
- };
+ private:
+ std::shared_ptr<Form> data;
+ };
}
diff --git a/Swiften/Elements/PubSubCreate.h b/Swiften/Elements/PubSubCreate.h
index 4c9ac76..5ece36e 100644
--- a/Swiften/Elements/PubSubCreate.h
+++ b/Swiften/Elements/PubSubCreate.h
@@ -1,47 +1,47 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubConfigure.h>
#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 ;
+ }
+
+ std::shared_ptr<PubSubConfigure> getConfigure() const {
+ return configure;
+ }
+
+ void setConfigure(std::shared_ptr<PubSubConfigure> value) {
+ this->configure = value ;
+ }
+
+
+ private:
+ std::string node;
+ std::shared_ptr<PubSubConfigure> configure;
+ };
}
diff --git a/Swiften/Elements/PubSubDefault.h b/Swiften/Elements/PubSubDefault.h
index b63ae72..08482b4 100644
--- a/Swiften/Elements/PubSubDefault.h
+++ b/Swiften/Elements/PubSubDefault.h
@@ -1,51 +1,52 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/optional.hpp>
#include <string>
+#include <boost/optional.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#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 1bb8a15..8f02258 100644
--- a/Swiften/Elements/PubSubEvent.h
+++ b/Swiften/Elements/PubSubEvent.h
@@ -1,23 +1,23 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/ContainerPayload.h>
+#include <Swiften/Elements/Payload.h>
#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 f521d86..5d963a0 100644
--- a/Swiften/Elements/PubSubEventAssociate.h
+++ b/Swiften/Elements/PubSubEventAssociate.h
@@ -1,36 +1,35 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <string>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Payload.h>
-#include <string>
+namespace Swift {
+ class SWIFTEN_API PubSubEventAssociate : public Payload {
+ public:
+ PubSubEventAssociate();
-namespace Swift {
- class SWIFTEN_API PubSubEventAssociate : public Payload {
- public:
-
- PubSubEventAssociate();
-
- virtual ~PubSubEventAssociate();
+ virtual ~PubSubEventAssociate();
- const std::string& getNode() const {
- return node;
- }
+ const std::string& getNode() const {
+ return node;
+ }
- void setNode(const std::string& value) {
- this->node = value ;
- }
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
- private:
- std::string node;
- };
+ private:
+ std::string node;
+ };
}
diff --git a/Swiften/Elements/PubSubEventCollection.h b/Swiften/Elements/PubSubEventCollection.h
index cbdb959..61056e2 100644
--- a/Swiften/Elements/PubSubEventCollection.h
+++ b/Swiften/Elements/PubSubEventCollection.h
@@ -1,58 +1,59 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
+#include <boost/optional.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubEventAssociate.h>
#include <Swiften/Elements/PubSubEventDisassociate.h>
#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 ;
+ }
+
+ std::shared_ptr<PubSubEventDisassociate> getDisassociate() const {
+ return disassociate;
+ }
+
+ void setDisassociate(std::shared_ptr<PubSubEventDisassociate> value) {
+ this->disassociate = value ;
+ }
+
+ std::shared_ptr<PubSubEventAssociate> getAssociate() const {
+ return associate;
+ }
+
+ void setAssociate(std::shared_ptr<PubSubEventAssociate> value) {
+ this->associate = value ;
+ }
+
+
+ private:
+ boost::optional< std::string > node;
+ std::shared_ptr<PubSubEventDisassociate> disassociate;
+ std::shared_ptr<PubSubEventAssociate> associate;
+ };
}
diff --git a/Swiften/Elements/PubSubEventConfiguration.h b/Swiften/Elements/PubSubEventConfiguration.h
index 0ac0b23..6c5305d 100644
--- a/Swiften/Elements/PubSubEventConfiguration.h
+++ b/Swiften/Elements/PubSubEventConfiguration.h
@@ -1,47 +1,47 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Form.h>
+#include <Swiften/Elements/Payload.h>
#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 ;
+ }
+
+ std::shared_ptr<Form> getData() const {
+ return data;
+ }
+
+ void setData(std::shared_ptr<Form> value) {
+ this->data = value ;
+ }
+
+
+ private:
+ std::string node;
+ std::shared_ptr<Form> data;
+ };
}
diff --git a/Swiften/Elements/PubSubEventDelete.h b/Swiften/Elements/PubSubEventDelete.h
index 71a972c..787dce0 100644
--- a/Swiften/Elements/PubSubEventDelete.h
+++ b/Swiften/Elements/PubSubEventDelete.h
@@ -1,47 +1,47 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubEventPayload.h>
#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 ;
+ }
+
+ std::shared_ptr<PubSubEventRedirect> getRedirects() const {
+ return redirects;
+ }
+
+ void setRedirects(std::shared_ptr<PubSubEventRedirect> value) {
+ this->redirects = value ;
+ }
+
+
+ private:
+ std::string node;
+ std::shared_ptr<PubSubEventRedirect> redirects;
+ };
}
diff --git a/Swiften/Elements/PubSubEventDisassociate.h b/Swiften/Elements/PubSubEventDisassociate.h
index 0377c23..826b1f4 100644
--- a/Swiften/Elements/PubSubEventDisassociate.h
+++ b/Swiften/Elements/PubSubEventDisassociate.h
@@ -1,36 +1,35 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <string>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Payload.h>
-#include <string>
+namespace Swift {
+ class SWIFTEN_API PubSubEventDisassociate : public Payload {
+ public:
+ PubSubEventDisassociate();
-namespace Swift {
- class SWIFTEN_API PubSubEventDisassociate : public Payload {
- public:
-
- PubSubEventDisassociate();
-
- virtual ~PubSubEventDisassociate();
+ virtual ~PubSubEventDisassociate();
- const std::string& getNode() const {
- return node;
- }
+ const std::string& getNode() const {
+ return node;
+ }
- void setNode(const std::string& value) {
- this->node = value ;
- }
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
- private:
- std::string node;
- };
+ private:
+ std::string node;
+ };
}
diff --git a/Swiften/Elements/PubSubEventItem.h b/Swiften/Elements/PubSubEventItem.h
index 17c3a52..50e8757 100644
--- a/Swiften/Elements/PubSubEventItem.h
+++ b/Swiften/Elements/PubSubEventItem.h
@@ -1,70 +1,70 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
+#include <boost/optional.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#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< std::shared_ptr<Payload> >& getData() const {
+ return data;
+ }
+
+ void setData(const std::vector< std::shared_ptr<Payload> >& value) {
+ this->data = value ;
+ }
+
+ void addData(std::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< std::shared_ptr<Payload> > data;
+ boost::optional< std::string > id;
+ };
}
diff --git a/Swiften/Elements/PubSubEventItems.h b/Swiften/Elements/PubSubEventItems.h
index e1d1269..48fd340 100644
--- a/Swiften/Elements/PubSubEventItems.h
+++ b/Swiften/Elements/PubSubEventItems.h
@@ -1,66 +1,66 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubEventItem.h>
#include <Swiften/Elements/PubSubEventPayload.h>
#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< std::shared_ptr<PubSubEventItem> >& getItems() const {
+ return items;
+ }
+
+ void setItems(const std::vector< std::shared_ptr<PubSubEventItem> >& value) {
+ this->items = value ;
+ }
+
+ void addItem(std::shared_ptr<PubSubEventItem> value) {
+ this->items.push_back(value);
+ }
+
+ const std::vector< std::shared_ptr<PubSubEventRetract> >& getRetracts() const {
+ return retracts;
+ }
+
+ void setRetracts(const std::vector< std::shared_ptr<PubSubEventRetract> >& value) {
+ this->retracts = value ;
+ }
+
+ void addRetract(std::shared_ptr<PubSubEventRetract> value) {
+ this->retracts.push_back(value);
+ }
+
+
+ private:
+ std::string node;
+ std::vector< std::shared_ptr<PubSubEventItem> > items;
+ std::vector< std::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 b878934..743cc25 100644
--- a/Swiften/Elements/PubSubEventPurge.h
+++ b/Swiften/Elements/PubSubEventPurge.h
@@ -1,36 +1,36 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
#include <string>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubEventPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubEventPurge : public PubSubEventPayload {
- public:
-
- PubSubEventPurge();
-
- virtual ~PubSubEventPurge();
+ class SWIFTEN_API PubSubEventPurge : public PubSubEventPayload {
+ public:
+
+ PubSubEventPurge();
+
+ virtual ~PubSubEventPurge();
- const std::string& getNode() const {
- return node;
- }
+ const std::string& getNode() const {
+ return node;
+ }
- void setNode(const std::string& value) {
- this->node = value ;
- }
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
- private:
- std::string node;
- };
+ private:
+ std::string node;
+ };
}
diff --git a/Swiften/Elements/PubSubEventRedirect.h b/Swiften/Elements/PubSubEventRedirect.h
index 9d10c6e..e0e351f 100644
--- a/Swiften/Elements/PubSubEventRedirect.h
+++ b/Swiften/Elements/PubSubEventRedirect.h
@@ -1,36 +1,35 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <string>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Payload.h>
-#include <string>
+namespace Swift {
+ class SWIFTEN_API PubSubEventRedirect : public Payload {
+ public:
+ PubSubEventRedirect();
-namespace Swift {
- class SWIFTEN_API PubSubEventRedirect : public Payload {
- public:
-
- PubSubEventRedirect();
-
- virtual ~PubSubEventRedirect();
+ virtual ~PubSubEventRedirect();
- const std::string& getURI() const {
- return uri;
- }
+ const std::string& getURI() const {
+ return uri;
+ }
- void setURI(const std::string& value) {
- this->uri = value ;
- }
+ void setURI(const std::string& value) {
+ this->uri = value ;
+ }
- private:
- std::string uri;
- };
+ private:
+ std::string uri;
+ };
}
diff --git a/Swiften/Elements/PubSubEventRetract.h b/Swiften/Elements/PubSubEventRetract.h
index 45c9a1f..b0aea96 100644
--- a/Swiften/Elements/PubSubEventRetract.h
+++ b/Swiften/Elements/PubSubEventRetract.h
@@ -1,36 +1,35 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <string>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Payload.h>
-#include <string>
+namespace Swift {
+ class SWIFTEN_API PubSubEventRetract : public Payload {
+ public:
+ PubSubEventRetract();
-namespace Swift {
- class SWIFTEN_API PubSubEventRetract : public Payload {
- public:
-
- PubSubEventRetract();
-
- virtual ~PubSubEventRetract();
+ virtual ~PubSubEventRetract();
- const std::string& getID() const {
- return id;
- }
+ const std::string& getID() const {
+ return id;
+ }
- void setID(const std::string& value) {
- this->id = value ;
- }
+ void setID(const std::string& value) {
+ this->id = value ;
+ }
- private:
- std::string id;
- };
+ private:
+ std::string id;
+ };
}
diff --git a/Swiften/Elements/PubSubEventSubscription.h b/Swiften/Elements/PubSubEventSubscription.h
index 80710f0..0b8297c 100644
--- a/Swiften/Elements/PubSubEventSubscription.h
+++ b/Swiften/Elements/PubSubEventSubscription.h
@@ -1,81 +1,82 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
+#include <string>
+
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/optional.hpp>
-#include <string>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubEventPayload.h>
#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 38e2560..d424ae4 100644
--- a/Swiften/Elements/PubSubItem.h
+++ b/Swiften/Elements/PubSubItem.h
@@ -1,51 +1,50 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#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< std::shared_ptr<Payload> >& getData() const {
+ return data;
+ }
+
+ void setData(const std::vector< std::shared_ptr<Payload> >& value) {
+ this->data = value ;
+ }
+
+ void addData(std::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< std::shared_ptr<Payload> > data;
+ std::string id;
+ };
}
diff --git a/Swiften/Elements/PubSubItems.h b/Swiften/Elements/PubSubItems.h
index d1200d2..9903075 100644
--- a/Swiften/Elements/PubSubItems.h
+++ b/Swiften/Elements/PubSubItems.h
@@ -1,71 +1,72 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
+#include <boost/optional.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubItem.h>
#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< std::shared_ptr<PubSubItem> >& getItems() const {
+ return items;
+ }
+
+ void setItems(const std::vector< std::shared_ptr<PubSubItem> >& value) {
+ this->items = value ;
+ }
+
+ void addItem(std::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< std::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 0b0ff77..2b312a7 100644
--- a/Swiften/Elements/PubSubOptions.h
+++ b/Swiften/Elements/PubSubOptions.h
@@ -1,67 +1,68 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
+#include <boost/optional.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Form.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubPayload.h>
#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 ;
+ }
+
+ std::shared_ptr<Form> getData() const {
+ return data;
+ }
+
+ void setData(std::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;
+ std::shared_ptr<Form> data;
+ boost::optional< std::string > subscriptionID;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerAffiliation.h b/Swiften/Elements/PubSubOwnerAffiliation.h
index 59060c5..a8c1d91 100644
--- a/Swiften/Elements/PubSubOwnerAffiliation.h
+++ b/Swiften/Elements/PubSubOwnerAffiliation.h
@@ -1,53 +1,51 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Payload.h>
-
-
#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 5e1b400..f1085bb 100644
--- a/Swiften/Elements/PubSubOwnerAffiliations.h
+++ b/Swiften/Elements/PubSubOwnerAffiliations.h
@@ -1,52 +1,52 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubOwnerAffiliation.h>
#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< std::shared_ptr<PubSubOwnerAffiliation> >& getAffiliations() const {
+ return affiliations;
+ }
+
+ void setAffiliations(const std::vector< std::shared_ptr<PubSubOwnerAffiliation> >& value) {
+ this->affiliations = value ;
+ }
+
+ void addAffiliation(std::shared_ptr<PubSubOwnerAffiliation> value) {
+ this->affiliations.push_back(value);
+ }
+
+
+ private:
+ std::string node;
+ std::vector< std::shared_ptr<PubSubOwnerAffiliation> > affiliations;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerConfigure.h b/Swiften/Elements/PubSubOwnerConfigure.h
index 34d4590..7dcf792 100644
--- a/Swiften/Elements/PubSubOwnerConfigure.h
+++ b/Swiften/Elements/PubSubOwnerConfigure.h
@@ -1,48 +1,49 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
+#include <boost/optional.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Form.h>
+#include <Swiften/Elements/Payload.h>
#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 ;
+ }
+
+ std::shared_ptr<Form> getData() const {
+ return data;
+ }
+
+ void setData(std::shared_ptr<Form> value) {
+ this->data = value ;
+ }
+
+
+ private:
+ boost::optional< std::string > node;
+ std::shared_ptr<Form> data;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerDefault.h b/Swiften/Elements/PubSubOwnerDefault.h
index dd306cc..322f47a 100644
--- a/Swiften/Elements/PubSubOwnerDefault.h
+++ b/Swiften/Elements/PubSubOwnerDefault.h
@@ -1,37 +1,37 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Form.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubOwnerPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubOwnerDefault : public PubSubOwnerPayload {
- public:
-
- PubSubOwnerDefault();
-
- virtual ~PubSubOwnerDefault();
+ class SWIFTEN_API PubSubOwnerDefault : public PubSubOwnerPayload {
+ public:
+
+ PubSubOwnerDefault();
+
+ virtual ~PubSubOwnerDefault();
- boost::shared_ptr<Form> getData() const {
- return data;
- }
+ std::shared_ptr<Form> getData() const {
+ return data;
+ }
- void setData(boost::shared_ptr<Form> value) {
- this->data = value ;
- }
+ void setData(std::shared_ptr<Form> value) {
+ this->data = value ;
+ }
- private:
- boost::shared_ptr<Form> data;
- };
+ private:
+ std::shared_ptr<Form> data;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerDelete.h b/Swiften/Elements/PubSubOwnerDelete.h
index 850f25a..7cc5d79 100644
--- a/Swiften/Elements/PubSubOwnerDelete.h
+++ b/Swiften/Elements/PubSubOwnerDelete.h
@@ -1,47 +1,47 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubOwnerPayload.h>
#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 ;
+ }
+
+ std::shared_ptr<PubSubOwnerRedirect> getRedirect() const {
+ return redirect;
+ }
+
+ void setRedirect(std::shared_ptr<PubSubOwnerRedirect> value) {
+ this->redirect = value ;
+ }
+
+
+ private:
+ std::string node;
+ std::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 790437a..f3474cf 100644
--- a/Swiften/Elements/PubSubOwnerPubSub.h
+++ b/Swiften/Elements/PubSubOwnerPubSub.h
@@ -1,21 +1,20 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/ContainerPayload.h>
-
#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 182a5c7..aca48e1 100644
--- a/Swiften/Elements/PubSubOwnerPurge.h
+++ b/Swiften/Elements/PubSubOwnerPurge.h
@@ -1,36 +1,36 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
#include <string>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubOwnerPayload.h>
namespace Swift {
- class SWIFTEN_API PubSubOwnerPurge : public PubSubOwnerPayload {
- public:
-
- PubSubOwnerPurge();
-
- virtual ~PubSubOwnerPurge();
+ class SWIFTEN_API PubSubOwnerPurge : public PubSubOwnerPayload {
+ public:
+
+ PubSubOwnerPurge();
+
+ virtual ~PubSubOwnerPurge();
- const std::string& getNode() const {
- return node;
- }
+ const std::string& getNode() const {
+ return node;
+ }
- void setNode(const std::string& value) {
- this->node = value ;
- }
+ void setNode(const std::string& value) {
+ this->node = value ;
+ }
- private:
- std::string node;
- };
+ private:
+ std::string node;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerRedirect.h b/Swiften/Elements/PubSubOwnerRedirect.h
index 042954e..c481f98 100644
--- a/Swiften/Elements/PubSubOwnerRedirect.h
+++ b/Swiften/Elements/PubSubOwnerRedirect.h
@@ -1,36 +1,35 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <string>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Payload.h>
-#include <string>
+namespace Swift {
+ class SWIFTEN_API PubSubOwnerRedirect : public Payload {
+ public:
+ PubSubOwnerRedirect();
-namespace Swift {
- class SWIFTEN_API PubSubOwnerRedirect : public Payload {
- public:
-
- PubSubOwnerRedirect();
-
- virtual ~PubSubOwnerRedirect();
+ virtual ~PubSubOwnerRedirect();
- const std::string& getURI() const {
- return uri;
- }
+ const std::string& getURI() const {
+ return uri;
+ }
- void setURI(const std::string& value) {
- this->uri = value ;
- }
+ void setURI(const std::string& value) {
+ this->uri = value ;
+ }
- private:
- std::string uri;
- };
+ private:
+ std::string uri;
+ };
}
diff --git a/Swiften/Elements/PubSubOwnerSubscription.h b/Swiften/Elements/PubSubOwnerSubscription.h
index 3af94f4..6a3fcc1 100644
--- a/Swiften/Elements/PubSubOwnerSubscription.h
+++ b/Swiften/Elements/PubSubOwnerSubscription.h
@@ -1,51 +1,49 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Payload.h>
-
-
#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 f4ab174..ec5aa17 100644
--- a/Swiften/Elements/PubSubOwnerSubscriptions.h
+++ b/Swiften/Elements/PubSubOwnerSubscriptions.h
@@ -1,52 +1,52 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubOwnerPayload.h>
#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< std::shared_ptr<PubSubOwnerSubscription> >& getSubscriptions() const {
+ return subscriptions;
+ }
+
+ void setSubscriptions(const std::vector< std::shared_ptr<PubSubOwnerSubscription> >& value) {
+ this->subscriptions = value ;
+ }
+
+ void addSubscription(std::shared_ptr<PubSubOwnerSubscription> value) {
+ this->subscriptions.push_back(value);
+ }
+
+
+ private:
+ std::string node;
+ std::vector< std::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 e4aec02..dff099b 100644
--- a/Swiften/Elements/PubSubPublish.h
+++ b/Swiften/Elements/PubSubPublish.h
@@ -1,52 +1,52 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubItem.h>
#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< std::shared_ptr<PubSubItem> >& getItems() const {
+ return items;
+ }
+
+ void setItems(const std::vector< std::shared_ptr<PubSubItem> >& value) {
+ this->items = value ;
+ }
+
+ void addItem(std::shared_ptr<PubSubItem> value) {
+ this->items.push_back(value);
+ }
+
+
+ private:
+ std::string node;
+ std::vector< std::shared_ptr<PubSubItem> > items;
+ };
}
diff --git a/Swiften/Elements/PubSubRetract.cpp b/Swiften/Elements/PubSubRetract.cpp
index 90a63e6..1b188ee 100644
--- a/Swiften/Elements/PubSubRetract.cpp
+++ b/Swiften/Elements/PubSubRetract.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,7 +8,7 @@
using namespace Swift;
-PubSubRetract::PubSubRetract() : notify(false) {
+PubSubRetract::PubSubRetract() {
}
PubSubRetract::~PubSubRetract() {
diff --git a/Swiften/Elements/PubSubRetract.h b/Swiften/Elements/PubSubRetract.h
index 15ecd00..2629c16 100644
--- a/Swiften/Elements/PubSubRetract.h
+++ b/Swiften/Elements/PubSubRetract.h
@@ -1,61 +1,62 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
+#include <boost/optional.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubItem.h>
#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< std::shared_ptr<PubSubItem> >& getItems() const {
+ return items;
+ }
+
+ void setItems(const std::vector< std::shared_ptr<PubSubItem> >& value) {
+ this->items = value ;
+ }
+
+ void addItem(std::shared_ptr<PubSubItem> value) {
+ this->items.push_back(value);
+ }
+
+ boost::optional<bool> isNotify() const {
+ return notify;
+ }
+
+ void setNotify(const boost::optional<bool>& value) {
+ this->notify = value ;
+ }
+
+
+ private:
+ std::string node;
+ std::vector< std::shared_ptr<PubSubItem> > items;
+ boost::optional<bool> notify;
+ };
}
diff --git a/Swiften/Elements/PubSubSubscribe.h b/Swiften/Elements/PubSubSubscribe.h
index 2b703da..a4c0b68 100644
--- a/Swiften/Elements/PubSubSubscribe.h
+++ b/Swiften/Elements/PubSubSubscribe.h
@@ -1,58 +1,59 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
+#include <boost/optional.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubOptions.h>
#include <Swiften/Elements/PubSubPayload.h>
#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 ;
+ }
+
+ std::shared_ptr<PubSubOptions> getOptions() const {
+ return options;
+ }
+
+ void setOptions(std::shared_ptr<PubSubOptions> value) {
+ this->options = value ;
+ }
+
+
+ private:
+ boost::optional< std::string > node;
+ JID jid;
+ std::shared_ptr<PubSubOptions> options;
+ };
}
diff --git a/Swiften/Elements/PubSubSubscribeOptions.h b/Swiften/Elements/PubSubSubscribeOptions.h
index 70baa56..c837787 100644
--- a/Swiften/Elements/PubSubSubscribeOptions.h
+++ b/Swiften/Elements/PubSubSubscribeOptions.h
@@ -1,36 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Payload.h>
+namespace Swift {
+ class SWIFTEN_API PubSubSubscribeOptions : public Payload {
+ public:
+ PubSubSubscribeOptions();
+ virtual ~PubSubSubscribeOptions();
-namespace Swift {
- class SWIFTEN_API PubSubSubscribeOptions : public Payload {
- public:
-
- PubSubSubscribeOptions();
-
- virtual ~PubSubSubscribeOptions();
-
- bool isRequired() const {
- return required;
- }
+ bool isRequired() const {
+ return required;
+ }
- void setRequired(bool value) {
- this->required = value ;
- }
+ void setRequired(bool value) {
+ this->required = value ;
+ }
- private:
- bool required;
- };
+ private:
+ bool required;
+ };
}
diff --git a/Swiften/Elements/PubSubSubscription.h b/Swiften/Elements/PubSubSubscription.h
index 5ebb791..e2b527f 100644
--- a/Swiften/Elements/PubSubSubscription.h
+++ b/Swiften/Elements/PubSubSubscription.h
@@ -1,82 +1,83 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
+#include <boost/optional.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubPayload.h>
#include <Swiften/Elements/PubSubSubscribeOptions.h>
#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 ;
+ }
+
+ std::shared_ptr<PubSubSubscribeOptions> getOptions() const {
+ return options;
+ }
+
+ void setOptions(std::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;
+ std::shared_ptr<PubSubSubscribeOptions> options;
+ SubscriptionType subscription;
+ };
}
diff --git a/Swiften/Elements/PubSubSubscriptions.h b/Swiften/Elements/PubSubSubscriptions.h
index 9c1db6d..441e6c1 100644
--- a/Swiften/Elements/PubSubSubscriptions.h
+++ b/Swiften/Elements/PubSubSubscriptions.h
@@ -1,53 +1,54 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
+#include <boost/optional.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubPayload.h>
#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< std::shared_ptr<PubSubSubscription> >& getSubscriptions() const {
+ return subscriptions;
+ }
+
+ void setSubscriptions(const std::vector< std::shared_ptr<PubSubSubscription> >& value) {
+ this->subscriptions = value ;
+ }
+
+ void addSubscription(std::shared_ptr<PubSubSubscription> value) {
+ this->subscriptions.push_back(value);
+ }
+
+
+ private:
+ boost::optional< std::string > node;
+ std::vector< std::shared_ptr<PubSubSubscription> > subscriptions;
+ };
}
diff --git a/Swiften/Elements/PubSubUnsubscribe.h b/Swiften/Elements/PubSubUnsubscribe.h
index 9c7bb0e..305af9a 100644
--- a/Swiften/Elements/PubSubUnsubscribe.h
+++ b/Swiften/Elements/PubSubUnsubscribe.h
@@ -1,56 +1,57 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/optional.hpp>
#include <string>
+#include <boost/optional.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/PubSubPayload.h>
#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 eadc8fd..d51981d 100644
--- a/Swiften/Elements/Replace.h
+++ b/Swiften/Elements/Replace.h
@@ -5,31 +5,31 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <Swiften/Base/API.h>
#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 std::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 e9bb6bd..c8e59d4 100644
--- a/Swiften/Elements/ResultSet.h
+++ b/Swiften/Elements/ResultSet.h
@@ -1,53 +1,56 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
#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.cpp b/Swiften/Elements/RosterItemExchangePayload.cpp
index abd5296..79d0371 100644
--- a/Swiften/Elements/RosterItemExchangePayload.cpp
+++ b/Swiften/Elements/RosterItemExchangePayload.cpp
@@ -4,8 +4,13 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Elements/RosterItemExchangePayload.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
diff --git a/Swiften/Elements/RosterItemExchangePayload.h b/Swiften/Elements/RosterItemExchangePayload.h
index 622c775..fc61f3d 100644
--- a/Swiften/Elements/RosterItemExchangePayload.h
+++ b/Swiften/Elements/RosterItemExchangePayload.h
@@ -4,84 +4,90 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <vector>
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
+#include <vector>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Payload.h>
#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 std::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 2228529..ea19fa5 100644
--- a/Swiften/Elements/RosterItemPayload.h
+++ b/Swiften/Elements/RosterItemPayload.h
@@ -1,52 +1,52 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <string>
+#include <vector>
#include <Swiften/Base/API.h>
#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 a41f039..d745357 100644
--- a/Swiften/Elements/RosterPayload.cpp
+++ b/Swiften/Elements/RosterPayload.cpp
@@ -1,23 +1,22 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Elements/RosterPayload.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
boost::optional<RosterItemPayload> RosterPayload::getItem(const JID& jid) const {
- foreach(const RosterItemPayload& item, items_) {
- // 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>();
+ for (const auto& item : items_) {
+ // FIXME: MSVC rejects this. Find out why.
+ //if (item.getJID() == jid) {
+ if (item.getJID().equals(jid, JID::WithResource)) {
+ return boost::optional<RosterItemPayload>(item);
+ }
+ }
+ return boost::optional<RosterItemPayload>();
}
}
diff --git a/Swiften/Elements/RosterPayload.h b/Swiften/Elements/RosterPayload.h
index dba8ded..5fc6bd1 100644
--- a/Swiften/Elements/RosterPayload.h
+++ b/Swiften/Elements/RosterPayload.h
@@ -1,49 +1,49 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <vector>
+
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/RosterItemPayload.h>
#include <Swiften/Elements/Payload.h>
-
+#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 std::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..e3f5206 100644
--- a/Swiften/Elements/S5BProxyRequest.h
+++ b/Swiften/Elements/S5BProxyRequest.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -25,45 +25,45 @@ namespace Swift {
class SWIFTEN_API S5BProxyRequest : public Payload {
public:
- typedef boost::shared_ptr<S5BProxyRequest> ref;
+ typedef std::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 1b1df0f..0fcb2b1 100644
--- a/Swiften/Elements/SearchPayload.h
+++ b/Swiften/Elements/SearchPayload.h
@@ -1,95 +1,96 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <string>
+
#include <boost/optional.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/Form.h>
-#include <string>
+#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 std::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 401ff7a..748c65e 100644
--- a/Swiften/Elements/SecurityLabel.h
+++ b/Swiften/Elements/SecurityLabel.h
@@ -1,77 +1,76 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
#include <string>
#include <vector>
-
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#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 3161c16..ba4d294 100644
--- a/Swiften/Elements/SecurityLabelsCatalog.h
+++ b/Swiften/Elements/SecurityLabelsCatalog.h
@@ -1,89 +1,89 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
+#include <vector>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/SecurityLabel.h>
+#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 std::shared_ptr<SecurityLabelsCatalog> ref;
+ class Item {
+ public:
+ Item() : default_(false) {}
+ std::shared_ptr<SecurityLabel> getLabel() const {
+ return label_;
+ }
+
+ void setLabel(std::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:
+ std::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 6ad5ea5..2bf582e 100644
--- a/Swiften/Elements/SoftwareVersion.h
+++ b/Swiften/Elements/SoftwareVersion.h
@@ -1,55 +1,55 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Base/API.h>
#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 std::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..0ff6b3c 100644
--- a/Swiften/Elements/Stanza.cpp
+++ b/Swiften/Elements/Stanza.cpp
@@ -10,60 +10,59 @@
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/Delay.h>
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);
+void Stanza::updatePayload(std::shared_ptr<Payload> payload) {
+ for (auto&& 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());
+static bool sameType(std::shared_ptr<Payload> a, std::shared_ptr<Payload> b) {
+ 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());
+void Stanza::removePayloadOfSameType(std::shared_ptr<Payload> payload) {
+ payloads_.erase(std::remove_if(payloads_.begin(), payloads_.end(),
+ boost::bind<bool>(&sameType, payload, _1)),
+ payloads_.end());
}
-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>();
+std::shared_ptr<Payload> Stanza::getPayloadOfSameType(std::shared_ptr<Payload> payload) const {
+ for (const auto& i : payloads_) {
+ if (typeid(*i.get()) == typeid(*payload.get())) {
+ return i;
+ }
+ }
+ return std::shared_ptr<Payload>();
}
boost::optional<boost::posix_time::ptime> Stanza::getTimestamp() const {
- boost::shared_ptr<Delay> delay = getPayload<Delay>();
- return delay ? delay->getStamp() : boost::optional<boost::posix_time::ptime>();
+ std::shared_ptr<Delay> delay = getPayload<Delay>();
+ return delay ? delay->getStamp() : boost::optional<boost::posix_time::ptime>();
}
boost::optional<boost::posix_time::ptime> Stanza::getTimestampFrom(const JID& jid) const {
- std::vector< 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< std::shared_ptr<Delay> > delays = getPayloads<Delay>();
+ for (auto& delay : delays) {
+ if (delay->getFrom() == jid) {
+ return delay->getStamp();
+ }
+ }
+ return getTimestamp();
}
diff --git a/Swiften/Elements/Stanza.h b/Swiften/Elements/Stanza.h
index 212ce10..8b4916e 100644
--- a/Swiften/Elements/Stanza.h
+++ b/Swiften/Elements/Stanza.h
@@ -6,91 +6,96 @@
#pragma once
+#include <memory>
#include <string>
#include <vector>
#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/optional/optional.hpp>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/ToplevelElement.h>
#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 std::shared_ptr<Stanza> ref;
+
+ protected:
+ Stanza();
+
+ public:
+ virtual ~Stanza();
+ SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Stanza)
+
+ template<typename T>
+ std::shared_ptr<T> getPayload() const {
+ for (const auto& payload : payloads_) {
+ std::shared_ptr<T> result(std::dynamic_pointer_cast<T>(payload));
+ if (result) {
+ return result;
+ }
+ }
+ return std::shared_ptr<T>();
+ }
+
+ template<typename T>
+ std::vector< std::shared_ptr<T> > getPayloads() const {
+ std::vector< std::shared_ptr<T> > results;
+ for (const auto& payload : payloads_) {
+ std::shared_ptr<T> result(std::dynamic_pointer_cast<T>(payload));
+ if (result) {
+ results.push_back(result);
+ }
+ }
+ return results;
+ }
+
+
+ const std::vector< std::shared_ptr<Payload> >& getPayloads() const {
+ return payloads_;
+ }
+
+ void addPayload(std::shared_ptr<Payload> payload) {
+ payloads_.push_back(payload);
+ }
+
+ template<typename InputIterator>
+ void addPayloads(InputIterator begin, InputIterator end) {
+ payloads_.insert(payloads_.end(), begin, end);
+ }
+
+ template<typename Container>
+ void addPayloads(const Container& container) {
+ payloads_.insert(payloads_.end(), std::begin(container), std::end(container));
+ }
+
+ void updatePayload(std::shared_ptr<Payload> payload);
+
+ void removePayloadOfSameType(std::shared_ptr<Payload>);
+ std::shared_ptr<Payload> getPayloadOfSameType(std::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< std::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..68f0a2f 100644
--- a/Swiften/Elements/StanzaAck.h
+++ b/Swiften/Elements/StanzaAck.h
@@ -1,37 +1,37 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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 std::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 9191ea9..a40865e 100644
--- a/Swiften/Elements/StartSession.h
+++ b/Swiften/Elements/StartSession.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,12 +7,13 @@
#pragma once
#include <string>
+
#include <Swiften/Base/API.h>
#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 a7620e4..2fd2eff 100644
--- a/Swiften/Elements/Status.h
+++ b/Swiften/Elements/Status.h
@@ -1,30 +1,31 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Payload.h>
-#include <string>
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 9f07c65..b339fa1 100644
--- a/Swiften/Elements/StatusShow.h
+++ b/Swiften/Elements/StatusShow.h
@@ -1,48 +1,49 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <cassert>
+
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Payload.h>
-#include <cassert>
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 8bbbc55..87cfb39 100644
--- a/Swiften/Elements/Storage.h
+++ b/Swiften/Elements/Storage.h
@@ -1,67 +1,67 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
#include <vector>
#include <boost/optional.hpp>
-#include <Swiften/Elements/Payload.h>
-#include <string>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Base/SafeString.h>
+#include <Swiften/Elements/Payload.h>
+#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 5a15f40..aa294fd 100644
--- a/Swiften/Elements/StreamError.h
+++ b/Swiften/Elements/StreamError.h
@@ -1,70 +1,70 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <string>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/ToplevelElement.h>
-#include <string>
namespace Swift {
- class SWIFTEN_API StreamError : public ToplevelElement {
- public:
- typedef boost::shared_ptr<StreamError> ref;
+ class SWIFTEN_API StreamError : public ToplevelElement {
+ public:
+ typedef std::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 10563a9..5832a24 100644
--- a/Swiften/Elements/StreamFeatures.h
+++ b/Swiften/Elements/StreamFeatures.h
@@ -1,106 +1,107 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
+#include <memory>
#include <string>
+#include <vector>
+
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Base/API.h>
#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 std::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 53c8f11..2bb9a0e 100644
--- a/Swiften/Elements/StreamInitiation.h
+++ b/Swiften/Elements/StreamInitiation.h
@@ -1,72 +1,73 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+#include <string>
#include <vector>
+
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
-#include <string>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Payload.h>
#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 std::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 bd920a0..f2dc5b9 100644
--- a/Swiften/Elements/StreamInitiationFileInfo.h
+++ b/Swiften/Elements/StreamInitiationFileInfo.h
@@ -1,103 +1,104 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <string>
+
#include <boost/date_time/posix_time/posix_time_types.hpp>
-#include <string>
+#include <Swiften/Base/API.h>
+#include <Swiften/Elements/Payload.h>
namespace Swift {
class SWIFTEN_API StreamInitiationFileInfo : public Payload {
public:
- typedef boost::shared_ptr<StreamInitiationFileInfo> ref;
-
+ typedef std::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 ca08546..0ded077 100644
--- a/Swiften/Elements/StreamResume.h
+++ b/Swiften/Elements/StreamResume.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,35 +7,36 @@
#pragma once
#include <string>
+
#include <boost/optional.hpp>
#include <Swiften/Base/API.h>
#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 68e0688..e1c80d9 100644
--- a/Swiften/Elements/StreamResumed.h
+++ b/Swiften/Elements/StreamResumed.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,35 +7,36 @@
#pragma once
#include <string>
+
#include <boost/optional.hpp>
#include <Swiften/Base/API.h>
#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 b25c31d..4f9444a 100644
--- a/Swiften/Elements/Subject.h
+++ b/Swiften/Elements/Subject.h
@@ -1,30 +1,31 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Payload.h>
-#include <string>
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 20459e2..7d6574d 100644
--- a/Swiften/Elements/UnblockPayload.h
+++ b/Swiften/Elements/UnblockPayload.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,24 +9,24 @@
#include <vector>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/Payload.h>
+#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 3fe8757..c728bde 100644
--- a/Swiften/Elements/UnitTest/FormTest.cpp
+++ b/Swiften/Elements/UnitTest/FormTest.cpp
@@ -1,57 +1,57 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Elements/Form.h>
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(std::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 = std::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(std::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 = std::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(std::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 c67fdc1..ed98c75 100644
--- a/Swiften/Elements/UnitTest/IQTest.cpp
+++ b/Swiften/Elements/UnitTest/IQTest.cpp
@@ -1,12 +1,13 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/SoftwareVersion.h>
@@ -15,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() {
+ std::shared_ptr<Payload> payload(new SoftwareVersion("myclient"));
+ std::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() {
+ std::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() {
+ std::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());
+ std::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 8bead5e..6a45bd8 100644
--- a/Swiften/Elements/UnitTest/StanzaTest.cpp
+++ b/Swiften/Elements/UnitTest/StanzaTest.cpp
@@ -1,231 +1,233 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
+#include <boost/date_time/posix_time/posix_time.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/date_time/posix_time/posix_time.hpp>
-#include <Swiften/Elements/Stanza.h>
-#include <Swiften/Elements/Payload.h>
-#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Delay.h>
+#include <Swiften/Elements/Message.h>
+#include <Swiften/Elements/Payload.h>
+#include <Swiften/Elements/Stanza.h>
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(std::make_shared<MyPayload1>());
+ m.addPayload(std::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(std::make_shared<DestroyingPayload>(&payloadAlive));
+ }
+
+ CPPUNIT_ASSERT(!payloadAlive);
+ }
+
+ void testDestructor_Copy() {
+ bool payloadAlive = true;
+ Message* m1 = new Message();
+ m1->addPayload(std::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(std::make_shared<MyPayload1>());
+ m.addPayload(std::make_shared<MyPayload2>());
+ m.addPayload(std::make_shared<MyPayload3>());
+
+ std::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
+ CPPUNIT_ASSERT(p);
+ }
+
+ void testGetPayload_NoSuchPayload() {
+ Message m;
+ m.addPayload(std::make_shared<MyPayload1>());
+ m.addPayload(std::make_shared<MyPayload3>());
+
+ std::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
+ CPPUNIT_ASSERT(!p);
+ }
+
+ void testGetPayloads() {
+ Message m;
+ std::shared_ptr<MyPayload2> payload1(new MyPayload2());
+ std::shared_ptr<MyPayload2> payload2(new MyPayload2());
+ m.addPayload(std::make_shared<MyPayload1>());
+ m.addPayload(payload1);
+ m.addPayload(std::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(std::make_shared<MyPayload1>());
+ m.addPayload(std::make_shared<MyPayload2>("foo"));
+ m.addPayload(std::make_shared<MyPayload3>());
+
+ m.updatePayload(std::make_shared<MyPayload2>("bar"));
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), m.getPayloads().size());
+ std::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), p->text_);
+ }
+
+ void testUpdatePayload_NewPayload() {
+ Message m;
+ m.addPayload(std::make_shared<MyPayload1>());
+ m.addPayload(std::make_shared<MyPayload3>());
+
+ m.updatePayload(std::make_shared<MyPayload2>("bar"));
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), m.getPayloads().size());
+ std::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), p->text_);
+ }
+
+ void testGetPayloadOfSameType() {
+ Message m;
+ m.addPayload(std::make_shared<MyPayload1>());
+ m.addPayload(std::make_shared<MyPayload2>("foo"));
+ m.addPayload(std::make_shared<MyPayload3>());
+
+ std::shared_ptr<MyPayload2> payload(std::dynamic_pointer_cast<MyPayload2>(m.getPayloadOfSameType(std::make_shared<MyPayload2>("bar"))));
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT_EQUAL(std::string("foo"), payload->text_);
+ }
+
+ void testGetPayloadOfSameType_NoSuchPayload() {
+ Message m;
+ m.addPayload(std::make_shared<MyPayload1>());
+ m.addPayload(std::make_shared<MyPayload3>());
+
+ CPPUNIT_ASSERT(!m.getPayloadOfSameType(std::make_shared<MyPayload2>("bar")));
+ }
+
+ void testGetTimestamp() {
+ Message m;
+ m.addPayload(std::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(std::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(std::make_shared<Delay>(boost::posix_time::from_time_t(0)));
+ m.addPayload(std::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo1@bar.com")));
+ m.addPayload(std::make_shared<Delay>(boost::posix_time::from_time_t(2), JID("foo2@bar.com")));
+ m.addPayload(std::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(std::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo1@bar.com")));
+ m.addPayload(std::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 a23da34..3bdaec6 100644
--- a/Swiften/Elements/UserLocation.h
+++ b/Swiften/Elements/UserLocation.h
@@ -1,227 +1,227 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/date_time/posix_time/posix_time_types.hpp>
-#include <boost/optional.hpp>
#include <string>
+#include <boost/date_time/posix_time/posix_time_types.hpp>
+#include <boost/optional.hpp>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/Payload.h>
namespace Swift {
- class SWIFTEN_API UserLocation : public Payload {
- public:
-
- UserLocation();
-
- virtual ~UserLocation();
+ class SWIFTEN_API UserLocation : public Payload {
+ public:
+
+ UserLocation();
+
+ virtual ~UserLocation();
+
+ const boost::optional< std::string >& getArea() const {
+ return area;
+ }
+
+ void setArea(const boost::optional< std::string >& value) {
+ this->area = value ;
+ }
- const boost::optional< std::string >& getArea() const {
- return area;
- }
+ const boost::optional< double >& getAltitude() const {
+ return altitude;
+ }
- void setArea(const boost::optional< std::string >& value) {
- this->area = value ;
- }
+ void setAltitude(const boost::optional< double >& value) {
+ this->altitude = value ;
+ }
- const boost::optional< float >& getAltitude() const {
- return altitude;
- }
+ const boost::optional< std::string >& getLocality() const {
+ return locality;
+ }
- void setAltitude(const boost::optional< float >& value) {
- this->altitude = value ;
- }
+ void setLocality(const boost::optional< std::string >& value) {
+ this->locality = value ;
+ }
- const boost::optional< std::string >& getLocality() const {
- return locality;
- }
+ const boost::optional< double >& getLatitude() const {
+ return latitude;
+ }
- void setLocality(const boost::optional< std::string >& value) {
- this->locality = value ;
- }
+ void setLatitude(const boost::optional< double >& value) {
+ this->latitude = value ;
+ }
- const boost::optional< float >& getLatitude() const {
- return latitude;
- }
+ const boost::optional< double >& getAccuracy() const {
+ return accuracy;
+ }
- void setLatitude(const boost::optional< float >& value) {
- this->latitude = value ;
- }
+ void setAccuracy(const boost::optional< double >& value) {
+ this->accuracy = value ;
+ }
- const boost::optional< float >& getAccuracy() const {
- return accuracy;
- }
+ const boost::optional< std::string >& getDescription() const {
+ return description;
+ }
- void setAccuracy(const boost::optional< float >& value) {
- this->accuracy = value ;
- }
+ void setDescription(const boost::optional< std::string >& value) {
+ this->description = value ;
+ }
- const boost::optional< std::string >& getDescription() const {
- return description;
- }
+ const boost::optional< std::string >& getCountryCode() const {
+ return countryCode;
+ }
- void setDescription(const boost::optional< std::string >& value) {
- this->description = value ;
- }
+ void setCountryCode(const boost::optional< std::string >& value) {
+ this->countryCode = value ;
+ }
- const boost::optional< std::string >& getCountryCode() const {
- return countryCode;
- }
+ const boost::optional< boost::posix_time::ptime >& getTimestamp() const {
+ return timestamp;
+ }
- void setCountryCode(const boost::optional< std::string >& value) {
- this->countryCode = value ;
- }
+ void setTimestamp(const boost::optional< boost::posix_time::ptime >& value) {
+ this->timestamp = value ;
+ }
- const boost::optional< boost::posix_time::ptime >& getTimestamp() const {
- return timestamp;
- }
+ const boost::optional< std::string >& getFloor() const {
+ return floor;
+ }
- void setTimestamp(const boost::optional< boost::posix_time::ptime >& value) {
- this->timestamp = value ;
- }
+ void setFloor(const boost::optional< std::string >& value) {
+ this->floor = value ;
+ }
- const boost::optional< std::string >& getFloor() const {
- return floor;
- }
+ const boost::optional< std::string >& getBuilding() const {
+ return building;
+ }
- void setFloor(const boost::optional< std::string >& value) {
- this->floor = value ;
- }
+ void setBuilding(const boost::optional< std::string >& value) {
+ this->building = value ;
+ }
- const boost::optional< std::string >& getBuilding() const {
- return building;
- }
+ const boost::optional< std::string >& getRoom() const {
+ return room;
+ }
- void setBuilding(const boost::optional< std::string >& value) {
- this->building = value ;
- }
+ void setRoom(const boost::optional< std::string >& value) {
+ this->room = 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 >& 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< double >& getLongitude() const {
+ return longitude;
+ }
+
+ void setLongitude(const boost::optional< double >& value) {
+ this->longitude = value ;
+ }
+
+ const boost::optional< double >& getError() const {
+ return error;
+ }
+
+ void setError(const boost::optional< double >& 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< double >& getBearing() const {
+ return bearing;
+ }
+
+ void setBearing(const boost::optional< double >& 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< double >& getSpeed() const {
+ return speed;
+ }
+
+ void setSpeed(const boost::optional< double >& value) {
+ this->speed = value ;
+ }
+
+
+ private:
+ boost::optional< std::string > area;
+ boost::optional< double > altitude;
+ boost::optional< std::string > locality;
+ boost::optional< double > latitude;
+ boost::optional< double > 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< double > longitude;
+ boost::optional< double > error;
+ boost::optional< std::string > postalCode;
+ boost::optional< double > bearing;
+ boost::optional< std::string > text;
+ boost::optional< std::string > datum;
+ boost::optional< std::string > street;
+ boost::optional< double > speed;
+ };
}
diff --git a/Swiften/Elements/UserTune.h b/Swiften/Elements/UserTune.h
index 3b0d304..7def9b9 100644
--- a/Swiften/Elements/UserTune.h
+++ b/Swiften/Elements/UserTune.h
@@ -1,91 +1,91 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Payload.h>
-#include <boost/optional.hpp>
#include <string>
+#include <boost/optional.hpp>
+#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
+#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..571ead4 100644
--- a/Swiften/Elements/VCard.cpp
+++ b/Swiften/Elements/VCard.cpp
@@ -1,25 +1,23 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Elements/VCard.h>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
VCard::EMailAddress VCard::getPreferredEMailAddress() const {
- foreach(const EMailAddress& address, emailAddresses_) {
- if (address.isPreferred) {
- return address;
- }
- }
- if (!emailAddresses_.empty()) {
- return emailAddresses_[0];
- }
- return EMailAddress();
+ for (const auto& 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 54f52c2..5a43c3c 100644
--- a/Swiften/Elements/VCard.h
+++ b/Swiften/Elements/VCard.h
@@ -1,302 +1,303 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <string>
+
#include <boost/date_time/posix_time/ptime.hpp>
-#include <string>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/Elements/Payload.h>
+#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 std::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 f4ff01a..037fde4 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardColor.cpp
+++ b/Swiften/Elements/Whiteboard/WhiteboardColor.cpp
@@ -4,52 +4,59 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Elements/Whiteboard/WhiteboardColor.h>
-#include <Swiften/Base/String.h>
+
#include <cstdio>
#include <iomanip>
#include <sstream>
-#include <iostream>
+
+#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 297e75a..ae0fe17 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,23 +13,23 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
+#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 std::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 df774d9..6f6ff4f 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardElement.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardElement.h
@@ -4,29 +4,37 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <string>
+
#include <Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h>
namespace Swift {
- class WhiteboardElement {
- public:
- typedef boost::shared_ptr<WhiteboardElement> ref;
+ class WhiteboardElement {
+ public:
+ typedef std::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 88d0907..8086aed 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,69 +13,69 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardColor.h>
+#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 std::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_ = 0;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h b/Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h
index 6e200fd..bc6c846 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h
@@ -5,60 +5,60 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <utility>
+#include <vector>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardColor.h>
-
-#include <vector>
-#include <utility>
+#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 std::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_ = 0;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h b/Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h
index d52adc2..256c17e 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,23 +13,23 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
+#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 std::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 267fb33..9c64977 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardLineElement.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardLineElement.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,60 +14,60 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardColor.h>
+#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 std::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 497d551..2e90c69 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardOperation.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardOperation.h
@@ -4,48 +4,56 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <Swiften/Base/API.h>
-#include <boost/smart_ptr/shared_ptr.hpp>
#include <string>
+#include <boost/smart_ptr/shared_ptr.hpp>
+
+#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 std::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_ = 0;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h b/Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h
index 38bc3e1..6ad5dc7 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::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_ = 0;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardRectElement.h b/Swiften/Elements/Whiteboard/WhiteboardRectElement.h
index f22ab5c..4dcdc8a 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardRectElement.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardRectElement.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,69 +13,69 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardColor.h>
+#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 std::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 bd9b579..2e1c145 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardTextElement.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardTextElement.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,59 +13,59 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardColor.h>
+#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 std::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_ = 0;
+ std::string text_;
+ WhiteboardColor color_;
+ };
}
diff --git a/Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h b/Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h
index af07e8f..36cbc6d 100644
--- a/Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h
+++ b/Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,32 +13,32 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
+#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 std::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_ = 0;
+ };
}
diff --git a/Swiften/Elements/WhiteboardPayload.h b/Swiften/Elements/WhiteboardPayload.h
index 3fcaa33..41c0acd 100644
--- a/Swiften/Elements/WhiteboardPayload.h
+++ b/Swiften/Elements/WhiteboardPayload.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::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 77d0cc6..0875fb1 100644
--- a/Swiften/Entity/Entity.cpp
+++ b/Swiften/Entity/Entity.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,42 +9,41 @@
#include <Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h>
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
-
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..7cef857 100644
--- a/Swiften/Entity/GenericPayloadPersister.h
+++ b/Swiften/Entity/GenericPayloadPersister.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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:
+ std::shared_ptr<PAYLOAD> loadPayloadGeneric(const boost::filesystem::path& path) {
+ return std::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 b92102e..3fd246c 100644
--- a/Swiften/Entity/PayloadPersister.cpp
+++ b/Swiften/Entity/PayloadPersister.cpp
@@ -1,19 +1,19 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Entity/PayloadPersister.h>
-#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem.hpp>
-#include <iostream>
+#include <boost/filesystem/fstream.hpp>
-#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h>
#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/Log.h>
#include <Swiften/Parser/PayloadParser.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h>
#include <Swiften/Serializer/PayloadSerializer.h>
using namespace Swift;
@@ -24,33 +24,33 @@ PayloadPersister::PayloadPersister() {
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;
- }
+void PayloadPersister::savePayload(std::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) {
+ SWIFT_LOG(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>();
+std::shared_ptr<Payload> PayloadPersister::loadPayload(const boost::filesystem::path& path) {
+ try {
+ if (boost::filesystem::exists(path)) {
+ ByteArray data;
+ readByteArrayFromFile(data, path);
+ std::shared_ptr<PayloadParser> parser(createParser());
+ PayloadParserTester tester(parser.get());
+ tester.parse(byteArrayToString(data));
+ return parser->getPayload();
+ }
+ }
+ catch (const boost::filesystem::filesystem_error& e) {
+ SWIFT_LOG(error) << e.what() << std::endl;
+ }
+ return std::shared_ptr<Payload>();
}
diff --git a/Swiften/Entity/PayloadPersister.h b/Swiften/Entity/PayloadPersister.h
index 5907c69..c747a41 100644
--- a/Swiften/Entity/PayloadPersister.h
+++ b/Swiften/Entity/PayloadPersister.h
@@ -1,32 +1,33 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/filesystem/path.hpp>
#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(std::shared_ptr<Payload>, const boost::filesystem::path&);
+ std::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/Entity/SConscript b/Swiften/Entity/SConscript
index 1342ec1..284e0c0 100644
--- a/Swiften/Entity/SConscript
+++ b/Swiften/Entity/SConscript
@@ -1,6 +1,6 @@
Import("swiften_env")
objects = swiften_env.SwiftenObject([
- "Entity.cpp",
- ])
+ "Entity.cpp",
+ ])
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
diff --git a/Swiften/EventLoop/BoostASIOEventLoop.cpp b/Swiften/EventLoop/BoostASIOEventLoop.cpp
index 1574434..30143b9 100644
--- a/Swiften/EventLoop/BoostASIOEventLoop.cpp
+++ b/Swiften/EventLoop/BoostASIOEventLoop.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -10,7 +10,7 @@
namespace Swift {
-BoostASIOEventLoop::BoostASIOEventLoop(boost::shared_ptr<boost::asio::io_service> ioService) : ioService_(ioService) {
+BoostASIOEventLoop::BoostASIOEventLoop(std::shared_ptr<boost::asio::io_service> ioService) : ioService_(ioService) {
}
@@ -19,19 +19,19 @@ BoostASIOEventLoop::~BoostASIOEventLoop() {
}
void BoostASIOEventLoop::handleASIOEvent() {
- {
- boost::recursive_mutex::scoped_lock lock(isEventInASIOEventLoopMutex_);
- isEventInASIOEventLoop_ = false;
- }
- handleNextEvents();
+ {
+ std::unique_lock<std::recursive_mutex> 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));
- }
+ std::unique_lock<std::recursive_mutex> 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..fbdf443 100644
--- a/Swiften/EventLoop/BoostASIOEventLoop.h
+++ b/Swiften/EventLoop/BoostASIOEventLoop.h
@@ -1,34 +1,35 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+#include <mutex>
+
#include <boost/asio/io_service.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/thread.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/EventLoop/Event.h>
#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(std::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:
+ std::shared_ptr<boost::asio::io_service> ioService_;
- bool isEventInASIOEventLoop_;
- boost::recursive_mutex isEventInASIOEventLoopMutex_;
- };
+ bool isEventInASIOEventLoop_ = false;
+ std::recursive_mutex isEventInASIOEventLoopMutex_;
+ };
}
diff --git a/Swiften/EventLoop/Cocoa/CocoaEvent.h b/Swiften/EventLoop/Cocoa/CocoaEvent.h
index 4453c74..945056e 100644
--- a/Swiften/EventLoop/Cocoa/CocoaEvent.h
+++ b/Swiften/EventLoop/Cocoa/CocoaEvent.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,8 +8,12 @@
#include <Foundation/Foundation.h>
+// The following line is a workaround for a bug in Boost 1.60 when building as C++11.
+// See ticket #11897 and #11863 in Boost's bug tracker.
+#undef check
+
namespace Swift {
- class CocoaEventLoop;
+ class CocoaEventLoop;
}
// Using deprecated declaration of instance vars in interface, because this
@@ -18,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 4f72c29..fc9695b 100644
--- a/Swiften/EventLoop/Cocoa/CocoaEvent.mm
+++ b/Swiften/EventLoop/Cocoa/CocoaEvent.mm
@@ -1,28 +1,29 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/EventLoop/Cocoa/CocoaEvent.h>
+
#include <Swiften/EventLoop/Cocoa/CocoaEventLoop.h>
@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..7f20e6c 100644
--- a/Swiften/EventLoop/Cocoa/CocoaEventLoop.h
+++ b/Swiften/EventLoop/Cocoa/CocoaEventLoop.h
@@ -1,28 +1,28 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/thread.hpp>
+#include <mutex>
#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_;
+ std::recursive_mutex isEventInCocoaEventLoopMutex_;
+ };
}
diff --git a/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm b/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm
index 2d7c613..b8ab621 100644
--- a/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm
+++ b/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -19,25 +19,25 @@ CocoaEventLoop::~CocoaEventLoop() {
}
void CocoaEventLoop::handleNextCocoaEvent() {
- {
- boost::recursive_mutex::scoped_lock lock(isEventInCocoaEventLoopMutex_);
- isEventInCocoaEventLoop_ = false;
- }
- handleNextEvents();
+ {
+ std::unique_lock<std::recursive_mutex> 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];
- }
+ std::unique_lock<std::recursive_mutex> 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..4dfbac3 100644
--- a/Swiften/EventLoop/DummyEventLoop.cpp
+++ b/Swiften/EventLoop/DummyEventLoop.cpp
@@ -1,39 +1,37 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/EventLoop/DummyEventLoop.h>
-#include <iostream>
+#include <Swiften/Base/Log.h>
namespace Swift {
-DummyEventLoop::DummyEventLoop() : hasEvents_(false) {
+DummyEventLoop::DummyEventLoop() {
}
DummyEventLoop::~DummyEventLoop() {
- if (hasEvents()) {
- std::cerr << "DummyEventLoop: Unhandled events at destruction time" << std::endl;
- }
+ if (hasEvents()) {
+ SWIFT_LOG(warning) << "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_;
+ return hasEvents_;
}
void DummyEventLoop::eventPosted() {
- boost::lock_guard<boost::mutex> lock(hasEventsMutex_);
- hasEvents_ = true;
+ hasEvents_ = true;
}
}
diff --git a/Swiften/EventLoop/DummyEventLoop.h b/Swiften/EventLoop/DummyEventLoop.h
index b41cd09..da2a360 100644
--- a/Swiften/EventLoop/DummyEventLoop.h
+++ b/Swiften/EventLoop/DummyEventLoop.h
@@ -1,33 +1,29 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <deque>
-
-#include <boost/thread/locks.hpp>
-#include <boost/thread/mutex.hpp>
+#include <atomic>
#include <Swiften/Base/API.h>
#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:
+ std::atomic<bool> hasEvents_ = ATOMIC_VAR_INIT(false);
+ };
}
diff --git a/Swiften/EventLoop/Event.cpp b/Swiften/EventLoop/Event.cpp
index 0da459b..15d7146 100644
--- a/Swiften/EventLoop/Event.cpp
+++ b/Swiften/EventLoop/Event.cpp
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/EventLoop/Event.h>
-#include <typeinfo>
#include <iostream>
+#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 082d366..e92bb33 100644
--- a/Swiften/EventLoop/Event.h
+++ b/Swiften/EventLoop/Event.h
@@ -1,30 +1,31 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/function.hpp>
#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) {
- }
-
- bool operator==(const Event& o) const {
- return o.id == id;
- }
-
- unsigned int id;
- boost::shared_ptr<EventOwner> owner;
- boost::function<void()> callback;
- };
+ class Event {
+ public:
+ Event(std::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;
+ }
+
+ unsigned int id;
+ std::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..186616f 100644
--- a/Swiften/EventLoop/EventLoop.cpp
+++ b/Swiften/EventLoop/EventLoop.cpp
@@ -8,31 +8,30 @@
#include <algorithm>
#include <cassert>
+#include <vector>
#include <boost/bind.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/optional.hpp>
-#include <boost/thread/locks.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
namespace lambda = boost::lambda;
namespace Swift {
inline void invokeCallback(const Event& event) {
- try {
- assert(!event.callback.empty());
- event.callback();
- }
- catch (const std::exception& e) {
- SWIFT_LOG(error) << "Uncaught exception in event loop: " << e.what() << std::endl;
- }
- catch (...) {
- SWIFT_LOG(error) << "Uncaught non-exception in event loop" << std::endl;
- }
+ 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 +41,62 @@ 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;
+ std::unique_lock<std::recursive_mutex> lock(removeEventsMutex_);
+ {
+ std::vector<Event> nextEvents;
+ {
+ std::unique_lock<std::recursive_mutex> lock(eventsMutex_);
+ for (int n = 0; ((n < eventsBatched) && !events_.empty()); n++) {
+ nextEvents.push_back(events_.front());
+ events_.pop_front();
+ }
+ callEventPosted = !events_.empty();
+ }
+ if (!nextEvents.empty()) {
+ for (const auto& 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();
- }
+void EventLoop::postEvent(boost::function<void ()> callback, std::shared_ptr<EventOwner> owner) {
+ Event event(owner, callback);
+ bool callEventPosted = false;
+ {
+ std::unique_lock<std::recursive_mutex> lock(eventsMutex_);
+
+ callEventPosted = events_.empty();
+
+ event.id = nextEventID_;
+ nextEventID_++;
+ events_.push_back(event);
+ }
+ if (callEventPosted) {
+ eventPosted();
+ }
}
-void EventLoop::removeEventsFromOwner(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);
+void EventLoop::removeEventsFromOwner(std::shared_ptr<EventOwner> owner) {
+ std::unique_lock<std::recursive_mutex> removeLock(removeEventsMutex_, std::defer_lock);
+ std::unique_lock<std::recursive_mutex> eventsLock(eventsMutex_, std::defer_lock);
+
+ std::lock(removeLock, eventsLock);
+
+ events_.remove_if(lambda::bind(&Event::owner, lambda::_1) == owner);
}
}
diff --git a/Swiften/EventLoop/EventLoop.h b/Swiften/EventLoop/EventLoop.h
index 2687501..06b9fbb 100644
--- a/Swiften/EventLoop/EventLoop.h
+++ b/Swiften/EventLoop/EventLoop.h
@@ -7,65 +7,65 @@
#pragma once
#include <list>
+#include <mutex>
#include <boost/function.hpp>
-#include <boost/thread.hpp>
#include <Swiften/Base/API.h>
#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 as \p owner, allowing later removal of events that have not yet been
+ * executed using the \ref removeEventsFromOwner method.
+ */
+ void postEvent(boost::function<void ()> event, std::shared_ptr<EventOwner> owner = std::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 \p owner from the
+ * event queue.
+ */
+ void removeEventsFromOwner(std::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_;
+ std::recursive_mutex eventsMutex_;
+ std::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..b1644c2 100644
--- a/Swiften/EventLoop/Qt/QtEventLoop.h
+++ b/Swiften/EventLoop/Qt/QtEventLoop.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/thread.hpp>
+#include <mutex>
#include <QCoreApplication>
#include <QEvent>
@@ -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() {
+ std::unique_lock<std::recursive_mutex> lock(isEventInQtEventLoopMutex_);
+ if (!isEventInQtEventLoop_) {
+ isEventInQtEventLoop_ = true;
+ QCoreApplication::postEvent(this, new Event());
+ }
+ }
+
+ virtual bool event(QEvent* qevent) {
+ Event* event = dynamic_cast<Event*>(qevent);
+ if (event) {
+ {
+ std::unique_lock<std::recursive_mutex> lock(isEventInQtEventLoopMutex_);
+ isEventInQtEventLoop_ = false;
+ }
+ handleNextEvents();
+ //event->deleteLater(); FIXME: Leak?
+ return true;
+ }
+
+ return false;
+ }
+
+ private:
+ struct Event : public QEvent {
+ Event() :
+ QEvent(QEvent::User) {
+ }
+ };
+
+ bool isEventInQtEventLoop_;
+ std::recursive_mutex isEventInQtEventLoopMutex_;
+ };
}
diff --git a/Swiften/EventLoop/SConscript b/Swiften/EventLoop/SConscript
index b810e8c..7aea53f 100644
--- a/Swiften/EventLoop/SConscript
+++ b/Swiften/EventLoop/SConscript
@@ -1,23 +1,23 @@
Import("swiften_env")
sources = [
- "BoostASIOEventLoop.cpp",
- "DummyEventLoop.cpp",
- "Event.cpp",
- "EventLoop.cpp",
- "EventOwner.cpp",
- "SimpleEventLoop.cpp",
- "SingleThreadedEventLoop.cpp",
- ]
+ "BoostASIOEventLoop.cpp",
+ "DummyEventLoop.cpp",
+ "Event.cpp",
+ "EventLoop.cpp",
+ "EventOwner.cpp",
+ "SimpleEventLoop.cpp",
+ "SingleThreadedEventLoop.cpp",
+ ]
objects = swiften_env.SwiftenObject(sources)
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
if swiften_env["PLATFORM"] == "darwin" and swiften_env["target"] == "native" or swiften_env["target"] == 'xcode':
- myenv = swiften_env.Clone()
- myenv.Append(CXXFLAGS = myenv["OBJCCFLAGS"])
- objects = myenv.SwiftenObject([
- "Cocoa/CocoaEventLoop.mm",
- "Cocoa/CocoaEvent.mm"
- ])
- swiften_env.Append(SWIFTEN_OBJECTS = [objects])
+ myenv = swiften_env.Clone()
+ myenv.Append(CXXFLAGS = myenv["OBJCCFLAGS"])
+ objects = myenv.SwiftenObject([
+ "Cocoa/CocoaEventLoop.mm",
+ "Cocoa/CocoaEvent.mm"
+ ])
+ swiften_env.Append(SWIFTEN_OBJECTS = [objects])
diff --git a/Swiften/EventLoop/SimpleEventLoop.cpp b/Swiften/EventLoop/SimpleEventLoop.cpp
index 59e799f..cac04e4 100644
--- a/Swiften/EventLoop/SimpleEventLoop.cpp
+++ b/Swiften/EventLoop/SimpleEventLoop.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,8 +8,6 @@
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
SimpleEventLoop::SimpleEventLoop() : isRunning_(true), eventAvailable_(false) {
@@ -19,40 +17,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_) {
+ {
+ std::unique_lock<std::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();
+ {
+ std::unique_lock<std::mutex> lock(eventAvailableMutex_);
+ eventAvailable_ = true;
+ }
+ eventAvailableCondition_.notify_one();
}
diff --git a/Swiften/EventLoop/SimpleEventLoop.h b/Swiften/EventLoop/SimpleEventLoop.h
index 221591e..fe5f509 100644
--- a/Swiften/EventLoop/SimpleEventLoop.h
+++ b/Swiften/EventLoop/SimpleEventLoop.h
@@ -1,47 +1,47 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/thread/mutex.hpp>
-#include <boost/thread/condition_variable.hpp>
+#include <condition_variable>
+#include <mutex>
#include <Swiften/Base/API.h>
#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_;
+ std::mutex eventAvailableMutex_;
+ std::condition_variable eventAvailableCondition_;
+ };
}
diff --git a/Swiften/EventLoop/SingleThreadedEventLoop.cpp b/Swiften/EventLoop/SingleThreadedEventLoop.cpp
index d617534..0542f37 100644
--- a/Swiften/EventLoop/SingleThreadedEventLoop.cpp
+++ b/Swiften/EventLoop/SingleThreadedEventLoop.cpp
@@ -4,17 +4,21 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "Swiften/EventLoop/SingleThreadedEventLoop.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
-#include <boost/bind.hpp>
-#include <iostream>
+#include <Swiften/EventLoop/SingleThreadedEventLoop.h>
-#include "Swiften/Base/foreach.h"
+#include <iostream>
+#include <boost/bind.hpp>
namespace Swift {
-SingleThreadedEventLoop::SingleThreadedEventLoop()
+SingleThreadedEventLoop::SingleThreadedEventLoop()
: shouldShutDown_(false), eventAvailable_(false)
{
}
@@ -24,33 +28,34 @@ SingleThreadedEventLoop::~SingleThreadedEventLoop() {
}
void SingleThreadedEventLoop::waitForEvents() {
- boost::unique_lock<boost::mutex> lock(eventAvailableMutex_);
- while (!eventAvailable_ && !shouldShutDown_) {
- eventAvailableCondition_.wait(lock);
- }
-
- if (shouldShutDown_)
- throw EventLoopCanceledException();
+ std::unique_lock<std::mutex> lock(eventAvailableMutex_);
+ while (!eventAvailable_ && !shouldShutDown_) {
+ eventAvailableCondition_.wait(lock);
+ }
+
+ if (shouldShutDown_) {
+ throw EventLoopCanceledException();
+ }
}
void SingleThreadedEventLoop::handleEvents() {
- {
- boost::lock_guard<boost::mutex> lock(eventAvailableMutex_);
- eventAvailable_ = false;
- }
- handleNextEvents();
+ {
+ std::lock_guard<std::mutex> lock(eventAvailableMutex_);
+ eventAvailable_ = false;
+ }
+ handleNextEvents();
}
void SingleThreadedEventLoop::stop() {
- boost::unique_lock<boost::mutex> lock(eventAvailableMutex_);
- shouldShutDown_ = true;
- eventAvailableCondition_.notify_one();
+ std::unique_lock<std::mutex> lock(eventAvailableMutex_);
+ shouldShutDown_ = true;
+ eventAvailableCondition_.notify_one();
}
void SingleThreadedEventLoop::eventPosted() {
- boost::lock_guard<boost::mutex> lock(eventAvailableMutex_);
- eventAvailable_ = true;
- eventAvailableCondition_.notify_one();
+ std::lock_guard<std::mutex> lock(eventAvailableMutex_);
+ eventAvailable_ = true;
+ eventAvailableCondition_.notify_one();
}
} // namespace Swift
diff --git a/Swiften/EventLoop/SingleThreadedEventLoop.h b/Swiften/EventLoop/SingleThreadedEventLoop.h
index 2145d652..9f8cb0a 100644
--- a/Swiften/EventLoop/SingleThreadedEventLoop.h
+++ b/Swiften/EventLoop/SingleThreadedEventLoop.h
@@ -4,13 +4,19 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
+#include <condition_variable>
+#include <mutex>
#include <vector>
-#include <boost/thread/mutex.hpp>
-#include <boost/thread/condition_variable.hpp>
-#include "Swiften/EventLoop/EventLoop.h"
+#include <Swiften/EventLoop/EventLoop.h>
// DESCRIPTION:
//
@@ -22,39 +28,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 { };
-
- 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();
-
- protected:
- virtual void eventPosted();
-
- private:
- bool shouldShutDown_;
-
- bool eventAvailable_;
- boost::mutex eventAvailableMutex_;
- boost::condition_variable eventAvailableCondition_;
- };
+ class SingleThreadedEventLoop : public EventLoop {
+ public:
+ class EventLoopCanceledException : public std::exception { };
+
+ 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();
+
+ protected:
+ virtual void eventPosted();
+
+ private:
+ bool shouldShutDown_;
+
+ bool eventAvailable_;
+ std::mutex eventAvailableMutex_;
+ std::condition_variable eventAvailableCondition_;
+ };
}
diff --git a/Swiften/EventLoop/UnitTest/EventLoopTest.cpp b/Swiften/EventLoop/UnitTest/EventLoopTest.cpp
index 509134e..00a4376 100644
--- a/Swiften/EventLoop/UnitTest/EventLoopTest.cpp
+++ b/Swiften/EventLoop/UnitTest/EventLoopTest.cpp
@@ -1,90 +1,92 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <thread>
+
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/thread.hpp>
-#include <boost/bind.hpp>
+#include <Swiften/Base/sleep.h>
+#include <Swiften/EventLoop/DummyEventLoop.h>
#include <Swiften/EventLoop/EventOwner.h>
#include <Swiften/EventLoop/SimpleEventLoop.h>
-#include <Swiften/EventLoop/DummyEventLoop.h>
-#include <Swiften/Base/sleep.h>
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;
+ std::shared_ptr<MyEventOwner> eventOwner1(new MyEventOwner());
+ std::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;
+ std::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, std::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 759ccad..3d096d3 100644
--- a/Swiften/EventLoop/UnitTest/SimpleEventLoopTest.cpp
+++ b/Swiften/EventLoop/UnitTest/SimpleEventLoopTest.cpp
@@ -1,67 +1,69 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <thread>
+
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/thread.hpp>
-#include <boost/bind.hpp>
-#include <Swiften/EventLoop/SimpleEventLoop.h>
#include <Swiften/Base/sleep.h>
+#include <Swiften/EventLoop/SimpleEventLoop.h>
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();
-
- public:
- void setUp() {
- counter_ = 0;
- }
-
- void testRun() {
- SimpleEventLoop testling;
- boost::thread thread(boost::bind(&SimpleEventLoopTest::runIncrementingThread, this, &testling));
- testling.run();
-
- CPPUNIT_ASSERT_EQUAL(10, counter_);
- }
-
- void testPostFromMainThread() {
- SimpleEventLoop testling;
- testling.postEvent(boost::bind(&SimpleEventLoopTest::incrementCounterAndStop, this, &testling));
- testling.run();
-
- 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();
- }
-
- void incrementCounter() {
- counter_++;
- }
-
- void incrementCounterAndStop(SimpleEventLoop* loop) {
- counter_++;
- loop->stop();
- }
-
- int counter_;
+ 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;
+ }
+
+ void testRun() {
+ SimpleEventLoop testling;
+ std::thread thread(boost::bind(&SimpleEventLoopTest::runIncrementingThread, this, &testling));
+ testling.run();
+
+ CPPUNIT_ASSERT_EQUAL(10, counter_);
+ }
+
+ void testPostFromMainThread() {
+ SimpleEventLoop testling;
+ testling.postEvent(boost::bind(&SimpleEventLoopTest::incrementCounterAndStop, this, &testling));
+ testling.run();
+
+ 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();
+ }
+
+ void incrementCounter() {
+ counter_++;
+ }
+
+ void incrementCounterAndStop(SimpleEventLoop* loop) {
+ counter_++;
+ loop->stop();
+ }
+
+ int counter_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SimpleEventLoopTest);
diff --git a/Swiften/Examples/BenchTool/BenchTool.cpp b/Swiften/Examples/BenchTool/BenchTool.cpp
index 5b6da5f..97d760d 100644
--- a/Swiften/Examples/BenchTool/BenchTool.cpp
+++ b/Swiften/Examples/BenchTool/BenchTool.cpp
@@ -1,21 +1,22 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/bind.hpp>
-#include <boost/thread.hpp>
#include <iostream>
+#include <thread>
+
+#include <boost/bind.hpp>
+#include <Swiften/Base/sleep.h>
#include <Swiften/Client/Client.h>
-#include <Swiften/Network/TimerFactory.h>
-#include <Swiften/Network/BoostNetworkFactories.h>
+#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/EventLoop/SimpleEventLoop.h>
+#include <Swiften/Network/BoostNetworkFactories.h>
+#include <Swiften/Network/TimerFactory.h>
#include <Swiften/Roster/GetRosterRequest.h>
-#include <Swiften/Client/ClientXMLTracer.h>
-#include <Swiften/Base/sleep.h>
#include <Swiften/TLS/BlindCertificateTrustChecker.h>
using namespace Swift;
@@ -27,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);
+ }
- 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();
- }
+ for (auto& client : clients) {
+ client->connect();
+ }
- eventLoop.run();
+ eventLoop.run();
- for (size_t i = 0; i < clients.size(); ++i) {
- delete clients[i];
- }
+ for (auto& client : clients) {
+ delete client;
+ }
- return 0;
+ return 0;
}
diff --git a/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp b/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp
index 306a0df..607038f 100644
--- a/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp
+++ b/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp
@@ -1,21 +1,22 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/bind.hpp>
-#include <boost/thread.hpp>
#include <iostream>
+#include <thread>
+
+#include <boost/bind.hpp>
#include <Swiften/Client/Client.h>
-#include <Swiften/Network/Timer.h>
-#include <Swiften/Network/TimerFactory.h>
-#include <Swiften/Network/BoostNetworkFactories.h>
-#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/Client/ClientXMLTracer.h>
-#include <Swiften/EventLoop/SimpleEventLoop.h>
#include <Swiften/Disco/GetDiscoInfoRequest.h>
+#include <Swiften/EventLoop/EventLoop.h>
+#include <Swiften/EventLoop/SimpleEventLoop.h>
+#include <Swiften/Network/BoostNetworkFactories.h>
+#include <Swiften/Network/Timer.h>
+#include <Swiften/Network/TimerFactory.h>
using namespace Swift;
@@ -24,78 +25,78 @@ enum ExitCodes {OK = 0, CANNOT_CONNECT, CANNOT_AUTH, NO_RESPONSE, DISCO_ERROR};
static SimpleEventLoop eventLoop;
static BoostNetworkFactories networkFactories(&eventLoop);
-static Client* client = 0;
+static Client* client = nullptr;
static JID recipient;
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;
- }
+static boost::signals2::connection errorConnection;
+
+static void handleServerDiscoInfoResponse(std::shared_ptr<DiscoInfo> /*info*/, ErrorPayload::ref 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/SConscript b/Swiften/Examples/LinkLocalTool/SConscript
index 18eb91f..d7617ed 100644
--- a/Swiften/Examples/LinkLocalTool/SConscript
+++ b/Swiften/Examples/LinkLocalTool/SConscript
@@ -5,5 +5,5 @@ myenv.UseFlags(myenv["SWIFTEN_FLAGS"])
myenv.UseFlags(myenv["SWIFTEN_DEP_FLAGS"])
linkLocalTool = myenv.Program("LinkLocalTool", [
- "main.cpp"
- ])
+ "main.cpp"
+ ])
diff --git a/Swiften/Examples/LinkLocalTool/main.cpp b/Swiften/Examples/LinkLocalTool/main.cpp
index 4f87810..a853f0e 100644
--- a/Swiften/Examples/LinkLocalTool/main.cpp
+++ b/Swiften/Examples/LinkLocalTool/main.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,41 +9,41 @@
#include <iostream>
#include <Swiften/EventLoop/SimpleEventLoop.h>
-#include <Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h>
-#include <Swiften/LinkLocal/DNSSD/DNSSDQuerier.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h>
+#include <Swiften/LinkLocal/DNSSD/DNSSDQuerier.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h>
+#include <Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h>
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);
+ std::shared_ptr<DNSSDQuerier> querier = factory.createQuerier();
+ querier->start();
+
+ if (std::string(argv[1]) == "browse") {
+ std::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;
+ }
+ std::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..10b0b40 100644
--- a/Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp
+++ b/Swiften/Examples/MUCListAndJoin/MUCListAndJoin.cpp
@@ -5,11 +5,10 @@
*/
#include <iostream>
+#include <memory>
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/Client.h>
#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/Disco/GetDiscoItemsRequest.h>
@@ -27,94 +26,94 @@ using namespace std;
static SimpleEventLoop eventLoop;
static BoostNetworkFactories networkFactories(&eventLoop);
-static boost::shared_ptr<Client> client;
+static std::shared_ptr<Client> client;
static MUC::ref muc;
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();
+static void handleRoomsItemsResponse(std::shared_ptr<DiscoItems> items, ErrorPayload::ref error) {
+ if (error) {
+ cout << "Error fetching list of rooms." << endl;
+ return;
+ }
+
+ int roomCount = 0;
+ cout << "List of rooms at " << mucJID.toString() << endl;
+ for (auto&& item : items->getItems()) {
+ roomCount++;
+ cout << "\t" << roomCount << ". " << item.getJID().getNode() << " - " << item.getName() << std::endl;
+ if (roomCount == 1) {
+ roomJID = item.getJID();
+ }
+ }
+ cout << endl;
+ joinMUC();
}
static void handleConnected() {
- cout << "Connected." << endl;
- // search for MUC rooms
+ 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;
- }
+static void handleIncomingMessage(std::shared_ptr<Message> message) {
+ 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 = std::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/SConscript b/Swiften/Examples/NetworkTool/SConscript
index 38622ff..c850232 100644
--- a/Swiften/Examples/NetworkTool/SConscript
+++ b/Swiften/Examples/NetworkTool/SConscript
@@ -1,10 +1,10 @@
Import("env")
if env["experimental"] :
- myenv = env.Clone()
- myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
- myenv.MergeFlags(myenv["SWIFTEN_DEP_FLAGS"])
+ myenv = env.Clone()
+ myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
+ myenv.MergeFlags(myenv["SWIFTEN_DEP_FLAGS"])
- linkLocalTool = myenv.Program("NetworkTool", [
- "main.cpp"
- ])
+ linkLocalTool = myenv.Program("NetworkTool", [
+ "main.cpp"
+ ])
diff --git a/Swiften/Examples/NetworkTool/main.cpp b/Swiften/Examples/NetworkTool/main.cpp
index 895bdc1..c50ab67 100644
--- a/Swiften/Examples/NetworkTool/main.cpp
+++ b/Swiften/Examples/NetworkTool/main.cpp
@@ -1,17 +1,18 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <iostream>
+
#include <boost/lexical_cast.hpp>
#include <Swiften/EventLoop/SimpleEventLoop.h>
-#include <Swiften/Network/PlatformNATTraversalWorker.h>
-#include <Swiften/Network/NATTraversalGetPublicIPRequest.h>
#include <Swiften/Network/NATTraversalForwardPortRequest.h>
+#include <Swiften/Network/NATTraversalGetPublicIPRequest.h>
#include <Swiften/Network/NATTraversalRemovePortForwardingRequest.h>
+#include <Swiften/Network/PlatformNATTraversalWorker.h>
#include <Swiften/Network/PlatformNetworkEnvironment.h>
using namespace Swift;
@@ -19,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") {
+ std::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;
+ }
+ std::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;
+ }
+ std::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 8bba86d..71b0611 100644
--- a/Swiften/Examples/ParserTester/ParserTester.cpp
+++ b/Swiften/Examples/ParserTester/ParserTester.cpp
@@ -1,60 +1,61 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <iostream>
+#include <Swiften/Parser/UnitTest/ParserTester.h>
+
#include <fstream>
+#include <iostream>
#include <typeinfo>
-#include <Swiften/Parser/UnitTest/ParserTester.h>
+#include <Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h>
+#include <Swiften/Parser/PlatformXMLParserFactory.h>
#include <Swiften/Parser/XMPPParser.h>
#include <Swiften/Parser/XMPPParserClient.h>
-#include <Swiften/Parser/PlatformXMLParserFactory.h>
-#include <Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h>
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(std::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/SConscript b/Swiften/Examples/SConscript
index 8a0a48f..601cba2 100644
--- a/Swiften/Examples/SConscript
+++ b/Swiften/Examples/SConscript
@@ -3,12 +3,12 @@ Import("swiften_env")
myenv = swiften_env.Clone()
SConscript(dirs = [
- "SendMessage",
- "SendFile",
- "ConnectivityTest",
- "LinkLocalTool",
- "NetworkTool",
- "ParserTester",
- "BenchTool",
- "MUCListAndJoin",
+ "SendMessage",
+ "SendFile",
+ "ConnectivityTest",
+ "LinkLocalTool",
+ "NetworkTool",
+ "ParserTester",
+ "BenchTool",
+ "MUCListAndJoin",
])
diff --git a/Swiften/Examples/SendFile/ReceiveFile.cpp b/Swiften/Examples/SendFile/ReceiveFile.cpp
index 8f045bd..193c1b7 100644
--- a/Swiften/Examples/SendFile/ReceiveFile.cpp
+++ b/Swiften/Examples/SendFile/ReceiveFile.cpp
@@ -1,28 +1,28 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <iostream>
+#include <memory>
+
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <iostream>
-#include <Swiften/Elements/Presence.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/Client.h>
-#include <Swiften/Elements/DiscoInfo.h>
-#include <Swiften/Network/BoostNetworkFactories.h>
-#include <Swiften/EventLoop/SimpleEventLoop.h>
#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/Disco/ClientDiscoManager.h>
-#include <Swiften/FileTransfer/IncomingFileTransferManager.h>
+#include <Swiften/Elements/DiscoInfo.h>
+#include <Swiften/Elements/Presence.h>
+#include <Swiften/EventLoop/SimpleEventLoop.h>
+#include <Swiften/FileTransfer/FileTransferManager.h>
#include <Swiften/FileTransfer/FileWriteBytestream.h>
-#include <Swiften/Jingle/JingleSessionManager.h>
+#include <Swiften/FileTransfer/IncomingFileTransferManager.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
-#include <Swiften/FileTransfer/FileTransferManager.h>
+#include <Swiften/Jingle/JingleSessionManager.h>
+#include <Swiften/Network/BoostNetworkFactories.h>
using namespace Swift;
@@ -35,101 +35,102 @@ 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() {
+ for (const auto& transfer : incomingFileTransfers) {
+ (void)transfer;
+ //transfer->stop();
+ }
+ client->disconnect();
+ }
+
+ private:
+ void handleConnected() {
+ Log::setLogLevel(Log::debug);
+ client->getFileTransferManager()->onIncomingFileTransfer.connect(boost::bind(&FileReceiver::handleIncomingFileTransfer, this, _1));
+
+ DiscoInfo discoInfo;
+ discoInfo.addIdentity(DiscoInfo::Identity(CLIENT_NAME, "client", "pc"));
+ discoInfo.addFeature(DiscoInfo::JingleFeature);
+ discoInfo.addFeature(DiscoInfo::JingleFTFeature);
+ discoInfo.addFeature(DiscoInfo::Bytestream);
+ discoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature);
+ discoInfo.addFeature(DiscoInfo::JingleTransportsS5BFeature);
+ client->getDiscoManager()->setCapsNode(CLIENT_NODE);
+ client->getDiscoManager()->setDiscoInfo(discoInfo);
+ client->getPresenceSender()->sendPresence(Presence::create());
+ }
+
+ void handleIncomingFileTransfer(IncomingFileTransfer::ref transfer) {
+ SWIFT_LOG(debug) << "foo" << std::endl;
+ incomingFileTransfers.push_back(transfer);
+ std::shared_ptr<FileWriteBytestream> out = std::make_shared<FileWriteBytestream>("out");
+ transfer->onFinished.connect(boost::bind(&FileReceiver::handleFileTransferFinished, this, _1, out));
+ transfer->accept(out);
+ }
+
+ void handleDisconnected(const boost::optional<ClientError>&) {
+ std::cerr << "Error!" << std::endl;
+ exit(-1);
+ }
+
+ void handleFileTransferFinished(
+ const boost::optional<FileTransferError>& error,
+ std::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..0e1fb23 100644
--- a/Swiften/Examples/SendFile/SendFile.cpp
+++ b/Swiften/Examples/SendFile/SendFile.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(nullptr) {
+ 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
+ std::shared_ptr<FileReadBytestream> fileStream = std::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 e32c9e8..0b46b41 100644
--- a/Swiften/Examples/SendMessage/SendMessage.cpp
+++ b/Swiften/Examples/SendMessage/SendMessage.cpp
@@ -1,90 +1,91 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/bind.hpp>
-#include <boost/thread.hpp>
#include <iostream>
+#include <thread>
+
+#include <boost/bind.hpp>
#include <Swiften/Client/Client.h>
+#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/Elements/Message.h>
-#include <Swiften/Network/BoostNetworkFactories.h>
-#include <Swiften/Network/TimerFactory.h>
#include <Swiften/EventLoop/EventLoop.h>
-#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/EventLoop/SimpleEventLoop.h>
+#include <Swiften/Network/BoostNetworkFactories.h>
+#include <Swiften/Network/TimerFactory.h>
using namespace Swift;
static SimpleEventLoop eventLoop;
static BoostNetworkFactories networkFactories(&eventLoop);
-static Client* client = 0;
+static Client* client = nullptr;
static JID recipient;
static std::string messageBody;
static int exitCode = 2;
-static boost::bsignals::connection errorConnection;
+static boost::signals2::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();
+ std::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 66095bf..cd9fa4a 100644
--- a/Swiften/FileTransfer/ByteArrayReadBytestream.cpp
+++ b/Swiften/FileTransfer/ByteArrayReadBytestream.cpp
@@ -1,33 +1,34 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/ByteArrayReadBytestream.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
#include <Swiften/Base/Algorithm.h>
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));
-
- onRead(*result);
- position += readSize;
- return result;
+std::shared_ptr<ByteArray> ByteArrayReadBytestream::read(size_t size) {
+ size_t readSize = size;
+ if (position + readSize > data.size()) {
+ readSize = data.size() - position;
+ }
+ std::shared_ptr<ByteArray> result = std::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;
}
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 308d8c5..d90e5cc 100644
--- a/Swiften/FileTransfer/ByteArrayReadBytestream.h
+++ b/Swiften/FileTransfer/ByteArrayReadBytestream.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,30 +9,30 @@
#include <vector>
#include <Swiften/Base/API.h>
-#include <Swiften/FileTransfer/ReadBytestream.h>
#include <Swiften/Base/ByteArray.h>
+#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 std::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 65fda9a..d278e79 100644
--- a/Swiften/FileTransfer/BytestreamsRequest.h
+++ b/Swiften/FileTransfer/BytestreamsRequest.h
@@ -1,35 +1,35 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/Bytestreams.h>
+#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 std::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, std::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, std::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, std::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, std::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..c6987c0 100644
--- a/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp
+++ b/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp
@@ -1,16 +1,16 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/DefaultFileTransferTransporter.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/FileTransfer/FailingTransportSession.h>
#include <Swiften/FileTransfer/FileTransferOptions.h>
@@ -33,268 +33,276 @@
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,
+ std::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 = std::make_shared<S5BProxyRequest>();
+ proxyRequest->setSID(s5bSessionID);
+ proxyRequest->setActivate(role == Initiator ? responder : initiator);
+
+ std::shared_ptr<GenericRequest<S5BProxyRequest> > request = std::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);
+std::shared_ptr<TransportSession> DefaultFileTransferTransporter::createIBBSendSession(
+ const std::string& sessionID, unsigned int blockSize, std::shared_ptr<ReadBytestream> stream) {
+ if (s5bServerManager->getServer()) {
+ closeLocalSession();
+ }
+ closeRemoteSession();
+ std::shared_ptr<IBBSendSession> ibbSession = std::make_shared<IBBSendSession>(
+ sessionID, initiator, responder, stream, router);
+ ibbSession->setBlockSize(blockSize);
+ return std::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);
+std::shared_ptr<TransportSession> DefaultFileTransferTransporter::createIBBReceiveSession(
+ const std::string& sessionID, unsigned long long size, std::shared_ptr<WriteBytestream> stream) {
+ if (s5bServerManager->getServer()) {
+ closeLocalSession();
+ }
+ closeRemoteSession();
+ std::shared_ptr<IBBReceiveSession> ibbSession = std::make_shared<IBBReceiveSession>(
+ sessionID, initiator, responder, size, stream, router);
+ return std::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);
+std::shared_ptr<TransportSession> DefaultFileTransferTransporter::createRemoteCandidateSession(
+ std::shared_ptr<ReadBytestream> stream, const JingleS5BTransportPayload::Candidate& /* candidate */) {
+ closeLocalSession();
+ return std::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);
+std::shared_ptr<TransportSession> DefaultFileTransferTransporter::createRemoteCandidateSession(
+ std::shared_ptr<WriteBytestream> stream, const JingleS5BTransportPayload::Candidate& /* candidate */) {
+ closeLocalSession();
+ return std::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>();
+std::shared_ptr<SOCKS5BytestreamServerSession> DefaultFileTransferTransporter::getServerSession() {
+ s5bRegistry->setHasBytestream(getSOCKS5DstAddr(), false);
+ std::vector<std::shared_ptr<SOCKS5BytestreamServerSession> > serverSessions =
+ s5bServerManager->getServer()->getSessions(getSOCKS5DstAddr());
+ while (serverSessions.size() > 1) {
+ std::shared_ptr<SOCKS5BytestreamServerSession> session = serverSessions.back();
+ serverSessions.pop_back();
+ session->stop();
+ }
+ return !serverSessions.empty() ? serverSessions.front() : std::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;
+std::shared_ptr<TransportSession> DefaultFileTransferTransporter::createLocalCandidateSession(
+ std::shared_ptr<ReadBytestream> stream, const JingleS5BTransportPayload::Candidate& candidate) {
+ closeRemoteSession();
+ std::shared_ptr<TransportSession> transportSession;
+ if (candidate.type == JingleS5BTransportPayload::Candidate::ProxyType) {
+ SOCKS5BytestreamClientSession::ref proxySession = s5bProxy->getProxySessionAndCloseOthers(candidate.jid, getLocalCandidateSOCKS5DstAddr());
+ if (proxySession) {
+ transportSession = std::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(proxySession, stream);
+ }
+ else {
+ SWIFT_LOG(error) << "Failed obtaining proxy session with candidate JID " << candidate.jid << " and dstAddr " << getLocalCandidateSOCKS5DstAddr() << "." << std::endl;
+ }
+ }
+
+ if (!transportSession) {
+ std::shared_ptr<SOCKS5BytestreamServerSession> serverSession = getServerSession();
+ if (serverSession) {
+ transportSession = std::make_shared<S5BTransportSession<SOCKS5BytestreamServerSession> >(serverSession, stream);
+ }
+ }
+
+ if (!transportSession) {
+ transportSession = std::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;
+std::shared_ptr<TransportSession> DefaultFileTransferTransporter::createLocalCandidateSession(
+ std::shared_ptr<WriteBytestream> stream, const JingleS5BTransportPayload::Candidate& candidate) {
+ closeRemoteSession();
+ std::shared_ptr<TransportSession> transportSession;
+ if (candidate.type == JingleS5BTransportPayload::Candidate::ProxyType) {
+ SOCKS5BytestreamClientSession::ref proxySession = s5bProxy->getProxySessionAndCloseOthers(candidate.jid, getLocalCandidateSOCKS5DstAddr());
+ if (proxySession) {
+ transportSession = std::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(proxySession, stream);
+ }
+ else {
+ SWIFT_LOG(error) << "Failed obtaining proxy session with candidate JID " << candidate.jid << " and dstAddr " << getLocalCandidateSOCKS5DstAddr() << "." << std::endl;
+ }
+ }
+
+ if (!transportSession) {
+ std::shared_ptr<SOCKS5BytestreamServerSession> serverSession = getServerSession();
+ if (serverSession) {
+ transportSession = std::make_shared<S5BTransportSession<SOCKS5BytestreamServerSession> >(serverSession, stream);
+ }
+ }
+
+ if (!transportSession) {
+ transportSession = std::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<std::shared_ptr<SOCKS5BytestreamServerSession> > serverSessions = s5bServerManager->getServer()->getSessions(getSOCKS5DstAddr());
+ for (auto&& 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 347c313..339232f 100644
--- a/Swiften/FileTransfer/DefaultFileTransferTransporter.h
+++ b/Swiften/FileTransfer/DefaultFileTransferTransporter.h
@@ -1,112 +1,112 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
-#include <Swiften/FileTransfer/FileTransferTransporter.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/ErrorPayload.h>
+#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 initialize();
+ virtual void initialize(const std::string& s5bSessionID);
- virtual void startGeneratingLocalCandidates() SWIFTEN_OVERRIDE;
- virtual void stopGeneratingLocalCandidates() SWIFTEN_OVERRIDE;
+ virtual void startGeneratingLocalCandidates() SWIFTEN_OVERRIDE;
+ virtual void stopGeneratingLocalCandidates() 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 void addRemoteCandidates(
+ const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) SWIFTEN_OVERRIDE;
+ virtual void startTryingRemoteCandidates() SWIFTEN_OVERRIDE;
+ virtual void stopTryingRemoteCandidates() SWIFTEN_OVERRIDE;
- virtual void startActivatingProxy(const JID& jid) SWIFTEN_OVERRIDE;
- virtual void stopActivatingProxy() SWIFTEN_OVERRIDE;
+ virtual void startActivatingProxy(const JID& jid) SWIFTEN_OVERRIDE;
+ virtual void stopActivatingProxy() 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 std::shared_ptr<TransportSession> createIBBSendSession(
+ const std::string& sessionID, unsigned int blockSize, std::shared_ptr<ReadBytestream>) SWIFTEN_OVERRIDE;
+ virtual std::shared_ptr<TransportSession> createIBBReceiveSession(
+ const std::string& sessionID, unsigned long long size, std::shared_ptr<WriteBytestream>) SWIFTEN_OVERRIDE;
+ virtual std::shared_ptr<TransportSession> createRemoteCandidateSession(
+ std::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE;
+ virtual std::shared_ptr<TransportSession> createRemoteCandidateSession(
+ std::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE;
+ virtual std::shared_ptr<TransportSession> createLocalCandidateSession(
+ std::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE;
+ virtual std::shared_ptr<TransportSession> createLocalCandidateSession(
+ std::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) 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();
+ private:
+ void handleLocalCandidatesGenerated(const std::vector<JingleS5BTransportPayload::Candidate>&);
+ void handleRemoteCandidateSelectFinished(
+ const boost::optional<JingleS5BTransportPayload::Candidate>&,
+ std::shared_ptr<SOCKS5BytestreamClientSession>);
+ void handleActivateProxySessionResult(const std::string& sessionID, ErrorPayload::ref error);
+ void closeLocalSession();
+ void closeRemoteSession();
+ std::shared_ptr<SOCKS5BytestreamServerSession> getServerSession();
- std::string getSOCKS5DstAddr() const;
- std::string getInitiatorCandidateSOCKS5DstAddr() const;
- std::string getResponderCandidateSOCKS5DstAddr() const;
- std::string getRemoteCandidateSOCKS5DstAddr() const;
- std::string getLocalCandidateSOCKS5DstAddr() const;
+ 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;
- };
+ private:
+ JID initiator;
+ JID responder;
+ Role role;
+ SOCKS5BytestreamRegistry* s5bRegistry;
+ SOCKS5BytestreamServerManager* s5bServerManager;
+ SOCKS5BytestreamProxiesManager* s5bProxy;
+ CryptoProvider* crypto;
+ IQRouter* router;
+ LocalJingleTransportCandidateGenerator* localCandidateGenerator;
+ RemoteJingleTransportCandidateSelector* remoteCandidateSelector;
+ std::string s5bSessionID;
+ std::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 93cf262..3cc3455 100644
--- a/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h
+++ b/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h
@@ -1,51 +1,51 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#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.cpp b/Swiften/FileTransfer/FailingTransportSession.cpp
new file mode 100644
index 0000000..d1eb6a6
--- /dev/null
+++ b/Swiften/FileTransfer/FailingTransportSession.cpp
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swiften/FileTransfer/FailingTransportSession.h>
+
+#include <Swiften/Base/Log.h>
+
+namespace Swift {
+
+FailingTransportSession::~FailingTransportSession() {
+}
+
+void FailingTransportSession::start() {
+ SWIFT_LOG(error) << "Trying to start failing transport." << std::endl;
+ onFinished(FileTransferError(FileTransferError::PeerError));
+}
+
+void FailingTransportSession::stop() {
+}
+
+}
diff --git a/Swiften/FileTransfer/FailingTransportSession.h b/Swiften/FileTransfer/FailingTransportSession.h
index c197052..6e0e16e 100644
--- a/Swiften/FileTransfer/FailingTransportSession.h
+++ b/Swiften/FileTransfer/FailingTransportSession.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -12,17 +12,11 @@
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 stop() SWIFTEN_OVERRIDE {
- }
+ virtual void start() SWIFTEN_OVERRIDE;
+ virtual void stop() SWIFTEN_OVERRIDE;
};
}
diff --git a/Swiften/FileTransfer/FileReadBytestream.cpp b/Swiften/FileTransfer/FileReadBytestream.cpp
index 4700a9c..2ff00dc 100644
--- a/Swiften/FileTransfer/FileReadBytestream.cpp
+++ b/Swiften/FileTransfer/FileReadBytestream.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,41 +7,41 @@
#include <Swiften/FileTransfer/FileReadBytestream.h>
#include <cassert>
+#include <memory>
#include <boost/filesystem/fstream.hpp>
#include <boost/numeric/conversion/cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/ByteArray.h>
namespace Swift {
-FileReadBytestream::FileReadBytestream(const boost::filesystem::path& file) : file(file), stream(NULL) {
+FileReadBytestream::FileReadBytestream(const boost::filesystem::path& file) : file(file), stream(nullptr) {
}
FileReadBytestream::~FileReadBytestream() {
- if (stream) {
- stream->close();
- delete stream;
- stream = NULL;
- }
+ if (stream) {
+ stream->close();
+ delete stream;
+ stream = nullptr;
+ }
}
-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;
+std::shared_ptr<ByteArray> FileReadBytestream::read(size_t size) {
+ if (!stream) {
+ stream = new boost::filesystem::ifstream(file, std::ios_base::in|std::ios_base::binary);
+ }
+ std::shared_ptr<ByteArray> result = std::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..aaf3de3 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 std::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..1d74a84 100644
--- a/Swiften/FileTransfer/FileTransfer.h
+++ b/Swiften/FileTransfer/FileTransfer.h
@@ -5,84 +5,85 @@
*/
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#include <boost/cstdint.hpp>
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#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 std::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::signals2::signal<void (size_t /* proccessedBytes */)> onProcessedBytes;
+ boost::signals2::signal<void (const State&)> onStateChanged;
+ boost::signals2::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..a5d7313 100644
--- a/Swiften/FileTransfer/FileTransferManager.cpp
+++ b/Swiften/FileTransfer/FileTransferManager.cpp
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/FileTransfer/FileTransferManager.h>
namespace Swift {
@@ -11,13 +17,4 @@ namespace Swift {
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;
-}
-
}
diff --git a/Swiften/FileTransfer/FileTransferManager.h b/Swiften/FileTransfer/FileTransferManager.h
index 2d75367..07cfc90 100644
--- a/Swiften/FileTransfer/FileTransferManager.h
+++ b/Swiften/FileTransfer/FileTransferManager.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,41 +13,40 @@
#pragma once
#include <string>
-#include <boost/filesystem/path.hpp>
+
#include <boost/date_time/posix_time/posix_time.hpp>
+#include <boost/filesystem/path.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Elements/DiscoInfo.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/FileTransfer/FileTransferOptions.h>
-#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
#include <Swiften/FileTransfer/IncomingFileTransfer.h>
+#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
+#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,
+ std::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,
+ std::shared_ptr<ReadBytestream> bytestream,
+ const FileTransferOptions& = FileTransferOptions()) = 0;
+
+ boost::signals2::signal<void (IncomingFileTransfer::ref)> onIncomingFileTransfer;
+ };
}
diff --git a/Swiften/FileTransfer/FileTransferManagerImpl.cpp b/Swiften/FileTransfer/FileTransferManagerImpl.cpp
index f4b4202..05dd3bb 100644
--- a/Swiften/FileTransfer/FileTransferManagerImpl.cpp
+++ b/Swiften/FileTransfer/FileTransferManagerImpl.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -16,11 +16,11 @@
#include <boost/cstdint.hpp>
#include <boost/filesystem.hpp>
-#include "Swiften/Disco/EntityCapsProvider.h"
#include <Swiften/Base/BoostFilesystemVersion.h>
#include <Swiften/Base/Log.h>
#include <Swiften/Base/Path.h>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Disco/EntityCapsProvider.h>
+#include <Swiften/Disco/FeatureOracle.h>
#include <Swiften/Elements/JingleFileTransferFileInfo.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h>
@@ -40,147 +40,126 @@
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();
-}
-
-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>();
+ s5bServerManager->stop();
}
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,
+ std::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,
+ std::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()) {
+ auto featureOracle = FeatureOracle(capsProvider, presenceOracle);
+ JID fullJID = featureOracle.getMostAvailableClientForFileTrasfer(receipient);
+ if (!fullJID.toString().empty()) {
+ receipient = fullJID;
+ } 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..026c8b7 100644
--- a/Swiften/FileTransfer/FileTransferManagerImpl.h
+++ b/Swiften/FileTransfer/FileTransferManagerImpl.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -18,11 +18,11 @@
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/optional.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/IDGenerator.h>
#include <Swiften/Base/Override.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Elements/S5BProxyRequest.h>
#include <Swiften/FileTransfer/FileTransferManager.h>
#include <Swiften/FileTransfer/FileTransferOptions.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,
+ std::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,
+ std::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 baaa36d..2bc4ee1 100644
--- a/Swiften/FileTransfer/FileTransferOptions.h
+++ b/Swiften/FileTransfer/FileTransferOptions.h
@@ -1,66 +1,66 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#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 cad3d28..e0ffc87 100644
--- a/Swiften/FileTransfer/FileTransferTransporter.h
+++ b/Swiften/FileTransfer/FileTransferTransporter.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,52 +9,52 @@
#include <vector>
#include <boost/optional/optional.hpp>
+#include <boost/signals2.hpp>
-#include <Swiften/Elements/JingleS5BTransportPayload.h>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
+#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 std::shared_ptr<TransportSession> createIBBSendSession(
+ const std::string& sessionID, unsigned int blockSize, std::shared_ptr<ReadBytestream>) = 0;
+ virtual std::shared_ptr<TransportSession> createIBBReceiveSession(
+ const std::string& sessionID, unsigned long long size, std::shared_ptr<WriteBytestream>) = 0;
+ virtual std::shared_ptr<TransportSession> createRemoteCandidateSession(
+ std::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0;
+ virtual std::shared_ptr<TransportSession> createRemoteCandidateSession(
+ std::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0;
+ virtual std::shared_ptr<TransportSession> createLocalCandidateSession(
+ std::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0;
+ virtual std::shared_ptr<TransportSession> createLocalCandidateSession(
+ std::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) = 0;
+
+ boost::signals2::signal<void (const std::string& /* sessionID */, const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string& /* dstAddr */)> onLocalCandidatesGenerated;
+ boost::signals2::signal<void (const std::string& /* sessionID */, const boost::optional<JingleS5BTransportPayload::Candidate>&)> onRemoteCandidateSelectFinished;
+ boost::signals2::signal<void (const std::string& /* sessionID */, std::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..e7daa2c 100644
--- a/Swiften/FileTransfer/FileWriteBytestream.cpp
+++ b/Swiften/FileTransfer/FileWriteBytestream.cpp
@@ -13,40 +13,40 @@
namespace Swift {
-FileWriteBytestream::FileWriteBytestream(const boost::filesystem::path& file) : file(file), stream(NULL) {
+FileWriteBytestream::FileWriteBytestream(const boost::filesystem::path& file) : file(file), stream(nullptr) {
}
FileWriteBytestream::~FileWriteBytestream() {
- if (stream) {
- stream->close();
- delete stream;
- stream = NULL;
- }
+ if (stream) {
+ stream->close();
+ delete stream;
+ stream = nullptr;
+ }
}
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 = nullptr;
+ }
}
}
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 ac58b34..24996ed 100644
--- a/Swiften/FileTransfer/IBBReceiveSession.cpp
+++ b/Swiften/FileTransfer/IBBReceiveSession.cpp
@@ -1,118 +1,118 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/IBBReceiveSession.h>
+#include <cassert>
+
#include <boost/bind.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/FileTransfer/IBBRequest.h>
#include <Swiften/FileTransfer/BytestreamException.h>
+#include <Swiften/FileTransfer/IBBRequest.h>
+#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Queries/SetResponder.h>
-#include <cassert>
-
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,
+ std::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 d400a1e..797394c 100644
--- a/Swiften/FileTransfer/IBBReceiveSession.h
+++ b/Swiften/FileTransfer/IBBReceiveSession.h
@@ -1,63 +1,64 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/optional/optional.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/FileTransfer/WriteBytestream.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/IBB.h>
#include <Swiften/FileTransfer/FileTransferError.h>
+#include <Swiften/FileTransfer/WriteBytestream.h>
+#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,
+ std::shared_ptr<WriteBytestream> bytestream,
+ IQRouter* router);
+ ~IBBReceiveSession();
+
+ void start();
+ void stop();
+
+ const JID& getSender() const {
+ return from;
+ }
+
+ const JID& getReceiver() const {
+ return to;
+ }
+
+ boost::signals2::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;
+ std::shared_ptr<WriteBytestream> bytestream;
+ IQRouter* router;
+ IBBResponder* responder;
+ bool active;
+ };
}
diff --git a/Swiften/FileTransfer/IBBReceiveTransportSession.cpp b/Swiften/FileTransfer/IBBReceiveTransportSession.cpp
index 4464946..6e47ac6 100644
--- a/Swiften/FileTransfer/IBBReceiveTransportSession.cpp
+++ b/Swiften/FileTransfer/IBBReceiveTransportSession.cpp
@@ -1,28 +1,28 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/bind.hpp>
-
#include <Swiften/FileTransfer/IBBReceiveTransportSession.h>
+#include <boost/bind.hpp>
+
namespace Swift {
-IBBReceiveTransportSession::IBBReceiveTransportSession(boost::shared_ptr<IBBReceiveSession> session) : session(session) {
- finishedConnection = session->onFinished.connect(boost::bind(boost::ref(onFinished), _1));
+IBBReceiveTransportSession::IBBReceiveTransportSession(std::shared_ptr<IBBReceiveSession> session) : session(session) {
+ 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 5fca26a..8b304c3 100644
--- a/Swiften/FileTransfer/IBBReceiveTransportSession.h
+++ b/Swiften/FileTransfer/IBBReceiveTransportSession.h
@@ -1,30 +1,31 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/FileTransfer/TransportSession.h>
#include <Swiften/FileTransfer/IBBReceiveSession.h>
+#include <Swiften/FileTransfer/TransportSession.h>
namespace Swift {
class SWIFTEN_API IBBReceiveTransportSession : public TransportSession {
- public:
- IBBReceiveTransportSession(boost::shared_ptr<IBBReceiveSession> session);
- virtual ~IBBReceiveTransportSession();
+ public:
+ IBBReceiveTransportSession(std::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:
+ std::shared_ptr<IBBReceiveSession> session;
+ boost::signals2::scoped_connection finishedConnection;
+ boost::signals2::scoped_connection bytesSentConnection;
};
}
diff --git a/Swiften/FileTransfer/IBBRequest.h b/Swiften/FileTransfer/IBBRequest.h
index 1eef64b..67bd33a 100644
--- a/Swiften/FileTransfer/IBBRequest.h
+++ b/Swiften/FileTransfer/IBBRequest.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,21 +7,20 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/IBB.h>
-
+#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 std::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, std::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, std::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..e51c91c 100644
--- a/Swiften/FileTransfer/IBBSendSession.cpp
+++ b/Swiften/FileTransfer/IBBSendSession.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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,
+ std::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 {
+ std::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..e45532d 100644
--- a/Swiften/FileTransfer/IBBSendSession.h
+++ b/Swiften/FileTransfer/IBBSendSession.h
@@ -1,16 +1,17 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Elements/ErrorPayload.h>
#include <Swiften/Elements/IBB.h>
#include <Swiften/FileTransfer/FileTransferError.h>
@@ -18,53 +19,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,
+ std::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::signals2::signal<void (boost::optional<FileTransferError>)> onFinished;
+ boost::signals2::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;
+ std::shared_ptr<ReadBytestream> bytestream;
+ IQRouter* router;
+ unsigned int blockSize;
+ int sequenceNumber;
+ bool active;
+ bool waitingForData;
+ std::shared_ptr<IBBRequest> currentRequest;
+ };
}
diff --git a/Swiften/FileTransfer/IBBSendTransportSession.cpp b/Swiften/FileTransfer/IBBSendTransportSession.cpp
index b4d2467..81972c9 100644
--- a/Swiften/FileTransfer/IBBSendTransportSession.cpp
+++ b/Swiften/FileTransfer/IBBSendTransportSession.cpp
@@ -1,29 +1,29 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/bind.hpp>
-
#include <Swiften/FileTransfer/IBBSendTransportSession.h>
+#include <boost/bind.hpp>
+
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));
+IBBSendTransportSession::IBBSendTransportSession(std::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));
}
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 20abbd7..d1e786b 100644
--- a/Swiften/FileTransfer/IBBSendTransportSession.h
+++ b/Swiften/FileTransfer/IBBSendTransportSession.h
@@ -1,30 +1,31 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/FileTransfer/TransportSession.h>
#include <Swiften/FileTransfer/IBBSendSession.h>
+#include <Swiften/FileTransfer/TransportSession.h>
namespace Swift {
class SWIFTEN_API IBBSendTransportSession : public TransportSession {
- public:
- IBBSendTransportSession(boost::shared_ptr<IBBSendSession> session);
- virtual ~IBBSendTransportSession();
+ public:
+ IBBSendTransportSession(std::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:
+ std::shared_ptr<IBBSendSession> session;
+ boost::signals2::scoped_connection finishedConnection;
+ boost::signals2::scoped_connection bytesSentConnection;
};
}
diff --git a/Swiften/FileTransfer/IncomingFileTransfer.h b/Swiften/FileTransfer/IncomingFileTransfer.h
index 16905b8..7236c35 100644
--- a/Swiften/FileTransfer/IncomingFileTransfer.h
+++ b/Swiften/FileTransfer/IncomingFileTransfer.h
@@ -1,37 +1,38 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/FileTransfer/FileTransfer.h>
#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 std::shared_ptr<IncomingFileTransfer> ref;
+
+ virtual ~IncomingFileTransfer();
+
+ virtual void accept(
+ std::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..1c2b788 100644
--- a/Swiften/FileTransfer/IncomingFileTransferManager.cpp
+++ b/Swiften/FileTransfer/IncomingFileTransferManager.cpp
@@ -6,7 +6,7 @@
#include <Swiften/FileTransfer/IncomingFileTransferManager.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Base/Log.h>
#include <Swiften/Elements/JingleDescription.h>
@@ -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 = std::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..a0cce10 100644
--- a/Swiften/FileTransfer/IncomingFileTransferManager.h
+++ b/Swiften/FileTransfer/IncomingFileTransferManager.h
@@ -1,45 +1,46 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/FileTransfer/IncomingFileTransfer.h>
#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::signals2::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..d5de5e4 100644
--- a/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp
+++ b/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp
@@ -6,13 +6,12 @@
#include <Swiften/FileTransfer/IncomingJingleFileTransfer.h>
+#include <memory>
#include <set>
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/JingleFileTransferDescription.h>
#include <Swiften/Elements/JingleFileTransferHash.h>
#include <Swiften/Elements/JingleIBBTransportPayload.h>
@@ -33,388 +32,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(nullptr) {
+ 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 = nullptr;
}
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));
- }
+ std::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 = std::make_shared<JingleS5BTransportPayload>();
+ transport->setSessionID(s5bSessionID);
+ transport->setMode(JingleS5BTransportPayload::TCPMode);
+ transport->setDstAddr(dstAddr);
+ for (auto&& 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;
+ for (const auto& hashElement : hashes) {
+ hashInfoAvailable |= !hashElement.second.empty();
+ }
+
+ if (!hashInfoAvailable) {
+ SWIFT_LOG(debug) << "No hash information yet. Waiting a while on hash info." << std::endl;
+ setState(WaitingForHash);
+ waitOnHashTimer->start();
+ }
+ else {
+ checkHashAndTerminate();
+ }
+ }
+ else if (receivedBytes > getFileSizeInBytes()) {
+ SWIFT_LOG(debug) << "We got more than we could handle!" << std::endl;
+ terminate(JinglePayload::Reason::MediaError);
+ }
}
void IncomingJingleFileTransfer::handleWriteStreamDataReceived(
- const std::vector<unsigned char>& data) {
- hashCalculator->feedData(data);
- receivedBytes += data.size();
- onProcessedBytes(data.size());
- checkIfAllDataReceived();
+ 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 = std::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 = nullptr;
+ }
+ 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;
+void IncomingJingleFileTransfer::startTransferring(std::shared_ptr<TransportSession> transportSession) {
+ 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());
+std::shared_ptr<TransportSession> IncomingJingleFileTransfer::createLocalCandidateSession() {
+ return transporter->createLocalCandidateSession(stream, theirCandidateChoice.get());
}
-boost::shared_ptr<TransportSession> IncomingJingleFileTransfer::createRemoteCandidateSession() {
- return transporter->createRemoteCandidateSession(stream, ourCandidateChoice.get());
+std::shared_ptr<TransportSession> IncomingJingleFileTransfer::createRemoteCandidateSession() {
+ 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 e30db5e..3dd206d 100644
--- a/Swiften/FileTransfer/IncomingJingleFileTransfer.h
+++ b/Swiften/FileTransfer/IncomingJingleFileTransfer.h
@@ -1,128 +1,129 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/cstdint.hpp>
+#include <memory>
#include <string>
+#include <boost/cstdint.hpp>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/Base/Override.h>
-#include <Swiften/Jingle/JingleContentID.h>
-#include <Swiften/FileTransfer/IncomingFileTransfer.h>
-#include <Swiften/FileTransfer/JingleFileTransfer.h>
#include <Swiften/Elements/JingleS5BTransportPayload.h>
#include <Swiften/FileTransfer/FileTransferOptions.h>
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/FileTransfer/IncomingFileTransfer.h>
+#include <Swiften/FileTransfer/JingleFileTransfer.h>
+#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 std::shared_ptr<IncomingJingleFileTransfer> ref;
+
+ IncomingJingleFileTransfer(
+ const JID& recipient,
+ std::shared_ptr<JingleSession>,
+ std::shared_ptr<JingleContentPayload> content,
+ FileTransferTransporterFactory*,
+ TimerFactory*,
+ CryptoProvider*);
+ virtual ~IncomingJingleFileTransfer();
+
+ virtual void accept(std::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(std::shared_ptr<JinglePayload>) SWIFTEN_OVERRIDE;
+ virtual void handleTransportReplaceReceived(
+ const JingleContentID&, std::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(std::shared_ptr<TransportSession>) SWIFTEN_OVERRIDE;
+ virtual bool isWaitingForPeerProxyActivate() const SWIFTEN_OVERRIDE;
+ virtual bool isWaitingForLocalProxyActivate() const SWIFTEN_OVERRIDE;
+ virtual bool isTryingCandidates() const SWIFTEN_OVERRIDE;
+ virtual std::shared_ptr<TransportSession> createLocalCandidateSession() SWIFTEN_OVERRIDE;
+ virtual std::shared_ptr<TransportSession> createRemoteCandidateSession() SWIFTEN_OVERRIDE;
+ virtual void terminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE;
+
+
+ private:
+ std::shared_ptr<JingleContentPayload> initialContent;
+ CryptoProvider* crypto;
+ State state;
+ std::shared_ptr<JingleFileTransferDescription> description;
+ std::shared_ptr<WriteBytestream> stream;
+ boost::uintmax_t receivedBytes;
+ IncrementalBytestreamHashCalculator* hashCalculator;
+ std::shared_ptr<Timer> waitOnHashTimer;
+ std::map<std::string, ByteArray> hashes;
+ FileTransferOptions options;
+
+ boost::signals2::scoped_connection writeStreamDataReceivedConnection;
+ boost::signals2::scoped_connection waitOnHashTimerTickedConnection;
+ boost::signals2::connection transferFinishedConnection;
+ };
}
diff --git a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp
index 7eb9560..f177304 100644
--- a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp
+++ b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2013-2014 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,63 +13,63 @@
#include <Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h>
-#include <Swiften/StringCodecs/Hexify.h>
#include <Swiften/Crypto/CryptoProvider.h>
+#include <Swiften/StringCodecs/Hexify.h>
namespace Swift {
IncrementalBytestreamHashCalculator::IncrementalBytestreamHashCalculator(bool doMD5, bool doSHA1, CryptoProvider* crypto) {
- md5Hasher = doMD5 ? crypto->createMD5() : NULL;
- sha1Hasher = doSHA1 ? crypto->createSHA1() : NULL;
+ md5Hasher = doMD5 ? crypto->createMD5() : nullptr;
+ sha1Hasher = doSHA1 ? crypto->createSHA1() : nullptr;
}
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 bc4ebf9..4477ec1 100644
--- a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h
+++ b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2013-2014 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,33 +14,34 @@
#include <string>
+#include <boost/optional.hpp>
+
#include <Swiften/Base/ByteArray.h>
#include <Swiften/Base/SafeByteArray.h>
-#include <boost/optional.hpp>
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..62c3a53 100644
--- a/Swiften/FileTransfer/JingleFileTransfer.cpp
+++ b/Swiften/FileTransfer/JingleFileTransfer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,7 +9,6 @@
#include <boost/typeof/typeof.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/FileTransfer/FileTransferTransporter.h>
#include <Swiften/JID/JID.h>
@@ -19,217 +18,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);
+ std::shared_ptr<JingleSession> session,
+ const JID& target,
+ FileTransferTransporterFactory* transporterFactory) :
+ session(session),
+ target(target),
+ transporterFactory(transporterFactory),
+ transporter(nullptr),
+ ourCandidateSelectFinished(false),
+ theirCandidateSelectFinished(false) {
+
+ session->addListener(this);
}
JingleFileTransfer::~JingleFileTransfer() {
- session->removeListener(this);
+ 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();
+ for (auto&& candidate : candidates) {
+ map[candidate.cid] = candidate;
+ }
}
/*
std::string JingleFileTransfer::getS5BDstAddr(const JID& requester, const JID& target) const {
- return Hexify::hexify(crypto->getSHA1Hash(
- createSafeByteArray(s5bSessionID + requester.toString() + target.toString())));
+ 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 = std::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 = std::make_shared<JingleS5BTransportPayload>();
+ proxyError->setSessionID(s5bSessionID);
+ proxyError->setProxyError(true);
+ session->sendTransportInfo(getContentID(), proxyError);
+ fallback();
+ }
+ else {
+ JingleS5BTransportPayload::ref proxyActivate = std::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 = std::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 = nullptr;
+ }
}
diff --git a/Swiften/FileTransfer/JingleFileTransfer.h b/Swiften/FileTransfer/JingleFileTransfer.h
index 16a55c6..5b9dd62 100644
--- a/Swiften/FileTransfer/JingleFileTransfer.h
+++ b/Swiften/FileTransfer/JingleFileTransfer.h
@@ -1,17 +1,17 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <vector>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Elements/ErrorPayload.h>
#include <Swiften/Elements/JingleS5BTransportPayload.h>
#include <Swiften/FileTransfer/FileTransfer.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(
+ std::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(std::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 std::shared_ptr<TransportSession> createLocalCandidateSession() = 0;
+ virtual std::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;
+ std::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;
+ std::shared_ptr<TransportSession> transportSession;
- boost::bsignals::scoped_connection localTransportCandidatesGeneratedConnection;
- boost::bsignals::scoped_connection remoteTransportCandidateSelectFinishedConnection;
- boost::bsignals::scoped_connection proxyActivatedConnection;
- };
+ boost::signals2::scoped_connection localTransportCandidatesGeneratedConnection;
+ boost::signals2::scoped_connection remoteTransportCandidateSelectFinishedConnection;
+ boost::signals2::scoped_connection proxyActivatedConnection;
+ };
}
diff --git a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp
index f6e6963..09b664f 100644
--- a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp
+++ b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp
@@ -5,21 +5,19 @@
*/
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h>
+#include <memory>
#include <vector>
#include <boost/bind.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/JingleS5BTransportPayload.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamServerManager.h>
@@ -31,162 +29,163 @@ 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();
+ for(auto&& 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();
+ for (auto&& 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()) {
+ for (auto&& 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;
+ auto address = HostAddress::fromString((*proxy->getStreamHost()).host);
+ if (address) {
+ candidate.hostPort = HostAddressPort(address.get(), (*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 bbf17a1..2159063 100644
--- a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h
+++ b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h
@@ -5,65 +5,66 @@
*/
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/IDGenerator.h>
#include <Swiften/Base/Override.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/JingleS5BTransportPayload.h>
#include <Swiften/FileTransfer/FileTransferOptions.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h>
+#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::signals2::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;
+ std::shared_ptr<SOCKS5BytestreamServerInitializeRequest> s5bServerInitializeRequest;
+ std::shared_ptr<SOCKS5BytestreamServerResourceUser> s5bServerResourceUser_;
+ std::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..07fc6d2 100644
--- a/Swiften/FileTransfer/OutgoingFileTransfer.h
+++ b/Swiften/FileTransfer/OutgoingFileTransfer.h
@@ -1,23 +1,23 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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 std::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 0ed2395..c74aefb 100644
--- a/Swiften/FileTransfer/OutgoingFileTransferManager.cpp
+++ b/Swiften/FileTransfer/OutgoingFileTransferManager.cpp
@@ -5,61 +5,61 @@
*/
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/OutgoingFileTransferManager.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <Swiften/Base/IDGenerator.h>
+#include <Swiften/FileTransfer/OutgoingJingleFileTransfer.h>
#include <Swiften/JID/JID.h>
-#include <Swiften/Jingle/JingleSessionManager.h>
-#include <Swiften/Jingle/JingleSessionImpl.h>
#include <Swiften/Jingle/JingleContentID.h>
-#include <Swiften/FileTransfer/OutgoingJingleFileTransfer.h>
-#include <Swiften/Base/IDGenerator.h>
+#include <Swiften/Jingle/JingleSessionImpl.h>
+#include <Swiften/Jingle/JingleSessionManager.h>
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));
+std::shared_ptr<OutgoingFileTransfer> OutgoingFileTransferManager::createOutgoingFileTransfer(
+ const JID& from,
+ const JID& recipient,
+ std::shared_ptr<ReadBytestream> readBytestream,
+ const JingleFileTransferFileInfo& fileInfo,
+ const FileTransferOptions& config) {
+ JingleSessionImpl::ref jingleSession = std::make_shared<JingleSessionImpl>(
+ from, recipient, idGenerator->generateID(), iqRouter);
+ jingleSessionManager->registerOutgoingSession(from, jingleSession);
+ return std::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..48a6e5a 100644
--- a/Swiften/FileTransfer/OutgoingFileTransferManager.h
+++ b/Swiften/FileTransfer/OutgoingFileTransferManager.h
@@ -5,53 +5,53 @@
*/
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#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();
+
+ std::shared_ptr<OutgoingFileTransfer> createOutgoingFileTransfer(
+ const JID& from,
+ const JID& to,
+ std::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..367fc97 100644
--- a/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp
+++ b/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp
@@ -10,20 +10,20 @@
* 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?
#include <Swiften/FileTransfer/OutgoingJingleFileTransfer.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <boost/typeof/typeof.hpp>
#include <Swiften/Base/IDGenerator.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Elements/JingleFileTransferDescription.h>
#include <Swiften/Elements/JingleFileTransferHash.h>
@@ -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,
+ std::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 = nullptr;
+ 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 = std::dynamic_pointer_cast<JingleS5BTransportPayload>(transportPayload)) {
+ transporter->addRemoteCandidates(s5bPayload->getCandidates(), s5bPayload->getDstAddr());
+ setInternalState(TryingCandidates);
+ transporter->startTryingRemoteCandidates();
+ }
+ else if (JingleIBBTransportPayload::ref ibbPayload = std::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 = std::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;
+void OutgoingJingleFileTransfer::handleTransportRejectReceived(const JingleContentID &, std::shared_ptr<JingleTransportPayload>) {
+ 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 = std::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 = std::make_shared<JingleFileTransferDescription>();
+ fileInfo.addHash(HashElement("sha-1", ByteArray()));
+ fileInfo.addHash(HashElement("md5", ByteArray()));
+ description->setFileInfo(fileInfo);
+
+ JingleTransportPayload::ref transport;
+ if (candidates.empty()) {
+ SWIFT_LOG(debug) << "no S5B candidates generated. Send IBB transport candidate." << std::endl;
+ JingleIBBTransportPayload::ref ibbTransport = std::make_shared<JingleIBBTransportPayload>();
+ ibbTransport->setBlockSize(DEFAULT_BLOCK_SIZE);
+ ibbTransport->setSessionID(idGenerator->generateID());
+ transport = ibbTransport;
+ }
+ else {
+ JingleS5BTransportPayload::ref s5bTransport = std::make_shared<JingleS5BTransportPayload>();
+ s5bTransport->setSessionID(s5bSessionID);
+ s5bTransport->setMode(JingleS5BTransportPayload::TCPMode);
+ s5bTransport->setDstAddr(dstAddr);
+ for (auto&& candidate : candidates) {
+ s5bTransport->addCandidate(candidate);
+ SWIFT_LOG(debug) << "\t" << "S5B candidate: " << candidate.hostPort.toString() << std::endl;
+ }
+ transport = s5bTransport;
+ }
+ setInternalState(WaitingForAccept);
+ session->sendInitiate(contentID, description, transport);
}
void OutgoingJingleFileTransfer::fallback() {
- if (options.isInBandAllowed()) {
- SWIFT_LOG(debug) << "Trying to fallback to IBB transport." << std::endl;
- JingleIBBTransportPayload::ref ibbTransport = 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 = std::make_shared<JingleIBBTransportPayload>();
+ ibbTransport->setBlockSize(DEFAULT_BLOCK_SIZE);
+ ibbTransport->setSessionID(idGenerator->generateID());
+ setInternalState(FallbackRequested);
+ session->sendTransportReplace(contentID, ibbTransport);
+ }
+ else {
+ SWIFT_LOG(debug) << "Fallback to IBB transport not allowed." << std::endl;
+ terminate(JinglePayload::Reason::ConnectivityError);
+ }
}
void OutgoingJingleFileTransfer::handleTransferFinished(boost::optional<FileTransferError> error) {
- SWIFT_LOG(debug) << std::endl;
- if (state != Transferring) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; }
-
- if (error) {
- terminate(JinglePayload::Reason::ConnectivityError);
- }
- 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;
+void OutgoingJingleFileTransfer::startTransferring(std::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();
+ 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());
+std::shared_ptr<TransportSession> OutgoingJingleFileTransfer::createLocalCandidateSession() {
+ return transporter->createLocalCandidateSession(stream, theirCandidateChoice.get());
}
-boost::shared_ptr<TransportSession> OutgoingJingleFileTransfer::createRemoteCandidateSession() {
- return transporter->createRemoteCandidateSession(stream, ourCandidateChoice.get());
+std::shared_ptr<TransportSession> OutgoingJingleFileTransfer::createRemoteCandidateSession() {
+ 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..cd45948 100644
--- a/Swiften/FileTransfer/OutgoingJingleFileTransfer.h
+++ b/Swiften/FileTransfer/OutgoingJingleFileTransfer.h
@@ -5,15 +5,16 @@
*/
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#include <boost/optional/optional.hpp>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/Override.h>
@@ -25,98 +26,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,
+ std::shared_ptr<JingleSession>,
+ std::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&, std::shared_ptr<JingleDescription>, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+ virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) SWIFTEN_OVERRIDE;
+ virtual void handleTransportAcceptReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+ virtual void handleTransportRejectReceived(const JingleContentID &, std::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(std::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 std::shared_ptr<TransportSession> createLocalCandidateSession() SWIFTEN_OVERRIDE;
+ virtual std::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;
+ std::shared_ptr<ReadBytestream> stream;
+ JingleFileTransferFileInfo fileInfo;
+ FileTransferOptions options;
+ JingleContentID contentID;
+ IncrementalBytestreamHashCalculator* hashCalculator;
+ State state;
+ bool candidateAcknowledged;
+
+ Timer::ref waitForRemoteTermination;
+
+ boost::signals2::connection processedBytesConnection;
+ boost::signals2::connection transferFinishedConnection;
+ };
}
diff --git a/Swiften/FileTransfer/ReadBytestream.h b/Swiften/FileTransfer/ReadBytestream.h
index 5841db7..f146c04 100644
--- a/Swiften/FileTransfer/ReadBytestream.h
+++ b/Swiften/FileTransfer/ReadBytestream.h
@@ -1,32 +1,33 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <vector>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#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 std::shared_ptr< std::vector<unsigned char> > read(size_t size) = 0;
+
+ virtual bool isFinished() const = 0;
+
+ public:
+ boost::signals2::signal<void ()> onDataAvailable;
+ boost::signals2::signal<void (const std::vector<unsigned char>&)> onRead;
+ };
}
diff --git a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp
index 05a0f0e..56013ca 100644
--- a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp
+++ b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp
@@ -5,93 +5,93 @@
*/
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/bind.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/JingleS5BTransportPayload.h>
-#include <Swiften/Network/ConnectionFactory.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
+#include <Swiften/Network/ConnectionFactory.h>
using namespace Swift;
RemoteJingleTransportCandidateSelector::RemoteJingleTransportCandidateSelector(
- ConnectionFactory* connectionFactory,
- TimerFactory* timerFactory,
- const FileTransferOptions& options) :
- connectionFactory(connectionFactory),
- timerFactory(timerFactory),
- options(options) {
+ 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) {
+ for (auto&& 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>(), std::shared_ptr<SOCKS5BytestreamClientSession>());
+ }
+ else {
+ lastCandidate = candidates.top();
+ candidates.pop();
+ SWIFT_LOG(debug) << "Trying candidate " << lastCandidate.cid << std::endl;
+ if ((lastCandidate.type == JingleS5BTransportPayload::Candidate::DirectType && options.isDirectAllowed()) ||
+ (lastCandidate.type == JingleS5BTransportPayload::Candidate::AssistedType && options.isAssistedAllowed()) ||
+ (lastCandidate.type == JingleS5BTransportPayload::Candidate::ProxyType && options.isProxiedAllowed())) {
+ std::shared_ptr<Connection> connection = connectionFactory->createConnection();
+ s5bSession = std::make_shared<SOCKS5BytestreamClientSession>(
+ 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 342655c..c4257f6 100644
--- a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h
+++ b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h
@@ -5,59 +5,58 @@
*/
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h>
+
+#include <memory>
#include <queue>
#include <vector>
-#include <boost/shared_ptr.hpp>
-
#include <Swiften/Base/Override.h>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Network/Connection.h>
-#include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h>
-#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h>
#include <Swiften/Elements/JingleS5BTransportPayload.h>
#include <Swiften/FileTransfer/FileTransferOptions.h>
-
+#include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h>
+#include <Swiften/JID/JID.h>
+#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::signals2::signal<void (const boost::optional<JingleS5BTransportPayload::Candidate>&, std::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;
+ std::shared_ptr<SOCKS5BytestreamClientSession> s5bSession;
+ boost::signals2::connection sessionReadyConnection;
+ JingleS5BTransportPayload::Candidate lastCandidate;
+ std::string socks5DstAddr;
+ FileTransferOptions options;
+ };
}
diff --git a/Swiften/FileTransfer/S5BTransportSession.h b/Swiften/FileTransfer/S5BTransportSession.h
index b3eee3c..3e064fa 100644
--- a/Swiften/FileTransfer/S5BTransportSession.h
+++ b/Swiften/FileTransfer/S5BTransportSession.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,9 +7,9 @@
#pragma once
#include <boost/bind.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/FileTransfer/ReadBytestream.h>
#include <Swiften/FileTransfer/TransportSession.h>
#include <Swiften/FileTransfer/WriteBytestream.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(
+ std::shared_ptr<T> session,
+ std::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(
+ std::shared_ptr<T> session,
+ std::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:
+ std::shared_ptr<T> session;
+ std::shared_ptr<ReadBytestream> readStream;
+ std::shared_ptr<WriteBytestream> writeStream;
- boost::bsignals::scoped_connection finishedConnection;
- boost::bsignals::scoped_connection bytesSentConnection;
+ boost::signals2::scoped_connection finishedConnection;
+ boost::signals2::scoped_connection bytesSentConnection;
};
}
diff --git a/Swiften/FileTransfer/SConscript b/Swiften/FileTransfer/SConscript
index 41af8d4..d49b596 100644
--- a/Swiften/FileTransfer/SConscript
+++ b/Swiften/FileTransfer/SConscript
@@ -1,52 +1,53 @@
Import("swiften_env", "env")
sources = [
- "ByteArrayReadBytestream.cpp",
- "OutgoingFileTransfer.cpp",
- "OutgoingJingleFileTransfer.cpp",
- "OutgoingFileTransferManager.cpp",
- "IncomingFileTransfer.cpp",
- "IncomingJingleFileTransfer.cpp",
- "IncomingFileTransferManager.cpp",
- "JingleFileTransfer.cpp",
- "FileTransferOptions.cpp",
- "FileTransferTransporter.cpp",
- "FileTransferTransporterFactory.cpp",
- "DefaultFileTransferTransporter.cpp",
- "DefaultFileTransferTransporterFactory.cpp",
- "RemoteJingleTransportCandidateSelector.cpp",
- "LocalJingleTransportCandidateGenerator.cpp",
- "ReadBytestream.cpp",
- "WriteBytestream.cpp",
- "FileReadBytestream.cpp",
- "FileWriteBytestream.cpp",
- "FileTransfer.cpp",
- "TransportSession.cpp",
- "IBBSendTransportSession.cpp",
- "IBBReceiveTransportSession.cpp",
- "SOCKS5BytestreamClientSession.cpp",
- "SOCKS5BytestreamServerManager.cpp",
- "SOCKS5BytestreamServer.cpp",
- "SOCKS5BytestreamServerSession.cpp",
- "SOCKS5BytestreamRegistry.cpp",
- "SOCKS5BytestreamProxiesManager.cpp",
- "SOCKS5BytestreamProxyFinder.cpp",
- "IBBSendSession.cpp",
- "IBBReceiveSession.cpp",
- "FileTransferManager.cpp",
- "FileTransferManagerImpl.cpp",
- "IncrementalBytestreamHashCalculator.cpp",
- "SOCKS5BytestreamServerResourceUser.cpp",
- "SOCKS5BytestreamServerPortForwardingUser.cpp",
- ]
+ "ByteArrayReadBytestream.cpp",
+ "DefaultFileTransferTransporter.cpp",
+ "DefaultFileTransferTransporterFactory.cpp",
+ "FailingTransportSession.cpp",
+ "FileReadBytestream.cpp",
+ "FileTransfer.cpp",
+ "FileTransferManager.cpp",
+ "FileTransferManagerImpl.cpp",
+ "FileTransferOptions.cpp",
+ "FileTransferTransporter.cpp",
+ "FileTransferTransporterFactory.cpp",
+ "FileWriteBytestream.cpp",
+ "IBBReceiveSession.cpp",
+ "IBBReceiveTransportSession.cpp",
+ "IBBSendSession.cpp",
+ "IBBSendTransportSession.cpp",
+ "IncomingFileTransfer.cpp",
+ "IncomingFileTransferManager.cpp",
+ "IncomingJingleFileTransfer.cpp",
+ "IncrementalBytestreamHashCalculator.cpp",
+ "JingleFileTransfer.cpp",
+ "LocalJingleTransportCandidateGenerator.cpp",
+ "OutgoingFileTransfer.cpp",
+ "OutgoingFileTransferManager.cpp",
+ "OutgoingJingleFileTransfer.cpp",
+ "ReadBytestream.cpp",
+ "RemoteJingleTransportCandidateSelector.cpp",
+ "SOCKS5BytestreamClientSession.cpp",
+ "SOCKS5BytestreamProxiesManager.cpp",
+ "SOCKS5BytestreamProxyFinder.cpp",
+ "SOCKS5BytestreamRegistry.cpp",
+ "SOCKS5BytestreamServer.cpp",
+ "SOCKS5BytestreamServerManager.cpp",
+ "SOCKS5BytestreamServerPortForwardingUser.cpp",
+ "SOCKS5BytestreamServerResourceUser.cpp",
+ "SOCKS5BytestreamServerSession.cpp",
+ "TransportSession.cpp",
+ "WriteBytestream.cpp",
+ ]
swiften_env.Append(SWIFTEN_OBJECTS = swiften_env.SwiftenObject(sources))
env.Append(UNITTEST_SOURCES = [
- File("UnitTest/SOCKS5BytestreamServerSessionTest.cpp"),
- File("UnitTest/SOCKS5BytestreamClientSessionTest.cpp"),
- File("UnitTest/IBBSendSessionTest.cpp"),
- File("UnitTest/IBBReceiveSessionTest.cpp"),
- File("UnitTest/IncomingJingleFileTransferTest.cpp"),
- File("UnitTest/OutgoingJingleFileTransferTest.cpp"),
- ])
+ File("UnitTest/IBBReceiveSessionTest.cpp"),
+ File("UnitTest/IBBSendSessionTest.cpp"),
+ File("UnitTest/IncomingJingleFileTransferTest.cpp"),
+ File("UnitTest/OutgoingJingleFileTransferTest.cpp"),
+ File("UnitTest/SOCKS5BytestreamClientSessionTest.cpp"),
+ File("UnitTest/SOCKS5BytestreamServerSessionTest.cpp"),
+ ])
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp
index 4fc0246..5ddd32b 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp
@@ -10,7 +10,7 @@
* See the COPYING file for more information.
*/
-#include "SOCKS5BytestreamClientSession.h"
+#include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h>
#include <boost/bind.hpp>
#include <boost/numeric/conversion/cast.hpp>
@@ -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));
+ std::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;
- }
+void SOCKS5BytestreamClientSession::startReceiving(std::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;
+ }
}
-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;
- }
+void SOCKS5BytestreamClientSession::startSending(std::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;
+ }
}
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 {
+ std::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());
- }
+void SOCKS5BytestreamClientSession::handleDataRead(std::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());
+ }
}
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..b819910 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h
@@ -5,15 +5,16 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/ByteArray.h>
@@ -37,75 +38,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 std::shared_ptr<SOCKS5BytestreamClientSession> ref;
public:
- SOCKS5BytestreamClientSession(
- boost::shared_ptr<Connection> connection,
- const HostAddressPort&,
- const std::string&,
- TimerFactory*);
- ~SOCKS5BytestreamClientSession();
+ SOCKS5BytestreamClientSession(
+ std::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(std::shared_ptr<WriteBytestream>);
+ void startSending(std::shared_ptr<ReadBytestream>);
- HostAddressPort getAddressPort() const;
+ HostAddressPort getAddressPort() const;
- boost::signal<void (bool /*error*/)> onSessionReady;
+ boost::signals2::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::signals2::signal<void (boost::optional<FileTransferError>)> onFinished;
+ boost::signals2::signal<void (size_t)> onBytesSent;
+ // boost::signals2::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(std::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))
+ std::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;
+ std::shared_ptr<WriteBytestream> writeBytestream;
+ std::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::signals2::scoped_connection connectFinishedConnection;
+ boost::signals2::scoped_connection dataWrittenConnection;
+ boost::signals2::scoped_connection dataReadConnection;
+ boost::signals2::scoped_connection disconnectedConnection;
};
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp
index a1ef8f6..cd4cfaa 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,11 +13,11 @@
#include <Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h>
#include <Swiften/Network/ConnectionFactory.h>
#include <Swiften/Network/DomainNameAddressQuery.h>
@@ -32,172 +32,176 @@ 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();
+ }
+
+ for (const auto& sessionsForID : proxySessions_) {
+ for (const auto& 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::fromString(proxy->getStreamHost().get().host), 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_) {
+ for (auto&& proxy : localS5BProxies_.get()) {
+ auto proxyHostAddress = HostAddress::fromString(proxy->getStreamHost().get().host);
+ if (proxyHostAddress) {
+ std::shared_ptr<Connection> conn = connectionFactory_->createConnection();
+ HostAddressPort addressPort = HostAddressPort(proxyHostAddress.get(), proxy->getStreamHost().get().port);
+ SWIFT_LOG_ASSERT(addressPort.isValid(), warning) << std::endl;
+ std::shared_ptr<SOCKS5BytestreamClientSession> session = std::make_shared<SOCKS5BytestreamClientSession>(conn, addressPort, sessionID, timerFactory_);
+ JID proxyJid = proxy->getStreamHost().get().jid;
+ clientSessions.push_back(std::pair<JID, std::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;
+std::shared_ptr<SOCKS5BytestreamClientSession> SOCKS5BytestreamProxiesManager::getProxySessionAndCloseOthers(const JID& proxyJID, const std::string& sessionID) {
+ // checking parameters
+ if (proxySessions_.find(sessionID) == proxySessions_.end()) {
+ return std::shared_ptr<SOCKS5BytestreamClientSession>();
+ }
+
+ // get active session
+ std::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();
+ }
+ }
+ SWIFT_LOG_ASSERT(activeSession, warning) << "No active session with matching ID found." << std::endl;
+
+ 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;
+std::shared_ptr<SOCKS5BytestreamClientSession> SOCKS5BytestreamProxiesManager::createSOCKS5BytestreamClientSession(HostAddressPort addressPort, const std::string& destAddr) {
+ SOCKS5BytestreamClientSession::ref connection = std::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));
+ for (auto&& proxy : proxyHosts) {
+ if (proxy) {
+ auto proxyHostAddress = HostAddress::fromString(proxy->getStreamHost().get().host);
+ if (proxyHostAddress) {
+ 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
+ for (const auto& address : addresses) {
+ S5BProxyRequest::StreamHost streamHost = proxy->getStreamHost().get();
+ S5BProxyRequest::ref proxyForAddress = std::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_ = std::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++;
- }
- }
- }
- }
+void SOCKS5BytestreamProxiesManager::handleProxySessionReady(const std::string& sessionID, const JID& jid, std::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++;
+ }
+ }
+ }
+ }
}
-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++;
- }
- }
- }
- }
+void SOCKS5BytestreamProxiesManager::handleProxySessionFinished(const std::string& sessionID, const JID& jid, std::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++;
+ }
+ }
+ }
+ }
}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h
index c7daee7..b5c5173 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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);
+ std::shared_ptr<SOCKS5BytestreamClientSession> getProxySessionAndCloseOthers(const JID& proxyJID, const std::string& sessionID);
- boost::shared_ptr<SOCKS5BytestreamClientSession> createSOCKS5BytestreamClientSession(HostAddressPort addressPort, const std::string& destAddr);
+ std::shared_ptr<SOCKS5BytestreamClientSession> createSOCKS5BytestreamClientSession(HostAddressPort addressPort, const std::string& destAddr);
- public:
- boost::signal<void ()> onDiscoveredProxiesChanged;
+ public:
+ boost::signals2::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, std::shared_ptr<SOCKS5BytestreamClientSession> session, bool error);
+ void handleProxySessionFinished(const std::string& sessionID, const JID& jid, std::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, std::shared_ptr<SOCKS5BytestreamClientSession> > > ProxyJIDClientSessionVector;
+ typedef std::map<std::string, ProxyJIDClientSessionVector> ProxySessionsMap;
+ ProxySessionsMap proxySessions_;
- boost::shared_ptr<SOCKS5BytestreamProxyFinder> proxyFinder_;
+ std::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..90c42dd 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp
@@ -5,18 +5,18 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/S5BProxyRequest.h>
#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Queries/IQRouter.h>
@@ -30,58 +30,57 @@ 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 = std::make_shared<DiscoServiceWalker>(service, iqRouter);
+ serviceWalker->onServiceFound.connect(boost::bind(&SOCKS5BytestreamProxyFinder::handleServiceFound, this, _1, _2));
+ serviceWalker->onWalkComplete.connect(boost::bind(&SOCKS5BytestreamProxyFinder::handleWalkEnded, this));
+ serviceWalker->beginWalk();
}
void SOCKS5BytestreamProxyFinder::stop() {
- typedef 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();
+ for (auto&& requester : pendingRequests) {
+ requester->onResponse.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleProxyResponse, this, requester, _1, _2));
+ }
+
+ serviceWalker->endWalk();
+ serviceWalker->onServiceFound.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleServiceFound, this, _1, _2));
+ serviceWalker->onWalkComplete.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleWalkEnded, this));
+ serviceWalker.reset();
}
void SOCKS5BytestreamProxyFinder::sendBytestreamQuery(const JID& jid) {
- S5BProxyRequest::ref proxyRequest = 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 = std::make_shared<S5BProxyRequest>();
+ std::shared_ptr<GenericRequest<S5BProxyRequest> > request = std::make_shared<GenericRequest<S5BProxyRequest> >(IQ::Get, jid, proxyRequest, iqRouter);
+ request->onResponse.connect(boost::bind(&SOCKS5BytestreamProxyFinder::handleProxyResponse, this, request, _1, _2));
+ pendingRequests.insert(request);
+ request->send();
}
-void SOCKS5BytestreamProxyFinder::handleServiceFound(const JID& jid, boost::shared_ptr<DiscoInfo> discoInfo) {
- if (discoInfo->hasFeature(DiscoInfo::Bytestream)) {
- sendBytestreamQuery(jid);
- }
+void SOCKS5BytestreamProxyFinder::handleServiceFound(const JID& jid, std::shared_ptr<DiscoInfo> discoInfo) {
+ if (discoInfo->hasFeature(DiscoInfo::Bytestream)) {
+ sendBytestreamQuery(jid);
+ }
}
void SOCKS5BytestreamProxyFinder::handleWalkEnded() {
- if (pendingRequests.empty()) {
- onProxiesFound(proxyHosts);
- }
+ 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);
- }
+void SOCKS5BytestreamProxyFinder::handleProxyResponse(std::shared_ptr<GenericRequest<S5BProxyRequest> > requester, std::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);
+ }
}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h
index 1c24497..893f475 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,7 +13,7 @@
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Disco/DiscoServiceWalker.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::signals2::signal<void(std::vector<std::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&, std::shared_ptr<DiscoInfo>);
+ void handleProxyResponse(std::shared_ptr<GenericRequest<S5BProxyRequest> > requester, std::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;
+ std::shared_ptr<DiscoServiceWalker> serviceWalker;
+ std::vector<S5BProxyRequest::ref> proxyHosts;
+ std::set<std::shared_ptr<GenericRequest<S5BProxyRequest> > > pendingRequests;
};
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp
index 5f3756d..9e214fc 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp
@@ -1,16 +1,15 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Base/Algorithm.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
@@ -18,20 +17,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 240d98d..2fa67fa 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,29 +7,29 @@
#pragma once
#include <map>
-#include <string>
#include <set>
+#include <string>
#include <Swiften/Base/API.h>
#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 da56438..483ea18 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,60 +9,59 @@
#include <boost/bind.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/StringCodecs/Hexify.h>
#include <Swiften/Crypto/CryptoProvider.h>
-#include <Swiften/FileTransfer/SOCKS5BytestreamServerSession.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamServerSession.h>
+#include <Swiften/StringCodecs/Hexify.h>
namespace Swift {
SOCKS5BytestreamServer::SOCKS5BytestreamServer(
- boost::shared_ptr<ConnectionServer> connectionServer,
- SOCKS5BytestreamRegistry* registry) :
- connectionServer(connectionServer),
- registry(registry) {
+ std::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));
+ for (auto&& 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();
+void SOCKS5BytestreamServer::handleNewConnection(std::shared_ptr<Connection> connection) {
+ std::shared_ptr<SOCKS5BytestreamServerSession> session =
+ std::make_shared<SOCKS5BytestreamServerSession>(connection, registry);
+ session->onFinished.connect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, session));
+ sessions.push_back(session);
+ session->start();
}
HostAddressPort SOCKS5BytestreamServer::getAddressPort() const {
- return connectionServer->getAddressPort();
+ 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;
+std::vector< std::shared_ptr<SOCKS5BytestreamServerSession> > SOCKS5BytestreamServer::getSessions(
+ const std::string& streamID) const {
+ std::vector< std::shared_ptr<SOCKS5BytestreamServerSession> > result;
+ for (auto&& 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));
+void SOCKS5BytestreamServer::handleSessionFinished(std::shared_ptr<SOCKS5BytestreamServerSession> session) {
+ sessions.erase(std::remove(sessions.begin(), sessions.end(), session), sessions.end());
+ session->onFinished.disconnect(boost::bind(&SOCKS5BytestreamServer::handleSessionFinished, this, session));
}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServer.h b/Swiften/FileTransfer/SOCKS5BytestreamServer.h
index c11de84..c8866c4 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServer.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServer.h
@@ -1,48 +1,48 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
#include <map>
-
-#include <Swiften/Network/ConnectionServer.h>
+#include <memory>
#include <string>
+
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/FileTransfer/ReadBytestream.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
+#include <Swiften/JID/JID.h>
+#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(
+ std::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< std::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(std::shared_ptr<Connection> connection);
+ void handleSessionFinished(std::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;
- };
+ std::shared_ptr<ConnectionServer> connectionServer;
+ SOCKS5BytestreamRegistry* registry;
+ std::vector<std::shared_ptr<SOCKS5BytestreamServerSession> > sessions;
+ };
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp
index 3b1be89..f749735 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp
@@ -12,11 +12,11 @@
#include <Swiften/FileTransfer/SOCKS5BytestreamServerManager.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamServer.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h>
@@ -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(nullptr),
+ 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;
+std::shared_ptr<SOCKS5BytestreamServerResourceUser> SOCKS5BytestreamServerManager::aquireResourceUser() {
+ std::shared_ptr<SOCKS5BytestreamServerResourceUser> resourceUser;
+ if (s5bServerResourceUser_.expired()) {
+ resourceUser = std::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;
+std::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> SOCKS5BytestreamServerManager::aquirePortForwardingUser() {
+ std::shared_ptr<SOCKS5BytestreamServerPortForwardingUser> portForwardingUser;
+ if (s5bServerPortForwardingUser_.expired()) {
+ portForwardingUser = std::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();
+ for (const auto& networkInterface : networkInterfaces) {
+ for (const auto& 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;
-
- // 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();
- }
+ 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::fromString("::").get(), 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();
+ }
}
bool SOCKS5BytestreamServerManager::isPortForwardingReady() const {
- return attemptedPortMapping_ && !getPublicIPRequest && !forwardPortRequest;
+ return attemptedPortMapping_ && !getPublicIPRequest && !forwardPortRequest;
}
void SOCKS5BytestreamServerManager::setupPortForwarding() {
- 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();
- }
-
- // 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();
- }
+ 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();
+ }
+
+ // 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();
- }
-
- state = Start;
+ 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 = nullptr;
+ }
+ if (connectionServer) {
+ connectionServer->stop();
+ connectionServer.reset();
+ }
+
+ 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;
- }
-
- portMapping = mapping;
- onPortForwardingSetup(mapping.is_initialized());
-
- forwardPortRequest->stop();
- forwardPortRequest.reset();
+ 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());
+
+ 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 180745d..3c06513 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.h
@@ -1,94 +1,94 @@
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <vector>
-#include <boost/shared_ptr.hpp>
-#include <boost/weak_ptr.hpp>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Network/HostAddressPort.h>
#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();
+
+ std::shared_ptr<SOCKS5BytestreamServerResourceUser> aquireResourceUser();
+ std::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::signals2::signal<void (bool /* success */)> onInitialized;
+ boost::signals2::signal<void (bool /* success */)> onPortForwardingSetup;
+
+ private:
+ friend class SOCKS5BytestreamServerInitializeRequest;
+ SOCKS5BytestreamRegistry* bytestreamRegistry;
+ ConnectionServerFactory* connectionServerFactory;
+ NetworkEnvironment* networkEnvironment;
+ NATTraverser* natTraverser;
+ enum { Start, Initializing, Initialized } state;
+ SOCKS5BytestreamServer* server;
+ std::shared_ptr<ConnectionServer> connectionServer;
+ int connectionServerPort = -1;
+
+ std::shared_ptr<NATTraversalGetPublicIPRequest> getPublicIPRequest;
+ std::shared_ptr<NATTraversalForwardPortRequest> forwardPortRequest;
+ std::shared_ptr<NATTraversalRemovePortForwardingRequest> unforwardPortRequest;
+ boost::optional<HostAddress> publicAddress;
+ boost::optional<NATPortMapping> portMapping;
+ bool attemptedPortMapping_;
+
+ std::weak_ptr<SOCKS5BytestreamServerResourceUser> s5bServerResourceUser_;
+ std::weak_ptr<SOCKS5BytestreamServerPortForwardingUser> s5bServerPortForwardingUser_;
+ };
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.cpp
index e3b6d34..fc7fe58 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.cpp
@@ -1,41 +1,41 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h>
-#include <Swiften/FileTransfer/SOCKS5BytestreamServerManager.h>
-
#include <boost/bind.hpp>
+#include <Swiften/FileTransfer/SOCKS5BytestreamServerManager.h>
+
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..19f3897 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h
@@ -1,33 +1,34 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
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::signals2::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::signals2::scoped_connection onPortForwardingSetupConnection_;
};
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.cpp
index b369347..2fc2e76 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.cpp
@@ -1,35 +1,35 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h>
-#include <Swiften/FileTransfer/SOCKS5BytestreamServerManager.h>
-
#include <boost/bind.hpp>
+#include <Swiften/FileTransfer/SOCKS5BytestreamServerManager.h>
+
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 15c4fc7..8e42637 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h
@@ -1,12 +1,13 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
namespace Swift {
@@ -14,20 +15,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::signals2::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::signals2::scoped_connection onInitializedConnection_;
};
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp
index 0e1eb6b..bc4e8e4 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));
+ std::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; }
+void SOCKS5BytestreamServerSession::startSending(std::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();
+ 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; }
+void SOCKS5BytestreamServerSession::startReceiving(std::shared_ptr<WriteBytestream> stream) {
+ 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));
- }
- }
+void SOCKS5BytestreamServerSession::handleDataRead(std::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));
+ }
+ }
}
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..c7e252c 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h
@@ -6,78 +6,79 @@
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/FileTransfer/FileTransferError.h>
#include <Swiften/FileTransfer/ReadBytestream.h>
#include <Swiften/FileTransfer/WriteBytestream.h>
#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 std::shared_ptr<SOCKS5BytestreamServerSession> ref;
+
+ public:
+ enum State {
+ Initial,
+ WaitingForAuthentication,
+ WaitingForRequest,
+ ReadyForTransfer,
+ ReadingData,
+ WritingData,
+ Finished
+ };
+
+ SOCKS5BytestreamServerSession(std::shared_ptr<Connection> connection, SOCKS5BytestreamRegistry* registry);
+ ~SOCKS5BytestreamServerSession();
+
+ void setChunkSize(int chunkSize) {
+ this->chunkSize = chunkSize;
+ }
+
+ void start();
+ void stop();
+
+ void startSending(std::shared_ptr<ReadBytestream>);
+ void startReceiving(std::shared_ptr<WriteBytestream>);
+
+ HostAddressPort getAddressPort() const;
+
+ boost::signals2::signal<void (boost::optional<FileTransferError>)> onFinished;
+ boost::signals2::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(std::shared_ptr<SafeByteArray>);
+ void handleDisconnected(const boost::optional<Connection::Error>&);
+ void handleDataAvailable();
+ void sendData();
+
+ private:
+ std::shared_ptr<Connection> connection;
+ SOCKS5BytestreamRegistry* bytestreams;
+ ByteArray unprocessedData;
+ State state;
+ int chunkSize;
+ std::string streamID;
+ std::shared_ptr<ReadBytestream> readBytestream;
+ std::shared_ptr<WriteBytestream> writeBytestream;
+ bool waitingForData;
+
+ boost::signals2::connection disconnectedConnection;
+ boost::signals2::connection dataReadConnection;
+ boost::signals2::connection dataWrittenConnection;
+ boost::signals2::connection dataAvailableConnection;
+
+ };
}
diff --git a/Swiften/FileTransfer/StreamInitiationRequest.h b/Swiften/FileTransfer/StreamInitiationRequest.h
index 7046eda..44e826c 100644
--- a/Swiften/FileTransfer/StreamInitiationRequest.h
+++ b/Swiften/FileTransfer/StreamInitiationRequest.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,28 +7,27 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/StreamInitiation.h>
-
+#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 std::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, std::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, std::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, std::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, std::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 c0560b7..dc6e59a 100644
--- a/Swiften/FileTransfer/TransportSession.h
+++ b/Swiften/FileTransfer/TransportSession.h
@@ -1,25 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/FileTransfer/FileTransferError.h>
-#include <Swiften/Base/boost_bsignals.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::signals2::signal<void (size_t)> onBytesSent;
+ boost::signals2::signal<void (boost::optional<FileTransferError>)> onFinished;
+ };
}
diff --git a/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h b/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h
index 26adb05..03e2476 100644
--- a/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h
+++ b/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h
@@ -4,46 +4,53 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <string>
-#include <boost/filesystem/path.hpp>
+
#include <boost/date_time/posix_time/posix_time.hpp>
+#include <boost/filesystem/path.hpp>
#include <Swiften/Base/Override.h>
#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&,
+ std::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&,
+ std::shared_ptr<ReadBytestream>,
+ const FileTransferOptions&) SWIFTEN_OVERRIDE {
+ return OutgoingFileTransfer::ref();
+ }
+
+ virtual void addS5BProxy(std::shared_ptr<S5BProxyRequest>) {
+ }
+
+ };
}
diff --git a/Swiften/FileTransfer/UnitTest/DummyFileTransferTransporterFactory.h b/Swiften/FileTransfer/UnitTest/DummyFileTransferTransporterFactory.h
index 00a931f..5db3368 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 std::shared_ptr<TransportSession> createIBBSendSession(const std::string& sessionID, unsigned int blockSize, std::shared_ptr<ReadBytestream> stream) {
+ std::shared_ptr<IBBSendSession> ibbSession = std::make_shared<IBBSendSession>(
+ sessionID, initiator_, responder_, stream, iqRouter_);
+ ibbSession->setBlockSize(blockSize);
+ return std::make_shared<IBBSendTransportSession>(ibbSession);
+ }
+
+ virtual std::shared_ptr<TransportSession> createIBBReceiveSession(const std::string& sessionID, unsigned long long size, std::shared_ptr<WriteBytestream> stream) {
+ std::shared_ptr<IBBReceiveSession> ibbSession = std::make_shared<IBBReceiveSession>(
+ sessionID, initiator_, responder_, size, stream, iqRouter_);
+ return std::make_shared<IBBReceiveTransportSession>(ibbSession);
+ }
+
+ virtual std::shared_ptr<TransportSession> createRemoteCandidateSession(
+ std::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) {
+ return std::shared_ptr<TransportSession>();
+ }
+
+ virtual std::shared_ptr<TransportSession> createRemoteCandidateSession(
+ std::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) {
+ return std::shared_ptr<TransportSession>();
+ }
+
+ virtual std::shared_ptr<TransportSession> createLocalCandidateSession(
+ std::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) {
+ return std::shared_ptr<TransportSession>();
+ }
+
+ virtual std::shared_ptr<TransportSession> createLocalCandidateSession(
+ std::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& /* candidate */) {
+ return std::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 nullptr;
+ }
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 41eb0ca..31f46de 100644
--- a/Swiften/FileTransfer/UnitTest/IBBReceiveSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/IBBReceiveSessionTest.cpp
@@ -1,185 +1,187 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <memory>
#include <vector>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
#include <Swiften/Base/ByteArray.h>
-#include <Swiften/FileTransfer/IBBReceiveSession.h>
+#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/FileTransfer/ByteArrayWriteBytestream.h>
+#include <Swiften/FileTransfer/IBBReceiveSession.h>
#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/Client/DummyStanzaChannel.h>
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 = std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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;
+ std::shared_ptr<ByteArrayWriteBytestream> bytestream;
};
CPPUNIT_TEST_SUITE_REGISTRATION(IBBReceiveSessionTest);
diff --git a/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp b/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp
index eac52bf..f9057f8 100644
--- a/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp
@@ -1,230 +1,232 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
#include <vector>
+
#include <boost/bind.hpp>
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
#include <Swiften/Base/ByteArray.h>
-#include <Swiften/FileTransfer/IBBSendSession.h>
+#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/FileTransfer/ByteArrayReadBytestream.h>
+#include <Swiften/FileTransfer/IBBSendSession.h>
#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/Client/DummyStanzaChannel.h>
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 = std::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg"));
+ finished = false;
+ }
+
+ void tearDown() {
+ delete iqRouter;
+ delete stanzaChannel;
+ }
+
+ void testStart() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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(), std::shared_ptr<IBB>());
+ }
+
+ private:
+ std::shared_ptr<IBBSendSession> createSession(const std::string& to) {
+ std::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;
+ std::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..72b933d 100644
--- a/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp
@@ -5,14 +5,13 @@
*/
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <iostream>
-
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -45,201 +44,200 @@
#include <Swiften/Queries/IQRouter.h>
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());
- }
+ std::shared_ptr<IncomingJingleFileTransfer> createTestling() {
+ JID ourJID("our@jid.org/full");
+ return std::make_shared<IncomingJingleFileTransfer>(ourJID, std::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 = std::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ eventLoop = new DummyEventLoop();
+ resolver = new StaticDomainNameResolver(eventLoop);
+ session = std::make_shared<FakeJingleSession>("foo@bar.com/baz", "mysession");
+ jingleContentPayload = std::make_shared<JingleContentPayload>();
+ // fakeRJTCSF = std::make_shared<FakeRemoteJingleTransportCandidateSelectorFactory>();
+ // fakeLJTCF = std::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
+ std::shared_ptr<JingleFileTransferDescription> desc = std::make_shared<JingleFileTransferDescription>();
+ desc->setFileInfo(JingleFileTransferFileInfo("foo.txt", "", 10));
+ jingleContentPayload->addDescription(desc);
+ JingleIBBTransportPayload::ref tpRef = std::make_shared<JingleIBBTransportPayload>();
+ tpRef->setSessionID("mysession");
+ jingleContentPayload->addTransport(tpRef);
+
+ std::shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling();
+
+ //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one)
+ std::shared_ptr<ByteArrayWriteBytestream> byteStream = std::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
+ std::shared_ptr<JingleFileTransferDescription> desc = std::make_shared<JingleFileTransferDescription>();
+ desc->setFileInfo(JingleFileTransferFileInfo("file.txt", "", 10));
+ jingleContentPayload->addDescription(desc);
+ JingleIBBTransportPayload::ref tpRef = std::make_shared<JingleIBBTransportPayload>();
+ tpRef->setSessionID("mysession");
+ jingleContentPayload->addTransport(tpRef);
+
+ std::shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling();
+
+ //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one)
+ std::shared_ptr<ByteArrayWriteBytestream> byteStream = std::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();
+
+ std::shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling();
+
+ //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one)
+ std::shared_ptr<ByteArrayWriteBytestream> byteStream = std::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 = std::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() {
+ std::shared_ptr<JingleFileTransferDescription> desc = std::make_shared<JingleFileTransferDescription>();
+ desc->setFileInfo(JingleFileTransferFileInfo("file.txt", "", 10));
+ jingleContentPayload->addDescription(desc);
+ }
+
+ std::shared_ptr<JingleS5BTransportPayload> addJingleS5BPayload() {
+ JingleS5BTransportPayload::ref payLoad = std::make_shared<JingleS5BTransportPayload>();
+ payLoad->setSessionID("mysession");
+ jingleContentPayload->addTransport(payLoad);
+ return payLoad;
+ }
+
+ std::shared_ptr<JingleIBBTransportPayload> addJingleIBBPayload() {
+ JingleIBBTransportPayload::ref payLoad = std::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;
+ std::shared_ptr<CryptoProvider> crypto;
+ std::shared_ptr<FakeJingleSession> session;
+ std::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..3f4d20f 100644
--- a/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp
@@ -11,10 +11,10 @@
*/
#include <iostream>
+#include <memory>
#include <boost/bind.hpp>
#include <boost/optional.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -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);
- }
+ std::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 std::shared_ptr<OutgoingJingleFileTransfer>(new OutgoingJingleFileTransfer(
+ to,
+ std::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 = std::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ fakeJingleSession = new FakeJingleSession("foo@bar.com/baz", "mysession");
+ jingleContentPayload = std::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 = std::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() {
+ std::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling();
+ transfer->start();
+
+ FakeJingleSession::InitiateCall call = getCall<FakeJingleSession::InitiateCall>(0);
+ JingleFileTransferDescription::ref description = std::dynamic_pointer_cast<JingleFileTransferDescription>(call.description);
+ CPPUNIT_ASSERT(description);
+ CPPUNIT_ASSERT(static_cast<size_t>(1048576) == description->getFileInfo().getSize());
+
+ JingleIBBTransportPayload::ref transport = std::dynamic_pointer_cast<JingleIBBTransportPayload>(call.payload);
+ CPPUNIT_ASSERT(transport);
+ }
+
+ void test_FallbackToIBBAfterFailingS5B() {
+ std::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling(FileTransferOptions().withAssistedAllowed(true).withDirectAllowed(true).withProxiedAllowed(true));
+ transfer->start();
+
+ FakeJingleSession::InitiateCall call = getCall<FakeJingleSession::InitiateCall>(0);
+
+ CPPUNIT_ASSERT(std::dynamic_pointer_cast<JingleS5BTransportPayload>(call.payload));
+ fakeJingleSession->handleSessionAcceptReceived(call.id, call.description, call.payload);
+
+ // send candidate failure
+ JingleS5BTransportPayload::ref candidateFailurePayload = std::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() {
+ std::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() {
+ std::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() {
+ std::shared_ptr<JingleFileTransferDescription> desc = std::make_shared<JingleFileTransferDescription>();
+ desc->setFileInfo(JingleFileTransferFileInfo());
+ jingleContentPayload->addDescription(desc);
+ }
+
+ std::shared_ptr<JingleS5BTransportPayload> addJingleS5BPayload() {
+ JingleS5BTransportPayload::ref payLoad = std::make_shared<JingleS5BTransportPayload>();
+ payLoad->setSessionID("mysession");
+ jingleContentPayload->addTransport(payLoad);
+ return payLoad;
+ }
+
+ std::shared_ptr<JingleIBBTransportPayload> addJingleIBBPayload() {
+ JingleIBBTransportPayload::ref payLoad = std::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;
+ std::shared_ptr<ByteArrayReadBytestream> stream;
+ FakeJingleSession* fakeJingleSession;
+ std::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;
+ std::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..290dda5 100644
--- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
@@ -5,16 +5,17 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <boost/bind.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <QA/Checker/IO.h>
@@ -43,275 +44,271 @@ 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::fromString("127.0.0.1").get(), 8888)) {}
+
+ void setUp() {
+ crypto = std::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
+ destination = "092a44d859d19c9eed676b551ee80025903351c2";
+ randomGen.seed(static_cast<unsigned int>(time(nullptr)));
+ eventLoop = std::unique_ptr<DummyEventLoop>(new DummyEventLoop());
+ timerFactory = std::unique_ptr<DummyTimerFactory>(new DummyTimerFactory());
+ connection = std::make_shared<MockeryConnection>(failingPorts, true, eventLoop.get());
+ //connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1));
+ //stream1 = std::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg")));
+// connection->onDataRead.connect(boost::bind(&SOCKS5BytestreamClientSessionTest::handleDataRead, this, _1));
+ }
+
+ void tearDown() {
+ //connection.reset();
+ }
+
+ void testForSessionReady() {
+ TestHelper helper;
+ connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
+
+ SOCKS5BytestreamClientSession::ref clientSession = std::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory.get());
+ 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 = std::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory.get());
+ 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 = std::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory.get());
+ 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 = std::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory.get());
+ 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);
+
+ std::shared_ptr<ByteArrayWriteBytestream> output = std::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 = std::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory.get());
+ 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);
+ std::shared_ptr<ByteArrayReadBytestream> input = std::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() {
+ std::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() {
+ std::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));
+
+ std::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;
+ 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;
+ }
+ };
-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);
- }
private:
- struct TestHelper {
- TestHelper() : sessionReadyCalled(false), sessionReadyError(false) {}
- ByteArray unprocessedInput;
- bool sessionReadyCalled;
- bool sessionReadyError;
+ struct MockeryConnection : public Connection, public EventOwner, public std::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 handleConnectionDataWritten(const SafeByteArray& data) {
- append(unprocessedInput, data);
- //SWIFT_LOG(debug) << "unprocessedInput (" << unprocessedInput.size() << "): " << Hexify::hexify(unprocessedInput) << std::endl;
- }
+ 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 handleSessionReady(bool error) {
- sessionReadyCalled = true;
- sessionReadyError = error;
- }
- };
+ HostAddressPort getLocalAddress() const { return HostAddressPort(); }
+ HostAddressPort getRemoteAddress() const { return HostAddressPort(); }
-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;
- };
+ void disconnect() {
+ disconnectCalled = true;
+ }
+
+ void write(const SafeByteArray& data) {
+ eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this());
+ onDataSent(data);
+ }
+
+ boost::signals2::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;
+ std::unique_ptr<DummyEventLoop> eventLoop;
+ std::unique_ptr<DummyTimerFactory> timerFactory;
+ std::shared_ptr<MockeryConnection> connection;
+ const std::vector<HostAddressPort> failingPorts;
+ std::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(SOCKS5BytestreamClientSessionTest);
diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
index eb853a5..d419b8a 100644
--- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
@@ -1,213 +1,213 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/ByteArray.h>
+#include <boost/bind.hpp>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/bind.hpp>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/Base/Concat.h>
-#include <Swiften/FileTransfer/SOCKS5BytestreamServerSession.h>
+#include <Swiften/Base/StartStopper.h>
+#include <Swiften/EventLoop/DummyEventLoop.h>
#include <Swiften/FileTransfer/ByteArrayReadBytestream.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamServerSession.h>
#include <Swiften/Network/DummyConnection.h>
-#include <Swiften/EventLoop/DummyEventLoop.h>
-#include <Swiften/Base/StartStopper.h>
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 = std::make_shared<DummyConnection>(eventLoop);
+ connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1));
+ stream1 = std::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg"));
+ finished = false;
+ }
+
+ void tearDown() {
+ connection.reset();
+ delete bytestreams;
+ delete eventLoop;
+ }
+
+ void testAuthenticate() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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;
+ std::shared_ptr<DummyConnection> connection;
+ std::vector<unsigned char> receivedData;
+ int receivedDataChunks;
+ std::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..5d9c3f8 100644
--- a/Swiften/FileTransfer/WriteBytestream.h
+++ b/Swiften/FileTransfer/WriteBytestream.h
@@ -6,27 +6,27 @@
#pragma once
+#include <memory>
#include <vector>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#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 std::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::signals2::signal<void (const std::vector<unsigned char>&)> onWrite;
+ };
}
diff --git a/Swiften/History/HistoryMessage.h b/Swiften/History/HistoryMessage.h
index cf33b0c..e910899 100644
--- a/Swiften/History/HistoryMessage.h
+++ b/Swiften/History/HistoryMessage.h
@@ -1,73 +1,74 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/JID/JID.h>
-#include <Swiften/Base/API.h>
#include <boost/date_time/posix_time/posix_time_types.hpp>
+#include <Swiften/Base/API.h>
+#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 99ade51..10b6bb0 100644
--- a/Swiften/History/HistoryStorage.h
+++ b/Swiften/History/HistoryStorage.h
@@ -1,34 +1,36 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <set>
#include <map>
+#include <set>
#include <vector>
+
+#include <boost/date_time/gregorian/gregorian_types.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/History/HistoryMessage.h>
-#include <boost/date_time/gregorian/gregorian_types.hpp>
+#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/SConscript b/Swiften/History/SConscript
index bd56818..65be489 100644
--- a/Swiften/History/SConscript
+++ b/Swiften/History/SConscript
@@ -2,10 +2,10 @@ Import("swiften_env")
myenv = swiften_env.Clone()
if myenv["target"] == "native":
- myenv.MergeFlags(swiften_env.get("SQLITE_FLAGS", {}))
+ myenv.MergeFlags(swiften_env.get("SQLITE_FLAGS", {}))
if myenv["experimental"]:
- objects = myenv.SwiftenObject([
- "SQLiteHistoryStorage.cpp",
- ])
- swiften_env.Append(SWIFTEN_OBJECTS = [objects])
+ objects = myenv.SwiftenObject([
+ "SQLiteHistoryStorage.cpp",
+ ])
+ swiften_env.Append(SWIFTEN_OBJECTS = [objects])
diff --git a/Swiften/History/SQLiteHistoryStorage.cpp b/Swiften/History/SQLiteHistoryStorage.cpp
index feb90d2..1b12367 100644
--- a/Swiften/History/SQLiteHistoryStorage.cpp
+++ b/Swiften/History/SQLiteHistoryStorage.cpp
@@ -1,379 +1,383 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swiften/History/SQLiteHistoryStorage.h>
+
#include <iostream>
+
+#include <boost/bind.hpp>
+#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <sqlite3.h>
-#include <Swiften/History/SQLiteHistoryStorage.h>
-#include <boost/date_time/gregorian/gregorian.hpp>
+
#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);
- }
+SQLiteHistoryStorage::SQLiteHistoryStorage(const boost::filesystem::path& file) : db_(nullptr) {
+ thread_ = new std::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)", nullptr, nullptr, &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)", nullptr, nullptr, &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(), nullptr, nullptr, &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, nullptr);
+ 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(), nullptr, nullptr, &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, nullptr);
+ 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, nullptr);
+ 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, nullptr);
+ 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, nullptr);
+ 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, nullptr);
+ 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 73352b1..57f0d35 100644
--- a/Swiften/History/SQLiteHistoryStorage.h
+++ b/Swiften/History/SQLiteHistoryStorage.h
@@ -1,43 +1,44 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <thread>
+
+#include <boost/filesystem/path.hpp>
#include <boost/optional.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/History/HistoryStorage.h>
-#include <boost/thread.hpp>
-#include <boost/filesystem/path.hpp>
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_;
+ std::thread* thread_;
+ };
}
diff --git a/Swiften/History/UnitTest/SQLiteHistoryManagerTest.cpp b/Swiften/History/UnitTest/SQLiteHistoryManagerTest.cpp
index 02c9c69..4d8a111 100644
--- a/Swiften/History/UnitTest/SQLiteHistoryManagerTest.cpp
+++ b/Swiften/History/UnitTest/SQLiteHistoryManagerTest.cpp
@@ -1,115 +1,116 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <boost/date_time/posix_time/posix_time.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/date_time/posix_time/posix_time.hpp>
#include <Swiften/History/SQLiteHistoryManager.h>
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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::shared_ptr<SQLiteHistoryManager> testling(createHistoryManager());
+
+ boost::optional<JID> result(testling->getJIDFromID(1));
+
+ CPPUNIT_ASSERT(!result);
+ }
+
+ void getIDFromJID() {
+ std::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() {
+ std::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..d6b0827 100644
--- a/Swiften/IDN/ICUConverter.cpp
+++ b/Swiften/IDN/ICUConverter.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2013 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+
+ std::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 eec6a59..0a0b0d3 100644
--- a/Swiften/IDN/ICUConverter.h
+++ b/Swiften/IDN/ICUConverter.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2013 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,16 +7,17 @@
#pragma once
#include <string>
+
#include <Swiften/Base/API.h>
#include <Swiften/Base/Override.h>
#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 ed3fafb..27ddd78 100644
--- a/Swiften/IDN/IDNConverter.h
+++ b/Swiften/IDN/IDNConverter.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,26 +7,28 @@
#pragma once
#include <string>
+
+#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
#include <Swiften/Base/SafeByteArray.h>
-#include <boost/optional.hpp>
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..0c01352 100644
--- a/Swiften/IDN/LibIDNConverter.cpp
+++ b/Swiften/IDN/LibIDNConverter.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,15 +7,15 @@
#include <Swiften/IDN/LibIDNConverter.h>
extern "C" {
- #include <stringprep.h>
- #include <idna.h>
+ #include <stringprep.h>
+ #include <idna.h>
}
#include <cassert>
#include <cstdlib>
#include <vector>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/Base/SafeAllocator.h>
@@ -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 nullptr;
+ }
- 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 6db8e0c..3f1d1f7 100644
--- a/Swiften/IDN/LibIDNConverter.h
+++ b/Swiften/IDN/LibIDNConverter.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2013 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,17 +7,18 @@
#pragma once
#include <string>
+
#include <Swiften/Base/API.h>
#include <Swiften/Base/Override.h>
#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..c85d3b6 100644
--- a/Swiften/IDN/PlatformIDNConverter.cpp
+++ b/Swiften/IDN/PlatformIDNConverter.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 nullptr;
#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/SConscript b/Swiften/IDN/SConscript
index 7a3c061..28596f7 100644
--- a/Swiften/IDN/SConscript
+++ b/Swiften/IDN/SConscript
@@ -5,27 +5,27 @@ objects = swiften_env.SwiftenObject(["IDNConverter.cpp"])
myenv = swiften_env.Clone()
if myenv.get("NEED_IDN"):
- myenv.Append(CPPDEFINES = ["NEED_IDN"])
+ myenv.Append(CPPDEFINES = ["NEED_IDN"])
if myenv.get("HAVE_ICU") :
- myenv.MergeFlags(swiften_env["ICU_FLAGS"])
- myenv.Append(CPPDEFINES = ["HAVE_ICU"])
- objects += myenv.SwiftenObject(["ICUConverter.cpp"])
+ myenv.MergeFlags(swiften_env["ICU_FLAGS"])
+ myenv.Append(CPPDEFINES = ["HAVE_ICU"])
+ objects += myenv.SwiftenObject(["ICUConverter.cpp"])
if myenv.get("HAVE_LIBIDN") :
- myenv.MergeFlags(swiften_env["LIBIDN_FLAGS"])
- myenv.Append(CPPDEFINES = ["HAVE_LIBIDN"])
- objects += myenv.SwiftenObject(["LibIDNConverter.cpp"])
+ myenv.MergeFlags(swiften_env["LIBIDN_FLAGS"])
+ myenv.Append(CPPDEFINES = ["HAVE_LIBIDN"])
+ objects += myenv.SwiftenObject(["LibIDNConverter.cpp"])
objects += myenv.SwiftenObject([
- "PlatformIDNConverter.cpp"
- ])
+ "PlatformIDNConverter.cpp"
+ ])
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
if env["TEST"] :
- test_env = myenv.Clone()
- test_env.UseFlags(swiften_env["CPPUNIT_FLAGS"])
- env.Append(UNITTEST_OBJECTS = test_env.SwiftenObject([
- File("UnitTest/IDNConverterTest.cpp"),
- File("UnitTest/UTF8ValidatorTest.cpp")
- ]))
+ test_env = myenv.Clone()
+ test_env.UseFlags(swiften_env["CPPUNIT_FLAGS"])
+ env.Append(UNITTEST_OBJECTS = test_env.SwiftenObject([
+ File("UnitTest/IDNConverterTest.cpp"),
+ File("UnitTest/UTF8ValidatorTest.cpp")
+ ]))
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 cb8fa0e..508a28c 100644
--- a/Swiften/IDN/UnitTest/IDNConverterTest.cpp
+++ b/Swiften/IDN/UnitTest/IDNConverterTest.cpp
@@ -1,63 +1,64 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/shared_ptr.hpp>
#include <Swiften/IDN/IDNConverter.h>
#include <Swiften/IDN/PlatformIDNConverter.h>
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();
-
- public:
- void setUp() {
- testling = boost::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
- }
-
- void testStringPrep() {
- std::string result = testling->getStringPrepared("tron\xc3\x87on", IDNConverter::NamePrep);
-
- 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 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_Invalid() {
- boost::optional<std::string> result = testling->getIDNAEncoded("www.foo,bar.com");
- CPPUNIT_ASSERT(!result);
- }
-
- private:
- boost::shared_ptr<IDNConverter> testling;
+ 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 = std::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
+ }
+
+ void testStringPrep() {
+ std::string result = testling->getStringPrepared("tron\xc3\x87on", IDNConverter::NamePrep);
+
+ 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 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_Invalid() {
+ boost::optional<std::string> result = testling->getIDNAEncoded("www.foo,bar.com");
+ CPPUNIT_ASSERT(!result);
+ }
+
+ private:
+ std::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 a0f18d5..c82674d 100644
--- a/Swiften/JID/JID.cpp
+++ b/Swiften/JID/JID.cpp
@@ -1,326 +1,267 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#define SWIFTEN_CACHE_JID_PREP
+#include <sstream>
+#include <string>
#include <vector>
-#include <list>
-#include <iostream>
-#include <string>
#ifdef SWIFTEN_CACHE_JID_PREP
-#include <boost/thread/mutex.hpp>
-#include <boost/unordered_map.hpp>
+#include <mutex>
+#include <unordered_map>
#endif
-#include <boost/assign/list_of.hpp>
-#include <boost/algorithm/string/find_format.hpp>
-#include <boost/algorithm/string/finder.hpp>
+
#include <boost/optional.hpp>
-#include <iostream>
-#include <sstream>
#include <Swiften/Base/String.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/IDN/IDNConverter.h>
+#include <Swiften/JID/JID.h>
+
#ifndef SWIFTEN_JID_NO_DEFAULT_IDN_CONVERTER
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/IDN/PlatformIDNConverter.h>
#endif
using namespace Swift;
#ifdef SWIFTEN_CACHE_JID_PREP
-typedef boost::unordered_map<std::string, std::string> PrepCache;
+typedef std::unordered_map<std::string, std::string> PrepCache;
-static boost::mutex namePrepCacheMutex;
+static std::mutex namePrepCacheMutex;
static PrepCache nodePrepCache;
static PrepCache domainPrepCache;
static PrepCache resourcePrepCache;
#endif
-static const std::list<char> escapedChars = boost::assign::list_of(' ')('"')('&')('\'')('/')('<')('>')('@')(':');
+static const std::vector<char> escapedChars = {' ', '"', '&', '\'', '/', '<', '>', '@', ':'};
-static IDNConverter* idnConverter = NULL;
+static IDNConverter* idnConverter = nullptr;
#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();
+ }
+ std::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);
- }
-};
-
-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();
- }
-};
-
-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);
- }
-};
-
-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);
- }
-};
-#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) {
- 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;
+ }
+
+ if (hasResource_ && resource.empty()) {
+ 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;
+ std::unique_lock<std::mutex> 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;
}
-
+
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;
}
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 9bcc7d5..dc92f53 100644
--- a/Swiften/JID/JID.h
+++ b/Swiften/JID/JID.h
@@ -1,198 +1,198 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <string>
#include <iosfwd>
+#include <string>
-#include <Swiften/Base/API.h>
#include <boost/optional/optional.hpp>
+#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/SConscript b/Swiften/JID/SConscript
index 12565fc..122388e 100644
--- a/Swiften/JID/SConscript
+++ b/Swiften/JID/SConscript
@@ -2,6 +2,6 @@ Import("swiften_env")
myenv = swiften_env.Clone()
objects = myenv.SwiftenObject([
- "JID.cpp",
- ])
+ "JID.cpp",
+ ])
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
diff --git a/Swiften/JID/UnitTest/JIDTest.cpp b/Swiften/JID/UnitTest/JIDTest.cpp
index 307243a..ca3e5ae 100644
--- a/Swiften/JID/UnitTest/JIDTest.cpp
+++ b/Swiften/JID/UnitTest/JIDTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,398 +13,418 @@ 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(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());
- }
-
- void testConstructorWithString_SpacesInNode() {
- CPPUNIT_ASSERT(!JID(" alice@wonderland.lit").isValid());
- CPPUNIT_ASSERT(!JID("alice @wonderland.lit").isValid());
- }
-
- void testConstructorWithStrings() {
- JID testling("foo", "bar", "baz");
+ CPPUNIT_TEST_SUITE(JIDTest);
+ CPPUNIT_TEST(testConstructorWithString);
+ CPPUNIT_TEST(testConstructorWithString_Empty);
+ 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_Empty() {
+ JID testling("");
+ CPPUNIT_ASSERT_EQUAL(false, 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());
+ }
- 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 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");
- void testConstructorWithStrings_EmptyDomain() {
- JID testling("foo", "", "baz");
+ 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 testIsBare() {
- CPPUNIT_ASSERT(JID("foo@bar").isBare());
- }
+ void testConstructorWithStrings() {
+ JID testling("foo", "bar", "baz");
- void testIsBare_NotBare() {
- CPPUNIT_ASSERT(!JID("foo@bar/baz").isBare());
- }
+ 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 testToBare() {
- JID testling("foo@bar/baz");
+ void testConstructorWithStrings_EmptyDomain() {
+ JID testling("foo", "", "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(!testling.isValid());
+ }
- void testToBare_EmptyNode() {
- JID testling("bar/baz");
+ void testConstructorWithStrings_EmptyResource() {
+ JID testling("foo", "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(testling.isValid());
- }
+ CPPUNIT_ASSERT(!testling.isValid());
+ }
- void testToBare_EmptyResource() {
- JID testling("bar/");
+ void testIsBare() {
+ CPPUNIT_ASSERT(JID("foo@bar").isBare());
+ }
- CPPUNIT_ASSERT_EQUAL(std::string(""), testling.toBare().getNode());
- CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.toBare().getDomain());
- CPPUNIT_ASSERT(testling.toBare().isBare());
- }
+ void testIsBare_NotBare() {
+ CPPUNIT_ASSERT(!JID("foo@bar/baz").isBare());
+ }
- void testToString() {
- JID testling("foo@bar/baz");
+ void testToBare() {
+ JID testling("foo@bar/baz");
- CPPUNIT_ASSERT_EQUAL(std::string("foo@bar/baz"), testling.toString());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.toBare().getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.toBare().getDomain());
+ CPPUNIT_ASSERT(testling.toBare().isBare());
+ }
- void testToString_EmptyNode() {
- JID testling("bar/baz");
+ void testToBare_EmptyNode() {
+ JID testling("bar/baz");
- CPPUNIT_ASSERT_EQUAL(std::string("bar/baz"), testling.toString());
- }
+ 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 testToString_NoResource() {
- JID testling("foo@bar");
+ void testToBare_EmptyResource() {
+ JID testling("bar/");
- CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), testling.toString());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string(""), testling.toBare().getNode());
+ CPPUNIT_ASSERT(!testling.isValid());
+ }
- void testToString_EmptyResource() {
- JID testling("foo@bar/");
+ void testToString() {
+ JID testling("foo@bar/baz");
- CPPUNIT_ASSERT_EQUAL(std::string("foo@bar/"), testling.toString());
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("foo@bar/baz"), testling.toString());
+ }
- void testCompare_SmallerNode() {
- JID testling1("a@c");
- JID testling2("b@b");
+ void testToString_EmptyNode() {
+ JID testling("bar/baz");
- CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("bar/baz"), testling.toString());
+ }
- void testCompare_LargerNode() {
- JID testling1("c@a");
- JID testling2("b@b");
+ void testToString_NoResource() {
+ JID testling("foo@bar");
- CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource));
- }
+ CPPUNIT_ASSERT_EQUAL(std::string("foo@bar"), testling.toString());
+ }
- void testCompare_SmallerDomain() {
- JID testling1("x@a/c");
- JID testling2("x@b/b");
+ void testToString_EmptyResource() {
+ JID testling("foo@bar/");
- CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource));
- }
+ CPPUNIT_ASSERT_EQUAL(false, testling.isValid());
+ }
- void testCompare_LargerDomain() {
- JID testling1("x@b/b");
- JID testling2("x@a/c");
+ 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_SmallerResource() {
- JID testling1("x@y/a");
- JID testling2("x@y/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_LargerResource() {
- JID testling1("x@y/b");
- JID testling2("x@y/a");
+ 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_Equal() {
- JID testling1("x@y/z");
- JID testling2("x@y/z");
+ void testCompare_LargerDomain() {
+ JID testling1("x@b/b");
+ JID testling2("x@a/c");
- CPPUNIT_ASSERT_EQUAL(0, testling1.compare(testling2, JID::WithResource));
- }
+ CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource));
+ }
- void testCompare_EqualWithoutResource() {
- 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(0, testling1.compare(testling2, JID::WithoutResource));
- }
+ CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource));
+ }
- void testCompare_NoResourceAndEmptyResource() {
- JID testling1("x@y/");
- JID testling2("x@y");
+ 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_EmptyResourceAndNoResource() {
- JID testling1("x@y");
- JID testling2("x@y/");
+ void testCompare_Equal() {
+ JID testling1("x@y/z");
+ JID testling2("x@y/z");
- CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource));
- }
+ CPPUNIT_ASSERT_EQUAL(0, testling1.compare(testling2, JID::WithResource));
+ }
- void testEquals() {
- JID testling1("x@y/c");
- JID testling2("x@y/c");
+ void testCompare_EqualWithoutResource() {
+ JID testling1("x@y/a");
+ JID testling2("x@y/b");
- 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_EQUAL(0, testling1.compare(testling2, JID::WithoutResource));
+ }
+
+ void testCompare_NoResourceAndEmptyResource() {
+ JID testling1("x@y/");
+ JID testling2("x@y");
+
+ CPPUNIT_ASSERT_EQUAL(-1, testling1.compare(testling2, JID::WithResource));
+ }
+
+ void testCompare_EmptyResourceAndNoResource() {
+ JID testling1("x@y");
+ JID testling2("x@y/");
+
+ CPPUNIT_ASSERT_EQUAL(1, testling1.compare(testling2, JID::WithResource));
+ }
+
+ 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());
+ CPPUNIT_ASSERT_EQUAL(true, testling.isValid());
+ }
+
+ {
+ JID testling("node@domain/");
+ CPPUNIT_ASSERT_EQUAL(false, testling.isValid());
+ }
+ }
+
+ 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..20edf15 100644
--- a/Swiften/Jingle/AbstractJingleSessionListener.cpp
+++ b/Swiften/Jingle/AbstractJingleSessionListener.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -10,32 +10,32 @@
using namespace Swift;
-void AbstractJingleSessionListener::handleSessionAcceptReceived(const JingleContentID&, boost::shared_ptr<JingleDescription>, boost::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+void AbstractJingleSessionListener::handleSessionAcceptReceived(const JingleContentID&, std::shared_ptr<JingleDescription>, std::shared_ptr<JingleTransportPayload>) {
+ SWIFT_LOG(warning) << "Unimplemented" << std::endl;
}
-void AbstractJingleSessionListener::handleSessionInfoReceived(boost::shared_ptr<JinglePayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+void AbstractJingleSessionListener::handleSessionInfoReceived(std::shared_ptr<JinglePayload>) {
+ 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;
+void AbstractJingleSessionListener::handleTransportAcceptReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) {
+ SWIFT_LOG(warning) << "Unimplemented" << std::endl;
}
-void AbstractJingleSessionListener::handleTransportInfoReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+void AbstractJingleSessionListener::handleTransportInfoReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) {
+ SWIFT_LOG(warning) << "Unimplemented" << std::endl;
}
-void AbstractJingleSessionListener::handleTransportRejectReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+void AbstractJingleSessionListener::handleTransportRejectReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) {
+ SWIFT_LOG(warning) << "Unimplemented" << std::endl;
}
-void AbstractJingleSessionListener::handleTransportReplaceReceived(const JingleContentID&, boost::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+void AbstractJingleSessionListener::handleTransportReplaceReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) {
+ 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..590cd14 100644
--- a/Swiften/Jingle/AbstractJingleSessionListener.h
+++ b/Swiften/Jingle/AbstractJingleSessionListener.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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&, std::shared_ptr<JingleDescription>, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+ virtual void handleSessionInfoReceived(std::shared_ptr<JinglePayload>) SWIFTEN_OVERRIDE;
+ virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) SWIFTEN_OVERRIDE;
+ virtual void handleTransportAcceptReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+ virtual void handleTransportInfoReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+ virtual void handleTransportRejectReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE;
+ virtual void handleTransportReplaceReceived(const JingleContentID&, std::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 864dd53..6b88477 100644
--- a/Swiften/Jingle/FakeJingleSession.cpp
+++ b/Swiften/Jingle/FakeJingleSession.cpp
@@ -5,15 +5,16 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Jingle/FakeJingleSession.h>
-#include <Swiften/Jingle/JingleSessionListener.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
+#include <Swiften/Jingle/JingleSessionListener.h>
namespace Swift {
@@ -25,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));
+void FakeJingleSession::sendInfo(std::shared_ptr<Payload> 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);
+void FakeJingleSession::handleSessionAcceptReceived(const JingleContentID& contentID, std::shared_ptr<JingleDescription> desc, std::shared_ptr<JingleTransportPayload> payload) {
+ notifyListeners(&JingleSessionListener::handleSessionAcceptReceived, contentID, desc, payload);
}
}
diff --git a/Swiften/Jingle/FakeJingleSession.h b/Swiften/Jingle/FakeJingleSession.h
index f250b1a..6218544 100644
--- a/Swiften/Jingle/FakeJingleSession.h
+++ b/Swiften/Jingle/FakeJingleSession.h
@@ -5,109 +5,110 @@
*/
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
+
+#include <boost/signals2.hpp>
#include <boost/variant.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/SimpleIDGenerator.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Base/Override.h>
-#include <Swiften/JID/JID.h>
+#include <Swiften/Base/SimpleIDGenerator.h>
#include <Swiften/Elements/JinglePayload.h>
-#include <Swiften/Jingle/JingleSession.h>
+#include <Swiften/JID/JID.h>
#include <Swiften/Jingle/JingleContentID.h>
+#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(std::shared_ptr<Payload> info) : payload(info) {}
+ std::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 std::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(std::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&, std::shared_ptr<JingleDescription>, std::shared_ptr<JingleTransportPayload>);
+ void handleSessionInfoReceived(std::shared_ptr<JinglePayload>);
+
+ void handleTransportReplaceReceived(const JingleContentID&, JingleTransportPayload::ref);
+ void handleTransportAcceptReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>);
+ void handleTransportInfoReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>);
+ void handleTransportRejectReceived(const JingleContentID&, std::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..0cd1a23 100644
--- a/Swiften/Jingle/Jingle.h
+++ b/Swiften/Jingle/Jingle.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 (const auto& content : contents) {
+ if (content->getDescription<T>()) {
+ return content;
+ }
+ }
+ 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 b0caa74..09bb234 100644
--- a/Swiften/Jingle/JingleResponder.cpp
+++ b/Swiften/Jingle/JingleResponder.cpp
@@ -1,17 +1,16 @@
/*
- * Copyright (c) 2011-2014 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Jingle/JingleResponder.h>
-#include <boost/smart_ptr/make_shared.hpp>
-
-#include <Swiften/Jingle/JingleSessionManager.h>
-#include <Swiften/Jingle/JingleSessionImpl.h>
+#include <memory>
#include <Swiften/Base/Log.h>
+#include <Swiften/Jingle/JingleSessionImpl.h>
+#include <Swiften/Jingle/JingleSessionManager.h>
namespace Swift {
@@ -21,42 +20,42 @@ JingleResponder::JingleResponder(JingleSessionManager* sessionManager, IQRouter*
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;
+bool JingleResponder::handleSetRequest(const JID& from, const JID& to, const std::string& id, std::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, std::shared_ptr<JinglePayload>());
+ if (!payload->getInitiator().isBare()) {
+ JingleSessionImpl::ref session = std::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, std::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 cf01e6f..cb9220c 100644
--- a/Swiften/Jingle/JingleResponder.h
+++ b/Swiften/Jingle/JingleResponder.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,22 +7,22 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/SetResponder.h>
#include <Swiften/Elements/JinglePayload.h>
+#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, std::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 bb3ce10..b5cfbef 100644
--- a/Swiften/Jingle/JingleSession.cpp
+++ b/Swiften/Jingle/JingleSession.cpp
@@ -1,23 +1,23 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Jingle/JingleSession.h>
-#include <boost/smart_ptr/make_shared.hpp>
#include <algorithm>
-#include <boost/function.hpp>
+#include <cassert>
+#include <memory>
-#include <Swiften/Base/foreach.h>
+#include <boost/function.hpp>
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 7d7d45e..22e6901 100644
--- a/Swiften/Jingle/JingleSession.h
+++ b/Swiften/Jingle/JingleSession.h
@@ -1,53 +1,54 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
#include <vector>
-#include <boost/shared_ptr.hpp>
+
#include <boost/optional.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/Listenable.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/JinglePayload.h>
+#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 std::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(std::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 a5273d6..06aa039 100644
--- a/Swiften/Jingle/JingleSessionImpl.cpp
+++ b/Swiften/Jingle/JingleSessionImpl.cpp
@@ -1,208 +1,207 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Jingle/JingleSessionImpl.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <boost/bind.hpp>
#include <algorithm>
+#include <memory>
-#include <Swiften/Parser/PayloadParsers/JingleParser.h>
+#include <boost/bind.hpp>
+
+#include <Swiften/Base/Log.h>
+#include <Swiften/Elements/JingleContentPayload.h>
#include <Swiften/Jingle/JingleContentID.h>
#include <Swiften/Jingle/JingleSessionListener.h>
-#include <Swiften/Elements/JingleContentPayload.h>
-#include <Swiften/Queries/Request.h>
+#include <Swiften/Parser/PayloadParsers/JingleParser.h>
#include <Swiften/Queries/GenericRequest.h>
-
-#include <Swiften/Base/Log.h>
-
+#include <Swiften/Queries/Request.h>
#include <Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h>
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 = std::make_shared<JinglePayload>(JinglePayload::SessionInitiate, getID());
+ payload->setInitiator(getInitiator());
+ JingleContentPayload::ref content = std::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 = std::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);
+void JingleSessionImpl::sendInfo(std::shared_ptr<Payload> info) {
+ JinglePayload::ref payload = std::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 = std::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 = std::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 = std::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 = std::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 = std::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();
+ std::shared_ptr<GenericRequest<JinglePayload> > request = std::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 = std::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 4c455a5..b42b790 100644
--- a/Swiften/Jingle/JingleSessionImpl.h
+++ b/Swiften/Jingle/JingleSessionImpl.h
@@ -1,50 +1,50 @@
/*
- * Copyright (c) 2011-2013 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
#include <map>
+#include <memory>
#include <Swiften/Jingle/JingleSession.h>
#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 std::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(std::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 std::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::signals2::connection > RequestsMap;
+ RequestsMap pendingRequests;
+ };
}
diff --git a/Swiften/Jingle/JingleSessionListener.h b/Swiften/Jingle/JingleSessionListener.h
index dabeb05..7c015f0 100644
--- a/Swiften/Jingle/JingleSessionListener.h
+++ b/Swiften/Jingle/JingleSessionListener.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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&,
+ std::shared_ptr<JingleDescription>,
+ std::shared_ptr<JingleTransportPayload>) = 0;
+ virtual void handleSessionInfoReceived(std::shared_ptr<JinglePayload>) = 0;
+ virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) = 0;
+ virtual void handleTransportAcceptReceived(
+ const JingleContentID&,
+ std::shared_ptr<JingleTransportPayload>) = 0;
+ virtual void handleTransportInfoReceived(
+ const JingleContentID&,
+ std::shared_ptr<JingleTransportPayload>) = 0;
+ virtual void handleTransportRejectReceived(
+ const JingleContentID&, std::shared_ptr<JingleTransportPayload>) = 0;
+ virtual void handleTransportReplaceReceived(
+ const JingleContentID&, std::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 2a94413..f7ed58e 100644
--- a/Swiften/Jingle/JingleSessionManager.cpp
+++ b/Swiften/Jingle/JingleSessionManager.cpp
@@ -1,54 +1,54 @@
/*
- * Copyright (c) 2011-2013 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Jingle/JingleSessionManager.h>
-#include <Swiften/Jingle/JingleResponder.h>
-#include <Swiften/Jingle/IncomingJingleSessionHandler.h>
-#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
+
#include <Swiften/Base/Algorithm.h>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Jingle/IncomingJingleSessionHandler.h>
+#include <Swiften/Jingle/JingleResponder.h>
namespace Swift {
JingleSessionManager::JingleSessionManager(IQRouter* router) : router(router) {
- responder = new JingleResponder(this, router);
- responder->start();
+ 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));
+ for (auto 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 ad47f84..f67a0fe 100644
--- a/Swiften/Jingle/JingleSessionManager.h
+++ b/Swiften/Jingle/JingleSessionManager.h
@@ -1,51 +1,52 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
#include <map>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#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/Jingle/SConscript b/Swiften/Jingle/SConscript
index 546c1b2..4d25a78 100644
--- a/Swiften/Jingle/SConscript
+++ b/Swiften/Jingle/SConscript
@@ -1,14 +1,14 @@
Import("swiften_env")
sources = [
- "JingleSession.cpp",
- "JingleSessionListener.cpp",
- "AbstractJingleSessionListener.cpp",
- "JingleSessionImpl.cpp",
- "IncomingJingleSessionHandler.cpp",
- "JingleSessionManager.cpp",
- "JingleResponder.cpp",
- "FakeJingleSession.cpp",
- ]
+ "JingleSession.cpp",
+ "JingleSessionListener.cpp",
+ "AbstractJingleSessionListener.cpp",
+ "JingleSessionImpl.cpp",
+ "IncomingJingleSessionHandler.cpp",
+ "JingleSessionManager.cpp",
+ "JingleResponder.cpp",
+ "FakeJingleSession.cpp",
+ ]
swiften_env.Append(SWIFTEN_OBJECTS = swiften_env.SwiftenObject(sources))
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.cpp
index 1b162ce..a1bdb3e 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.cpp
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.cpp
@@ -1,60 +1,61 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h>
-#include <boost/bind.hpp>
#include <iostream>
+#include <boost/bind.hpp>
+
#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h>
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 efa31ac..a227613 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,30 +8,30 @@
#include <avahi-client/lookup.h>
+#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h>
-#include <Swiften/EventLoop/EventLoop.h>
namespace Swift {
- class AvahiQuerier;
+ class AvahiQuerier;
+
+ class AvahiBrowseQuery : public DNSSDBrowseQuery, public AvahiQuery {
+ public:
+ AvahiBrowseQuery(std::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 1e2e08f..1b79946 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,9 +9,9 @@
#include <iostream>
#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h>
-#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h>
-#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h>
#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h>
+#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h>
+#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h>
namespace Swift {
@@ -21,46 +21,46 @@ AvahiQuerier::AvahiQuerier(EventLoop* eventLoop) : eventLoop(eventLoop), client(
AvahiQuerier::~AvahiQuerier() {
}
-boost::shared_ptr<DNSSDBrowseQuery> AvahiQuerier::createBrowseQuery() {
- return boost::shared_ptr<DNSSDBrowseQuery>(new AvahiBrowseQuery(shared_from_this(), eventLoop));
+std::shared_ptr<DNSSDBrowseQuery> AvahiQuerier::createBrowseQuery() {
+ return std::make_shared<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));
+std::shared_ptr<DNSSDRegisterQuery> AvahiQuerier::createRegisterQuery(const std::string& name, int port, const ByteArray& info) {
+ return std::make_shared<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));
+std::shared_ptr<DNSSDResolveServiceQuery> AvahiQuerier::createResolveServiceQuery(const DNSSDServiceID& service) {
+ return std::make_shared<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));
+std::shared_ptr<DNSSDResolveHostnameQuery> AvahiQuerier::createResolveHostnameQuery(const std::string& hostname, int interfaceIndex) {
+ return std::make_shared<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 2109be4..5dce19d 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h
@@ -1,55 +1,55 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/enable_shared_from_this.hpp>
+#include <memory>
+
#include <avahi-client/client.h>
#include <avahi-client/lookup.h>
+#include <avahi-common/error.h>
+#include <avahi-common/malloc.h>
#include <avahi-common/thread-watch.h>
#include <avahi-common/watch.h>
-#include <avahi-common/malloc.h>
-#include <avahi-common/error.h>
-#include <Swiften/LinkLocal/DNSSD/DNSSDQuerier.h>
#include <Swiften/Base/ByteArray.h>
+#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 std::enable_shared_from_this<AvahiQuerier> {
+ public:
+ AvahiQuerier(EventLoop* eventLoop);
+ ~AvahiQuerier();
+
+ std::shared_ptr<DNSSDBrowseQuery> createBrowseQuery();
+ std::shared_ptr<DNSSDRegisterQuery> createRegisterQuery(
+ const std::string& name, int port, const ByteArray& info);
+ std::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery(
+ const DNSSDServiceID&);
+ std::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.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.cpp
index bfd7822..08997f6 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.cpp
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.cpp
@@ -1,15 +1,16 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h>
+
#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h>
namespace Swift {
-AvahiQuery::AvahiQuery(boost::shared_ptr<AvahiQuerier> q, EventLoop* eventLoop) : querier(q), eventLoop(eventLoop) {
+AvahiQuery::AvahiQuery(std::shared_ptr<AvahiQuerier> q, EventLoop* eventLoop) : querier(q), eventLoop(eventLoop) {
}
AvahiQuery::~AvahiQuery() {
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h
index 35c02e4..1b98bbf 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h
@@ -1,30 +1,29 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/enable_shared_from_this.hpp>
+#include <memory>
#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 std::enable_shared_from_this<AvahiQuery> {
+ public:
+ AvahiQuery(std::shared_ptr<AvahiQuerier>, EventLoop* eventLoop);
+ virtual ~AvahiQuery();
+
+ protected:
+ std::shared_ptr<AvahiQuerier> querier;
+ EventLoop* eventLoop;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.cpp
index d163ec9..04790d5 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.cpp
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,6 +7,7 @@
#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h>
#include <iostream>
+
#include <boost/bind.hpp>
#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h>
@@ -14,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 6f2f221..68281d0 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,50 +8,50 @@
#include <avahi-client/publish.h>
-#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h>
-#include <Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/EventLoop/EventLoop.h>
+#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h>
+#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, std::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 bfd0067..08de722 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp
@@ -1,22 +1,25 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h>
-#include <iostream>
#include <boost/bind.hpp>
+#include <netinet/in.h>
+
+#include <Swiften/Base/Log.h>
+
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;
+AvahiResolveHostnameQuery::AvahiResolveHostnameQuery(const std::string& hostname, int, std::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop) : AvahiQuery(querier, eventLoop), hostname(hostname) {
+ SWIFT_LOG(debug) << "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), HostAddress::fromString(hostname)), shared_from_this());
}
}
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h
index a29c0a8..33c425f 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,27 +7,26 @@
#pragma once
#include <string>
+
+#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h>
-#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/Network/HostAddress.h>
-#include <netinet/in.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, std::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 d4ff0c8..a5e52b2 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.cpp
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.cpp
@@ -1,65 +1,66 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h>
-#include <boost/bind.hpp>
#include <iostream>
+#include <boost/bind.hpp>
+
#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h>
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 a370344..c05c73e 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveServiceQuery.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,32 +8,32 @@
#include <avahi-client/lookup.h>
+#include <Swiften/Base/ByteArray.h>
+#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h>
#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
-#include <Swiften/Base/ByteArray.h>
-#include <Swiften/EventLoop/EventLoop.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, std::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 69bbabb..c049ed2 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h
@@ -1,62 +1,63 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/numeric/conversion/cast.hpp>
+
+#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h>
-#include <Swiften/EventLoop/EventLoop.h>
-#include <boost/numeric/conversion/cast.hpp>
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(std::shared_ptr<BonjourQuerier> q, EventLoop* eventLoop) : BonjourQuery(q, eventLoop) {
+ DNSServiceErrorType result = DNSServiceBrowse(
+ &sdRef, 0, 0, "_presence._tcp", nullptr,
+ &BonjourBrowseQuery::handleServiceDiscoveredStatic, this);
+ if (result != kDNSServiceErr_NoError) {
+ sdRef = nullptr;
+ }
+ }
+
+ 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 ffce3a9..0906ffc 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp
@@ -1,136 +1,135 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h>
-#include <unistd.h>
-#include <sys/socket.h>
#include <fcntl.h>
+#include <sys/socket.h>
+#include <unistd.h>
+#include <Swiften/Base/Algorithm.h>
#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h>
#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h>
-#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h>
#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Base/Algorithm.h>
+#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h>
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];
+BonjourQuerier::BonjourQuerier(EventLoop* eventLoop) : eventLoop(eventLoop), stopRequested(false), thread(nullptr) {
+ int fds[2];
+ int result = pipe(fds);
+ assert(result == 0);
+ (void) result;
+ interruptSelectReadSocket = fds[0];
+ fcntl(interruptSelectReadSocket, F_SETFL, fcntl(interruptSelectReadSocket, F_GETFL)|O_NONBLOCK);
+ interruptSelectWriteSocket = fds[1];
}
BonjourQuerier::~BonjourQuerier() {
- assert(!thread);
+ assert(!thread);
}
-boost::shared_ptr<DNSSDBrowseQuery> BonjourQuerier::createBrowseQuery() {
- return boost::shared_ptr<DNSSDBrowseQuery>(new BonjourBrowseQuery(shared_from_this(), eventLoop));
+std::shared_ptr<DNSSDBrowseQuery> BonjourQuerier::createBrowseQuery() {
+ return std::make_shared<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));
+std::shared_ptr<DNSSDRegisterQuery> BonjourQuerier::createRegisterQuery(const std::string& name, int port, const ByteArray& info) {
+ return std::make_shared<BonjourRegisterQuery>(name, port, info, shared_from_this(), eventLoop);
}
-boost::shared_ptr<DNSSDResolveServiceQuery> BonjourQuerier::createResolveServiceQuery(const DNSSDServiceID& service) {
- return boost::shared_ptr<DNSSDResolveServiceQuery>(new BonjourResolveServiceQuery(service, shared_from_this(), eventLoop));
+std::shared_ptr<DNSSDResolveServiceQuery> BonjourQuerier::createResolveServiceQuery(const DNSSDServiceID& service) {
+ return std::make_shared<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));
+std::shared_ptr<DNSSDResolveHostnameQuery> BonjourQuerier::createResolveHostnameQuery(const std::string& hostname, int interfaceIndex) {
+ return std::make_shared<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();
+void BonjourQuerier::addRunningQuery(std::shared_ptr<BonjourQuery> query) {
+ {
+ std::lock_guard<std::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);
- }
+void BonjourQuerier::removeRunningQuery(std::shared_ptr<BonjourQuery> query) {
+ {
+ std::lock_guard<std::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 std::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 = nullptr;
+ 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;
+ {
+ std::unique_lock<std::mutex> lock(runningQueriesMutex);
+ if (runningQueries.empty()) {
+ runningQueriesAvailableEvent.wait(lock);
+ if (runningQueries.empty()) {
+ continue;
+ }
+ }
+
+ // Run all running queries
+ FD_ZERO(&fdSet);
+ maxSocket = interruptSelectReadSocket;
+ FD_SET(interruptSelectReadSocket, &fdSet);
+
+ for (const auto& query : runningQueries) {
+ int socketID = query->getSocketID();
+ maxSocket = std::max(maxSocket, socketID);
+ FD_SET(socketID, &fdSet);
+ }
+ }
+
+ if (select(maxSocket+1, &fdSet, nullptr, nullptr, nullptr) <= 0) {
+ continue;
+ }
+
+ if (FD_ISSET(interruptSelectReadSocket, &fdSet)) {
+ char dummy;
+ while (read(interruptSelectReadSocket, &dummy, 1) > 0) {}
+ }
+
+ {
+ std::lock_guard<std::mutex> lock(runningQueriesMutex);
+ for (auto&& 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 6d6ffd5..77326bc 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h
@@ -1,56 +1,55 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/enable_shared_from_this.hpp>
#include <list>
-#include <boost/thread/thread.hpp>
-#include <boost/thread/mutex.hpp>
+#include <memory>
+#include <mutex>
+#include <thread>
-#include <Swiften/LinkLocal/DNSSD/DNSSDQuerier.h>
-#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h>
#include <Swiften/Base/ByteArray.h>
+#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h>
+#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 std::enable_shared_from_this<BonjourQuerier> {
+ public:
+ BonjourQuerier(EventLoop* eventLoop);
+ ~BonjourQuerier();
+
+ std::shared_ptr<DNSSDBrowseQuery> createBrowseQuery();
+ std::shared_ptr<DNSSDRegisterQuery> createRegisterQuery(
+ const std::string& name, int port, const ByteArray& info);
+ std::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery(
+ const DNSSDServiceID&);
+ std::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery(
+ const std::string& hostname, int interfaceIndex);
+
+ void start();
+ void stop();
+
+ private:
+ friend class BonjourQuery;
+
+ void addRunningQuery(std::shared_ptr<BonjourQuery>);
+ void removeRunningQuery(std::shared_ptr<BonjourQuery>);
+ void interruptSelect();
+ void run();
+
+ private:
+ EventLoop* eventLoop;
+ bool stopRequested;
+ std::thread* thread;
+ std::mutex runningQueriesMutex;
+ std::list< std::shared_ptr<BonjourQuery> > runningQueries;
+ int interruptSelectReadSocket;
+ int interruptSelectWriteSocket;
+ std::condition_variable runningQueriesAvailableEvent;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.cpp b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.cpp
index 79f99b9..b4448c7 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.cpp
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.cpp
@@ -1,37 +1,38 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h>
+
#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h>
namespace Swift {
-BonjourQuery::BonjourQuery(boost::shared_ptr<BonjourQuerier> q, EventLoop* eventLoop) : eventLoop(eventLoop), querier(q), sdRef(0) {
+BonjourQuery::BonjourQuery(std::shared_ptr<BonjourQuerier> q, EventLoop* eventLoop) : eventLoop(eventLoop), querier(q), sdRef(nullptr) {
}
BonjourQuery::~BonjourQuery() {
- DNSServiceRefDeallocate(sdRef);
+ DNSServiceRefDeallocate(sdRef);
}
void BonjourQuery::processResult() {
- boost::lock_guard<boost::mutex> lock(sdRefMutex);
- DNSServiceProcessResult(sdRef);
+ std::lock_guard<std::mutex> lock(sdRefMutex);
+ DNSServiceProcessResult(sdRef);
}
int BonjourQuery::getSocketID() const {
- boost::lock_guard<boost::mutex> lock(sdRefMutex);
- return DNSServiceRefSockFD(sdRef);
+ std::lock_guard<std::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 3c606bf..d3cebe4 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h
@@ -1,40 +1,40 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+#include <mutex>
+
#include <dns_sd.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/enable_shared_from_this.hpp>
-#include <boost/thread/mutex.hpp>
#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 std::enable_shared_from_this<BonjourQuery> {
+ public:
+ BonjourQuery(std::shared_ptr<BonjourQuerier>, EventLoop* eventLoop);
+ virtual ~BonjourQuery();
+
+ void processResult();
+ int getSocketID() const;
+
+ protected:
+ void run();
+ void finish();
+
+ protected:
+ EventLoop* eventLoop;
+ std::shared_ptr<BonjourQuerier> querier;
+ mutable std::mutex sdRefMutex;
+ DNSServiceRef sdRef;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h
index b48fbf4..8b2e955 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h
@@ -1,13 +1,14 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <mutex>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <boost/thread.hpp>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/EventLoop/EventLoop.h>
@@ -15,50 +16,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, std::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) {
+ DNSServiceErrorType result = DNSServiceRegister(
+ &sdRef, 0, 0, name.c_str(), "_presence._tcp", nullptr, nullptr, boost::numeric_cast<unsigned short>(port),
+ boost::numeric_cast<unsigned short>(txtRecord.size()), vecptr(txtRecord),
+ &BonjourRegisterQuery::handleServiceRegisteredStatic, this);
+ if (result != kDNSServiceErr_NoError) {
+ sdRef = nullptr;
+ }
+ }
- 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) {
+ std::lock_guard<std::mutex> lock(sdRefMutex);
+ DNSServiceUpdateRecord(sdRef, nullptr, 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..dbf3f0e 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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, std::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 = nullptr;
+ }
+ }
- //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 32a00d8..7a5555e 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h
@@ -1,64 +1,66 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/numeric/conversion/cast.hpp>
+
+#include <Swiften/Base/ByteArray.h>
+#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h>
#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
-#include <Swiften/Base/ByteArray.h>
-#include <Swiften/EventLoop/EventLoop.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, std::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 = nullptr;
+ }
+ }
- 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 2f432de..f598be1 100644
--- a/Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h
+++ b/Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h
@@ -1,25 +1,25 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
#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::signals2::signal<void (const DNSSDServiceID&)> onServiceAdded;
+ boost::signals2::signal<void (const DNSSDServiceID&)> onServiceRemoved;
+ boost::signals2::signal<void ()> onError;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h b/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h
index 924b7c9..8f3c3ec 100644
--- a/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h
+++ b/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h
@@ -1,35 +1,35 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#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 std::shared_ptr<DNSSDBrowseQuery> createBrowseQuery() = 0;
+ virtual std::shared_ptr<DNSSDRegisterQuery> createRegisterQuery(
+ const std::string& name, int port, const ByteArray& info) = 0;
+ virtual std::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery(
+ const DNSSDServiceID&) = 0;
+ virtual std::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 f2d5951..6639a85 100644
--- a/Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h
+++ b/Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h
@@ -1,26 +1,26 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
#include <boost/optional.hpp>
+#include <boost/signals2.hpp>
-#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
#include <Swiften/Base/ByteArray.h>
+#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::signals2::signal<void (boost::optional<DNSSDServiceID>)> onRegisterFinished;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h b/Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h
index ced8f6b..f14c248 100644
--- a/Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h
+++ b/Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h
@@ -1,24 +1,24 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
#include <boost/optional.hpp>
+#include <boost/signals2.hpp>
#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::signals2::signal<void (const boost::optional<HostAddress>&)> onHostnameResolved;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h b/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h
index acf9650..b55447a 100644
--- a/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h
+++ b/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
#include <boost/optional.hpp>
+#include <boost/signals2.hpp>
-#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
#include <Swiften/Base/ByteArray.h>
+#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::signals2::signal<void (const boost::optional<Result>&)> onServiceResolved;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/DNSSDServiceID.h b/Swiften/LinkLocal/DNSSD/DNSSDServiceID.h
index 2807515..5f8c2eb 100644
--- a/Swiften/LinkLocal/DNSSD/DNSSDServiceID.h
+++ b/Swiften/LinkLocal/DNSSD/DNSSDServiceID.h
@@ -1,73 +1,74 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/API.h>
#include <string>
+#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 04cdc2c..15d8128 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDBrowseQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDBrowseQuery.h
@@ -1,28 +1,28 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h>
+#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(std::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 bec914b..c17f8b2 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp
@@ -1,21 +1,21 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h>
-#include <boost/bind.hpp>
#include <iostream>
-#include <Swiften/Base/foreach.h>
+#include <boost/bind.hpp>
+
#include <Swiften/Base/Algorithm.h>
+#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDBrowseQuery.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h>
-#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveHostnameQuery.h>
-#include <Swiften/EventLoop/EventLoop.h>
+#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h>
namespace Swift {
@@ -23,117 +23,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()));
+std::shared_ptr<DNSSDBrowseQuery> FakeDNSSDQuerier::createBrowseQuery() {
+ return std::make_shared<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()));
+std::shared_ptr<DNSSDRegisterQuery> FakeDNSSDQuerier::createRegisterQuery(const std::string& name, int port, const ByteArray& info) {
+ return std::make_shared<FakeDNSSDRegisterQuery>(name, port, info, shared_from_this());
}
-boost::shared_ptr<DNSSDResolveServiceQuery> FakeDNSSDQuerier::createResolveServiceQuery(const DNSSDServiceID& service) {
- return boost::shared_ptr<DNSSDResolveServiceQuery>(new FakeDNSSDResolveServiceQuery(service, shared_from_this()));
+std::shared_ptr<DNSSDResolveServiceQuery> FakeDNSSDQuerier::createResolveServiceQuery(const DNSSDServiceID& service) {
+ return std::make_shared<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()));
+std::shared_ptr<DNSSDResolveHostnameQuery> FakeDNSSDQuerier::createResolveHostnameQuery(const std::string& hostname, int interfaceIndex) {
+ return std::make_shared<FakeDNSSDResolveHostnameQuery>(hostname, interfaceIndex, shared_from_this());
}
-void FakeDNSSDQuerier::addRunningQuery(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());
- }
- }
+void FakeDNSSDQuerier::addRunningQuery(std::shared_ptr<FakeDNSSDQuery> query) {
+ runningQueries.push_back(query);
+ allQueriesEverRun.push_back(query);
+ if (std::shared_ptr<FakeDNSSDBrowseQuery> browseQuery = std::dynamic_pointer_cast<FakeDNSSDBrowseQuery>(query)) {
+ for (const auto& service : services) {
+ eventLoop->postEvent(boost::bind(boost::ref(browseQuery->onServiceAdded), service), shared_from_this());
+ }
+ }
+ else if (std::shared_ptr<FakeDNSSDResolveServiceQuery> resolveQuery = std::dynamic_pointer_cast<FakeDNSSDResolveServiceQuery>(query)) {
+ for (const auto& i : serviceInfo) {
+ if (i.first == resolveQuery->service) {
+ eventLoop->postEvent(boost::bind(boost::ref(resolveQuery->onServiceResolved), i.second), shared_from_this());
+ }
+ }
+ }
+ else if (std::shared_ptr<FakeDNSSDRegisterQuery> registerQuery = std::dynamic_pointer_cast<FakeDNSSDRegisterQuery>(query)) {
+ DNSSDServiceID service(registerQuery->name, domain);
+ eventLoop->postEvent(boost::bind(boost::ref(registerQuery->onRegisterFinished), service), shared_from_this());
+ }
+ else if (std::shared_ptr<FakeDNSSDResolveHostnameQuery> resolveHostnameQuery = std::dynamic_pointer_cast<FakeDNSSDResolveHostnameQuery>(query)) {
+ std::map<std::string,boost::optional<HostAddress> >::const_iterator i = addresses.find(resolveHostnameQuery->hostname);
+ if (i != addresses.end()) {
+ eventLoop->postEvent(
+ boost::bind(
+ boost::ref(resolveHostnameQuery->onHostnameResolved), i->second),
+ shared_from_this());
+ }
+ }
}
-void FakeDNSSDQuerier::removeRunningQuery(boost::shared_ptr<FakeDNSSDQuery> query) {
- erase(runningQueries, query);
+void FakeDNSSDQuerier::removeRunningQuery(std::shared_ptr<FakeDNSSDQuery> 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);
+ for (const auto& query : getQueries<FakeDNSSDBrowseQuery>()) {
+ eventLoop->postEvent(boost::bind(boost::ref(query->onServiceAdded), id), shared_from_this());
+ }
}
void FakeDNSSDQuerier::removeService(const DNSSDServiceID& id) {
- services.erase(id);
- serviceInfo.erase(id);
- foreach(const 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);
+ for (const auto& query : getQueries<FakeDNSSDBrowseQuery>()) {
+ eventLoop->postEvent(boost::bind(boost::ref(query->onServiceRemoved), id), shared_from_this());
+ }
}
void FakeDNSSDQuerier::setServiceInfo(const DNSSDServiceID& id, const DNSSDResolveServiceQuery::Result& info) {
- std::pair<ServiceInfoMap::iterator, bool> r = serviceInfo.insert(std::make_pair(id, info));
- if (!r.second) {
- r.first->second = info;
- }
- foreach(const 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;
+ }
+ for (const auto& query : getQueries<FakeDNSSDResolveServiceQuery>()) {
+ if (query->service == id) {
+ eventLoop->postEvent(boost::bind(boost::ref(query->onServiceResolved), info), shared_from_this());
+ }
+ }
}
bool FakeDNSSDQuerier::isServiceRegistered(const std::string& name, int port, const ByteArray& info) {
- foreach(const boost::shared_ptr<FakeDNSSDRegisterQuery>& query, getQueries<FakeDNSSDRegisterQuery>()) {
- if (query->name == name && query->port == port && query->info == info) {
- return true;
- }
- }
- return false;
+ for (const auto& query : getQueries<FakeDNSSDRegisterQuery>()) {
+ if (query->name == name && query->port == port && query->info == info) {
+ return true;
+ }
+ }
+ return false;
}
void FakeDNSSDQuerier::setBrowseError() {
- foreach(const boost::shared_ptr<FakeDNSSDBrowseQuery>& query, getQueries<FakeDNSSDBrowseQuery>()) {
- eventLoop->postEvent(boost::ref(query->onError), shared_from_this());
- }
+ for (const auto& 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());
- }
+ for (const auto& query : getQueries<FakeDNSSDRegisterQuery>()) {
+ eventLoop->postEvent(boost::bind(boost::ref(query->onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this());
+ }
}
void FakeDNSSDQuerier::setAddress(const std::string& hostname, boost::optional<HostAddress> address) {
- addresses[hostname] = address;
- foreach(const 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;
+ for (const auto& query : getQueries<FakeDNSSDResolveHostnameQuery>()) {
+ if (query->hostname == hostname) {
+ eventLoop->postEvent(boost::bind(
+ boost::ref(query->onHostnameResolved), address), shared_from_this());
+ }
+ }
}
}
diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h
index fc635d9..633ca6d 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h
@@ -1,17 +1,16 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/enable_shared_from_this.hpp>
#include <list>
+#include <memory>
#include <set>
-
#include <string>
+
#include <Swiften/Base/API.h>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/EventLoop/EventOwner.h>
@@ -20,78 +19,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 std::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);
+ std::shared_ptr<DNSSDBrowseQuery> createBrowseQuery();
+ std::shared_ptr<DNSSDRegisterQuery> createRegisterQuery(
+ const std::string& name, int port, const ByteArray& info);
+ std::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery(
+ const DNSSDServiceID&);
+ std::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery(
+ const std::string& hostname, int interfaceIndex);
- void addRunningQuery(boost::shared_ptr<FakeDNSSDQuery>);
- void removeRunningQuery(boost::shared_ptr<FakeDNSSDQuery>);
+ void addRunningQuery(std::shared_ptr<FakeDNSSDQuery>);
+ void removeRunningQuery(std::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< std::shared_ptr<T> > getAllQueriesEverRun() const {
+ std::vector< std::shared_ptr<T> > result;
+ for (const auto& i : allQueriesEverRun) {
+ if (std::shared_ptr<T> resultQuery = std::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< std::shared_ptr<T> > getQueries() const {
+ std::vector< std::shared_ptr<T> > result;
+ for (const auto& runningQuerie : runningQueries) {
+ if (std::shared_ptr<T> resultQuery = std::dynamic_pointer_cast<T>(runningQuerie)) {
+ 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< std::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 550747f..0e05968 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.cpp
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.cpp
@@ -1,26 +1,27 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h>
+
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h>
namespace Swift {
-FakeDNSSDQuery::FakeDNSSDQuery(boost::shared_ptr<FakeDNSSDQuerier> querier) : querier(querier) {
+FakeDNSSDQuery::FakeDNSSDQuery(std::shared_ptr<FakeDNSSDQuerier> querier) : querier(querier) {
}
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 34beb93..5d869d4 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h
@@ -1,31 +1,30 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/enable_shared_from_this.hpp>
+#include <memory>
#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 std::enable_shared_from_this<FakeDNSSDQuery> {
+ public:
+ FakeDNSSDQuery(std::shared_ptr<FakeDNSSDQuerier>);
+ virtual ~FakeDNSSDQuery();
+
+ protected:
+ void run();
+ void finish();
+
+ protected:
+ std::shared_ptr<FakeDNSSDQuerier> querier;
+ };
}
diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h
index 527ea74..7478841 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h
@@ -1,38 +1,39 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h>
-#include <Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h>
-#include <Swiften/Base/ByteArray.h>
#include <string>
+#include <Swiften/Base/ByteArray.h>
+#include <Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h>
+#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, std::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 db29ad4..60dc144 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveHostnameQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveHostnameQuery.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,27 +7,28 @@
#pragma once
#include <string>
-#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h>
+
#include <Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h>
+#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h>
#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, std::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 3ce00ea..8a02e7b 100644
--- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h
@@ -1,31 +1,31 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h>
+#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h>
#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, std::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..e20326b 100644
--- a/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.cpp
+++ b/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -18,22 +18,22 @@ namespace Swift {
PlatformDNSSDQuerierFactory::PlatformDNSSDQuerierFactory(EventLoop* eventLoop) : eventLoop(eventLoop) {
}
-boost::shared_ptr<DNSSDQuerier> PlatformDNSSDQuerierFactory::createQuerier() {
+std::shared_ptr<DNSSDQuerier> PlatformDNSSDQuerierFactory::createQuerier() {
#if defined(HAVE_BONJOUR)
- return boost::shared_ptr<DNSSDQuerier>(new BonjourQuerier(eventLoop));
+ return std::make_shared<BonjourQuerier>(eventLoop);
#elif defined(HAVE_AVAHI)
- return boost::shared_ptr<DNSSDQuerier>(new AvahiQuerier(eventLoop));
+ return std::make_shared<AvahiQuerier>(eventLoop);
#else
- (void)eventLoop;
- return boost::shared_ptr<DNSSDQuerier>();
+ (void)eventLoop;
+ return std::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..68e10cf 100644
--- a/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h
+++ b/Swiften/LinkLocal/DNSSD/PlatformDNSSDQuerierFactory.h
@@ -1,28 +1,28 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#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();
+ std::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 deba4a9..9d446a9 100644
--- a/Swiften/LinkLocal/IncomingLinkLocalSession.cpp
+++ b/Swiften/LinkLocal/IncomingLinkLocalSession.cpp
@@ -1,68 +1,69 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/LinkLocal/IncomingLinkLocalSession.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/ProtocolHeader.h>
+#include <Swiften/Elements/StreamFeatures.h>
#include <Swiften/Network/Connection.h>
-#include <Swiften/StreamStack/StreamStack.h>
#include <Swiften/StreamStack/ConnectionLayer.h>
+#include <Swiften/StreamStack/StreamStack.h>
#include <Swiften/StreamStack/XMPPLayer.h>
-#include <Swiften/Elements/StreamFeatures.h>
-#include <Swiften/Elements/IQ.h>
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,
+ std::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(std::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);
+void IncomingLinkLocalSession::handleElement(std::shared_ptr<ToplevelElement> element) {
+ std::shared_ptr<Stanza> stanza = std::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 f1aa321..9760bb7 100644
--- a/Swiften/LinkLocal/IncomingLinkLocalSession.h
+++ b/Swiften/LinkLocal/IncomingLinkLocalSession.h
@@ -1,45 +1,46 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/boost_bsignals.h>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Session/Session.h>
#include <Swiften/JID/JID.h>
#include <Swiften/Network/Connection.h>
+#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,
+ std::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory);
+
+ boost::signals2::signal<void ()> onSessionStarted;
+
+ private:
+ void handleElement(std::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 d89523b..d961030 100644
--- a/Swiften/LinkLocal/LinkLocalConnector.cpp
+++ b/Swiften/LinkLocal/LinkLocalConnector.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,71 +8,71 @@
#include <boost/bind.hpp>
+#include <Swiften/LinkLocal/DNSSD/DNSSDQuerier.h>
+#include <Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h>
#include <Swiften/Network/Connection.h>
#include <Swiften/Network/ConnectionFactory.h>
#include <Swiften/Network/HostAddress.h>
#include <Swiften/Network/HostAddressPort.h>
-#include <Swiften/LinkLocal/DNSSD/DNSSDQuerier.h>
-#include <Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h>
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,
+ std::shared_ptr<DNSSDQuerier> querier,
+ std::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,
+ std::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);
+void LinkLocalConnector::queueElement(std::shared_ptr<ToplevelElement> element) {
+ queuedElements.push_back(element);
}
diff --git a/Swiften/LinkLocal/LinkLocalConnector.h b/Swiften/LinkLocal/LinkLocalConnector.h
index e6ddc92..2c49185 100644
--- a/Swiften/LinkLocal/LinkLocalConnector.h
+++ b/Swiften/LinkLocal/LinkLocalConnector.h
@@ -1,66 +1,66 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/enable_shared_from_this.hpp>
+#include <memory>
#include <vector>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Network/Connection.h>
#include <Swiften/LinkLocal/LinkLocalService.h>
+#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 std::enable_shared_from_this<LinkLocalConnector> {
+ public:
+ LinkLocalConnector(
+ const LinkLocalService& service,
+ std::shared_ptr<DNSSDQuerier> querier,
+ std::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(std::shared_ptr<ToplevelElement> element);
- const std::vector<boost::shared_ptr<ToplevelElement> >& getQueuedElements() const {
- return queuedElements;
- }
+ const std::vector<std::shared_ptr<ToplevelElement> >& getQueuedElements() const {
+ return queuedElements;
+ }
- boost::shared_ptr<Connection> getConnection() const {
- return connection;
- }
+ std::shared_ptr<Connection> getConnection() const {
+ return connection;
+ }
- boost::signal<void (bool)> onConnectFinished;
+ boost::signals2::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;
+ std::shared_ptr<DNSSDQuerier> querier;
+ std::shared_ptr<DNSSDResolveHostnameQuery> resolveQuery;
+ boost::signals2::connection resolveQueryHostNameResolvedConnection;
+ std::shared_ptr<Connection> connection;
+ boost::signals2::connection connectionConnectFinishedConnection;
+ std::vector<std::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 07132b3..9b0e2ab 100644
--- a/Swiften/LinkLocal/LinkLocalService.h
+++ b/Swiften/LinkLocal/LinkLocalService.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,47 +7,48 @@
#pragma once
#include <string>
+
#include <Swiften/Base/API.h>
#include <Swiften/JID/JID.h>
-#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h>
+#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
#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 3e4ea75..b79f184 100644
--- a/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp
+++ b/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp
@@ -1,155 +1,157 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/bind.hpp>
+#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
+
#include <iostream>
-#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
+#include <boost/bind.hpp>
+
#include <Swiften/LinkLocal/DNSSD/DNSSDBrowseQuery.h>
#include <Swiften/Network/HostAddress.h>
namespace Swift {
-LinkLocalServiceBrowser::LinkLocalServiceBrowser(boost::shared_ptr<DNSSDQuerier> querier) : querier(querier), haveError(false) {
+LinkLocalServiceBrowser::LinkLocalServiceBrowser(std::shared_ptr<DNSSDQuerier> querier) : querier(querier), haveError(false) {
}
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 (const auto& service : services) {
+ result.push_back(LinkLocalService(service.first, service.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, std::shared_ptr<DNSSDResolveServiceQuery>()));
+ if (r.second) {
+ // There was no existing query yet. Start a new query.
+ std::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 6ac1283..c59a4d0 100644
--- a/Swiften/LinkLocal/LinkLocalServiceBrowser.h
+++ b/Swiften/LinkLocal/LinkLocalServiceBrowser.h
@@ -1,75 +1,76 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/optional.hpp>
#include <map>
+#include <memory>
+#include <string>
#include <vector>
-#include <string>
+#include <boost/optional.hpp>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDQuerier.h>
-#include <Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h>
+#include <Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
#include <Swiften/LinkLocal/LinkLocalService.h>
#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(std::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
+ std::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::signals2::signal<void (const LinkLocalService&)> onServiceAdded;
+ boost::signals2::signal<void (const LinkLocalService&)> onServiceChanged;
+ boost::signals2::signal<void (const LinkLocalService&)> onServiceRemoved;
+ boost::signals2::signal<void (const DNSSDServiceID&)> onServiceRegistered;
+ boost::signals2::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:
+ std::shared_ptr<DNSSDQuerier> querier;
+ boost::optional<DNSSDServiceID> selfService;
+ std::shared_ptr<DNSSDBrowseQuery> browseQuery;
+ std::shared_ptr<DNSSDRegisterQuery> registerQuery;
+ typedef std::map<DNSSDServiceID, std::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 6112824..9f15c6e 100644
--- a/Swiften/LinkLocal/LinkLocalServiceInfo.h
+++ b/Swiften/LinkLocal/LinkLocalServiceInfo.h
@@ -1,66 +1,67 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <boost/optional.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/ByteArray.h>
-#include <string>
#include <Swiften/JID/JID.h>
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 180111f..a639ec5 100644
--- a/Swiften/LinkLocal/OutgoingLinkLocalSession.cpp
+++ b/Swiften/LinkLocal/OutgoingLinkLocalSession.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,45 +8,44 @@
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/StreamStack/XMPPLayer.h>
+#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/ProtocolHeader.h>
#include <Swiften/Elements/StreamFeatures.h>
-#include <Swiften/Elements/IQ.h>
+#include <Swiften/StreamStack/XMPPLayer.h>
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,
+ std::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory) :
+ Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory) {
+ setLocalJID(localJID);
+ setRemoteJID(remoteJID);
}
void OutgoingLinkLocalSession::handleSessionStarted() {
- ProtocolHeader header;
- header.setFrom(getLocalJID());
- getXMPPLayer()->writeHeader(header);
+ 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();
+ for (const auto& stanza : queuedElements_) {
+ sendElement(stanza);
+ }
+ queuedElements_.clear();
}
-void OutgoingLinkLocalSession::handleElement(boost::shared_ptr<ToplevelElement> element) {
- onElementReceived(element);
+void OutgoingLinkLocalSession::handleElement(std::shared_ptr<ToplevelElement> element) {
+ onElementReceived(element);
}
-void OutgoingLinkLocalSession::queueElement(boost::shared_ptr<ToplevelElement> element) {
- queuedElements_.push_back(element);
+void OutgoingLinkLocalSession::queueElement(std::shared_ptr<ToplevelElement> element) {
+ queuedElements_.push_back(element);
}
diff --git a/Swiften/LinkLocal/OutgoingLinkLocalSession.h b/Swiften/LinkLocal/OutgoingLinkLocalSession.h
index b3e7b39..34f7af9 100644
--- a/Swiften/LinkLocal/OutgoingLinkLocalSession.h
+++ b/Swiften/LinkLocal/OutgoingLinkLocalSession.h
@@ -1,45 +1,45 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/enable_shared_from_this.hpp>
+#include <memory>
#include <vector>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Session/Session.h>
#include <Swiften/JID/JID.h>
+#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,
+ std::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory);
+
+ void queueElement(std::shared_ptr<ToplevelElement> element);
+
+ private:
+ void handleSessionStarted();
+ void handleElement(std::shared_ptr<ToplevelElement>);
+ void handleStreamStart(const ProtocolHeader&);
+
+ private:
+ std::vector<std::shared_ptr<ToplevelElement> > queuedElements_;
+ };
}
diff --git a/Swiften/LinkLocal/SConscript b/Swiften/LinkLocal/SConscript
index 29ea692..697037a 100644
--- a/Swiften/LinkLocal/SConscript
+++ b/Swiften/LinkLocal/SConscript
@@ -4,39 +4,39 @@ myenv = swiften_env.Clone()
myenv.MergeFlags(swiften_env.get("BONJOUR_FLAGS", ""))
sources = [
- "DNSSD/DNSSDBrowseQuery.cpp",
- "DNSSD/DNSSDQuerier.cpp",
- "DNSSD/DNSSDRegisterQuery.cpp",
- "DNSSD/DNSSDResolveHostnameQuery.cpp",
- "DNSSD/DNSSDResolveServiceQuery.cpp",
- "DNSSD/DNSSDServiceID.cpp",
- "DNSSD/Fake/FakeDNSSDQuerier.cpp",
- "DNSSD/Fake/FakeDNSSDQuery.cpp",
- "DNSSD/PlatformDNSSDQuerierFactory.cpp",
- "IncomingLinkLocalSession.cpp",
- "LinkLocalConnector.cpp",
- "LinkLocalService.cpp",
- "LinkLocalServiceBrowser.cpp",
- "LinkLocalServiceInfo.cpp",
- "OutgoingLinkLocalSession.cpp",
- ]
+ "DNSSD/DNSSDBrowseQuery.cpp",
+ "DNSSD/DNSSDQuerier.cpp",
+ "DNSSD/DNSSDRegisterQuery.cpp",
+ "DNSSD/DNSSDResolveHostnameQuery.cpp",
+ "DNSSD/DNSSDResolveServiceQuery.cpp",
+ "DNSSD/DNSSDServiceID.cpp",
+ "DNSSD/Fake/FakeDNSSDQuerier.cpp",
+ "DNSSD/Fake/FakeDNSSDQuery.cpp",
+ "DNSSD/PlatformDNSSDQuerierFactory.cpp",
+ "IncomingLinkLocalSession.cpp",
+ "LinkLocalConnector.cpp",
+ "LinkLocalService.cpp",
+ "LinkLocalServiceBrowser.cpp",
+ "LinkLocalServiceInfo.cpp",
+ "OutgoingLinkLocalSession.cpp",
+ ]
if myenv.get("HAVE_BONJOUR", 0) :
- myenv.Append(CPPDEFINES = "HAVE_BONJOUR")
- sources += [
- "DNSSD/Bonjour/BonjourQuerier.cpp",
- "DNSSD/Bonjour/BonjourQuery.cpp",
- ]
+ myenv.Append(CPPDEFINES = "HAVE_BONJOUR")
+ sources += [
+ "DNSSD/Bonjour/BonjourQuerier.cpp",
+ "DNSSD/Bonjour/BonjourQuery.cpp",
+ ]
elif myenv.get("HAVE_AVAHI", 0) :
- myenv.Append(CPPDEFINES = ["HAVE_AVAHI"])
- sources += [
- "DNSSD/Avahi/AvahiQuerier.cpp",
- "DNSSD/Avahi/AvahiQuery.cpp",
- "DNSSD/Avahi/AvahiResolveHostnameQuery.cpp",
- "DNSSD/Avahi/AvahiResolveServiceQuery.cpp",
- "DNSSD/Avahi/AvahiRegisterQuery.cpp",
- "DNSSD/Avahi/AvahiBrowseQuery.cpp",
- ]
+ myenv.Append(CPPDEFINES = ["HAVE_AVAHI"])
+ sources += [
+ "DNSSD/Avahi/AvahiQuerier.cpp",
+ "DNSSD/Avahi/AvahiQuery.cpp",
+ "DNSSD/Avahi/AvahiResolveHostnameQuery.cpp",
+ "DNSSD/Avahi/AvahiResolveServiceQuery.cpp",
+ "DNSSD/Avahi/AvahiRegisterQuery.cpp",
+ "DNSSD/Avahi/AvahiBrowseQuery.cpp",
+ ]
objects = myenv.SwiftenObject(sources)
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp
index a5417bf..85ae537 100644
--- a/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp
+++ b/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp
@@ -1,143 +1,143 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/bind.hpp>
-
-#include <Swiften/LinkLocal/LinkLocalConnector.h>
-#include <Swiften/LinkLocal/LinkLocalService.h>
-#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
+#include <Swiften/EventLoop/DummyEventLoop.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h>
+#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h>
-#include <Swiften/EventLoop/DummyEventLoop.h>
+#include <Swiften/LinkLocal/LinkLocalConnector.h>
+#include <Swiften/LinkLocal/LinkLocalService.h>
#include <Swiften/Network/FakeConnection.h>
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 = std::make_shared<FakeDNSSDQuerier>("rabbithole.local", eventLoop);
+ connection = std::make_shared<FakeConnection>(eventLoop);
+ connectFinished = false;
+ }
+
+ void tearDown() {
+ querier->clearAllQueriesEverRun();
+ delete eventLoop;
+ }
+
+ void testConnect() {
+ std::shared_ptr<LinkLocalConnector>
+ testling(createConnector("rabbithole.local", 1234));
+ querier->setAddress("rabbithole.local", HostAddress::fromString("192.168.1.1").get());
+
+ 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() {
+ std::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() {
+ std::shared_ptr<LinkLocalConnector>
+ testling(createConnector("rabbithole.local", 1234));
+ querier->setAddress("rabbithole.local", HostAddress::fromString("192.168.1.1").get());
+ connection->setError(Connection::ReadError);
+
+ testling->connect();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(connectFinished);
+ CPPUNIT_ASSERT(connectError);
+ CPPUNIT_ASSERT(!connection->connectedTo);
+ }
+
+ void testCancel_DuringResolve() {
+ std::shared_ptr<LinkLocalConnector>
+ testling(createConnector("rabbithole.local", 1234));
+ testling->connect();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT(!connectFinished);
+
+ testling->cancel();
+ eventLoop->processEvents();
+ querier->setAddress("rabbithole.local", HostAddress::fromString("192.168.1.1").get());
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(FakeConnection::Disconnected == connection->state);
+ }
+
+ void testCancel_DuringConnect() {
+ std::shared_ptr<LinkLocalConnector>
+ testling(createConnector("rabbithole.local", 1234));
+ querier->setAddress("rabbithole.local", HostAddress::fromString("192.168.1.1").get());
+ connection->setDelayConnect();
+ testling->connect();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT(FakeConnection::Connecting == connection->state);
+
+ testling->cancel();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT(FakeConnection::Disconnected == connection->state);
+ }
+
+ private:
+ std::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()));
+ std::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;
+ std::shared_ptr<FakeDNSSDQuerier> querier;
+ std::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 53b0a3d..a80d748 100644
--- a/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp
+++ b/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp
@@ -1,412 +1,414 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <map>
+#include <memory>
+
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <map>
-#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
-#include <Swiften/LinkLocal/LinkLocalService.h>
-#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
+#include <Swiften/EventLoop/DummyEventLoop.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h>
+#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h>
-#include <Swiften/EventLoop/DummyEventLoop.h>
+#include <Swiften/LinkLocal/LinkLocalService.h>
+#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
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 = std::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() {
+ std::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+
+ CPPUNIT_ASSERT(!testling->isRunning());
+ CPPUNIT_ASSERT(!testling->hasError());
+ }
+
+ void testStart() {
+ std::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
+ testling->start();
+
+ CPPUNIT_ASSERT(testling->isRunning());
+ CPPUNIT_ASSERT(!testling->hasError());
+
+ testling->stop();
+ }
+
+ void testServiceAdded() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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:
+ std::shared_ptr<LinkLocalServiceBrowser> createTestling() {
+ std::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;
+ std::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 e59a5a9..0a94a98 100644
--- a/Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp
+++ b/Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp
@@ -1,72 +1,72 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/ByteArray.h>
#include <QA/Checker/IO.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
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 361dd7b..cfb38f6 100644
--- a/Swiften/MUC/MUC.h
+++ b/Swiften/MUC/MUC.h
@@ -1,100 +1,100 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/JID/JID.h>
-#include <Swiften/Base/API.h>
+#include <map>
+#include <memory>
#include <string>
+
+#include <boost/signals2.hpp>
+#include <boost/signals2/connection.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Elements/Form.h>
+#include <Swiften/Elements/MUCAdminPayload.h>
+#include <Swiften/Elements/MUCOccupant.h>
+#include <Swiften/Elements/MUCOwnerPayload.h>
#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Presence.h>
-#include <Swiften/Elements/MUCOccupant.h>
+#include <Swiften/JID/JID.h>
#include <Swiften/MUC/MUCRegistry.h>
-#include <Swiften/Elements/MUCOwnerPayload.h>
-#include <Swiften/Elements/MUCAdminPayload.h>
-#include <Swiften/Elements/Form.h>
-
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/signals/connection.hpp>
-
-#include <map>
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 std::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::signals2::signal<void (const std::string& /*nick*/)> onJoinComplete;
+ boost::signals2::signal<void (ErrorPayload::ref)> onJoinFailed;
+ boost::signals2::signal<void (ErrorPayload::ref, const JID&, MUCOccupant::Role)> onRoleChangeFailed;
+ boost::signals2::signal<void (ErrorPayload::ref, const JID&, MUCOccupant::Affiliation)> onAffiliationChangeFailed;
+ boost::signals2::signal<void (ErrorPayload::ref)> onConfigurationFailed;
+ boost::signals2::signal<void (ErrorPayload::ref)> onAffiliationListFailed;
+ boost::signals2::signal<void (Presence::ref)> onOccupantPresenceChange;
+ boost::signals2::signal<void (const std::string&, const MUCOccupant& /*now*/, const MUCOccupant::Role& /*old*/)> onOccupantRoleChanged;
+ boost::signals2::signal<void (const std::string&, const MUCOccupant::Affiliation& /*new*/, const MUCOccupant::Affiliation& /*old*/)> onOccupantAffiliationChanged;
+ boost::signals2::signal<void (const MUCOccupant&)> onOccupantJoined;
+ boost::signals2::signal<void (const std::string& /*oldNickname*/, const std::string& /*newNickname*/ )> onOccupantNicknameChanged;
+ boost::signals2::signal<void (const MUCOccupant&, LeavingType, const std::string& /*reason*/)> onOccupantLeft;
+ boost::signals2::signal<void (Form::ref)> onConfigurationFormReceived;
+ boost::signals2::signal<void (MUCOccupant::Affiliation, const std::vector<JID>&)> onAffiliationListReceived;
+ boost::signals2::signal<void ()> onUnlocked;
+ /* boost::signals2::signal<void (const MUCInfo&)> onInfoResult; */
+ /* boost::signals2::signal<void (const blah&)> onItemsResult; */
- };
+ };
}
diff --git a/Swiften/MUC/MUCBookmark.h b/Swiften/MUC/MUCBookmark.h
index cca44be..92050f1 100644
--- a/Swiften/MUC/MUCBookmark.h
+++ b/Swiften/MUC/MUCBookmark.h
@@ -1,89 +1,90 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <boost/optional.hpp>
-#include <string>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/Storage.h>
+#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 4eb2ae6..9f8ae77 100644
--- a/Swiften/MUC/MUCBookmarkManager.cpp
+++ b/Swiften/MUC/MUCBookmarkManager.cpp
@@ -1,121 +1,119 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "MUCBookmarkManager.h"
+#include <Swiften/MUC/MUCBookmarkManager.h>
+
+#include <memory>
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <iostream>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Queries/Requests/GetPrivateStorageRequest.h>
#include <Swiften/Queries/Requests/SetPrivateStorageRequest.h>
-
namespace Swift {
MUCBookmarkManager::MUCBookmarkManager(IQRouter* iqRouter) {
- iqRouter_ = iqRouter;
- ready_ = false;
- GetPrivateStorageRequest<Storage>::ref request = GetPrivateStorageRequest<Storage>::create(iqRouter_);
- request->onResponse.connect(boost::bind(&MUCBookmarkManager::handleBookmarksReceived, this, _1, _2));
- request->send();
+ 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;
+void MUCBookmarkManager::handleBookmarksReceived(std::shared_ptr<Storage> payload, ErrorPayload::ref error) {
+ if (error) {
+ return;
+ }
+
+ ready_ = true;
+ onBookmarksReady();
+
+ storage = payload;
+
+ std::vector<MUCBookmark> receivedBookmarks;
+ for (const auto& room : payload->getRooms()) {
+ receivedBookmarks.push_back(MUCBookmark(room));
+ }
+
+ std::vector<MUCBookmark> newBookmarks;
+ for (const auto& oldBookmark : bookmarks_) {
+ if (containsEquivalent(receivedBookmarks, oldBookmark)) {
+ newBookmarks.push_back(oldBookmark);
+ } else {
+ onBookmarkRemoved(oldBookmark);
+ }
+ }
+
+ for (const auto& newBookmark : receivedBookmarks) {
+ if (!containsEquivalent(bookmarks_, newBookmark)) {
+ newBookmarks.push_back(newBookmark);
+ onBookmarkAdded(newBookmark);
+ }
+ }
+ bookmarks_ = newBookmarks;
}
bool MUCBookmarkManager::containsEquivalent(const std::vector<MUCBookmark>& list, const MUCBookmark& bookmark) {
- return std::find(list.begin(), list.end(), bookmark) != list.end();
+ 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 (auto& bookmark : bookmarks_) {
+ if (bookmark == oldBookmark) {
+ bookmark = newBookmark;
+ flush();
+ onBookmarkRemoved(oldBookmark);
+ onBookmarkAdded(newBookmark);
+ return;
+ }
+ }
}
void MUCBookmarkManager::addBookmark(const MUCBookmark& bookmark) {
- if (!ready_) return;
- bookmarks_.push_back(bookmark);
- onBookmarkAdded(bookmark);
- flush();
+ 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 = std::make_shared<Storage>();
+ }
+ // Update the storage element
+ storage->clearRooms();
+ for (const auto& bookmark : bookmarks_) {
+ storage->addRoom(bookmark.toStorage());
+ }
+
+ // Send an iq to save the storage element
+ SetPrivateStorageRequest<Storage>::ref request = SetPrivateStorageRequest<Storage>::create(storage, iqRouter_);
+ // FIXME: We should care about the result
+ //request->onResponse.connect(boost::bind(&MUCBookmarkManager::handleBookmarksSet, this, _1, _2));
+ request->send();
}
const std::vector<MUCBookmark>& MUCBookmarkManager::getBookmarks() const {
- return bookmarks_;
+ return bookmarks_;
}
}
diff --git a/Swiften/MUC/MUCBookmarkManager.h b/Swiften/MUC/MUCBookmarkManager.h
index 5163006..78fbbb0 100644
--- a/Swiften/MUC/MUCBookmarkManager.h
+++ b/Swiften/MUC/MUCBookmarkManager.h
@@ -1,52 +1,52 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <vector>
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/boost_bsignals.h>
#include <boost/optional.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/MUC/MUCBookmark.h>
-#include <Swiften/Elements/Storage.h>
#include <Swiften/Elements/ErrorPayload.h>
+#include <Swiften/Elements/Storage.h>
+#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::signals2::signal<void (const MUCBookmark&)> onBookmarkAdded;
+ boost::signals2::signal<void (const MUCBookmark&)> onBookmarkRemoved;
+ /**
+ * When server bookmarks are ready to be used (request response has been received).
+ */
+ boost::signals2::signal<void ()> onBookmarksReady;
+
+ private:
+ bool containsEquivalent(const std::vector<MUCBookmark>& list, const MUCBookmark& bookmark);
+ void handleBookmarksReceived(std::shared_ptr<Storage> payload, ErrorPayload::ref error);
+ void flush();
+
+ private:
+ bool ready_;
+ std::vector<MUCBookmark> bookmarks_;
+ IQRouter* iqRouter_;
+ std::shared_ptr<Storage> storage;
+ };
}
diff --git a/Swiften/MUC/MUCImpl.cpp b/Swiften/MUC/MUCImpl.cpp
index 56e6e3f..029bb4b 100644
--- a/Swiften/MUC/MUCImpl.cpp
+++ b/Swiften/MUC/MUCImpl.cpp
@@ -1,37 +1,36 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/MUC/MUCImpl.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Presence/DirectedPresenceSender.h>
#include <Swiften/Client/StanzaChannel.h>
-#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Elements/CapsInfo.h>
#include <Swiften/Elements/Form.h>
-#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/IQ.h>
-#include <Swiften/Elements/MUCUserPayload.h>
#include <Swiften/Elements/MUCAdminPayload.h>
-#include <Swiften/Elements/MUCPayload.h>
#include <Swiften/Elements/MUCDestroyPayload.h>
#include <Swiften/Elements/MUCInvitationPayload.h>
+#include <Swiften/Elements/MUCPayload.h>
+#include <Swiften/Elements/MUCUserPayload.h>
+#include <Swiften/Elements/Message.h>
#include <Swiften/MUC/MUCRegistry.h>
+#include <Swiften/Presence/DirectedPresenceSender.h>
#include <Swiften/Queries/GenericRequest.h>
+#include <Swiften/Queries/IQRouter.h>
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));
+MUCImpl::MUCImpl(StanzaChannel* stanzaChannel, IQRouter* iqRouter, DirectedPresenceSender* presenceSender, const JID &muc, MUCRegistry* mucRegistry) : ownMUCJID(muc), stanzaChannel(stanzaChannel), iqRouter_(iqRouter), presenceSender(presenceSender), mucRegistry(mucRegistry) {
+ scopedConnection_ = stanzaChannel->onPresenceReceived.connect(boost::bind(&MUCImpl::handleIncomingPresence, this, _1));
}
MUCImpl::~MUCImpl()
@@ -44,427 +43,435 @@ 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() : std::make_shared<Presence>();
+ assert(joinPresence->getType() == Presence::Available);
+ joinPresence->setTo(ownMUCJID);
+ MUCPayload::ref mucPayload = std::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 = std::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;
+ for (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) {
+ onJoinFailed(presence->getPayload<ErrorPayload>());
+ return;
+ }
+ else if (presence->getType() == Presence::Available) {
+ 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 = std::make_shared<Presence>(**presenceSender->getLastSentUndirectedPresence());
+ latestPresence->setTo(ownMUCJID);
+ presenceSender->sendPresence(latestPresence);
+ }
+ }
+ else if (presence->getType() == Presence::Unavailable) {
+ onJoinFailed(std::shared_ptr<ErrorPayload>());
+ return;
+ }
+ }
+
+ 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 (std::dynamic_pointer_cast<MUCDestroyPayload>(mucPayload->getPayload())) {
+ type = LeaveDestroy;
+ }
+ else {
+ for (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;
+ for (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(std::make_shared<Form>(Form::SubmitType));
+ std::shared_ptr< GenericRequest<MUCOwnerPayload> > request = std::make_shared< GenericRequest<MUCOwnerPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_);
+ request->onResponse.connect(boost::bind(&MUCImpl::handleCreationConfigResponse, this, _1, _2));
+ request->send();
+ }
+ }
+ }
+
+ if (joinComplete_ && !isLocked) {
+ assert(hasOccupant(getOwnNick()));
+ 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 = std::make_shared<MUCAdminPayload>();
+ MUCItem item;
+ item.role = role;
+ item.nick = jid.getResource();
+ mucPayload->addItem(item);
+ std::shared_ptr<GenericRequest<MUCAdminPayload> > request = std::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 = std::make_shared<MUCAdminPayload>();
+ MUCItem item;
+ item.affiliation = affiliation;
+ mucPayload->addItem(item);
+ std::shared_ptr<GenericRequest<MUCAdminPayload> > request = std::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 = std::make_shared<MUCAdminPayload>();
+ MUCItem item;
+ item.affiliation = affiliation;
+ item.realJID = jid.toBare();
+ mucPayload->addItem(item);
+ std::shared_ptr<GenericRequest<MUCAdminPayload> > request = std::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;
+ for (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 = std::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());
+ std::shared_ptr<GenericRequest<MUCOwnerPayload> > request = std::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(std::make_shared<Form>(Form::CancelType));
+ std::shared_ptr<GenericRequest<MUCOwnerPayload> > request = std::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);
+ std::shared_ptr<GenericRequest<MUCOwnerPayload> > request = std::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 = std::make_shared<MUCOwnerPayload>();
+ MUCDestroyPayload::ref mucDestroyPayload = std::make_shared<MUCDestroyPayload>();
+ mucPayload->setPayload(mucDestroyPayload);
+ std::shared_ptr< GenericRequest<MUCOwnerPayload> > request = std::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 = std::make_shared<Message>();
+ message->setTo(person);
+ message->setType(Message::Normal);
+ MUCInvitationPayload::ref invite = std::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 4e86c00..1c02dee 100644
--- a/Swiften/MUC/MUCImpl.h
+++ b/Swiften/MUC/MUCImpl.h
@@ -1,130 +1,130 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/MUC/MUC.h>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Base/API.h>
+#include <map>
+#include <memory>
#include <string>
+
+#include <boost/signals2.hpp>
+#include <boost/signals2/connection.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Elements/Form.h>
+#include <Swiften/Elements/MUCAdminPayload.h>
+#include <Swiften/Elements/MUCOccupant.h>
+#include <Swiften/Elements/MUCOwnerPayload.h>
#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Presence.h>
-#include <Swiften/Elements/MUCOccupant.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/MUC/MUC.h>
#include <Swiften/MUC/MUCRegistry.h>
-#include <Swiften/Elements/MUCOwnerPayload.h>
-#include <Swiften/Elements/MUCAdminPayload.h>
-#include <Swiften/Elements/Form.h>
-
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/signals/connection.hpp>
-
-#include <map>
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 std::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_ = false;
+ bool joinComplete_ = false;
+ boost::signals2::scoped_connection scopedConnection_;
+ boost::posix_time::ptime joinSince_;
+ bool createAsReservedIfNew = false;
+ bool unlocking = false;
+ bool isUnlocked_ = false;
+ boost::optional<std::string> password;
+ Presence::ref joinRequestPresence_;
+ };
}
diff --git a/Swiften/MUC/MUCManager.cpp b/Swiften/MUC/MUCManager.cpp
index 1c7f546..81e5cd5 100644
--- a/Swiften/MUC/MUCManager.cpp
+++ b/Swiften/MUC/MUCManager.cpp
@@ -1,10 +1,11 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/MUC/MUCManager.h>
+
#include <Swiften/MUC/MUCImpl.h>
namespace Swift {
@@ -13,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 std::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..aa341e4 100644
--- a/Swiften/MUC/MUCRegistry.h
+++ b/Swiften/MUC/MUCRegistry.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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:
+ virtual ~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 ea71ff5..115787e 100644
--- a/Swiften/MUC/UnitTest/MUCTest.cpp
+++ b/Swiften/MUC/UnitTest/MUCTest.cpp
@@ -1,277 +1,277 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <boost/bind.hpp>
-#include <Swiften/MUC/MUCImpl.h>
#include <Swiften/Client/DummyStanzaChannel.h>
-#include <Swiften/Presence/StanzaChannelPresenceSender.h>
-#include <Swiften/Presence/DirectedPresenceSender.h>
-#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/Elements/MUCUserPayload.h>
+#include <Swiften/Elements/CapsInfo.h>
#include <Swiften/Elements/MUCOwnerPayload.h>
+#include <Swiften/Elements/MUCUserPayload.h>
#include <Swiften/Elements/VCard.h>
-#include <Swiften/Elements/CapsInfo.h>
-
+#include <Swiften/MUC/MUCImpl.h>
+#include <Swiften/Presence/DirectedPresenceSender.h>
+#include <Swiften/Presence/StanzaChannelPresenceSender.h>
+#include <Swiften/Queries/IQRouter.h>
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 = std::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 = std::make_shared<Presence>();
+ initialPresence->setStatus("");
+ VCard::ref vcard = std::make_shared<VCard>();
+ vcard->setPhoto(createByteArray("15c30080ae98ec48be94bf0e191d43edd06e500a"));
+ initialPresence->addPayload(vcard);
+ CapsInfo::ref caps = std::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 = std::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 = std::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 = std::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 = std::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 = std::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 = std::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 = std::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 9c77e92..becfa72 100644
--- a/Swiften/MUC/UnitTest/MockMUC.h
+++ b/Swiften/MUC/UnitTest/MockMUC.h
@@ -1,96 +1,98 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/MUC/MUC.h>
-#include <Swiften/MUC/MUCRegistry.h>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Elements/Message.h>
-#include <Swiften/Elements/Presence.h>
+#include <map>
+#include <memory>
+#include <string>
+
+#include <boost/signals2.hpp>
+#include <boost/signals2/connection.hpp>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Elements/Form.h>
+#include <Swiften/Elements/MUCAdminPayload.h>
#include <Swiften/Elements/MUCOccupant.h>
#include <Swiften/Elements/MUCOwnerPayload.h>
-#include <Swiften/Elements/MUCAdminPayload.h>
-#include <Swiften/Elements/Form.h>
-#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/signals/connection.hpp>
-#include <boost/shared_ptr.hpp>
-#include <string>
-#include <map>
+#include <Swiften/Elements/Message.h>
+#include <Swiften/Elements/Presence.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/MUC/MUC.h>
+#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 std::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..1c468f1 100644
--- a/Swiften/Network/BOSHConnection.cpp
+++ b/Swiften/Network/BOSHConnection.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,10 +13,10 @@
#include <Swiften/Network/BOSHConnection.h>
#include <string>
+#include <thread>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
-#include <boost/thread.hpp>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/Base/Concat.h>
@@ -32,362 +32,362 @@
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_ = std::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_ = std::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(std::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());
+void BOSHConnection::handleRawDataRead(std::shared_ptr<SafeByteArray> data) {
+ SWIFT_LOG(debug) << std::endl;
+ tlsLayer_->handleDataRead(*data.get());
}
-void BOSHConnection::handleTLSError(boost::shared_ptr<TLSError> /* error */) {
+void BOSHConnection::handleTLSError(std::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);
- }
+void BOSHConnection::handleDataRead(std::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 ? std::shared_ptr<BOSHError>() : std::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..b75e51f 100644
--- a/Swiften/Network/BOSHConnection.h
+++ b/Swiften/Network/BOSHConnection.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,7 +13,7 @@
#pragma once
-#include <boost/enable_shared_from_this.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Base/Error.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 std::shared_ptr<BOSHError> ref;
+
+ private:
+ Type type;
+ };
+
+ class SWIFTEN_API BOSHConnection : public std::enable_shared_from_this<BOSHConnection> {
+ public:
+ typedef std::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::signals2::signal<void (bool /* error */)> onConnectFinished;
+ boost::signals2::signal<void (bool /* error */)> onDisconnected;
+ boost::signals2::signal<void (BOSHError::ref)> onSessionTerminated;
+ boost::signals2::signal<void (const std::string& /*sid*/, size_t /*requests*/)> onSessionStarted;
+ boost::signals2::signal<void (const SafeByteArray&)> onXMPPDataRead;
+ boost::signals2::signal<void (const SafeByteArray&)> onBOSHDataRead;
+ boost::signals2::signal<void (const SafeByteArray&)> onBOSHDataWritten;
+ boost::signals2::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(std::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(std::shared_ptr<SafeByteArray> data);
+ void handleTLSError(std::shared_ptr<TLSError> error);
+ void writeData(const SafeByteArray& data);
+
+ URL boshURL_;
+ Connector::ref connector_;
+ XMLParserFactory* parserFactory_;
+ std::shared_ptr<Connection> connection_;
+ std::shared_ptr<HighLayer> dummyLayer_;
+ std::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..e4ca471 100644
--- a/Swiften/Network/BOSHConnectionPool.cpp
+++ b/Swiften/Network/BOSHConnectionPool.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -12,290 +12,289 @@
#include <Swiften/Base/Log.h>
#include <Swiften/Base/SafeString.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Network/CachingDomainNameResolver.h>
#include <Swiften/Network/HTTPConnectProxiedConnectionFactory.h>
namespace Swift {
-BOSHConnectionPool::BOSHConnectionPool(const URL& boshURL, DomainNameResolver* realResolver, ConnectionFactory* connectionFactoryParameter, XMLParserFactory* parserFactory, TLSContextFactory* tlsFactory, TimerFactory* timerFactory, EventLoop* eventLoop, const std::string& to, unsigned long long initialRID, const URL& boshHTTPConnectProxyURL, const SafeString& boshHTTPConnectProxyAuthID, const SafeString& boshHTTPConnectProxyAuthPassword, const TLSOptions& tlsOptions, 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);
+BOSHConnectionPool::BOSHConnectionPool(const URL& boshURL, DomainNameResolver* realResolver, ConnectionFactory* connectionFactoryParameter, XMLParserFactory* parserFactory, TLSContextFactory* tlsFactory, TimerFactory* timerFactory, EventLoop* eventLoop, const std::string& to, unsigned long long initialRID, const URL& boshHTTPConnectProxyURL, const SafeString& boshHTTPConnectProxyAuthID, const SafeString& boshHTTPConnectProxyAuthPassword, const TLSOptions& tlsOptions, std::shared_ptr<HTTPTrafficFilter> trafficFilter) :
+ boshURL(boshURL),
+ connectionFactory(connectionFactoryParameter),
+ xmlParserFactory(parserFactory),
+ timerFactory(timerFactory),
+ rid(initialRID),
+ pendingTerminate(false),
+ to(to),
+ requestLimit(2),
+ restartCount(0),
+ pendingRestart(false),
+ tlsContextFactory_(tlsFactory),
+ tlsOptions_(tlsOptions) {
+
+ if (!boshHTTPConnectProxyURL.isEmpty()) {
+ connectionFactory = new HTTPConnectProxiedConnectionFactory(realResolver, connectionFactory, timerFactory, boshHTTPConnectProxyURL.getHost(), URL::getPortOrDefaultPort(boshHTTPConnectProxyURL), boshHTTPConnectProxyAuthID, boshHTTPConnectProxyAuthPassword, trafficFilter);
+ }
+ resolver = new CachingDomainNameResolver(realResolver, eventLoop);
}
BOSHConnectionPool::~BOSHConnectionPool() {
- /* Don't do a normal close here. Instead kill things forcibly, as close() or writeFooter() will already have been called */
- std::vector<BOSHConnection::ref> connectionCopies = connections;
- foreach (BOSHConnection::ref connection, connectionCopies) {
- 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;
+ for (auto&& connection : connectionCopies) {
+ if (connection) {
+ destroyConnection(connection);
+ connection->disconnect();
+ }
+ }
+ for (auto 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_;
+std::shared_ptr<CertificateVerificationError> BOSHConnectionPool::getPeerCertificateVerificationError() const {
+ 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;
+ for (auto&& 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(std::make_shared<BOSHError>(BOSHError::UndefinedCondition));
+ /*TODO: We can probably manage to not terminate the stream here and use the rid/ack retry
+ * logic to just swallow the error and try again (some number of tries).
+ */
+ }
+ else {
+ if (connection->getPeerCertificate() && pinnedCertificateChain_.empty()) {
+ pinnedCertificateChain_ = connection->getPeerCertificateChain();
+ }
+ if (!pinnedCertificateChain_.empty()) {
+ lastVerificationError_ = connection->getPeerCertificateVerificationError();
+ }
+
+ if (sid.empty()) {
+ connection->startStream(to, rid);
+ }
+ if (pendingRestart) {
+ restartStream();
+ }
+ tryToSendQueuedData();
+ }
}
BOSHConnection::ref BOSHConnectionPool::getSuitableConnection() {
- BOSHConnection::ref suitableConnection;
- foreach (BOSHConnection::ref connection, connections) {
- 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;
+ for (auto&& connection : connections) {
+ if (connection->isReadyToSend()) {
+ suitableConnection = connection;
+ break;
+ }
+ }
+
+ if (!suitableConnection && connections.size() < requestLimit) {
+ /* This is not a suitable connection because it won't have yet connected and added TLS if needed. */
+ BOSHConnection::ref newConnection = createConnection();
+ newConnection->setSID(sid);
+ }
+ assert(connections.size() <= requestLimit);
+ assert((!suitableConnection) || suitableConnection->isReadyToSend());
+ return suitableConnection;
}
void BOSHConnectionPool::tryToSendQueuedData() {
- if (sid.empty()) {
- /* If we've not got as far as stream start yet, pend */
- return;
- }
-
- BOSHConnection::ref suitableConnection = getSuitableConnection();
- bool toSend = !dataQueue.empty();
- if (suitableConnection) {
- if (toSend) {
- rid++;
- suitableConnection->setRID(rid);
- SafeByteArray data;
- foreach (const SafeByteArray& datum, dataQueue) {
- 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;
+ for (const auto& datum : dataQueue) {
+ data.insert(data.end(), datum.begin(), datum.end());
+ }
+ suitableConnection->write(data);
+ dataQueue.clear();
+ }
+ else if (pendingTerminate) {
+ rid++;
+ suitableConnection->setRID(rid);
+ suitableConnection->terminateStream();
+ sid = "";
+ close();
+ }
+ }
+ if (!pendingTerminate) {
+ /* Ensure there's always a session waiting to read data for us */
+ bool pending = false;
+ for (auto&& connection : connections) {
+ if (connection && !connection->isReadyToSend()) {
+ pending = true;
+ }
+ }
+ if (!pending) {
+ if (restartCount >= 1) {
+ /* Don't open a second connection until we've restarted the stream twice - i.e. we've authed and resource bound.*/
+ if (suitableConnection) {
+ rid++;
+ suitableConnection->setRID(rid);
+ suitableConnection->write(createSafeByteArray(""));
+ }
+ else {
+ /* My thought process I went through when writing this, to aid anyone else confused why this can happen...
+ *
+ * What to do here? I think this isn't possible.
+ If you didn't have two connections, suitable would have made one.
+ If you have two connections and neither is suitable, pending would be true.
+ If you have a non-pending connection, it's suitable.
+
+ If I decide to do something here, remove assert above.
+
+ Ah! Yes, because there's a period between creating the connection and it being connected. */
+ }
+ }
+ }
+ }
}
void BOSHConnectionPool::handleHTTPError(const std::string& /*errorCode*/) {
- handleSessionTerminated(boost::make_shared<BOSHError>(BOSHError::UndefinedCondition));
+ handleSessionTerminated(std::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(std::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;
+std::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;
}
-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));
+void BOSHConnectionPool::destroyConnection(std::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));
}
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..1a805de 100644
--- a/Swiften/Network/BOSHConnectionPool.h
+++ b/Swiften/Network/BOSHConnectionPool.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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::signals2::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, std::shared_ptr<HTTPTrafficFilter> trafficFilter = std::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;
+ std::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::signals2::signal<void (BOSHError::ref)> onSessionTerminated;
+ boost::signals2::signal<void ()> onSessionStarted;
+ boost::signals2::signal<void (const SafeByteArray&)> onXMPPDataRead;
+ boost::signals2::signal<void (const SafeByteArray&)> onBOSHDataRead;
+ boost::signals2::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<std::shared_ptr<Certificate> > pinnedCertificateChain_;
+ std::shared_ptr<CertificateVerificationError> lastVerificationError_;
+ };
}
diff --git a/Swiften/Network/BoostConnection.cpp b/Swiften/Network/BoostConnection.cpp
index f495795..0de7b25 100644
--- a/Swiften/Network/BoostConnection.cpp
+++ b/Swiften/Network/BoostConnection.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,15 +7,14 @@
#include <Swiften/Network/BoostConnection.h>
#include <algorithm>
-#include <iostream>
+#include <memory>
+#include <mutex>
#include <string>
#include <boost/asio/placeholders.hpp>
#include <boost/asio/write.hpp>
#include <boost/bind.hpp>
#include <boost/numeric/conversion/cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <boost/thread.hpp>
#include <Swiften/Base/Algorithm.h>
#include <Swiften/Base/ByteArray.h>
@@ -33,145 +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:
+ std::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) {
+BoostConnection::BoostConnection(std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) :
+ 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().
+ std::lock_guard<std::mutex> lock(writeMutex_);
+ if (writing_) {
+ closeSocketAfterNextWrite_ = true;
+ } else {
+ closeSocket();
+ }
}
void BoostConnection::closeSocket() {
- boost::system::error_code errorCode;
- socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, errorCode);
- socket_.close();
+ std::lock_guard<std::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);
- }
+ std::lock_guard<std::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);
- 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_ = std::make_shared<SafeByteArray>(BUFFER_SIZE);
+ std::lock_guard<std::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());
+ }
+ {
+ std::lock_guard<std::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 f933cd8..03122da 100644
--- a/Swiften/Network/BoostConnection.h
+++ b/Swiften/Network/BoostConnection.h
@@ -1,15 +1,16 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+#include <mutex>
+
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
-#include <boost/enable_shared_from_this.hpp>
-#include <boost/thread/mutex.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/SafeByteArray.h>
@@ -20,61 +21,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_;
- };
+ class EventLoop;
+
+ class SWIFTEN_API BoostConnection : public Connection, public EventOwner, public std::enable_shared_from_this<BoostConnection> {
+ public:
+ typedef std::shared_ptr<BoostConnection> ref;
+
+ virtual ~BoostConnection();
+
+ static ref create(std::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;
+ std::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const;
+
+ private:
+ BoostConnection(std::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;
+ std::shared_ptr<boost::asio::io_service> ioService;
+ boost::asio::ip::tcp::socket socket_;
+ std::shared_ptr<SafeByteArray> readBuffer_;
+ std::mutex writeMutex_;
+ bool writing_;
+ SafeByteArray writeQueue_;
+ bool closeSocketAfterNextWrite_;
+ std::mutex readCloseMutex_;
+ };
}
diff --git a/Swiften/Network/BoostConnectionFactory.cpp b/Swiften/Network/BoostConnectionFactory.cpp
index 36bae5e..9ec30f5 100644
--- a/Swiften/Network/BoostConnectionFactory.cpp
+++ b/Swiften/Network/BoostConnectionFactory.cpp
@@ -1,19 +1,20 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/BoostConnectionFactory.h>
+
#include <Swiften/Network/BoostConnection.h>
namespace Swift {
-BoostConnectionFactory::BoostConnectionFactory(boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : ioService(ioService), eventLoop(eventLoop) {
+BoostConnectionFactory::BoostConnectionFactory(std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : ioService(ioService), eventLoop(eventLoop) {
}
-boost::shared_ptr<Connection> BoostConnectionFactory::createConnection() {
- return BoostConnection::create(ioService, eventLoop);
+std::shared_ptr<Connection> BoostConnectionFactory::createConnection() {
+ return BoostConnection::create(ioService, eventLoop);
}
}
diff --git a/Swiften/Network/BoostConnectionFactory.h b/Swiften/Network/BoostConnectionFactory.h
index 574ea3e..a4e3b0d 100644
--- a/Swiften/Network/BoostConnectionFactory.h
+++ b/Swiften/Network/BoostConnectionFactory.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,20 +9,20 @@
#include <boost/asio/io_service.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Network/ConnectionFactory.h>
#include <Swiften/Network/BoostConnection.h>
+#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(std::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop);
- virtual boost::shared_ptr<Connection> createConnection();
+ virtual std::shared_ptr<Connection> createConnection();
- private:
- boost::shared_ptr<boost::asio::io_service> ioService;
- EventLoop* eventLoop;
- };
+ private:
+ std::shared_ptr<boost::asio::io_service> ioService;
+ EventLoop* eventLoop;
+ };
}
diff --git a/Swiften/Network/BoostConnectionServer.cpp b/Swiften/Network/BoostConnectionServer.cpp
index 48b323d..34b5799 100644
--- a/Swiften/Network/BoostConnectionServer.cpp
+++ b/Swiften/Network/BoostConnectionServer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -19,91 +19,91 @@
namespace Swift {
-BoostConnectionServer::BoostConnectionServer(int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : port_(port), ioService_(ioService), eventLoop(eventLoop), acceptor_(NULL) {
+BoostConnectionServer::BoostConnectionServer(int port, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : port_(port), ioService_(ioService), eventLoop(eventLoop), acceptor_(nullptr) {
}
-BoostConnectionServer::BoostConnectionServer(const HostAddress &address, int port, boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : address_(address), port_(port), ioService_(ioService), eventLoop(eventLoop), acceptor_(NULL) {
+BoostConnectionServer::BoostConnectionServer(const HostAddress &address, int port, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : address_(address), port_(port), ioService_(ioService), eventLoop(eventLoop), acceptor_(nullptr) {
}
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_ = nullptr;
+ }
+ 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();
- }
+void BoostConnectionServer::handleAccept(std::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();
+ }
}
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 d1879a3..3dd9830 100644
--- a/Swiften/Network/BoostConnectionServer.h
+++ b/Swiften/Network/BoostConnectionServer.h
@@ -1,57 +1,57 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
-#include <boost/enable_shared_from_this.hpp>
+#include <boost/optional/optional.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/EventLoop/EventOwner.h>
#include <Swiften/Network/BoostConnection.h>
#include <Swiften/Network/ConnectionServer.h>
-#include <Swiften/EventLoop/EventOwner.h>
-#include <boost/optional/optional.hpp>
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 std::enable_shared_from_this<BoostConnectionServer> {
+ public:
+ typedef std::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, std::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, std::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::signals2::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, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop);
+ BoostConnectionServer(const HostAddress &address, int port, std::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(std::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_;
+ std::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 04c614e..8b3fd2f 100644
--- a/Swiften/Network/BoostConnectionServerFactory.cpp
+++ b/Swiften/Network/BoostConnectionServerFactory.cpp
@@ -4,20 +4,27 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Network/BoostConnectionServerFactory.h>
+
#include <Swiften/Network/BoostConnectionServer.h>
namespace Swift {
-BoostConnectionServerFactory::BoostConnectionServerFactory(boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : ioService(ioService), eventLoop(eventLoop) {
+BoostConnectionServerFactory::BoostConnectionServerFactory(std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : ioService(ioService), eventLoop(eventLoop) {
}
-boost::shared_ptr<ConnectionServer> BoostConnectionServerFactory::createConnectionServer(int port) {
- return BoostConnectionServer::create(port, ioService, eventLoop);
+std::shared_ptr<ConnectionServer> BoostConnectionServerFactory::createConnectionServer(int port) {
+ 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);
+std::shared_ptr<ConnectionServer> BoostConnectionServerFactory::createConnectionServer(const Swift::HostAddress &hostAddress, int port) {
+ return BoostConnectionServer::create(hostAddress, port, ioService, eventLoop);
}
}
diff --git a/Swiften/Network/BoostConnectionServerFactory.h b/Swiften/Network/BoostConnectionServerFactory.h
index 1ef4951..033e63d 100644
--- a/Swiften/Network/BoostConnectionServerFactory.h
+++ b/Swiften/Network/BoostConnectionServerFactory.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -15,22 +15,22 @@
#include <boost/asio/io_service.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Network/ConnectionServerFactory.h>
#include <Swiften/Network/BoostConnectionServer.h>
+#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(std::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop);
- virtual boost::shared_ptr<ConnectionServer> createConnectionServer(int port);
+ virtual std::shared_ptr<ConnectionServer> createConnectionServer(int port);
- virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress &hostAddress, int port);
+ virtual std::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress &hostAddress, int port);
- private:
- boost::shared_ptr<boost::asio::io_service> ioService;
- EventLoop* eventLoop;
- };
+ private:
+ std::shared_ptr<boost::asio::io_service> ioService;
+ EventLoop* eventLoop;
+ };
}
diff --git a/Swiften/Network/BoostIOServiceThread.cpp b/Swiften/Network/BoostIOServiceThread.cpp
index af74c85..756e660 100644
--- a/Swiften/Network/BoostIOServiceThread.cpp
+++ b/Swiften/Network/BoostIOServiceThread.cpp
@@ -6,32 +6,34 @@
#include <Swiften/Network/BoostIOServiceThread.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
+#include <boost/bind.hpp>
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));
- }
+BoostIOServiceThread::BoostIOServiceThread(std::shared_ptr<boost::asio::io_service> ioService) {
+ if (!!ioService) {
+ ioService_ = ioService;
+ thread_ = nullptr;
+ }
+ else {
+ ioService_ = std::make_shared<boost::asio::io_service>();
+ thread_ = new std::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 428837b..b9183fd 100644
--- a/Swiften/Network/BoostIOServiceThread.h
+++ b/Swiften/Network/BoostIOServiceThread.h
@@ -1,40 +1,41 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+#include <thread>
+
#include <boost/asio/io_service.hpp>
-#include <boost/thread/thread.hpp>
-#include <boost/shared_ptr.hpp>
#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();
-
- boost::shared_ptr<boost::asio::io_service> getIOService() const {
- return ioService_;
- }
-
- private:
- void doRun();
-
- private:
- boost::shared_ptr<boost::asio::io_service> ioService_;
- boost::thread* thread_;
- };
+ 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(std::shared_ptr<boost::asio::io_service> ioService = std::shared_ptr<boost::asio::io_service>());
+ ~BoostIOServiceThread();
+
+ std::shared_ptr<boost::asio::io_service> getIOService() const {
+ return ioService_;
+ }
+
+ private:
+ void doRun();
+
+ private:
+ std::shared_ptr<boost::asio::io_service> ioService_;
+ std::thread* thread_;
+ };
}
diff --git a/Swiften/Network/BoostNetworkFactories.cpp b/Swiften/Network/BoostNetworkFactories.cpp
index 871a38b..9fef73c 100644
--- a/Swiften/Network/BoostNetworkFactories.cpp
+++ b/Swiften/Network/BoostNetworkFactories.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -28,45 +28,45 @@
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);
+BoostNetworkFactories::BoostNetworkFactories(EventLoop* eventLoop, std::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);
#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..72afb04 100644
--- a/Swiften/Network/BoostNetworkFactories.h
+++ b/Swiften/Network/BoostNetworkFactories.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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, std::shared_ptr<boost::asio::io_service> ioService = std::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..a177504 100644
--- a/Swiften/Network/BoostTimer.cpp
+++ b/Swiften/Network/BoostTimer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,49 +14,49 @@
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));
+BoostTimer::BoostTimer(int milliseconds, std::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));
}
BoostTimer::~BoostTimer() {
- {
- boost::mutex::scoped_lock lockTimer(timerMutex);
- timer.reset();
- }
+ {
+ std::unique_lock<std::mutex> 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));
- }
+ {
+ std::unique_lock<std::mutex> 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());
- }
+ {
+ std::unique_lock<std::mutex> 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 {
+ {
+ std::unique_lock<std::mutex> 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..68ae28c 100644
--- a/Swiften/Network/BoostTimer.h
+++ b/Swiften/Network/BoostTimer.h
@@ -1,48 +1,49 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+#include <mutex>
+
#include <boost/asio/deadline_timer.hpp>
#include <boost/asio/io_service.hpp>
-#include <boost/enable_shared_from_this.hpp>
#include <boost/scoped_ptr.hpp>
-#include <boost/thread/mutex.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/EventLoop/EventOwner.h>
#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 std::enable_shared_from_this<BoostTimer> {
+ public:
+ typedef std::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, std::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, std::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;
+ std::shared_ptr<boost::asio::io_service> ioService;
+ boost::scoped_ptr<boost::asio::deadline_timer> timer;
+ std::mutex timerMutex;
+ EventLoop* eventLoop;
+ bool shuttingDown;
+ };
}
diff --git a/Swiften/Network/BoostTimerFactory.cpp b/Swiften/Network/BoostTimerFactory.cpp
index dbc72df..ffa9b30 100644
--- a/Swiften/Network/BoostTimerFactory.cpp
+++ b/Swiften/Network/BoostTimerFactory.cpp
@@ -1,19 +1,20 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/BoostTimerFactory.h>
+
#include <Swiften/Network/BoostTimer.h>
namespace Swift {
-BoostTimerFactory::BoostTimerFactory(boost::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : ioService(ioService), eventLoop(eventLoop) {
+BoostTimerFactory::BoostTimerFactory(std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : ioService(ioService), eventLoop(eventLoop) {
}
-boost::shared_ptr<Timer> BoostTimerFactory::createTimer(int milliseconds) {
- return BoostTimer::create(milliseconds, ioService, eventLoop);
+std::shared_ptr<Timer> BoostTimerFactory::createTimer(int milliseconds) {
+ return BoostTimer::create(milliseconds, ioService, eventLoop);
}
}
diff --git a/Swiften/Network/BoostTimerFactory.h b/Swiften/Network/BoostTimerFactory.h
index 9b97467..ca9a833 100644
--- a/Swiften/Network/BoostTimerFactory.h
+++ b/Swiften/Network/BoostTimerFactory.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,21 +9,21 @@
#include <boost/asio/io_service.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Network/TimerFactory.h>
#include <Swiften/Network/BoostTimer.h>
+#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(std::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop);
- virtual boost::shared_ptr<Timer> createTimer(int milliseconds);
+ virtual std::shared_ptr<Timer> createTimer(int milliseconds);
- private:
- boost::shared_ptr<boost::asio::io_service> ioService;
- EventLoop* eventLoop;
- };
+ private:
+ std::shared_ptr<boost::asio::io_service> ioService;
+ EventLoop* eventLoop;
+ };
}
diff --git a/Swiften/Network/CachingDomainNameResolver.cpp b/Swiften/Network/CachingDomainNameResolver.cpp
index 8a2336b..8846e09 100644
--- a/Swiften/Network/CachingDomainNameResolver.cpp
+++ b/Swiften/Network/CachingDomainNameResolver.cpp
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/CachingDomainNameResolver.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
namespace Swift {
@@ -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..9339a77 100644
--- a/Swiften/Network/CachingDomainNameResolver.h
+++ b/Swiften/Network/CachingDomainNameResolver.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Network/DomainNameResolver.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..ea55db3 100644
--- a/Swiften/Network/ChainedConnector.cpp
+++ b/Swiften/Network/ChainedConnector.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -11,86 +11,85 @@
#include <boost/bind.hpp>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Network/ConnectionFactory.h>
#include <Swiften/Network/Connector.h>
using namespace Swift;
ChainedConnector::ChainedConnector(
- const std::string& hostname,
- int port,
- const boost::optional<std::string>& serviceLookupPrefix,
- DomainNameResolver* resolver,
- const std::vector<ConnectionFactory*>& connectionFactories,
- TimerFactory* timerFactory) :
- hostname(hostname),
- port(port),
- serviceLookupPrefix(serviceLookupPrefix),
- resolver(resolver),
- connectionFactories(connectionFactories),
- timerFactory(timerFactory),
- timeoutMilliseconds(0) {
+ 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(std::shared_ptr<Connection>(), std::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(std::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();
- }
+void ChainedConnector::handleConnectorFinished(std::shared_ptr<Connection> connection, std::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();
+ }
}
-void ChainedConnector::finish(boost::shared_ptr<Connection> connection, boost::shared_ptr<Error> error) {
- onConnectFinished(connection, error);
+void ChainedConnector::finish(std::shared_ptr<Connection> connection, std::shared_ptr<Error> error) {
+ onConnectFinished(connection, error);
}
diff --git a/Swiften/Network/ChainedConnector.h b/Swiften/Network/ChainedConnector.h
index 9bcc961..a00d7e5 100644
--- a/Swiften/Network/ChainedConnector.h
+++ b/Swiften/Network/ChainedConnector.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,49 +7,49 @@
#pragma once
#include <deque>
+#include <memory>
#include <string>
#include <vector>
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/Error.h>
-#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::signals2::signal<void (std::shared_ptr<Connection>, std::shared_ptr<Error>)> onConnectFinished;
+
+ private:
+ void finish(std::shared_ptr<Connection> connection, std::shared_ptr<Error>);
+ void tryNextConnectionFactory();
+ void handleConnectorFinished(std::shared_ptr<Connection>, std::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;
+ std::shared_ptr<Connector> currentConnector;
+ std::shared_ptr<Error> lastError;
+ };
}
diff --git a/Swiften/Network/Connection.h b/Swiften/Network/Connection.h
index 39b63d4..85f33a8 100644
--- a/Swiften/Network/Connection.h
+++ b/Swiften/Network/Connection.h
@@ -1,44 +1,45 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/SafeByteArray.h>
-#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 std::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::signals2::signal<void (bool /* error */)> onConnectFinished;
+ boost::signals2::signal<void (const boost::optional<Error>&)> onDisconnected;
+ boost::signals2::signal<void (std::shared_ptr<SafeByteArray>)> onDataRead;
+ boost::signals2::signal<void ()> onDataWritten;
+ };
}
diff --git a/Swiften/Network/ConnectionFactory.h b/Swiften/Network/ConnectionFactory.h
index d8e1b71..e749fa3 100644
--- a/Swiften/Network/ConnectionFactory.h
+++ b/Swiften/Network/ConnectionFactory.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#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 std::shared_ptr<Connection> createConnection() = 0;
+ };
}
diff --git a/Swiften/Network/ConnectionServer.h b/Swiften/Network/ConnectionServer.h
index 33fc7b3..769ab9f 100644
--- a/Swiften/Network/ConnectionServer.h
+++ b/Swiften/Network/ConnectionServer.h
@@ -1,37 +1,38 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/optional/optional.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Network/Connection.h>
#include <Swiften/Network/HostAddressPort.h>
-#include <boost/optional/optional.hpp>
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::signals2::signal<void (std::shared_ptr<Connection>)> onNewConnection;
+ };
}
diff --git a/Swiften/Network/ConnectionServerFactory.h b/Swiften/Network/ConnectionServerFactory.h
index 672cac7..413131e 100644
--- a/Swiften/Network/ConnectionServerFactory.h
+++ b/Swiften/Network/ConnectionServerFactory.h
@@ -5,26 +5,27 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#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 std::shared_ptr<ConnectionServer> createConnectionServer(int port) = 0;
- virtual boost::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, int port) = 0;
- };
+ virtual std::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, int port) = 0;
+ };
}
diff --git a/Swiften/Network/Connector.cpp b/Swiften/Network/Connector.cpp
index 5510acb..457d8a9 100644
--- a/Swiften/Network/Connector.cpp
+++ b/Swiften/Network/Connector.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -21,170 +21,175 @@ 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;
+ auto hostAddress = HostAddress::fromString(hostname);
+ 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 is already a valid address; skip name lookup.
+ foundSomeDNS = true;
+ addressQueryResults.push_back(hostAddress.get());
+ tryNextAddress();
+ } else {
+ queryAddress(hostname);
+ }
}
void Connector::stop() {
- finish(boost::shared_ptr<Connection>());
+ if (currentConnection) {
+ currentConnection->onConnectFinished.disconnect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1));
+ currentConnection->disconnect();
+ }
+ finish(std::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(std::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>());
+void Connector::finish(std::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) ? std::shared_ptr<Error>() : std::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 f34eaa6..d8a1b88 100644
--- a/Swiften/Network/Connector.h
+++ b/Swiften/Network/Connector.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,73 +7,75 @@
#pragma once
#include <deque>
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <string>
+
#include <boost/optional.hpp>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Network/DomainNameServiceQuery.h>
#include <Swiften/Network/Connection.h>
-#include <Swiften/Network/Timer.h>
-#include <Swiften/Network/HostAddressPort.h>
-#include <string>
#include <Swiften/Network/DomainNameResolveError.h>
+#include <Swiften/Network/DomainNameServiceQuery.h>
+#include <Swiften/Network/HostAddressPort.h>
+#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::signals2::trackable, public std::enable_shared_from_this<Connector> {
+ public:
+ typedef std::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::signals2::signal<void (std::shared_ptr<Connection>, std::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(std::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;
+ std::shared_ptr<Timer> timer;
+ std::shared_ptr<DomainNameServiceQuery> serviceQuery;
+ std::deque<DomainNameServiceQuery::Result> serviceQueryResults;
+ std::shared_ptr<DomainNameAddressQuery> addressQuery;
+ std::deque<HostAddress> addressQueryResults;
+ bool queriedAllServices;
+ std::shared_ptr<Connection> currentConnection;
+ bool foundSomeDNS;
+ };
}
diff --git a/Swiften/Network/DomainNameAddressQuery.h b/Swiften/Network/DomainNameAddressQuery.h
index fc04c2f..7f89546 100644
--- a/Swiften/Network/DomainNameAddressQuery.h
+++ b/Swiften/Network/DomainNameAddressQuery.h
@@ -1,27 +1,28 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
+#include <memory>
+
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Network/DomainNameResolveError.h>
#include <Swiften/Network/HostAddress.h>
namespace Swift {
- class DomainNameAddressQuery {
- public:
- typedef boost::shared_ptr<DomainNameAddressQuery> ref;
+ class DomainNameAddressQuery {
+ public:
+ typedef std::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::signals2::signal<void (const std::vector<HostAddress>&, boost::optional<DomainNameResolveError>)> onResult;
+ };
}
diff --git a/Swiften/Network/DomainNameResolveError.h b/Swiften/Network/DomainNameResolveError.h
index c788537..7a5eed1 100644
--- a/Swiften/Network/DomainNameResolveError.h
+++ b/Swiften/Network/DomainNameResolveError.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -10,8 +10,10 @@
#include <Swiften/Base/Error.h>
namespace Swift {
- class SWIFTEN_API DomainNameResolveError : public Error {
- public:
- DomainNameResolveError() {}
- };
+ class SWIFTEN_API DomainNameResolveError : public Error {
+ public:
+ DomainNameResolveError() {}
+ SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(DomainNameResolveError)
+ SWIFTEN_DEFAULT_COPY_ASSIGMNENT_OPERATOR(DomainNameResolveError)
+ };
}
diff --git a/Swiften/Network/DomainNameResolver.h b/Swiften/Network/DomainNameResolver.h
index 8bc1b35..5fe30d5 100644
--- a/Swiften/Network/DomainNameResolver.h
+++ b/Swiften/Network/DomainNameResolver.h
@@ -1,26 +1,26 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#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 std::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) = 0;
+ virtual std::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& name) = 0;
+ };
}
diff --git a/Swiften/Network/DomainNameServiceQuery.cpp b/Swiften/Network/DomainNameServiceQuery.cpp
index 33331a7..708bbce 100644
--- a/Swiften/Network/DomainNameServiceQuery.cpp
+++ b/Swiften/Network/DomainNameServiceQuery.cpp
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/DomainNameServiceQuery.h>
-#include <numeric>
#include <cassert>
#include <functional>
#include <iterator>
+#include <numeric>
-#include <Swiften/Base/RandomGenerator.h>
-#include <boost/numeric/conversion/cast.hpp>
-#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
+#include <boost/lambda/lambda.hpp>
+#include <boost/numeric/conversion/cast.hpp>
#include <boost/typeof/typeof.hpp>
+#include <Swiften/Base/RandomGenerator.h>
+
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 {
@@ -34,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 1e2f2f3..b27f32e 100644
--- a/Swiften/Network/DomainNameServiceQuery.h
+++ b/Swiften/Network/DomainNameServiceQuery.h
@@ -1,40 +1,41 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/optional.hpp>
+#include <memory>
+#include <string>
#include <vector>
-#include <boost/shared_ptr.hpp>
-#include <string>
+#include <boost/optional.hpp>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
#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 std::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::signals2::signal<void (const std::vector<Result>&)> onResult;
+ };
}
diff --git a/Swiften/Network/DummyConnection.cpp b/Swiften/Network/DummyConnection.cpp
index e750890..3024b21 100644
--- a/Swiften/Network/DummyConnection.cpp
+++ b/Swiften/Network/DummyConnection.cpp
@@ -1,14 +1,15 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/DummyConnection.h>
-#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <cassert>
+#include <memory>
+
+#include <boost/bind.hpp>
namespace Swift {
@@ -16,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), std::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..e58edf6 100644
--- a/Swiften/Network/DummyConnection.h
+++ b/Swiften/Network/DummyConnection.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/enable_shared_from_this.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/EventLoop/EventLoop.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 std::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::signals2::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..d723283 100644
--- a/Swiften/Network/DummyConnectionFactory.h
+++ b/Swiften/Network/DummyConnectionFactory.h
@@ -4,9 +4,15 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Network/ConnectionFactory.h>
#include <Swiften/Network/DummyConnection.h>
@@ -17,13 +23,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 std::shared_ptr<Connection> createConnection() {
+ return std::make_shared<DummyConnection>(eventLoop);
+ }
private:
- EventLoop* eventLoop;
+ EventLoop* eventLoop;
};
}
diff --git a/Swiften/Network/DummyConnectionServer.h b/Swiften/Network/DummyConnectionServer.h
index c0c2efc..970cbb7 100644
--- a/Swiften/Network/DummyConnectionServer.h
+++ b/Swiften/Network/DummyConnectionServer.h
@@ -1,43 +1,43 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/enable_shared_from_this.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
-#include <Swiften/Network/ConnectionServer.h>
-#include <Swiften/Network/HostAddressPort.h>
#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/EventLoop/EventOwner.h>
+#include <Swiften/Network/ConnectionServer.h>
+#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 std::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..822f95f 100644
--- a/Swiften/Network/DummyConnectionServerFactory.h
+++ b/Swiften/Network/DummyConnectionServerFactory.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Network/ConnectionServerFactory.h>
#include <Swiften/Network/DummyConnectionServer.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 std::shared_ptr<ConnectionServer> createConnectionServer(int port) {
+ return std::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 std::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, int port) {
+ return std::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..0bad7be 100644
--- a/Swiften/Network/DummyTimerFactory.cpp
+++ b/Swiften/Network/DummyTimerFactory.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,53 +8,52 @@
#include <algorithm>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Network/Timer.h>
namespace Swift {
class DummyTimerFactory::DummyTimer : public Timer {
- public:
- DummyTimer(int timeout, DummyTimerFactory* factory) : timeout(timeout), factory(factory), isRunning(false), startTime(~0) {
- }
-
- virtual void start() {
- isRunning = true;
- startTime = factory->currentTime;
- }
-
- virtual void stop() {
- isRunning = false;
- }
-
- int getAlarmTime() const {
- return startTime + timeout;
- }
-
- int timeout;
- DummyTimerFactory* factory;
- bool isRunning;
- int startTime;
+ public:
+ DummyTimer(int timeout, DummyTimerFactory* factory) : timeout(timeout), factory(factory), isRunning(false), startTime(~0) {
+ }
+
+ virtual void start() {
+ isRunning = true;
+ startTime = factory->currentTime;
+ }
+
+ virtual void stop() {
+ isRunning = false;
+ }
+
+ int getAlarmTime() const {
+ return startTime + timeout;
+ }
+
+ int timeout;
+ DummyTimerFactory* factory;
+ bool isRunning;
+ int startTime;
};
DummyTimerFactory::DummyTimerFactory() : currentTime(0) {
}
-boost::shared_ptr<Timer> DummyTimerFactory::createTimer(int milliseconds) {
- boost::shared_ptr<DummyTimer> timer(new DummyTimer(milliseconds, this));
- timers.push_back(timer);
- return timer;
+std::shared_ptr<Timer> DummyTimerFactory::createTimer(int milliseconds) {
+ std::shared_ptr<DummyTimer> timer(new DummyTimer(milliseconds, this));
+ timers.push_back(timer);
+ return timer;
}
void DummyTimerFactory::setTime(int time) {
- assert(time > currentTime);
- foreach(boost::shared_ptr<DummyTimer> timer, timers) {
- if (timer->getAlarmTime() > currentTime && timer->getAlarmTime() <= time && timer->isRunning) {
- timer->onTick();
- }
- }
- currentTime = time;
+ assert(time > currentTime);
+ for (auto&& 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..5ccbf93 100644
--- a/Swiften/Network/DummyTimerFactory.h
+++ b/Swiften/Network/DummyTimerFactory.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::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<std::shared_ptr<DummyTimer> > timers;
+ };
}
diff --git a/Swiften/Network/EnvironmentProxyProvider.cpp b/Swiften/Network/EnvironmentProxyProvider.cpp
index 7701da1..8edb136 100644
--- a/Swiften/Network/EnvironmentProxyProvider.cpp
+++ b/Swiften/Network/EnvironmentProxyProvider.cpp
@@ -4,45 +4,53 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swiften/Network/EnvironmentProxyProvider.h>
+
#include <stdio.h>
#include <stdlib.h>
+
#include <iostream>
#include <Swiften/Base/Log.h>
-#include <Swiften/Network/EnvironmentProxyProvider.h>
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 = nullptr;
+ 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 != nullptr ? envVar : "0.0.0.0";
+ if(envVar != nullptr && 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::fromString(address).get_value_or(HostAddress()), 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..08c1d75 100644
--- a/Swiften/Network/FakeConnection.h
+++ b/Swiften/Network/FakeConnection.h
@@ -1,14 +1,14 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <vector>
-#include <boost/enable_shared_from_this.hpp>
#include <boost/optional.hpp>
#include <Swiften/Base/API.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 std::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 8d97c68..35303d5 100644
--- a/Swiften/Network/GConfProxyProvider.cpp
+++ b/Swiften/Network/GConfProxyProvider.cpp
@@ -4,55 +4,63 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swiften/Network/GConfProxyProvider.h>
+
#include <stdio.h>
#include <stdlib.h>
+
#include <iostream>
#include <gconf/gconf-client.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Network/GConfProxyProvider.h>
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..b5e521b 100644
--- a/Swiften/Network/HTTPConnectProxiedConnection.cpp
+++ b/Swiften/Network/HTTPConnectProxiedConnection.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -24,7 +24,6 @@
#include <Swiften/Base/ByteArray.h>
#include <Swiften/Base/Log.h>
#include <Swiften/Base/String.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Network/ConnectionFactory.h>
#include <Swiften/Network/HTTPTrafficFilter.h>
#include <Swiften/Network/HostAddressPort.h>
@@ -33,133 +32,131 @@
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() {
}
-void HTTPConnectProxiedConnection::setHTTPTrafficFilter(boost::shared_ptr<HTTPTrafficFilter> trafficFilter) {
- trafficFilter_ = trafficFilter;
+void HTTPConnectProxiedConnection::setHTTPTrafficFilter(std::shared_ptr<HTTPTrafficFilter> trafficFilter) {
+ trafficFilter_ = trafficFilter;
}
void HTTPConnectProxiedConnection::initializeProxy() {
- httpResponseBuffer_.clear();
-
- std::stringstream connect;
- connect << "CONNECT " << getServer().getAddress().toString() << ":" << getServer().getPort() << " HTTP/1.1\r\n";
- SafeByteArray data = createSafeByteArray(connect.str());
- if (!authID_.empty() && !authPassword_.empty()) {
- append(data, createSafeByteArray("Proxy-Authorization: Basic "));
- SafeByteArray credentials = authID_;
- append(credentials, createSafeByteArray(":"));
- append(credentials, authPassword_);
- append(data, Base64::encode(credentials));
- append(data, createSafeByteArray("\r\n"));
- }
- else if (!nextHTTPRequestHeaders_.empty()) {
- typedef std::pair<std::string, std::string> StringPair;
- foreach(const StringPair& headerField, nextHTTPRequestHeaders_) {
- 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()) {
+ for (const auto& headerField : nextHTTPRequestHeaders_) {
+ append(data, createSafeByteArray(headerField.first));
+ append(data, createSafeByteArray(": "));
+ append(data, createSafeByteArray(headerField.second));
+ append(data, createSafeByteArray("\r\n"));
+ }
+
+ nextHTTPRequestHeaders_.clear();
+ }
+ append(data, createSafeByteArray("\r\n"));
+ SWIFT_LOG(debug) << "HTTP Proxy send headers: " << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl;
+ write(data);
}
void HTTPConnectProxiedConnection::parseHTTPHeader(const std::string& data, std::string& statusLine, std::vector<std::pair<std::string, std::string> >& headerFields) {
- std::istringstream dataStream(data);
-
- // parse status line
- std::getline(dataStream, statusLine);
-
- // parse fields
- std::string headerLine;
- std::string::size_type splitIndex;
- while (std::getline(dataStream, headerLine) && headerLine != "\r") {
- splitIndex = headerLine.find(':', 0);
- if (splitIndex != std::string::npos) {
- headerFields.push_back(std::pair<std::string, std::string>(headerLine.substr(0, splitIndex), headerLine.substr(splitIndex + 1)));
- }
- }
+ 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()));
+ std::stringstream request;
+
+ request << statusLine << "\r\n";
+ for (const auto& 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();
+void HTTPConnectProxiedConnection::handleProxyInitializeData(std::shared_ptr<SafeByteArray> data) {
+ std::string dataString = byteArrayToString(ByteArray(data->begin(), data->end()));
+ SWIFT_LOG(debug) << data << std::endl;
+ httpResponseBuffer_.append(dataString);
+
+ std::string statusLine;
+ std::vector<std::pair<std::string, std::string> > headerFields;
+
+ std::string::size_type headerEnd = httpResponseBuffer_.find("\r\n\r\n", 0);
+ if (headerEnd == std::string::npos) {
+ if ((httpResponseBuffer_.size() > 4) && (httpResponseBuffer_.substr(0, 4) != "HTTP")) {
+ setProxyInitializeFinished(false);
+ }
+ return;
+ }
+
+ parseHTTPHeader(httpResponseBuffer_.substr(0, headerEnd), statusLine, headerFields);
+
+ if (trafficFilter_) {
+ std::vector<std::pair<std::string, std::string> > newHeaderFields = trafficFilter_->filterHTTPResponseHeader(statusLine, headerFields);
+ if (!newHeaderFields.empty()) {
+ std::stringstream statusLine;
+ reconnect();
+ nextHTTPRequestHeaders_ = newHeaderFields;
+ 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..21b3960 100644
--- a/Swiften/Network/HTTPConnectProxiedConnection.h
+++ b/Swiften/Network/HTTPConnectProxiedConnection.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,44 +13,44 @@
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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 std::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(std::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(std::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_;
+ std::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..91ace3d 100644
--- a/Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp
+++ b/Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -16,17 +16,17 @@
namespace Swift {
-HTTPConnectProxiedConnectionFactory::HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter) : resolver_(resolver), connectionFactory_(connectionFactory), timerFactory_(timerFactory), proxyHost_(proxyHost), proxyPort_(proxyPort), authID_(""), authPassword_(""), httpTrafficFilter_(httpTrafficFilter) {
+HTTPConnectProxiedConnectionFactory::HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter) : resolver_(resolver), connectionFactory_(connectionFactory), timerFactory_(timerFactory), proxyHost_(proxyHost), proxyPort_(proxyPort), authID_(""), authPassword_(""), httpTrafficFilter_(httpTrafficFilter) {
}
-HTTPConnectProxiedConnectionFactory::HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword, boost::shared_ptr<HTTPTrafficFilter> httpTrafficFilter) : resolver_(resolver), connectionFactory_(connectionFactory), timerFactory_(timerFactory), proxyHost_(proxyHost), proxyPort_(proxyPort), authID_(authID), authPassword_(authPassword), httpTrafficFilter_(httpTrafficFilter) {
+HTTPConnectProxiedConnectionFactory::HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword, std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter) : resolver_(resolver), connectionFactory_(connectionFactory), timerFactory_(timerFactory), proxyHost_(proxyHost), proxyPort_(proxyPort), authID_(authID), authPassword_(authPassword), httpTrafficFilter_(httpTrafficFilter) {
}
-boost::shared_ptr<Connection> HTTPConnectProxiedConnectionFactory::createConnection() {
- HTTPConnectProxiedConnection::ref proxyConnection = HTTPConnectProxiedConnection::create(resolver_, connectionFactory_, timerFactory_, proxyHost_, proxyPort_, authID_, authPassword_);
- proxyConnection->setHTTPTrafficFilter(httpTrafficFilter_);
- return proxyConnection;
+std::shared_ptr<Connection> HTTPConnectProxiedConnectionFactory::createConnection() {
+ 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 9d2c982..74d6279 100644
--- a/Swiften/Network/HTTPConnectProxiedConnectionFactory.h
+++ b/Swiften/Network/HTTPConnectProxiedConnectionFactory.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,31 +13,31 @@
#pragma once
#include <Swiften/Base/API.h>
+#include <Swiften/Base/SafeString.h>
#include <Swiften/Network/ConnectionFactory.h>
#include <Swiften/Network/HostAddressPort.h>
-#include <Swiften/Base/SafeString.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, std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter = std::shared_ptr<HTTPTrafficFilter>());
+ HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword, std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter = std::shared_ptr<HTTPTrafficFilter>());
- virtual boost::shared_ptr<Connection> createConnection();
+ virtual std::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_;
+ std::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 c9de1f0..6eca80b 100644
--- a/Swiften/Network/HostAddress.cpp
+++ b/Swiften/Network/HostAddress.cpp
@@ -1,20 +1,17 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/HostAddress.h>
-#include <boost/numeric/conversion/cast.hpp>
-#include <boost/lexical_cast.hpp>
#include <cassert>
-#include <stdexcept>
-#include <boost/array.hpp>
-
-#include <Swiften/Base/foreach.h>
+#include <cstring>
#include <string>
+#include <Swiften/Base/Log.h>
+
static boost::asio::ip::address localhost4 = boost::asio::ip::address(boost::asio::ip::address_v4::loopback());
static boost::asio::ip::address localhost6 = boost::asio::ip::address(boost::asio::ip::address_v6::loopback());
@@ -23,49 +20,55 @@ namespace Swift {
HostAddress::HostAddress() {
}
-HostAddress::HostAddress(const std::string& address) {
- 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;
+ std::memcpy(data.data(), address, length);
+ address_ = boost::asio::ip::address(boost::asio::ip::address_v4(data));
+ }
+ else {
+ boost::asio::ip::address_v6::bytes_type data;
+ std::memcpy(data.data(), address, length);
+ 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();
+ std::string addressString;
+ boost::system::error_code errorCode;
+
+ addressString = address_.to_string(errorCode);
+ if (errorCode) {
+ SWIFT_LOG(debug) << "error: " << errorCode.message() << std::endl;
+ }
+
+ return addressString;
}
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;
+}
+
+boost::optional<HostAddress> HostAddress::fromString(const std::string& addressString) {
+ boost::optional<HostAddress> hostAddress;
+ boost::system::error_code errorCode;
+ boost::asio::ip::address address = boost::asio::ip::address::from_string(addressString, errorCode);
+ if (!errorCode) {
+ hostAddress = HostAddress(address);
+ }
+ return hostAddress;
}
}
diff --git a/Swiften/Network/HostAddress.h b/Swiften/Network/HostAddress.h
index 57c34f0..e4ddffb 100644
--- a/Swiften/Network/HostAddress.h
+++ b/Swiften/Network/HostAddress.h
@@ -1,34 +1,38 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+
#pragma once
#include <string>
+
#include <boost/asio/ip/address.hpp>
+#include <boost/optional.hpp>
#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 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;
+
+ static boost::optional<HostAddress> fromString(const std::string& addressString);
+
+ 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 325ef06..81c0995 100644
--- a/Swiften/Network/HostNameOrAddress.h
+++ b/Swiften/Network/HostNameOrAddress.h
@@ -1,16 +1,18 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
#include <string>
-#include <Swiften/Network/HostAddress.h>
+
#include <boost/variant.hpp>
+#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..232fc60 100644
--- a/Swiften/Network/MacOSXProxyProvider.cpp
+++ b/Swiften/Network/MacOSXProxyProvider.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -16,9 +16,10 @@
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
-#include <boost/numeric/conversion/cast.hpp>
#include <utility>
+#include <boost/numeric/conversion/cast.hpp>
+
#ifndef SWIFTEN_PLATFORM_IPHONE
#include <SystemConfiguration/SystemConfiguration.h>
#endif
@@ -29,49 +30,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 = nullptr;
+ 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, nullptr);
+ CFRelease(zero);
+
+ if(result != kCFCompareEqualTo) {
+ int port = 0;
+ std::string host = "";
+
+ try {
+ CFNumberRef numberValue = reinterpret_cast<CFNumberRef> (CFDictionaryGetValue(dict, portKey));
+ if(numberValue != nullptr) {
+ CFNumberGetValue(numberValue, kCFNumberIntType, &port);
+ }
+
+ CFStringRef stringValue = reinterpret_cast<CFStringRef> (CFDictionaryGetValue(dict, hostKey));
+ if(stringValue != nullptr) {
+ 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(char& iter : buffer) {
+ host += iter;
+ }
+ }
+ }
+ }
+ catch(...) {
+ std::cerr << "Exception caught ... " << std::endl;
+ }
+
+ if(host != "" && port != 0) {
+ ret = HostAddressPort(HostAddress::fromString(host).get(), port);
+ }
+ }
+ }
+ return ret;
}
#endif
namespace Swift {
@@ -80,27 +81,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(nullptr);
+ if(proxies != nullptr) {
+ 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(nullptr);
+ if(proxies != nullptr) {
+ 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 6666d30..56ffd9f 100644
--- a/Swiften/Network/MacOSXProxyProvider.h
+++ b/Swiften/Network/MacOSXProxyProvider.h
@@ -4,15 +4,23 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <Swiften/Network/ProxyProvider.h>
+
#include <CoreFoundation/CoreFoundation.h>
+#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 357fe69..dbe8bcd 100644
--- a/Swiften/Network/MiniUPnPInterface.cpp
+++ b/Swiften/Network/MiniUPnPInterface.cpp
@@ -5,112 +5,118 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/MiniUPnPInterface.h>
+#include <memory>
+
+#include <boost/lexical_cast.hpp>
+
#include <miniupnpc.h>
#include <upnpcommands.h>
#include <upnperrors.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <boost/lexical_cast.hpp>
#include <Swiften/Base/Log.h>
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;
+MiniUPnPInterface::MiniUPnPInterface() : p(new Private()) {
+ p->isValid = false;
+ int error = 0;
+#if MINIUPNPC_API_VERSION > 13
+ p->deviceList = upnpDiscover(1500 /* timeout in ms */, nullptr, nullptr, 0, 0 /* do IPv6? */, 2 /* default TTL */, &error);
+#else
+ p->deviceList = upnpDiscover(1500 /* timeout in ms */, nullptr, nullptr, 0, 0 /* do IPv6? */, &error);
+#endif
+ 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::fromString(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",
+ nullptr,
+ 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", nullptr);
+ 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..89457b8 100644
--- a/Swiften/Network/MiniUPnPInterface.h
+++ b/Swiften/Network/MiniUPnPInterface.h
@@ -6,27 +6,28 @@
#pragma once
+#include <memory>
+
#include <boost/noncopyable.hpp>
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Network/NATPortMapping.h>
#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;
+ const std::unique_ptr<Private> p;
+ };
}
diff --git a/Swiften/Network/NATPMPInterface.cpp b/Swiften/Network/NATPMPInterface.cpp
index 064cfc8..5e0b3b3 100644
--- a/Swiften/Network/NATPMPInterface.cpp
+++ b/Swiften/Network/NATPMPInterface.cpp
@@ -5,14 +5,15 @@
*/
/*
-* Copyright (c) 2014 Isode Limited.
-* All rights reserved.v3.
-* See the COPYING file for more information.
-*/
+ * Copyright (c) 2014-2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
#include <Swiften/Network/NATPMPInterface.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
#include <Swiften/Base/Log.h>
@@ -26,117 +27,117 @@
namespace Swift {
struct NATPMPInterface::Private {
- natpmp_t natpmp;
+ natpmp_t natpmp;
};
-NATPMPInterface::NATPMPInterface() : p(boost::make_shared<Private>()) {
- initnatpmp(&p->natpmp, 0, 0);
+NATPMPInterface::NATPMPInterface() : p(new Private()) {
+ 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, nullptr, nullptr, &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, nullptr, nullptr, &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, nullptr, nullptr, &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..e1666c8 100644
--- a/Swiften/Network/NATPMPInterface.h
+++ b/Swiften/Network/NATPMPInterface.h
@@ -6,27 +6,28 @@
#pragma once
+#include <memory>
+
#include <boost/noncopyable.hpp>
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Network/NATPortMapping.h>
#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;
+ const std::unique_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 48f85ea..0f9c62c 100644
--- a/Swiften/Network/NATTraversalForwardPortRequest.h
+++ b/Swiften/Network/NATTraversalForwardPortRequest.h
@@ -4,21 +4,27 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#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::signals2::signal<void (boost::optional<NATPortMapping>)> onResult;
+ };
}
diff --git a/Swiften/Network/NATTraversalGetPublicIPRequest.h b/Swiften/Network/NATTraversalGetPublicIPRequest.h
index 725afd2..8b34e0f 100644
--- a/Swiften/Network/NATTraversalGetPublicIPRequest.h
+++ b/Swiften/Network/NATTraversalGetPublicIPRequest.h
@@ -5,25 +5,26 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#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::signals2::signal<void (boost::optional<HostAddress>)> onResult;
+ };
}
diff --git a/Swiften/Network/NATTraversalInterface.cpp b/Swiften/Network/NATTraversalInterface.cpp
index 333fbf9..18ee843 100644
--- a/Swiften/Network/NATTraversalInterface.cpp
+++ b/Swiften/Network/NATTraversalInterface.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
@@ -8,7 +8,6 @@
#include <Swiften/Base/Log.h>
-
namespace Swift {
NATTraversalInterface::~NATTraversalInterface() {
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..3db9ee1 100644
--- a/Swiften/Network/NATTraversalRemovePortForwardingRequest.h
+++ b/Swiften/Network/NATTraversalRemovePortForwardingRequest.h
@@ -5,38 +5,39 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#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::signals2::signal<void (boost::optional<bool> /* failure */)> onResult;
+ };
}
diff --git a/Swiften/Network/NATTraverser.h b/Swiften/Network/NATTraverser.h
index e86704a..716bfcb 100644
--- a/Swiften/Network/NATTraverser.h
+++ b/Swiften/Network/NATTraverser.h
@@ -1,26 +1,26 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#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 std::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest() = 0;
+ virtual std::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort) = 0;
+ virtual std::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort) = 0;
+ };
}
diff --git a/Swiften/Network/NetworkEnvironment.cpp b/Swiften/Network/NetworkEnvironment.cpp
index 75fa15d..87883c1 100644
--- a/Swiften/Network/NetworkEnvironment.cpp
+++ b/Swiften/Network/NetworkEnvironment.cpp
@@ -1,14 +1,13 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/NetworkEnvironment.h>
-#include <Swiften/Network/NetworkInterface.h>
#include <Swiften/Network/HostAddress.h>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Network/NetworkInterface.h>
namespace Swift {
@@ -16,17 +15,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();
+ for (const auto& iface : networkInterfaces) {
+ if (!iface.isLoopback()) {
+ for (const auto& 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..0f68c29 100644
--- a/Swiften/Network/NetworkEnvironment.h
+++ b/Swiften/Network/NetworkEnvironment.h
@@ -4,21 +4,28 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <vector>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#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 b4ae66b..cc8bae0 100644
--- a/Swiften/Network/NullNATTraverser.cpp
+++ b/Swiften/Network/NullNATTraverser.cpp
@@ -1,82 +1,83 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/NullNATTraverser.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <Swiften/Network/NATTraversalGetPublicIPRequest.h>
+#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/Network/NATTraversalForwardPortRequest.h>
+#include <Swiften/Network/NATTraversalGetPublicIPRequest.h>
#include <Swiften/Network/NATTraversalRemovePortForwardingRequest.h>
-#include <Swiften/EventLoop/EventLoop.h>
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);
+std::shared_ptr<NATTraversalGetPublicIPRequest> NullNATTraverser::createGetPublicIPRequest() {
+ return std::make_shared<NullNATTraversalGetPublicIPRequest>(eventLoop);
}
-boost::shared_ptr<NATTraversalForwardPortRequest> NullNATTraverser::createForwardPortRequest(int, int) {
- return boost::make_shared<NullNATTraversalForwardPortRequest>(eventLoop);
+std::shared_ptr<NATTraversalForwardPortRequest> NullNATTraverser::createForwardPortRequest(int, int) {
+ return std::make_shared<NullNATTraversalForwardPortRequest>(eventLoop);
}
-boost::shared_ptr<NATTraversalRemovePortForwardingRequest> NullNATTraverser::createRemovePortForwardingRequest(int, int) {
- return boost::make_shared<NullNATTraversalRemovePortForwardingRequest>(eventLoop);
+std::shared_ptr<NATTraversalRemovePortForwardingRequest> NullNATTraverser::createRemovePortForwardingRequest(int, int) {
+ return std::make_shared<NullNATTraversalRemovePortForwardingRequest>(eventLoop);
}
}
diff --git a/Swiften/Network/NullNATTraverser.h b/Swiften/Network/NullNATTraverser.h
index 3e388d9..d3a6640 100644
--- a/Swiften/Network/NullNATTraverser.h
+++ b/Swiften/Network/NullNATTraverser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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);
+ std::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest();
+ std::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort);
+ std::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..6cb3e0a 100644
--- a/Swiften/Network/PlatformDomainNameAddressQuery.h
+++ b/Swiften/Network/PlatformDomainNameAddressQuery.h
@@ -1,41 +1,41 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
#include <boost/asio/io_service.hpp>
-#include <boost/enable_shared_from_this.hpp>
#include <Swiften/EventLoop/EventOwner.h>
#include <Swiften/Network/DomainNameAddressQuery.h>
#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 std::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..a279f20 100644
--- a/Swiften/Network/PlatformDomainNameQuery.h
+++ b/Swiften/Network/PlatformDomainNameQuery.h
@@ -1,31 +1,31 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
namespace Swift {
- class PlatformDomainNameResolver;
+ class PlatformDomainNameResolver;
- class PlatformDomainNameQuery {
- public:
- typedef boost::shared_ptr<PlatformDomainNameQuery> ref;
+ class PlatformDomainNameQuery {
+ public:
+ typedef std::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..40e385d 100644
--- a/Swiften/Network/PlatformDomainNameResolver.cpp
+++ b/Swiften/Network/PlatformDomainNameResolver.cpp
@@ -1,81 +1,80 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/PlatformDomainNameResolver.h>
-// Putting this early on, because some system types conflict with thread
-#include <Swiften/Network/PlatformDomainNameServiceQuery.h>
-
+#include <algorithm>
+#include <mutex>
#include <string>
+#include <thread>
#include <vector>
+
#include <boost/bind.hpp>
-#include <boost/thread.hpp>
-#include <algorithm>
-#include <string>
+#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/IDN/IDNConverter.h>
+#include <Swiften/Network/DomainNameAddressQuery.h>
#include <Swiften/Network/HostAddress.h>
-#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/Network/HostAddressPort.h>
-#include <Swiften/Network/DomainNameAddressQuery.h>
#include <Swiften/Network/PlatformDomainNameAddressQuery.h>
+#include <Swiften/Network/PlatformDomainNameServiceQuery.h>
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 std::thread(boost::bind(&PlatformDomainNameResolver::run, this));
}
PlatformDomainNameResolver::~PlatformDomainNameResolver() {
- stopRequested = true;
- addQueryToQueue(boost::shared_ptr<PlatformDomainNameQuery>());
- thread->join();
- delete thread;
+ stopRequested = true;
+ addQueryToQueue(std::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));
+std::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 std::make_shared<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));
+std::shared_ptr<DomainNameAddressQuery> PlatformDomainNameResolver::createAddressQuery(const std::string& name) {
+ return std::make_shared<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;
+ {
+ std::unique_lock<std::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();
+ {
+ std::lock_guard<std::mutex> lock(queueMutex);
+ queue.push_back(query);
+ }
+ queueNonEmpty.notify_one();
}
}
diff --git a/Swiften/Network/PlatformDomainNameResolver.h b/Swiften/Network/PlatformDomainNameResolver.h
index ae94179..4ddb999 100644
--- a/Swiften/Network/PlatformDomainNameResolver.h
+++ b/Swiften/Network/PlatformDomainNameResolver.h
@@ -1,16 +1,15 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <condition_variable>
#include <deque>
-
-#include <boost/thread/condition_variable.hpp>
-#include <boost/thread/mutex.hpp>
-#include <boost/thread/thread.hpp>
+#include <mutex>
+#include <thread>
#include <Swiften/Base/API.h>
#include <Swiften/Base/Atomic.h>
@@ -20,30 +19,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;
+ std::thread* thread;
+ std::deque<PlatformDomainNameQuery::ref> queue;
+ std::mutex queueMutex;
+ std::condition_variable queueNonEmpty;
+ };
}
diff --git a/Swiften/Network/PlatformDomainNameServiceQuery.cpp b/Swiften/Network/PlatformDomainNameServiceQuery.cpp
index 673aaff..5cffcdb 100644
--- a/Swiften/Network/PlatformDomainNameServiceQuery.cpp
+++ b/Swiften/Network/PlatformDomainNameServiceQuery.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -29,7 +29,6 @@
#include <Swiften/Base/ByteArray.h>
#include <Swiften/EventLoop/EventLoop.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/BoostRandomGenerator.h>
#include <Swiften/Base/Log.h>
#include <Swiften/Network/PlatformDomainNameResolver.h>
@@ -39,148 +38,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..0d690f3 100644
--- a/Swiften/Network/PlatformDomainNameServiceQuery.h
+++ b/Swiften/Network/PlatformDomainNameServiceQuery.h
@@ -1,36 +1,35 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
-#include <boost/enable_shared_from_this.hpp>
-
#include <Swiften/EventLoop/EventOwner.h>
#include <Swiften/Network/DomainNameServiceQuery.h>
#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 std::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..f56de0b 100644
--- a/Swiften/Network/PlatformNATTraversalWorker.cpp
+++ b/Swiften/Network/PlatformNATTraversalWorker.cpp
@@ -4,10 +4,16 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "PlatformNATTraversalWorker.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swiften/Network/PlatformNATTraversalWorker.h>
+
+#include <memory>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <boost/enable_shared_from_this.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <Swiften/Base/Log.h>
@@ -25,194 +31,194 @@
namespace Swift {
-class PlatformNATTraversalRequest : public boost::enable_shared_from_this<PlatformNATTraversalRequest>, public EventOwner {
- public:
- typedef boost::shared_ptr<PlatformNATTraversalRequest> ref;
+class PlatformNATTraversalRequest : public std::enable_shared_from_this<PlatformNATTraversalRequest>, public EventOwner {
+ public:
+ typedef std::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));
+PlatformNATTraversalWorker::PlatformNATTraversalWorker(EventLoop* eventLoop) : eventLoop(eventLoop), stopRequested(false), natPMPSupported(boost::logic::indeterminate), natPMPInterface(nullptr), miniUPnPSupported(boost::logic::indeterminate), miniUPnPInterface(nullptr) {
+ nullNATTraversalInterface = new NullNATTraversalInterface();
+ // FIXME: This should be done from start(), and the current start() should be an internal method
+ thread = new std::thread(boost::bind(&PlatformNATTraversalWorker::start, this));
}
PlatformNATTraversalWorker::~PlatformNATTraversalWorker() {
- stopRequested = true;
- addRequestToQueue(boost::shared_ptr<PlatformNATTraversalRequest>());
- thread->join();
- delete thread;
+ stopRequested = true;
+ addRequestToQueue(std::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);
+std::shared_ptr<NATTraversalGetPublicIPRequest> PlatformNATTraversalWorker::createGetPublicIPRequest() {
+ return std::make_shared<PlatformNATTraversalGetPublicIPRequest>(this);
}
-boost::shared_ptr<NATTraversalForwardPortRequest> PlatformNATTraversalWorker::createForwardPortRequest(int localPort, int publicPort) {
- return boost::make_shared<PlatformNATTraversalForwardPortRequest>(this, localPort, publicPort);
+std::shared_ptr<NATTraversalForwardPortRequest> PlatformNATTraversalWorker::createForwardPortRequest(int localPort, int publicPort) {
+ return std::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);
+std::shared_ptr<NATTraversalRemovePortForwardingRequest> PlatformNATTraversalWorker::createRemovePortForwardingRequest(int localPort, int publicPort) {
+ NATPortMapping mapping(localPort, publicPort, NATPortMapping::TCP); // FIXME
+ return std::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;
+ {
+ std::unique_lock<std::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();
+ {
+ std::lock_guard<std::mutex> lock(queueMutex);
+ queue.push_back(request);
+ }
+ queueNonEmpty.notify_one();
}
}
diff --git a/Swiften/Network/PlatformNATTraversalWorker.h b/Swiften/Network/PlatformNATTraversalWorker.h
index 2c03dca..3607dac 100644
--- a/Swiften/Network/PlatformNATTraversalWorker.h
+++ b/Swiften/Network/PlatformNATTraversalWorker.h
@@ -12,13 +12,13 @@
#pragma once
+#include <condition_variable>
#include <deque>
+#include <mutex>
+#include <thread>
#include <boost/logic/tribool.hpp>
#include <boost/optional.hpp>
-#include <boost/thread/condition_variable.hpp>
-#include <boost/thread/mutex.hpp>
-#include <boost/thread/thread.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/Atomic.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);
+ std::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest();
+ std::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort);
+ std::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(std::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;
+ std::thread* thread;
+ std::deque<std::shared_ptr<PlatformNATTraversalRequest> > queue;
+ std::mutex queueMutex;
+ std::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 c44c1f5..aa6c4d2 100644
--- a/Swiften/Network/ProxiedConnection.cpp
+++ b/Swiften/Network/ProxiedConnection.cpp
@@ -1,126 +1,127 @@
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-
#include <Swiften/Network/ProxiedConnection.h>
-#include <iostream>
-
#include <boost/bind.hpp>
#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/Log.h>
#include <Swiften/Network/ConnectionFactory.h>
#include <Swiften/Network/HostAddressPort.h>
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::fromString("0.0.0.0").get(), 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_) {
- std::cerr << "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() {
- connected_ = false;
- 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);
- }
+void ProxiedConnection::handleDataRead(std::shared_ptr<SafeByteArray> 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..38194aa 100644
--- a/Swiften/Network/ProxiedConnection.h
+++ b/Swiften/Network/ProxiedConnection.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,7 +7,7 @@
#pragma once
-#include <boost/enable_shared_from_this.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Base/SafeString.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 std::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(std::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(std::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_;
+ std::shared_ptr<Connection> connection_;
+ };
}
diff --git a/Swiften/Network/ProxyProvider.cpp b/Swiften/Network/ProxyProvider.cpp
index fe235b1..dd07d3a 100644
--- a/Swiften/Network/ProxyProvider.cpp
+++ b/Swiften/Network/ProxyProvider.cpp
@@ -4,7 +4,13 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "ProxyProvider.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swiften/Network/ProxyProvider.h>
namespace Swift {
diff --git a/Swiften/Network/ProxyProvider.h b/Swiften/Network/ProxyProvider.h
index b5e3eca..bf737c0 100644
--- a/Swiften/Network/ProxyProvider.h
+++ b/Swiften/Network/ProxyProvider.h
@@ -5,25 +5,26 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+
#include <map>
-#include <Swiften/Network/HostAddressPort.h>
-#include <Swiften/Base/String.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/String.h>
+#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/SConscript b/Swiften/Network/SConscript
index e9da1bc..9c2a134 100644
--- a/Swiften/Network/SConscript
+++ b/Swiften/Network/SConscript
@@ -3,109 +3,109 @@ Import("swiften_env")
myenv = swiften_env.Clone()
if myenv.get("unbound", False) :
- myenv.MergeFlags(myenv.get("UNBOUND_FLAGS", {}))
- myenv.MergeFlags(myenv.get("LDNS_FLAGS", {}))
+ myenv.MergeFlags(myenv.get("UNBOUND_FLAGS", {}))
+ myenv.MergeFlags(myenv.get("LDNS_FLAGS", {}))
sourceList = [
- "ProxiedConnection.cpp",
- "HTTPConnectProxiedConnection.cpp",
- "HTTPConnectProxiedConnectionFactory.cpp",
- "SOCKS5ProxiedConnection.cpp",
- "SOCKS5ProxiedConnectionFactory.cpp",
- "BoostConnection.cpp",
- "BoostConnectionFactory.cpp",
- "BoostConnectionServer.cpp",
- "BoostConnectionServerFactory.cpp",
- "BoostIOServiceThread.cpp",
- "BOSHConnection.cpp",
- "BOSHConnectionPool.cpp",
- "CachingDomainNameResolver.cpp",
- "ConnectionFactory.cpp",
- "ConnectionServer.cpp",
- "ConnectionServerFactory.cpp",
- "DummyConnection.cpp",
- "FakeConnection.cpp",
- "ChainedConnector.cpp",
- "Connector.cpp",
- "Connection.cpp",
- "TimerFactory.cpp",
- "DummyTimerFactory.cpp",
- "BoostTimerFactory.cpp",
- "DomainNameResolver.cpp",
- "DomainNameAddressQuery.cpp",
- "DomainNameServiceQuery.cpp",
- "StaticDomainNameResolver.cpp",
- "HostAddress.cpp",
- "HostAddressPort.cpp",
- "HostNameOrAddress.cpp",
- "NetworkFactories.cpp",
- "BoostNetworkFactories.cpp",
- "NetworkEnvironment.cpp",
- "Timer.cpp",
- "TLSConnection.cpp",
- "TLSConnectionFactory.cpp",
- "BoostTimer.cpp",
- "ProxyProvider.cpp",
- "NullProxyProvider.cpp",
- "NATTraverser.cpp",
- "NullNATTraverser.cpp",
- "NATTraversalGetPublicIPRequest.cpp",
- "NATTraversalForwardPortRequest.cpp",
- "NATTraversalRemovePortForwardingRequest.cpp",
- "NATTraversalInterface.cpp",
- "HTTPTrafficFilter.cpp",
- ]
+ "ProxiedConnection.cpp",
+ "HTTPConnectProxiedConnection.cpp",
+ "HTTPConnectProxiedConnectionFactory.cpp",
+ "SOCKS5ProxiedConnection.cpp",
+ "SOCKS5ProxiedConnectionFactory.cpp",
+ "BoostConnection.cpp",
+ "BoostConnectionFactory.cpp",
+ "BoostConnectionServer.cpp",
+ "BoostConnectionServerFactory.cpp",
+ "BoostIOServiceThread.cpp",
+ "BOSHConnection.cpp",
+ "BOSHConnectionPool.cpp",
+ "CachingDomainNameResolver.cpp",
+ "ConnectionFactory.cpp",
+ "ConnectionServer.cpp",
+ "ConnectionServerFactory.cpp",
+ "DummyConnection.cpp",
+ "FakeConnection.cpp",
+ "ChainedConnector.cpp",
+ "Connector.cpp",
+ "Connection.cpp",
+ "TimerFactory.cpp",
+ "DummyTimerFactory.cpp",
+ "BoostTimerFactory.cpp",
+ "DomainNameResolver.cpp",
+ "DomainNameAddressQuery.cpp",
+ "DomainNameServiceQuery.cpp",
+ "StaticDomainNameResolver.cpp",
+ "HostAddress.cpp",
+ "HostAddressPort.cpp",
+ "HostNameOrAddress.cpp",
+ "NetworkFactories.cpp",
+ "BoostNetworkFactories.cpp",
+ "NetworkEnvironment.cpp",
+ "Timer.cpp",
+ "TLSConnection.cpp",
+ "TLSConnectionFactory.cpp",
+ "BoostTimer.cpp",
+ "ProxyProvider.cpp",
+ "NullProxyProvider.cpp",
+ "NATTraverser.cpp",
+ "NullNATTraverser.cpp",
+ "NATTraversalGetPublicIPRequest.cpp",
+ "NATTraversalForwardPortRequest.cpp",
+ "NATTraversalRemovePortForwardingRequest.cpp",
+ "NATTraversalInterface.cpp",
+ "HTTPTrafficFilter.cpp",
+ ]
if myenv.get("unbound", False) :
- myenv.Append(CPPDEFINES = "USE_UNBOUND")
- sourceList.append("UnboundDomainNameResolver.cpp")
+ myenv.Append(CPPDEFINES = "USE_UNBOUND")
+ sourceList.append("UnboundDomainNameResolver.cpp")
else :
- sourceList.append("PlatformDomainNameResolver.cpp")
- sourceList.append("PlatformDomainNameServiceQuery.cpp")
- sourceList.append("PlatformDomainNameAddressQuery.cpp")
+ sourceList.append("PlatformDomainNameResolver.cpp")
+ sourceList.append("PlatformDomainNameServiceQuery.cpp")
+ sourceList.append("PlatformDomainNameAddressQuery.cpp")
if myenv["PLATFORM"] == "darwin" and myenv["target"] != "android":
- myenv.Append(FRAMEWORKS = ["CoreServices", "SystemConfiguration"])
- sourceList += [ "MacOSXProxyProvider.cpp" ]
- sourceList += [ "UnixNetworkEnvironment.cpp" ]
+ myenv.Append(FRAMEWORKS = ["CoreServices", "SystemConfiguration"])
+ sourceList += [ "MacOSXProxyProvider.cpp" ]
+ sourceList += [ "UnixNetworkEnvironment.cpp" ]
elif myenv["PLATFORM"] == "win32" :
- sourceList += [ "WindowsProxyProvider.cpp" ]
- sourceList += [ "WindowsNetworkEnvironment.cpp" ]
+ sourceList += [ "WindowsProxyProvider.cpp" ]
+ sourceList += [ "WindowsNetworkEnvironment.cpp" ]
elif myenv["PLATFORM"] == "sunos" :
- sourceList += [ "UnixProxyProvider.cpp" ]
- sourceList += [ "SolarisNetworkEnvironment.cpp" ]
- sourceList += [ "EnvironmentProxyProvider.cpp" ]
+ sourceList += [ "UnixProxyProvider.cpp" ]
+ sourceList += [ "SolarisNetworkEnvironment.cpp" ]
+ sourceList += [ "EnvironmentProxyProvider.cpp" ]
else :
- sourceList += [ "UnixNetworkEnvironment.cpp" ]
- sourceList += [ "UnixProxyProvider.cpp" ]
- sourceList += [ "EnvironmentProxyProvider.cpp" ]
- if myenv.get("HAVE_GCONF", 0) :
- myenv.Append(CPPDEFINES = "HAVE_GCONF")
- myenv.MergeFlags(myenv["GCONF_FLAGS"])
- sourceList += [ "GConfProxyProvider.cpp" ]
+ sourceList += [ "UnixNetworkEnvironment.cpp" ]
+ sourceList += [ "UnixProxyProvider.cpp" ]
+ sourceList += [ "EnvironmentProxyProvider.cpp" ]
+ if myenv.get("HAVE_GCONF", 0) :
+ myenv.Append(CPPDEFINES = "HAVE_GCONF")
+ myenv.MergeFlags(myenv["GCONF_FLAGS"])
+ sourceList += [ "GConfProxyProvider.cpp" ]
objects = myenv.SwiftenObject(sourceList)
if myenv["experimental_ft"] :
- # LibNATPMP classes
- if myenv.get("HAVE_LIBNATPMP", False) :
- natpmp_env = myenv.Clone()
- natpmp_env.Append(CPPDEFINES = natpmp_env["LIBNATPMP_FLAGS"].get("INTERNAL_CPPDEFINES", []))
- myenv.Append(CPPDEFINES = ["HAVE_LIBNATPMP"])
- objects += natpmp_env.SwiftenObject([
- "NATPMPInterface.cpp",
- ])
+ # LibNATPMP classes
+ if myenv.get("HAVE_LIBNATPMP", False) :
+ natpmp_env = myenv.Clone()
+ natpmp_env.Append(CPPDEFINES = natpmp_env["LIBNATPMP_FLAGS"].get("INTERNAL_CPPDEFINES", []))
+ myenv.Append(CPPDEFINES = ["HAVE_LIBNATPMP"])
+ objects += natpmp_env.SwiftenObject([
+ "NATPMPInterface.cpp",
+ ])
- # LibMINIUPnP classes
- if myenv.get("HAVE_LIBMINIUPNPC", False) :
- upnp_env = myenv.Clone()
- upnp_env.Append(CPPDEFINES = upnp_env["LIBMINIUPNPC_FLAGS"].get("INTERNAL_CPPDEFINES", []))
- myenv.Append(CPPDEFINES = ["HAVE_LIBMINIUPNPC"])
- objects += upnp_env.SwiftenObject([
- "MiniUPnPInterface.cpp",
- ])
- objects += myenv.SwiftenObject([
- "PlatformNATTraversalWorker.cpp",
- ])
+ # LibMINIUPnP classes
+ if myenv.get("HAVE_LIBMINIUPNPC", False) :
+ upnp_env = myenv.Clone()
+ upnp_env.Append(CPPDEFINES = upnp_env["LIBMINIUPNPC_FLAGS"].get("INTERNAL_CPPDEFINES", []))
+ myenv.Append(CPPDEFINES = ["HAVE_LIBMINIUPNPC"])
+ objects += upnp_env.SwiftenObject([
+ "MiniUPnPInterface.cpp",
+ ])
+ objects += myenv.SwiftenObject([
+ "PlatformNATTraversalWorker.cpp",
+ ])
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
diff --git a/Swiften/Network/SOCKS5ProxiedConnection.cpp b/Swiften/Network/SOCKS5ProxiedConnection.cpp
index 666620d..2492827 100644
--- a/Swiften/Network/SOCKS5ProxiedConnection.cpp
+++ b/Swiften/Network/SOCKS5ProxiedConnection.cpp
@@ -5,118 +5,116 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/SOCKS5ProxiedConnection.h>
-#include <iostream>
#include <boost/bind.hpp>
-#include <boost/thread.hpp>
-#include <Swiften/Network/ConnectionFactory.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/Base/Log.h>
#include <Swiften/Base/String.h>
-#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Network/ConnectionFactory.h>
#include <Swiften/Network/HostAddressPort.h>
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());
+void SOCKS5ProxiedConnection::handleProxyInitializeData(std::shared_ptr<SafeByteArray> data) {
+ 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);
- 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;
- /*
+ }
+ 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(...) {
+ SWIFT_LOG(error) << "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);
- }
- }
+ 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 {
+ SWIFT_LOG(error) << "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..c8faae9 100644
--- a/Swiften/Network/SOCKS5ProxiedConnection.h
+++ b/Swiften/Network/SOCKS5ProxiedConnection.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::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(std::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..01ce8ac 100644
--- a/Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp
+++ b/Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Network/SOCKS5ProxiedConnectionFactory.h>
#include <Swiften/Network/SOCKS5ProxiedConnection.h>
@@ -13,8 +19,8 @@ namespace Swift {
SOCKS5ProxiedConnectionFactory::SOCKS5ProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort) : resolver_(resolver), connectionFactory_(connectionFactory), timerFactory_(timerFactory), proxyHost_(proxyHost), proxyPort_(proxyPort) {
}
-boost::shared_ptr<Connection> SOCKS5ProxiedConnectionFactory::createConnection() {
- return SOCKS5ProxiedConnection::create(resolver_, connectionFactory_, timerFactory_, proxyHost_, proxyPort_);
+std::shared_ptr<Connection> SOCKS5ProxiedConnectionFactory::createConnection() {
+ return SOCKS5ProxiedConnection::create(resolver_, connectionFactory_, timerFactory_, proxyHost_, proxyPort_);
}
}
diff --git a/Swiften/Network/SOCKS5ProxiedConnectionFactory.h b/Swiften/Network/SOCKS5ProxiedConnectionFactory.h
index 0915a9b..8631239 100644
--- a/Swiften/Network/SOCKS5ProxiedConnectionFactory.h
+++ b/Swiften/Network/SOCKS5ProxiedConnectionFactory.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::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 c7d5c2d..db8c740 100644
--- a/Swiften/Network/SolarisNetworkEnvironment.cpp
+++ b/Swiften/Network/SolarisNetworkEnvironment.cpp
@@ -5,28 +5,30 @@
*/
/*
-* Copyright (c) 2013-2014 Isode Limited.
-* All rights reserved.v3.
-* See the COPYING file for more information.
-*/
+ * Copyright (c) 2013-2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
#include <Swiften/Network/SolarisNetworkEnvironment.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <map>
#include <string>
#include <vector>
-#include <map>
+
#include <boost/optional.hpp>
+#include <boost/signals2.hpp>
-#include <unistd.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <string.h>
-#include <sys/sockio.h>
+#include <net/if.h>
#include <sys/socket.h>
+#include <sys/sockio.h>
#include <sys/types.h>
-#include <net/if.h>
+#include <unistd.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Network/HostAddress.h>
#include <Swiften/Network/NetworkInterface.h>
@@ -37,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
@@ -61,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 */
@@ -255,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 b344033..199fc6f 100644
--- a/Swiften/Network/SolarisNetworkEnvironment.h
+++ b/Swiften/Network/SolarisNetworkEnvironment.h
@@ -5,25 +5,25 @@
*/
/*
-* Copyright (c) 2013-2014 Isode Limited.
-* All rights reserved.v3.
-* See the COPYING file for more information.
-*/
+ * Copyright (c) 2013-2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
#pragma once
#include <vector>
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
#include <Swiften/Network/NetworkEnvironment.h>
#include <Swiften/Network/NetworkInterface.h>
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 c744085..95b3dd9 100644
--- a/Swiften/Network/StaticDomainNameResolver.cpp
+++ b/Swiften/Network/StaticDomainNameResolver.cpp
@@ -1,80 +1,81 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/StaticDomainNameResolver.h>
+#include <string>
+
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
-#include <Swiften/Network/DomainNameResolveError.h>
#include <Swiften/EventLoop/EventOwner.h>
-#include <string>
+#include <Swiften/Network/DomainNameResolveError.h>
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 std::enable_shared_from_this<ServiceQuery> {
+ ServiceQuery(const std::string& service, Swift::StaticDomainNameResolver* resolver, EventLoop* eventLoop, std::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(const auto& i : resolver->getServices()) {
+ 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;
+ std::shared_ptr<EventOwner> owner;
+ };
+
+ struct AddressQuery : public DomainNameAddressQuery, public std::enable_shared_from_this<AddressQuery> {
+ AddressQuery(const std::string& host, StaticDomainNameResolver* resolver, EventLoop* eventLoop, std::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;
+ std::shared_ptr<EventOwner> owner;
+ };
}
class StaticDomainNameResolverEventOwner : public EventOwner {
- public:
- ~StaticDomainNameResolverEventOwner() {
+ public:
+ ~StaticDomainNameResolverEventOwner() {
- }
+ }
};
@@ -84,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));
+std::shared_ptr<DomainNameServiceQuery> StaticDomainNameResolver::createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) {
+ return std::make_shared<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));
+std::shared_ptr<DomainNameAddressQuery> StaticDomainNameResolver::createAddressQuery(const std::string& name) {
+ return std::make_shared<AddressQuery>(name, this, eventLoop, owner);
}
}
diff --git a/Swiften/Network/StaticDomainNameResolver.h b/Swiften/Network/StaticDomainNameResolver.h
index ebbc29f..76394d0 100644
--- a/Swiften/Network/StaticDomainNameResolver.h
+++ b/Swiften/Network/StaticDomainNameResolver.h
@@ -7,6 +7,7 @@
#pragma once
#include <map>
+#include <memory>
#include <vector>
#include <Swiften/Base/API.h>
@@ -18,43 +19,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 std::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain);
+ virtual std::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& name);
+ private:
+ EventLoop* eventLoop;
+ bool isResponsive;
+ AddressesMap addresses;
+ ServicesCollection services;
+ std::shared_ptr<EventOwner> owner;
+ };
}
diff --git a/Swiften/Network/TLSConnection.cpp b/Swiften/Network/TLSConnection.cpp
index c7087ae..7c293d1 100644
--- a/Swiften/Network/TLSConnection.cpp
+++ b/Swiften/Network/TLSConnection.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::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);
+void TLSConnection::handleRawDataRead(std::shared_ptr<SafeByteArray> data) {
+ context->handleDataFromNetwork(*data);
}
void TLSConnection::handleRawDataWritten() {
- onDataWritten();
+ onDataWritten();
}
}
diff --git a/Swiften/Network/TLSConnection.h b/Swiften/Network/TLSConnection.h
index b3acffc..0c395d1 100644
--- a/Swiften/Network/TLSConnection.h
+++ b/Swiften/Network/TLSConnection.h
@@ -1,52 +1,52 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/enable_shared_from_this.hpp>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/SafeByteArray.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Network/Connection.h>
#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(std::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..b311c7d 100644
--- a/Swiften/Network/TLSConnectionFactory.cpp
+++ b/Swiften/Network/TLSConnectionFactory.cpp
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Network/TLSConnectionFactory.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Network/TLSConnection.h>
@@ -21,8 +21,8 @@ TLSConnectionFactory::~TLSConnectionFactory() {
}
-boost::shared_ptr<Connection> TLSConnectionFactory::createConnection() {
- return boost::make_shared<TLSConnection>(connectionFactory->createConnection(), contextFactory, options_);
+std::shared_ptr<Connection> TLSConnectionFactory::createConnection() {
+ return std::make_shared<TLSConnection>(connectionFactory->createConnection(), contextFactory, options_);
}
}
diff --git a/Swiften/Network/TLSConnectionFactory.h b/Swiften/Network/TLSConnectionFactory.h
index 0c67014..148e345 100644
--- a/Swiften/Network/TLSConnectionFactory.h
+++ b/Swiften/Network/TLSConnectionFactory.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Network/ConnectionFactory.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 std::shared_ptr<Connection> createConnection();
+ private:
+ TLSContextFactory* contextFactory;
+ ConnectionFactory* connectionFactory;
+ TLSOptions options_;
+ };
}
diff --git a/Swiften/Network/Timer.h b/Swiften/Network/Timer.h
index ad9752f..977ed89 100644
--- a/Swiften/Network/Timer.h
+++ b/Swiften/Network/Timer.h
@@ -1,41 +1,42 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
namespace Swift {
- /**
- * A class for triggering an event after a given period.
- */
- class SWIFTEN_API Timer {
- public:
- typedef boost::shared_ptr<Timer> ref;
-
- virtual ~Timer();
-
- /**
- * 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;
-
- /**
- * Emitted when the timer expires.
- */
- boost::signal<void ()> onTick;
- };
+ /**
+ * A class for triggering an event after a given period.
+ */
+ class SWIFTEN_API Timer {
+ public:
+ typedef std::shared_ptr<Timer> ref;
+
+ virtual ~Timer();
+
+ /**
+ * 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;
+
+ /**
+ * Emitted when the timer expires.
+ */
+ boost::signals2::signal<void ()> onTick;
+ };
}
diff --git a/Swiften/Network/TimerFactory.h b/Swiften/Network/TimerFactory.h
index a27e76e..ebb1b6e 100644
--- a/Swiften/Network/TimerFactory.h
+++ b/Swiften/Network/TimerFactory.h
@@ -1,21 +1,21 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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 bc280eb..1df6b8f 100755..100644
--- a/Swiften/Network/UnboundDomainNameResolver.cpp
+++ b/Swiften/Network/UnboundDomainNameResolver.cpp
@@ -4,13 +4,23 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "UnboundDomainNameResolver.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+#include <Swiften/Network/UnboundDomainNameResolver.h>
+
+#include <memory>
#include <vector>
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <boost/enable_shared_from_this.hpp>
+
+#include <arpa/inet.h>
+#include <ldns/ldns.h>
+#include <unbound.h>
+#include <unistd.h>
#include <Swiften/Base/Log.h>
#include <Swiften/EventLoop/EventLoop.h>
@@ -21,227 +31,222 @@
#include <Swiften/Network/HostAddress.h>
#include <Swiften/Network/TimerFactory.h>
-#include <arpa/inet.h>
-#include <unbound.h>
-#include <ldns/ldns.h>
-#include <unistd.h>
-
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, std::shared_ptr<UnboundQuery> query) : resolver(resolver), query(query) {}
+ UnboundDomainNameResolver* resolver;
+ std::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;
+class UnboundDomainNameServiceQuery : public DomainNameServiceQuery, public UnboundQuery, public std::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;
};
-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;
+class UnboundDomainNameAddressQuery : public DomainNameAddressQuery, public UnboundQuery, public std::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;
};
-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>();
+UnboundDomainNameResolver::UnboundDomainNameResolver(IDNConverter* idnConverter, std::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 = std::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);
+void UnboundDomainNameResolver::unbound_callback(std::shared_ptr<UnboundQuery> query, int err, ub_result* 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);
+std::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 std::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(""));
+std::shared_ptr<DomainNameAddressQuery> UnboundDomainNameResolver::createAddressQuery(const std::string& name) {
+ return std::make_shared<UnboundDomainNameAddressQuery>(this, ubContext, idnConverter->getIDNAEncoded(name).get_value_or(""));
}
}
diff --git a/Swiften/Network/UnboundDomainNameResolver.h b/Swiften/Network/UnboundDomainNameResolver.h
index 6b78cf3..a97e385 100755..100644
--- a/Swiften/Network/UnboundDomainNameResolver.h
+++ b/Swiften/Network/UnboundDomainNameResolver.h
@@ -4,50 +4,56 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <Swiften/Network/DomainNameResolver.h>
-#include <Swiften/Network/Timer.h>
-#include <Swiften/EventLoop/EventOwner.h>
+#include <memory>
-#include <boost/shared_ptr.hpp>
-#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
+#include <Swiften/EventLoop/EventOwner.h>
+#include <Swiften/Network/DomainNameResolver.h>
+#include <Swiften/Network/Timer.h>
+
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 std::enable_shared_from_this<UnboundDomainNameResolver> {
+ public:
+ UnboundDomainNameResolver(IDNConverter* idnConverter, std::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 std::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain);
+ virtual std::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(std::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;
+ std::shared_ptr<EventOwner> eventOwner;
+ std::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..5d6fedd 100644
--- a/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp
+++ b/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp
@@ -1,14 +1,14 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <QA/Checker/IO.h>
@@ -29,440 +29,440 @@
using namespace Swift;
-typedef boost::shared_ptr<BOSHConnectionPool> PoolRef;
+typedef std::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::fromString("127.0.0.1").get());
+ 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() {
+ std::shared_ptr<MockConnection> c0;
+ std::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::fromString("127.0.0.1").get());
+ 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() {
+ std::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*>(nullptr), 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) {
+ }
+
+ std::shared_ptr<Connection> createConnection() {
+ std::shared_ptr<MockConnection> connection = std::make_shared<MockConnection>(failingPorts, eventLoop, autoFinishConnect);
+ connections.push_back(connection);
+ return connection;
+ }
+
+ EventLoop* eventLoop;
+ std::vector< std::shared_ptr<MockConnection> > connections;
+ std::vector<HostAddressPort> failingPorts;
+ bool autoFinishConnect;
+ };
+
+ void readResponse(const std::string& response, std::shared_ptr<MockConnection> connection) {
+ connection->pending = false;
+ std::shared_ptr<SafeByteArray> data1 = std::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);
+ std::shared_ptr<SafeByteArray> data2 = std::make_shared<SafeByteArray>(createSafeByteArray(boost::lexical_cast<std::string>(response.size())));
+ connection->onDataRead(data2);
+ std::shared_ptr<SafeByteArray> data3 = std::make_shared<SafeByteArray>(createSafeByteArray("\r\n\r\n"));
+ connection->onDataRead(data3);
+ std::shared_ptr<SafeByteArray> data4 = std::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..99dd462 100644
--- a/Swiften/Network/UnitTest/BOSHConnectionTest.cpp
+++ b/Swiften/Network/UnitTest/BOSHConnectionTest.cpp
@@ -1,14 +1,14 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <QA/Checker/IO.h>
@@ -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 = nullptr;
+ 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());
+ std::shared_ptr<MockConnection> connection = connectionFactory->connections[0];
+ std::shared_ptr<SafeByteArray> data1 = std::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"));
+ std::shared_ptr<SafeByteArray> data2 = std::make_shared<SafeByteArray>(createSafeByteArray(
+ "\r\n<body xmlns='http://jabber.org/protocol/httpbind'>"
+ "<bl"));
+ std::shared_ptr<SafeByteArray> data3 = std::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::fromString("127.0.0.1").get());
+ 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) {
+ }
+
+ std::shared_ptr<Connection> createConnection() {
+ std::shared_ptr<MockConnection> connection = std::make_shared<MockConnection>(failingPorts, eventLoop);
+ connections.push_back(connection);
+ return connection;
+ }
+
+ EventLoop* eventLoop;
+ std::vector< std::shared_ptr<MockConnection> > connections;
+ std::vector<HostAddressPort> failingPorts;
+ };
+
+ void readResponse(const std::string& response, std::shared_ptr<MockConnection> connection) {
+ std::shared_ptr<SafeByteArray> data1 = std::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);
+ std::shared_ptr<SafeByteArray> data2 = std::make_shared<SafeByteArray>(createSafeByteArray(boost::lexical_cast<std::string>(response.size())));
+ connection->onDataRead(data2);
+ std::shared_ptr<SafeByteArray> data3 = std::make_shared<SafeByteArray>(createSafeByteArray("\r\n\r\n"));
+ connection->onDataRead(data3);
+ std::shared_ptr<SafeByteArray> data4 = std::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..2d78cd7 100644
--- a/Swiften/Network/UnitTest/ChainedConnectorTest.cpp
+++ b/Swiften/Network/UnitTest/ChainedConnectorTest.cpp
@@ -1,11 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -22,166 +23,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::fromString("1.1.1.1").get(), 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() {
+ std::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, std::dynamic_pointer_cast<MockConnection>(connections[0])->id);
+ CPPUNIT_ASSERT(!std::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_SecondConnectorSucceeds() {
+ std::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, std::dynamic_pointer_cast<MockConnection>(connections[0])->id);
+ CPPUNIT_ASSERT(!std::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_NoConnectorSucceeds() {
+ std::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(!std::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_NoDNS() {
+ /* Reset resolver so there's no record */
+ delete resolver;
+ resolver = new StaticDomainNameResolver(eventLoop);
+ std::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(std::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testStop() {
+ std::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:
+ std::shared_ptr<ChainedConnector> createConnector() {
+ std::vector<ConnectionFactory*> factories;
+ factories.push_back(connectionFactory1);
+ factories.push_back(connectionFactory2);
+ std::shared_ptr<ChainedConnector> connector = std::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(std::shared_ptr<Connection> connection, std::shared_ptr<Error> resultError) {
+ error = resultError;
+ std::shared_ptr<MockConnection> c(std::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) {
+ }
+
+ std::shared_ptr<Connection> createConnection() {
+ return std::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< std::shared_ptr<MockConnection> > connections;
+ std::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..8524439 100644
--- a/Swiften/Network/UnitTest/ConnectorTest.cpp
+++ b/Swiften/Network/UnitTest/ConnectorTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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::fromString("1.1.1.1").get(), 1234);
+ host2 = HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 2345);
+ host3 = HostAddressPort(HostAddress::fromString("3.3.3.3").get(), 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(!std::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(!std::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(!std::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(!std::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_FirstAddressHostFails() {
+ Connector::ref testling(createConnector());
+
+ auto address1 = HostAddress::fromString("1.1.1.1").get();
+ auto address2 = HostAddress::fromString("2.2.2.2").get();
+ 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(!std::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(std::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(!std::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(!std::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(!std::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(!std::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(std::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(!std::dynamic_pointer_cast<DomainNameResolveError>(error));
+ }
+
+ void testConnect_TimeoutDuringConnectToCandidateFallsBack() {
+ Connector::ref testling(createConnector());
+ testling->setTimeoutMilliseconds(10);
+
+ auto address2 = HostAddress::fromString("2.2.2.2").get();
+
+ resolver->addXMPPClientService("foo.com", "host-foo.com", 1234);
+ resolver->addAddress("host-foo.com", HostAddress::fromString("1.1.1.1").get());
+ 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(!std::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(!std::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(std::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(std::shared_ptr<Connection> connection, std::shared_ptr<Error> resultError) {
+ std::shared_ptr<MockConnection> c(std::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) {
+ }
+
+ std::shared_ptr<Connection> createConnection() {
+ return std::make_shared<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< std::shared_ptr<MockConnection> > connections;
+ std::shared_ptr<Error> error;
};
diff --git a/Swiften/Network/UnitTest/DomainNameServiceQueryTest.cpp b/Swiften/Network/UnitTest/DomainNameServiceQueryTest.cpp
index e9bbdcd..7042b27 100644
--- a/Swiften/Network/UnitTest/DomainNameServiceQueryTest.cpp
+++ b/Swiften/Network/UnitTest/DomainNameServiceQueryTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,73 +9,73 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Network/DomainNameServiceQuery.h>
#include <Swiften/Base/RandomGenerator.h>
+#include <Swiften/Network/DomainNameServiceQuery.h>
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..1a160b7 100644
--- a/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp
+++ b/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp
@@ -1,15 +1,15 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <QA/Checker/IO.h>
@@ -18,7 +18,6 @@
#include <Swiften/Base/Algorithm.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/EventLoop/DummyEventLoop.h>
#include <Swiften/Network/Connection.h>
#include <Swiften/Network/ConnectionFactory.h>
@@ -31,409 +30,408 @@
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) {
+ for (const auto& 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::fromString("1.1.1.1").get(), proxyPort);
+ host = HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 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::fromString("2.2.2.2").get(), 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::fromString("2.2.2.2").get(), 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::fromString("2.2.2.2").get(), 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::fromString("2.2.2.2").get(), 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::fromString("2.2.2.2").get(), 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::fromString("2.2.2.2").get(), 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::fromString("2.2.2.2").get(), 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::fromString("2.2.2.2").get(), 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::fromString("2.2.2.2").get(), 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());
+
+ std::shared_ptr<ExampleHTTPTrafficFilter> httpTrafficFilter = std::make_shared<ExampleHTTPTrafficFilter>();
+
+ testling->setHTTPTrafficFilter(httpTrafficFilter);
+ connect(testling, HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 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();
+
+ std::shared_ptr<ProxyAuthenticationHTTPTrafficFilter> httpTrafficFilter = std::make_shared<ProxyAuthenticationHTTPTrafficFilter>();
+ testling->setHTTPTrafficFilter(httpTrafficFilter);
+
+ connect(testling, HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 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() {
+ std::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(std::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) {
+ }
+
+ std::shared_ptr<Connection> createConnection() {
+ std::shared_ptr<MockConnection> connection = std::make_shared<MockConnection>(failingPorts, eventLoop);
+ connections.push_back(connection);
+ SWIFT_LOG(debug) << "new connection created" << std::endl;
+ return connection;
+ }
+
+ EventLoop* eventLoop;
+ std::vector< std::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 76d0e11..226346b 100644
--- a/Swiften/Network/UnitTest/HostAddressTest.cpp
+++ b/Swiften/Network/UnitTest/HostAddressTest.cpp
@@ -1,66 +1,67 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <string>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <Swiften/Network/HostAddress.h>
-#include <string>
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() {
+ auto testling = HostAddress::fromString("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() {
+ auto testling = HostAddress::fromString("invalid");
- CPPUNIT_ASSERT(!testling.isValid());
- }
+ CPPUNIT_ASSERT(!testling);
+ }
- 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..dc90589 100644
--- a/Swiften/Network/UnixNetworkEnvironment.cpp
+++ b/Swiften/Network/UnixNetworkEnvironment.cpp
@@ -4,60 +4,68 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Network/UnixNetworkEnvironment.h>
+#include <map>
#include <string>
#include <vector>
-#include <map>
+
#include <boost/optional.hpp>
-#include <sys/types.h>
-#include <sys/socket.h>
+#include <boost/signals2.hpp>
+
#include <arpa/inet.h>
#include <net/if.h>
+#include <sys/socket.h>
+#include <sys/types.h>
#ifndef __ANDROID__
#include <ifaddrs.h>
#endif
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Network/HostAddress.h>
#include <Swiften/Network/NetworkInterface.h>
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 = nullptr;
+ int ret = getifaddrs(&addrs);
+ if (ret != 0) {
+ return std::vector<NetworkInterface>();
+ }
+
+ for (ifaddrs* a = addrs; a != nullptr; 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 8b51cae..89a01ab 100644
--- a/Swiften/Network/UnixNetworkEnvironment.h
+++ b/Swiften/Network/UnixNetworkEnvironment.h
@@ -4,11 +4,17 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <vector>
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
#include <Swiften/Network/NetworkEnvironment.h>
#include <Swiften/Network/NetworkInterface.h>
@@ -16,8 +22,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..e6afa3d 100644
--- a/Swiften/Network/UnixProxyProvider.cpp
+++ b/Swiften/Network/UnixProxyProvider.cpp
@@ -4,12 +4,14 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include <stdio.h>
-#include <stdlib.h>
-#include <iostream>
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
-#include <Swiften/Base/foreach.h>
#include <Swiften/Network/UnixProxyProvider.h>
+
#if defined(HAVE_GCONF)
# include "Swiften/Network/GConfProxyProvider.h"
#endif
@@ -17,48 +19,48 @@
namespace Swift {
UnixProxyProvider::UnixProxyProvider() :
- gconfProxyProvider(0),
- environmentProxyProvider()
+ gconfProxyProvider(nullptr),
+ 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 e2d1966..e90a5c6 100644
--- a/Swiften/Network/WindowsNetworkEnvironment.cpp
+++ b/Swiften/Network/WindowsNetworkEnvironment.cpp
@@ -4,63 +4,70 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Network/WindowsNetworkEnvironment.h>
+#include <map>
#include <string>
#include <vector>
-#include <map>
+
#include <boost/optional.hpp>
-#include <Swiften/Network/HostAddress.h>
-#include <Swiften/Network/NetworkInterface.h>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Base/ByteArray.h>
-#include <winsock2.h>
#include <iphlpapi.h>
+#include <winsock2.h>
+
+#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Network/HostAddress.h>
+#include <Swiften/Network/NetworkInterface.h>
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 (const auto& interface : interfaces) {
+ result.push_back(interface.second);
+ }
+ return result;
}
}
diff --git a/Swiften/Network/WindowsNetworkEnvironment.h b/Swiften/Network/WindowsNetworkEnvironment.h
index 18996ed..81de826 100644
--- a/Swiften/Network/WindowsNetworkEnvironment.h
+++ b/Swiften/Network/WindowsNetworkEnvironment.h
@@ -4,17 +4,24 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <vector>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#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 3ae43e0..78bd72f 100644
--- a/Swiften/Network/WindowsProxyProvider.cpp
+++ b/Swiften/Network/WindowsProxyProvider.cpp
@@ -4,110 +4,121 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swiften/Network/WindowsProxyProvider.h>
+
+#include <math.h>
#include <stdio.h>
#include <stdlib.h>
-#include <math.h>
-#include <iostream>
-#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/log.h>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Network/WindowsProxyProvider.h>
-#include <Swiften/Base/ByteArray.h>
+#include <boost/lexical_cast.hpp>
#include <windows.h>
+#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Network/HostAddress.h>
+#include <Swiften/Network/HostAddressPort.h>
+
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;
+ for(auto&& 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::fromString(tmp.first).get(), port);
+ }
+ catch(...) {
+ SWIFT_LOG(error) << "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..0ca897d 100644
--- a/Swiften/Network/WindowsProxyProvider.h
+++ b/Swiften/Network/WindowsProxyProvider.h
@@ -4,21 +4,28 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Base/API.h>
+#include <Swiften/Network/HostAddressPort.h>
#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 9f86338..c112d52 100644
--- a/Swiften/Parser/AttributeMap.cpp
+++ b/Swiften/Parser/AttributeMap.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,9 +7,10 @@
#include <Swiften/Parser/AttributeMap.h>
#include <algorithm>
-#include <boost/optional.hpp>
-#include <boost/lambda/lambda.hpp>
+
#include <boost/lambda/bind.hpp>
+#include <boost/lambda/lambda.hpp>
+#include <boost/optional.hpp>
using namespace Swift;
namespace lambda = boost::lambda;
@@ -18,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 93c163b..804d6aa 100644
--- a/Swiften/Parser/AttributeMap.h
+++ b/Swiften/Parser/AttributeMap.h
@@ -1,54 +1,55 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
-#include <string>
#include <map>
+#include <string>
+#include <vector>
+
#include <boost/optional/optional.hpp>
#include <Swiften/Base/API.h>
#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 b6ffec8..cf69672 100644
--- a/Swiften/Parser/AuthChallengeParser.cpp
+++ b/Swiften/Parser/AuthChallengeParser.cpp
@@ -1,10 +1,11 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/AuthChallengeParser.h>
+
#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
@@ -13,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 1278221..48e2bfb 100644
--- a/Swiften/Parser/AuthChallengeParser.h
+++ b/Swiften/Parser/AuthChallengeParser.h
@@ -1,27 +1,28 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/AuthChallenge.h>
-#include <string>
+#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 a494ebe..1706290 100644
--- a/Swiften/Parser/AuthFailureParser.h
+++ b/Swiften/Parser/AuthFailureParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,12 +7,12 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/AuthFailure.h>
+#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 4d21fc4..a24be8d 100644
--- a/Swiften/Parser/AuthRequestParser.cpp
+++ b/Swiften/Parser/AuthRequestParser.cpp
@@ -1,10 +1,11 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/AuthRequestParser.h>
+
#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
@@ -13,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 c6510c8..ac94abf 100644
--- a/Swiften/Parser/AuthRequestParser.h
+++ b/Swiften/Parser/AuthRequestParser.h
@@ -1,27 +1,28 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/AuthRequest.h>
-#include <string>
+#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 960a840..59f6455 100644
--- a/Swiften/Parser/AuthResponseParser.cpp
+++ b/Swiften/Parser/AuthResponseParser.cpp
@@ -1,10 +1,11 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/AuthResponseParser.h>
+
#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
@@ -13,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 abb6585..6cbfa22 100644
--- a/Swiften/Parser/AuthResponseParser.h
+++ b/Swiften/Parser/AuthResponseParser.h
@@ -1,27 +1,28 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/AuthResponse.h>
-#include <string>
+#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 2212fdc..964fd6c 100644
--- a/Swiften/Parser/AuthSuccessParser.cpp
+++ b/Swiften/Parser/AuthSuccessParser.cpp
@@ -1,10 +1,11 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/AuthSuccessParser.h>
+
#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
@@ -13,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 b16f80e..cedc8d1 100644
--- a/Swiften/Parser/AuthSuccessParser.h
+++ b/Swiften/Parser/AuthSuccessParser.h
@@ -1,27 +1,28 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/AuthSuccess.h>
-#include <string>
+#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 0a32ee1..c45d338 100644
--- a/Swiften/Parser/BOSHBodyExtractor.cpp
+++ b/Swiften/Parser/BOSHBodyExtractor.cpp
@@ -1,139 +1,140 @@
/*
- * Copyright (c) 2011-2013 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/BOSHBodyExtractor.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/Parser/XMLParserClient.h>
#include <Swiften/Parser/XMLParser.h>
+#include <Swiften/Parser/XMLParserClient.h>
#include <Swiften/Parser/XMLParserFactory.h>
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);
+ std::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 daf81da..f98503d 100644
--- a/Swiften/Parser/ComponentHandshakeParser.cpp
+++ b/Swiften/Parser/ComponentHandshakeParser.cpp
@@ -1,10 +1,11 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/ComponentHandshakeParser.h>
+
#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
@@ -13,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 61739d9..5f4af80 100644
--- a/Swiften/Parser/ComponentHandshakeParser.h
+++ b/Swiften/Parser/ComponentHandshakeParser.h
@@ -1,27 +1,28 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/ComponentHandshake.h>
-#include <string>
+#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 eca53aa..5c171ee 100644
--- a/Swiften/Parser/CompressFailureParser.h
+++ b/Swiften/Parser/CompressFailureParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,12 +7,12 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/CompressFailure.h>
+#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 9b22db2..6f0a0cb 100644
--- a/Swiften/Parser/CompressParser.h
+++ b/Swiften/Parser/CompressParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,24 @@
#pragma once
#include <string>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/CompressRequest.h>
+#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 33f56b2..859b509 100644
--- a/Swiften/Parser/CompressedParser.h
+++ b/Swiften/Parser/CompressedParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,12 +7,12 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/Compressed.h>
+#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 c54230b..71d4bce 100644
--- a/Swiften/Parser/ElementParser.h
+++ b/Swiften/Parser/ElementParser.h
@@ -1,27 +1,27 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-
+#include <memory>
#include <string>
+
#include <Swiften/Base/API.h>
#include <Swiften/Elements/ToplevelElement.h>
#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 std::shared_ptr<ToplevelElement> getElement() const = 0;
+ };
}
diff --git a/Swiften/Parser/EnableStreamManagementParser.h b/Swiften/Parser/EnableStreamManagementParser.h
index 54d8d40..b010740 100644
--- a/Swiften/Parser/EnableStreamManagementParser.h
+++ b/Swiften/Parser/EnableStreamManagementParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,12 +7,12 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/EnableStreamManagement.h>
+#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 a3baa3b..cf17ead 100644
--- a/Swiften/Parser/EnumParser.h
+++ b/Swiften/Parser/EnumParser.h
@@ -1,37 +1,38 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <string>
-#include <map>
#include <cassert>
+#include <map>
+#include <string>
+
#include <boost/optional.hpp>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#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..77d959c 100644
--- a/Swiften/Parser/ExpatParser.cpp
+++ b/Swiften/Parser/ExpatParser.cpp
@@ -1,14 +1,17 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/ExpatParser.h>
-#include <iostream>
+#include <cassert>
+#include <memory>
#include <string>
+
#include <expat.h>
+
#include <boost/numeric/conversion/cast.hpp>
#include <Swiften/Base/String.h>
@@ -21,75 +24,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..12df463 100644
--- a/Swiften/Parser/ExpatParser.h
+++ b/Swiften/Parser/ExpatParser.h
@@ -1,29 +1,30 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#include <boost/noncopyable.hpp>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Base/API.h>
#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;
+ const std::unique_ptr<Private> p;
+ };
}
diff --git a/Swiften/Parser/GenericElementParser.h b/Swiften/Parser/GenericElementParser.h
index 9cdec23..5aa62c9 100644
--- a/Swiften/Parser/GenericElementParser.h
+++ b/Swiften/Parser/GenericElementParser.h
@@ -1,47 +1,46 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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_ = std::make_shared<ElementType>();
+ }
- virtual boost::shared_ptr<ElementType> getElementGeneric() const {
- return stanza_;
- }
+ virtual std::shared_ptr<ToplevelElement> getElement() const {
+ return stanza_;
+ }
- private:
- virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
- }
+ virtual std::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:
+ std::shared_ptr<ElementType> stanza_;
+ };
}
diff --git a/Swiften/Parser/GenericPayloadParser.h b/Swiften/Parser/GenericPayloadParser.h
index b6cd2d7..ea0a7bd 100644
--- a/Swiften/Parser/GenericPayloadParser.h
+++ b/Swiften/Parser/GenericPayloadParser.h
@@ -1,43 +1,42 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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_ = std::make_shared<PAYLOAD_TYPE>();
+ }
+
+ virtual std::shared_ptr<Payload> getPayload() const {
+ return payload_;
+ }
+
+ virtual std::shared_ptr<PAYLOAD_TYPE> getPayloadInternal() const {
+ return payload_;
+ }
+
+ private:
+ std::shared_ptr<PAYLOAD_TYPE> payload_;
+ };
}
diff --git a/Swiften/Parser/GenericPayloadParserFactory.h b/Swiften/Parser/GenericPayloadParserFactory.h
index 8e476c0..fcdec62 100644
--- a/Swiften/Parser/GenericPayloadParserFactory.h
+++ b/Swiften/Parser/GenericPayloadParserFactory.h
@@ -1,38 +1,39 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <Swiften/Base/API.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-#include <string>
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 633050e..f55d317 100644
--- a/Swiften/Parser/GenericPayloadParserFactory2.h
+++ b/Swiften/Parser/GenericPayloadParserFactory2.h
@@ -1,40 +1,41 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <Swiften/Base/API.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-#include <string>
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..b4da1a9 100644
--- a/Swiften/Parser/GenericPayloadTreeParser.h
+++ b/Swiften/Parser/GenericPayloadTreeParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,48 +7,46 @@
#pragma once
#include <deque>
-
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Parser/GenericPayloadParser.h>
#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_ = std::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..2686f2f 100644
--- a/Swiften/Parser/GenericStanzaParser.h
+++ b/Swiften/Parser/GenericStanzaParser.h
@@ -1,38 +1,37 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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_ = std::make_shared<STANZA_TYPE>();
+ }
+
+ virtual std::shared_ptr<ToplevelElement> getElement() const {
+ return stanza_;
+ }
+
+ virtual std::shared_ptr<STANZA_TYPE> getStanzaGeneric() const {
+ return stanza_;
+ }
+
+ private:
+ std::shared_ptr<STANZA_TYPE> stanza_;
+ };
}
diff --git a/Swiften/Parser/IQParser.cpp b/Swiften/Parser/IQParser.cpp
index eb442ec..5cfae34 100644
--- a/Swiften/Parser/IQParser.cpp
+++ b/Swiften/Parser/IQParser.cpp
@@ -1,40 +1,41 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <iostream>
+#include <Swiften/Parser/IQParser.h>
+
#include <boost/optional.hpp>
-#include <Swiften/Parser/IQParser.h>
+#include <Swiften/Base/Log.h>
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 {
+ SWIFT_LOG(warning) << "Unknown IQ type: " << *type << std::endl;
+ getStanzaGeneric()->setType(IQ::Get);
+ }
+ }
}
}
diff --git a/Swiften/Parser/IQParser.h b/Swiften/Parser/IQParser.h
index c87e161..5250bfb 100644
--- a/Swiften/Parser/IQParser.h
+++ b/Swiften/Parser/IQParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,15 +7,15 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericStanzaParser.h>
#include <Swiften/Elements/IQ.h>
+#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 b74be5b..be0a92d 100644
--- a/Swiften/Parser/LibXMLParser.cpp
+++ b/Swiften/Parser/LibXMLParser.cpp
@@ -1,62 +1,65 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/LibXMLParser.h>
-#include <iostream>
-#include <boost/numeric/conversion/cast.hpp>
#include <cassert>
#include <cstring>
-#include <libxml/parser.h>
+#include <memory>
#include <string>
+#include <boost/numeric/conversion/cast.hpp>
+
+#include <libxml/parser.h>
+
+#include <Swiften/Base/Log.h>
#include <Swiften/Parser/XMLParserClient.h>
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 :-)
+ SWIFT_LOG(error) << "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*, ... ) {
@@ -65,42 +68,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, nullptr, 0, nullptr);
+ 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..9f752ce 100644
--- a/Swiften/Parser/LibXMLParser.h
+++ b/Swiften/Parser/LibXMLParser.h
@@ -6,27 +6,28 @@
#pragma once
+#include <memory>
+
#include <boost/noncopyable.hpp>
-#include <boost/shared_ptr.hpp>
#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();
-
- bool parse(const std::string& data);
-
- private:
- static bool initialized;
-
- struct Private;
- boost::shared_ptr<Private> p;
- };
+ /**
+ * 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);
+
+ private:
+ static bool initialized;
+
+ struct Private;
+ const std::unique_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 ab2c008..cfbfc38 100644
--- a/Swiften/Parser/MessageParser.h
+++ b/Swiften/Parser/MessageParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,15 +7,15 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericStanzaParser.h>
#include <Swiften/Elements/Message.h>
+#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 5bde98e..a824922 100644
--- a/Swiften/Parser/PayloadParser.h
+++ b/Swiften/Parser/PayloadParser.h
@@ -1,51 +1,50 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-
+#include <memory>
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/AttributeMap.h>
#include <Swiften/Elements/Payload.h>
+#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 std::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 856345e..bca1e83 100644
--- a/Swiften/Parser/PayloadParserFactoryCollection.cpp
+++ b/Swiften/Parser/PayloadParserFactoryCollection.cpp
@@ -1,37 +1,42 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/bind.hpp>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
+
#include <algorithm>
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
+#include <boost/bind.hpp>
+
#include <Swiften/Parser/PayloadParserFactory.h>
namespace Swift {
-PayloadParserFactoryCollection::PayloadParserFactoryCollection() : defaultFactory_(NULL) {
+PayloadParserFactoryCollection::PayloadParserFactoryCollection() : defaultFactory_(nullptr) {
+}
+
+PayloadParserFactoryCollection::~PayloadParserFactoryCollection() {
}
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 c106940..cc0db5a 100644
--- a/Swiften/Parser/PayloadParserFactoryCollection.h
+++ b/Swiften/Parser/PayloadParserFactoryCollection.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,24 +8,25 @@
#include <vector>
-#include <Swiften/Parser/AttributeMap.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Parser/AttributeMap.h>
namespace Swift {
- class PayloadParserFactory;
+ class PayloadParserFactory;
- class SWIFTEN_API PayloadParserFactoryCollection {
- public:
- PayloadParserFactoryCollection();
+ class SWIFTEN_API PayloadParserFactoryCollection {
+ public:
+ PayloadParserFactoryCollection();
+ virtual ~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..405c593 100644
--- a/Swiften/Parser/PayloadParsers/BytestreamsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/BytestreamsParser.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,8 +8,6 @@
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
BytestreamsParser::BytestreamsParser() : level(TopLevel) {
@@ -19,26 +17,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..e4f8ab9 100644
--- a/Swiften/Parser/PayloadParsers/CarbonsReceivedParser.cpp
+++ b/Swiften/Parser/PayloadParsers/CarbonsReceivedParser.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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_ = std::dynamic_pointer_cast<ForwardedParser>(std::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..6cc1f43 100644
--- a/Swiften/Parser/PayloadParsers/CarbonsReceivedParser.h
+++ b/Swiften/Parser/PayloadParsers/CarbonsReceivedParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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_;
+ std::shared_ptr<ForwardedParser> forwardedParser_;
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/CarbonsSentParser.cpp b/Swiften/Parser/PayloadParsers/CarbonsSentParser.cpp
index b430249..f446042 100644
--- a/Swiften/Parser/PayloadParsers/CarbonsSentParser.cpp
+++ b/Swiften/Parser/PayloadParsers/CarbonsSentParser.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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_ = std::dynamic_pointer_cast<ForwardedParser>(std::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..d4e12ba 100644
--- a/Swiften/Parser/PayloadParsers/CarbonsSentParser.h
+++ b/Swiften/Parser/PayloadParsers/CarbonsSentParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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_;
+ std::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 a2f2c5b..80686d2 100644
--- a/Swiften/Parser/PayloadParsers/CommandParser.cpp
+++ b/Swiften/Parser/PayloadParsers/CommandParser.cpp
@@ -1,143 +1,145 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/CommandParser.h>
+#include <cassert>
+
#include <boost/cast.hpp>
-#include <Swiften/Parser/PayloadParsers/FormParserFactory.h>
#include <Swiften/Parser/PayloadParsers/FormParser.h>
+#include <Swiften/Parser/PayloadParsers/FormParserFactory.h>
namespace Swift {
-CommandParser::CommandParser() : level_(TopLevel), inNote_(false), inActions_(false), noteType_(Command::Note::Info), formParser_(0) {
- formParserFactory_ = new FormParserFactory();
+CommandParser::CommandParser() : level_(TopLevel), inNote_(false), inActions_(false), noteType_(Command::Note::Info), formParser_(nullptr) {
+ 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);
- }
-
- 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) {
- }
-
- if (formParser_) {
- formParser_->handleStartElement(element, ns, attributes);
- }
+ ++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);
+ }
+
+ 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);
+ }
}
void CommandParser::handleEndElement(const std::string& element, const std::string& 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 (formParser_) {
+ formParser_->handleEndElement(element, ns);
+ }
+
+ if (level_ == FormOrNoteOrActionsLevel) {
+ if (formParser_) {
+ Form::ref form(std::dynamic_pointer_cast<Form>(formParser_->getPayload()));
+ assert(form);
+ getPayloadInternal()->setForm(form);
+ delete formParser_;
+ formParser_ = nullptr;
+ }
+ 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 eaf9359..6ded2e2 100644
--- a/Swiften/Parser/PayloadParsers/DiscoInfoParser.cpp
+++ b/Swiften/Parser/PayloadParsers/DiscoInfoParser.cpp
@@ -1,59 +1,62 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/DiscoInfoParser.h>
+#include <cassert>
+
#include <boost/optional.hpp>
+
#include <Swiften/Parser/PayloadParsers/FormParser.h>
namespace Swift {
-DiscoInfoParser::DiscoInfoParser() : level_(TopLevel), formParser_(NULL) {
+DiscoInfoParser::DiscoInfoParser() : level_(TopLevel), formParser_(nullptr) {
}
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_ = nullptr;
+ }
}
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 e2e225a..222bcbd 100644
--- a/Swiften/Parser/PayloadParsers/ErrorParser.cpp
+++ b/Swiften/Parser/PayloadParsers/ErrorParser.cpp
@@ -1,12 +1,13 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/ErrorParser.h>
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
+
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
namespace Swift {
@@ -14,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..10f5431 100644
--- a/Swiften/Parser/PayloadParsers/ErrorParser.h
+++ b/Swiften/Parser/PayloadParsers/ErrorParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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_;
+ std::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 d400c4c..dff45df 100644
--- a/Swiften/Parser/PayloadParsers/FormParser.cpp
+++ b/Swiften/Parser/PayloadParsers/FormParser.cpp
@@ -1,254 +1,252 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <iostream>
#include <Swiften/Parser/PayloadParsers/FormParser.h>
+
#include <map>
-#include <Swiften/Base/foreach.h>
namespace Swift {
-FormParser::FormParser() : level_(TopLevel), parsingItem_(false), parsingReported_(false), parsingOption_(false), parseStarted_(false), hasReportedRef_(false){
+FormParser::FormParser() : level_(TopLevel), parsingItem_(false), parsingReported_(false), parsingOption_(false), hasReportedRef_(false){
}
void FormParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
- if (level_ == TopLevel) {
- parseStarted_ = true;
- 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_ = std::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_ = std::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_ = std::make_shared<FormSection>();
+ currentSection_->setLabel(attributes.getAttribute("label"));
+ sectionStack_.push_back(currentSection_);
+ currentSections_.push_back(currentSection_);
+ }
+ if (element == "reportedref") {
+ currentReportedRef_ = std::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_ = std::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 pRef, page->getFieldRefs()) {
- if (pRef == currentField_->getName()) {
- page->addField(currentField_);
- }
- }
- }
- foreach (boost::shared_ptr<FormSection> section, currentSections_) {
- foreach (std::string sRef, section->getFieldRefs()) {
- if (sRef == 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 it's 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) {
+ for (const auto& page : currentPages_) {
+ for (const auto& pageRef : page->getFieldRefs()) {
+ if (pageRef == currentField_->getName()) {
+ page->addField(currentField_);
+ }
+ }
+ }
+ for (const auto& section : currentSections_) {
+ for (const auto& sectionRef : section->getFieldRefs()) {
+ if (sectionRef == currentField_->getName()) {
+ section->addField(currentField_);
+ }
+ }
+ }
+ } else {
+ getPayloadInternal()->addField(currentField_);
+ }
+ }
+ currentField_.reset();
+ }
+ }
+ if (level_ > PayloadLevel) {
+ if (element == "section") {
+ if (sectionStack_.size() > 1) {
+ // Add the section at the top of the stack to the level below
+ sectionStack_.at(sectionStack_.size()-2)->addChildSection(sectionStack_.at(sectionStack_.size()-1));
+ sectionStack_.pop_back();
+ }
+ else if (sectionStack_.size() == 1) {
+ // Add the remaining section on the stack to its parent page
+ currentPage_->addChildSection(sectionStack_.at(sectionStack_.size()-1));
+ sectionStack_.pop_back();
+ }
+ }
+ if (currentReportedRef_ && !hasReportedRef_) {
+ if (sectionStack_.size() > 0) {
+ sectionStack_.at(sectionStack_.size()-1)->addReportedRef(currentReportedRef_);
+ } else if (currentPage_) {
+ currentPage_->addReportedRef(currentReportedRef_);
+ }
+ 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 a3b7556..e1491b1 100644
--- a/Swiften/Parser/PayloadParsers/FormParser.h
+++ b/Swiften/Parser/PayloadParsers/FormParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -11,37 +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 parseStarted_;
- 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<std::shared_ptr<FormPage> > currentPages_;
+ std::vector<std::shared_ptr<FormSection> > sectionStack_;
+ std::vector<std::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 431c65c..72a665a 100644
--- a/Swiften/Parser/PayloadParsers/ForwardedParser.cpp
+++ b/Swiften/Parser/PayloadParsers/ForwardedParser.cpp
@@ -1,72 +1,73 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swiften/Parser/PayloadParsers/ForwardedParser.h>
+
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
+
#include <Swiften/Base/DateTime.h>
#include <Swiften/Parser/IQParser.h>
#include <Swiften/Parser/MessageParser.h>
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/DelayParser.h>
-#include <Swiften/Parser/PayloadParsers/ForwardedParser.h>
#include <Swiften/Parser/PresenceParser.h>
-
using namespace Swift;
ForwardedParser::ForwardedParser(PayloadParserFactoryCollection* factories) : factories_(factories), level_(TopLevel) {
}
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_ = std::dynamic_pointer_cast<StanzaParser>(std::make_shared<IQParser>(factories_));
+ } else if (element == "message" && ns == "jabber:client") {
+ childParser_ = std::dynamic_pointer_cast<StanzaParser>(std::make_shared<MessageParser>(factories_));
+ } else if (element == "presence" && ns == "jabber:client") {
+ childParser_ = std::dynamic_pointer_cast<StanzaParser>(std::make_shared<PresenceParser>(factories_));
+ } else if (element == "delay" && ns == "urn:xmpp:delay") { /* nested delay payload */
+ delayParser_ = std::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(std::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 ad400e8..f91fda5 100644
--- a/Swiften/Parser/PayloadParsers/ForwardedParser.h
+++ b/Swiften/Parser/PayloadParsers/ForwardedParser.h
@@ -1,40 +1,40 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Forwarded.h>
#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_;
+ std::shared_ptr<StanzaParser> childParser_;
+ std::shared_ptr<DelayParser> delayParser_;
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp b/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp
index d791819..b67556e 100644
--- a/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp
+++ b/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp
@@ -1,17 +1,14 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h>
-#include <Swiften/Base/foreach.h>
-
#include <Swiften/Elements/BlockListPayload.h>
#include <Swiften/Elements/BlockPayload.h>
#include <Swiften/Elements/UnblockPayload.h>
-
#include <Swiften/Parser/GenericPayloadParser.h>
#include <Swiften/Parser/GenericPayloadParserFactory.h>
#include <Swiften/Parser/GenericPayloadParserFactory2.h>
@@ -46,7 +43,6 @@
#include <Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.h>
#include <Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h>
#include <Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.h>
-#include <Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.h>
#include <Swiften/Parser/PayloadParsers/JingleParserFactory.h>
#include <Swiften/Parser/PayloadParsers/JingleReasonParser.h>
#include <Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.h>
@@ -92,99 +88,97 @@
#include <Swiften/Parser/PayloadParsers/VCardUpdateParser.h>
#include <Swiften/Parser/PayloadParsers/WhiteboardParser.h>
-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(std::make_shared<GenericPayloadParserFactory<IBBParser> >("", "http://jabber.org/protocol/ibb"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<StatusShowParser> >("show"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<StatusParser> >("status"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<ReplaceParser> >("replace", "http://swift.im/protocol/replace"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<ReplaceParser> >("replace", "urn:xmpp:message-correct:0"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<LastParser> >("query", "jabber:iq:last"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<BodyParser> >("body"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<SubjectParser> >("subject"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<ThreadParser> >("thread"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<PriorityParser> >("priority"));
+ factories_.push_back(std::make_shared<ErrorParserFactory>(this));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<DelayParser> >("delay", "urn:xmpp:delay"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<SoftwareVersionParser> >("query", "jabber:iq:version"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<StorageParser> >("storage", "storage:bookmarks"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<RosterItemExchangeParser> >("x", "http://jabber.org/protocol/rosterx"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<RosterParser> >("query", "jabber:iq:roster"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<DiscoInfoParser> >("query", "http://jabber.org/protocol/disco#info"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<DiscoItemsParser> >("query", "http://jabber.org/protocol/disco#items"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<CapsInfoParser> >("c", "http://jabber.org/protocol/caps"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<ResourceBindParser> >("bind", "urn:ietf:params:xml:ns:xmpp-bind"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<StartSessionParser> >("session", "urn:ietf:params:xml:ns:xmpp-session"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<BlockParser<BlockPayload> > >("block", "urn:xmpp:blocking"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<BlockParser<BlockListPayload> > >("blocklist", "urn:xmpp:blocking"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<BlockParser<UnblockPayload> > >("unblock", "urn:xmpp:blocking"));
+ factories_.push_back(std::make_shared<SecurityLabelParserFactory>());
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<SecurityLabelsCatalogParser> >("catalog", "urn:xmpp:sec-label:catalog:2"));
+ factories_.push_back(std::make_shared<FormParserFactory>());
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<CommandParser> >("command", "http://jabber.org/protocol/commands"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<InBandRegistrationPayloadParser> >("query", "jabber:iq:register"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<SearchPayloadParser> >("query", "jabber:iq:search"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<StreamInitiationParser> >("si", "http://jabber.org/protocol/si"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<BytestreamsParser> >("query", "http://jabber.org/protocol/bytestreams"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<VCardUpdateParser> >("x", "vcard-temp:x:update"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<VCardParser> >("vCard", "vcard-temp"));
+ factories_.push_back(std::make_shared<PrivateStorageParserFactory>(this));
+ factories_.push_back(std::make_shared<ChatStateParserFactory>());
+ factories_.push_back(std::make_shared<MUCUserPayloadParserFactory>(this));
+ factories_.push_back(std::make_shared<MUCOwnerPayloadParserFactory>(this));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<MUCInvitationPayloadParser> >("x", "jabber:x:conference"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<MUCAdminPayloadParser> >("query", "http://jabber.org/protocol/muc#admin"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<MUCDestroyPayloadParser> >("destroy", "http://jabber.org/protocol/muc#user"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<MUCDestroyPayloadParser> >("destroy", "http://jabber.org/protocol/muc#owner"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<NicknameParser> >("nick", "http://jabber.org/protocol/nick"));
+ factories_.push_back(std::make_shared<JingleParserFactory>(this));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<JingleReasonParser> >("reason", "urn:xmpp:jingle:1"));
+ factories_.push_back(std::make_shared<JingleContentPayloadParserFactory>(this));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<JingleIBBTransportMethodPayloadParser> >("transport", "urn:xmpp:jingle:transports:ibb:1"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<JingleS5BTransportMethodPayloadParser> >("transport", "urn:xmpp:jingle:transports:s5b:1"));
+ factories_.push_back(std::make_shared<JingleFileTransferDescriptionParserFactory>(this));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<StreamInitiationFileInfoParser> >("file", "http://jabber.org/protocol/si/profile/file-transfer"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<JingleFileTransferFileInfoParser> >("file", "urn:xmpp:jingle:apps:file-transfer:4"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<JingleFileTransferHashParser> >("checksum"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<S5BProxyRequestParser> >("query", "http://jabber.org/protocol/bytestreams"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<WhiteboardParser> >("wb", "http://swift.im/whiteboard"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<UserLocationParser> >("geoloc", "http://jabber.org/protocol/geoloc"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<UserTuneParser> >("tune", "http://jabber.org/protocol/tune"));
+ factories_.push_back(std::make_shared<DeliveryReceiptParserFactory>());
+ factories_.push_back(std::make_shared<DeliveryReceiptRequestParserFactory>());
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<IdleParser> >("idle", "urn:xmpp:idle:1"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory2<PubSubParser> >("pubsub", "http://jabber.org/protocol/pubsub", this));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory2<PubSubOwnerPubSubParser> >("pubsub", "http://jabber.org/protocol/pubsub#owner", this));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory2<PubSubEventParser> >("event", "http://jabber.org/protocol/pubsub#event", this));
+ factories_.push_back(std::make_shared<PubSubErrorParserFactory>());
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<ResultSetParser> >("set", "http://jabber.org/protocol/rsm"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory2<ForwardedParser> >("forwarded", "urn:xmpp:forward:0", this));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory2<MAMResultParser> >("result", "urn:xmpp:mam:0", this));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<MAMQueryParser> >("query", "urn:xmpp:mam:0"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<MAMFinParser> >("fin", "urn:xmpp:mam:0"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory2<IsodeIQDelegationParser> >("delegate", "http://isode.com/iq_delegation", this));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<CarbonsEnableParser> >("enable", "urn:xmpp:carbons:2"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<CarbonsDisableParser> >("disable", "urn:xmpp:carbons:2"));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory2<CarbonsReceivedParser> >("received", "urn:xmpp:carbons:2", this));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory2<CarbonsSentParser> >("sent", "urn:xmpp:carbons:2", this));
+ factories_.push_back(std::make_shared<GenericPayloadParserFactory<CarbonsPrivateParser> >("private", "urn:xmpp:carbons:2"));
- foreach(shared_ptr<PayloadParserFactory> factory, factories_) {
- addFactory(factory.get());
- }
- defaultFactory_ = new RawXMLPayloadParserFactory();
- setDefaultFactory(defaultFactory_);
+ for (auto& 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(nullptr);
+ delete defaultFactory_;
+ for (auto& factory : factories_) {
+ removeFactory(factory.get());
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h b/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h
index 73d785e..e59a6e0 100644
--- a/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h
+++ b/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h
@@ -1,26 +1,26 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <vector>
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#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< std::shared_ptr<PayloadParserFactory> > factories_;
+ PayloadParserFactory* defaultFactory_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/IBBParser.cpp b/Swiften/Parser/PayloadParsers/IBBParser.cpp
index c04e3cc..9b6babc 100644
--- a/Swiften/Parser/PayloadParsers/IBBParser.cpp
+++ b/Swiften/Parser/PayloadParsers/IBBParser.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,7 +8,6 @@
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
@@ -20,57 +19,56 @@ 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 (char c : currentText) {
+ 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 e8bbcf6..c1922c0 100644
--- a/Swiften/Parser/PayloadParsers/IdleParser.h
+++ b/Swiften/Parser/PayloadParsers/IdleParser.h
@@ -5,27 +5,27 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-
+
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Idle.h>
#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 a9aa266..f0241b0 100644
--- a/Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.cpp
@@ -1,131 +1,133 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.h>
+#include <cassert>
+
#include <boost/cast.hpp>
-#include <Swiften/Parser/PayloadParsers/FormParserFactory.h>
#include <Swiften/Parser/PayloadParsers/FormParser.h>
+#include <Swiften/Parser/PayloadParsers/FormParserFactory.h>
namespace Swift {
-InBandRegistrationPayloadParser::InBandRegistrationPayloadParser() : level(TopLevel), formParser(NULL) {
- formParserFactory = new FormParserFactory();
+InBandRegistrationPayloadParser::InBandRegistrationPayloadParser() : level(TopLevel), formParser(nullptr) {
+ 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 = nullptr;
+ }
+ 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..2efe3c8 100644
--- a/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.cpp
+++ b/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.cpp
@@ -1,19 +1,15 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
using namespace Swift;
@@ -24,36 +20,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(std::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 fcdbeb1..eaedd27 100644
--- a/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.h
+++ b/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/IsodeIQDelegation.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.cpp b/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.cpp
index 1431b9e..3a01676 100644
--- a/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.cpp
@@ -4,71 +4,77 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "JingleContentPayloadParser.h"
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
-#include <Swiften/Parser/PayloadParserFactory.h>
-#include <Swiften/Elements/JinglePayload.h>
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h>
#include <Swiften/Base/Log.h>
+#include <Swiften/Elements/JinglePayload.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
+#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) {
+ std::shared_ptr<JingleTransportPayload> transport = std::dynamic_pointer_cast<JingleTransportPayload>(currentPayloadParser->getPayload());
+ if (transport) {
+ getPayloadInternal()->addTransport(transport);
+ }
+
+ std::shared_ptr<JingleDescription> description = std::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..fde07cb 100644
--- a/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h
+++ b/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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 fb1836f..1e433a6 100644
--- a/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.cpp
@@ -5,19 +5,19 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h>
-#include <boost/optional.hpp>
#include <boost/lexical_cast.hpp>
+#include <boost/optional.hpp>
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
-#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Base/DateTime.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
@@ -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) {
+ std::shared_ptr<JingleFileTransferFileInfo> info = std::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..b148d9b 100644
--- a/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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 2a62f23..4f8b9a9 100644
--- a/Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.cpp
@@ -1,79 +1,79 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.h>
-#include <boost/optional.hpp>
#include <boost/lexical_cast.hpp>
+#include <boost/optional.hpp>
#include <Swiften/Base/DateTime.h>
#include <Swiften/StringCodecs/Base64.h>
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 6a1a031..4adf3bd 100644
--- a/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.cpp
@@ -5,54 +5,55 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "JingleFileTransferHashParser.h"
+#include <Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h>
+
+#include <memory>
-#include <boost/shared_ptr.hpp>
#include <boost/algorithm/string.hpp>
-#include <Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.h>
#include <Swiften/Parser/GenericPayloadParserFactory.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParsers/JingleFileTransferFileInfoParser.h>
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 = std::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) {
+ std::shared_ptr<JingleFileTransferFileInfo> info = std::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..1b47921 100644
--- a/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014-2015 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
};
}
diff --git a/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp b/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp
index e4c86cc..438420b 100644
--- a/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp
@@ -5,43 +5,43 @@
*/
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.h>
+
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
-#include "JingleIBBTransportMethodPayloadParser.h"
-
#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 7041a92..a88a5b2 100644
--- a/Swiften/Parser/PayloadParsers/JingleParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleParser.cpp
@@ -5,115 +5,116 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/JingleParser.h>
-#include <Swiften/Parser/PayloadParserFactory.h>
-#include <Swiften/Elements/JingleContentPayload.h>
-#include <Swiften/Elements/JingleFileTransferHash.h>
-#include <Swiften/Base/Log.h>
#include <boost/intrusive_ptr.hpp>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Elements/JingleContentPayload.h>
+#include <Swiften/Elements/JingleFileTransferHash.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
+
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) {
+ std::shared_ptr<JinglePayload::Reason> reason = std::dynamic_pointer_cast<JinglePayload::Reason>(currentPayloadParser->getPayload());
+ if (reason) {
+ getPayloadInternal()->setReason(*reason);
+ }
+
+ std::shared_ptr<JingleContentPayload> payload = std::dynamic_pointer_cast<JingleContentPayload>(currentPayloadParser->getPayload());
+ if (payload) {
+ getPayloadInternal()->addContent(payload);
+ }
+
+ std::shared_ptr<JingleFileTransferHash> hash = std::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..1dcc9e7 100644
--- a/Swiften/Parser/PayloadParsers/JingleParser.h
+++ b/Swiften/Parser/PayloadParsers/JingleParser.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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 3df82ae..9a81e5f 100644
--- a/Swiften/Parser/PayloadParsers/JingleReasonParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleReasonParser.cpp
@@ -4,78 +4,84 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include "JingleReasonParser.h"
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swiften/Parser/PayloadParsers/JingleReasonParser.h>
#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 dc05352..e639e20 100644
--- a/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp
@@ -5,91 +5,89 @@
*/
/*
-* Copyright (c) 2014-2015 Isode Limited.
-* All rights reserved.v3.
-* See the COPYING file for more information.
-*/
+ * Copyright (c) 2014-2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.h>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
-#include "JingleS5BTransportMethodPayloadParser.h"
-
#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("");
+ 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::fromString(attributes.getAttributeValue("host").get_value_or("")).get_value_or(HostAddress()), 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"));
- 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);
+ }
+ }
- 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;
+ }
- ++level;
- }
-
- void JingleS5BTransportMethodPayloadParser::handleEndElement(const std::string&, const std::string&) {
- --level;
-
+ void JingleS5BTransportMethodPayloadParser::handleEndElement(const std::string&, const std::string&) {
+ --level;
+ }
- }
-
- void JingleS5BTransportMethodPayloadParser::handleCharacterData(const std::string&) {
+ 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;
- }
- }
+ 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 adf66ef..88dd571 100644
--- a/Swiften/Parser/PayloadParsers/MAMFinParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MAMFinParser.cpp
@@ -1,16 +1,18 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swiften/Parser/PayloadParsers/MAMFinParser.h>
+
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
+
#include <Swiften/Base/DateTime.h>
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/ResultSetParser.h>
-#include <Swiften/Parser/PayloadParsers/MAMFinParser.h>
using namespace Swift;
@@ -18,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_ = std::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(std::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 ec1605a..f08231e 100644
--- a/Swiften/Parser/PayloadParsers/MAMFinParser.h
+++ b/Swiften/Parser/PayloadParsers/MAMFinParser.h
@@ -1,36 +1,36 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericPayloadParser.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/MAMFin.h>
+#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:
+ std::shared_ptr<ResultSetParser> resultSetParser_;
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/MAMQueryParser.cpp b/Swiften/Parser/PayloadParsers/MAMQueryParser.cpp
index 54eaf84..4919d22 100644
--- a/Swiften/Parser/PayloadParsers/MAMQueryParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MAMQueryParser.cpp
@@ -1,15 +1,17 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swiften/Parser/PayloadParsers/MAMQueryParser.h>
+
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
+
#include <Swiften/Base/DateTime.h>
#include <Swiften/Parser/PayloadParsers/FormParser.h>
#include <Swiften/Parser/PayloadParsers/ResultSetParser.h>
-#include <Swiften/Parser/PayloadParsers/MAMQueryParser.h>
using namespace Swift;
@@ -17,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_ = std::make_shared<FormParser>();
+ } else if (element == "set" && ns == "http://jabber.org/protocol/rsm") {
+ resultSetParser_ = std::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(std::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(std::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 23286c8..7e4b58a 100644
--- a/Swiften/Parser/PayloadParsers/MAMQueryParser.h
+++ b/Swiften/Parser/PayloadParsers/MAMQueryParser.h
@@ -1,40 +1,39 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
-
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/MAMQuery.h>
#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:
+ std::shared_ptr<FormParser> formParser_;
+ std::shared_ptr<ResultSetParser> resultSetParser_;
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/MAMResultParser.cpp b/Swiften/Parser/PayloadParsers/MAMResultParser.cpp
index 41a7336..b810b87 100644
--- a/Swiften/Parser/PayloadParsers/MAMResultParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MAMResultParser.cpp
@@ -1,15 +1,16 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swiften/Parser/PayloadParsers/MAMResultParser.h>
+
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
#include <Swiften/Base/DateTime.h>
#include <Swiften/Parser/PayloadParsers/ForwardedParser.h>
-#include <Swiften/Parser/PayloadParsers/MAMResultParser.h>
using namespace Swift;
@@ -17,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_ = std::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(std::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 f0c9ee5..e68e365 100644
--- a/Swiften/Parser/PayloadParsers/MAMResultParser.h
+++ b/Swiften/Parser/PayloadParsers/MAMResultParser.h
@@ -1,40 +1,39 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
-
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/MAMResult.h>
#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:
+ std::shared_ptr<ForwardedParser> payloadParser_;
+ PayloadParserFactoryCollection* factories_;
+ int level_;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp b/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp
index 717fc60..bac2a78 100644
--- a/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,16 +8,15 @@
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/MUCOccupant.h>
namespace Swift {
void MUCAdminPayloadParser::handleTree(ParserElement::ref root) {
- foreach (ParserElement::ref itemElement, root->getChildren("item", "http://jabber.org/protocol/muc#admin")) {
- MUCItem item = MUCItemParser::itemFromTree(itemElement);
- getPayloadInternal()->addItem(item);
- }
+ for (const auto& itemElement : root->getChildren("item", "http://jabber.org/protocol/muc#admin")) {
+ MUCItem item = MUCItemParser::itemFromTree(itemElement);
+ getPayloadInternal()->addItem(item);
+ }
}
}
diff --git a/Swiften/Parser/PayloadParsers/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..46bc9c5 100644
--- a/Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.cpp
@@ -1,22 +1,20 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.h>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
void MUCDestroyPayloadParser::handleTree(ParserElement::ref root) {
- std::string ns = root->getNamespace();
- std::string jid = root->getAttributes().getAttribute("jid");
- if (!jid.empty()) {
- getPayloadInternal()->setNewVenue(JID(jid));
- }
- getPayloadInternal()->setReason(root->getChild("reason", ns)->getText());
+ 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 e61c2b2..14d6d16 100644
--- a/Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.cpp
@@ -1,23 +1,24 @@
/*
- * Copyright (c) 2011-2014 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.h>
+
#include <Swiften/Parser/Tree/NullParserElement.h>
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(!std::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 9a0d84a..ce74671 100644
--- a/Swiften/Parser/PayloadParsers/MUCItemParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCItemParser.cpp
@@ -1,80 +1,79 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/MUCItemParser.h>
+#include <cassert>
+
#include <boost/lexical_cast.hpp>
#include <Swiften/Elements/MUCOccupant.h>
-#include <cassert>
-#include <iostream>
-
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 f8f0937..7e7c0d4 100644
--- a/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.cpp
@@ -1,12 +1,13 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.h>
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
+
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
namespace Swift {
@@ -14,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..4c1f048 100644
--- a/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.h
+++ b/Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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 45be402..b1bf78e 100644
--- a/Swiften/Parser/PayloadParsers/MUCUserPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/MUCUserPayloadParser.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,51 +8,50 @@
#include <boost/lexical_cast.hpp>
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
-#include <Swiften/Parser/PayloadParserFactory.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/MUCOccupant.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/Tree/TreeReparser.h>
namespace Swift {
void MUCUserPayloadParser::handleTree(ParserElement::ref root) {
- foreach (ParserElement::ref child, root->getAllChildren()) {
- 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));
- }
- }
+ for (const auto& child : root->getAllChildren()) {
+ if (child->getName() == "item" && child->getNamespace() == root->getNamespace()) {
+ MUCItem item = MUCItemParser::itemFromTree(child);
+ getPayloadInternal()->addItem(item);
+ }
+ else if (child->getName() == "password" && child->getNamespace() == root->getNamespace()) {
+ getPayloadInternal()->setPassword(child->getText());
+ }
+ else if (child->getName() == "invite" && child->getNamespace() == root->getNamespace()) {
+ MUCUserPayload::Invite invite;
+ std::string to = child->getAttributes().getAttribute("to");
+ if (!to.empty()) {
+ invite.to = to;
+ }
+ std::string from = child->getAttributes().getAttribute("from");
+ if (!from.empty()) {
+ invite.from = from;
+ }
+ ParserElement::ref reason = child->getChild("reason", root->getNamespace());
+ if (reason) {
+ invite.reason = reason->getText();
+ }
+ getPayloadInternal()->setInvite(invite);
+ }
+ else if (child->getName() == "status" && child->getNamespace() == root->getNamespace()) {
+ MUCUserPayload::StatusCode status;
+ try {
+ status.code = boost::lexical_cast<int>(child->getAttributes().getAttribute("code").c_str());
+ getPayloadInternal()->addStatusCode(status);
+ } catch (boost::bad_lexical_cast&) {
+ }
+ }
+ 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 945895b..e40249a 100644
--- a/Swiften/Parser/PayloadParsers/PrivateStorageParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PrivateStorageParser.cpp
@@ -1,12 +1,13 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/PrivateStorageParser.h>
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
+
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
namespace Swift {
@@ -14,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..c1d695c 100644
--- a/Swiften/Parser/PayloadParsers/PrivateStorageParser.h
+++ b/Swiften/Parser/PayloadParsers/PrivateStorageParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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..764b3a7 100644
--- a/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.cpp
@@ -1,64 +1,58 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubAffiliationParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
-#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/EnumParser.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
using namespace Swift;
-PubSubAffiliationParser::PubSubAffiliationParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubAffiliationParser::PubSubAffiliationParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ 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 fa13bd4..eabe3db 100644
--- a/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubAffiliation.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.cpp
index b316134..ffa5d2d 100644
--- a/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.cpp
@@ -1,18 +1,15 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/PubSubAffiliationParser.h>
using namespace Swift;
@@ -24,42 +21,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 == 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 == 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 = std::make_shared<PubSubAffiliationParser>(parsers);
+ }
+ }
+
+ 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);
- }
-
- if (level == 1) {
- if (element == "affiliation" && ns == "http://jabber.org/protocol/pubsub") {
- getPayloadInternal()->addAffiliation(boost::dynamic_pointer_cast<PubSubAffiliation>(currentPayloadParser->getPayload()));
- }
- currentPayloadParser.reset();
- }
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+ if (element == "affiliation" && ns == "http://jabber.org/protocol/pubsub") {
+ getPayloadInternal()->addAffiliation(std::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 25314a9..2f80dbd 100644
--- a/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubAffiliations.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubConfigureParser.cpp b/Swiften/Parser/PayloadParsers/PubSubConfigureParser.cpp
index cac9924..e0a5847 100644
--- a/Swiften/Parser/PayloadParsers/PubSubConfigureParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubConfigureParser.cpp
@@ -1,61 +1,57 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubConfigureParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParsers/FormParser.h>
using namespace Swift;
-PubSubConfigureParser::PubSubConfigureParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubConfigureParser::PubSubConfigureParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 = std::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(std::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 8708fb7..90c2f3e 100644
--- a/Swiften/Parser/PayloadParsers/PubSubConfigureParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubConfigureParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubConfigure.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubCreateParser.cpp b/Swiften/Parser/PayloadParsers/PubSubCreateParser.cpp
index fbf2eba..4f03e29 100644
--- a/Swiften/Parser/PayloadParsers/PubSubCreateParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubCreateParser.cpp
@@ -1,59 +1,52 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubCreateParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-
using namespace Swift;
-PubSubCreateParser::PubSubCreateParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubCreateParser::PubSubCreateParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 65a4c59..a1ada74 100644
--- a/Swiften/Parser/PayloadParsers/PubSubCreateParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubCreateParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubCreate.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubDefaultParser.cpp b/Swiften/Parser/PayloadParsers/PubSubDefaultParser.cpp
index bf5a210..a6d751c 100644
--- a/Swiften/Parser/PayloadParsers/PubSubDefaultParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubDefaultParser.cpp
@@ -1,64 +1,58 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubDefaultParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
-#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/EnumParser.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
using namespace Swift;
-PubSubDefaultParser::PubSubDefaultParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubDefaultParser::PubSubDefaultParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ 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 d9ad21a..01bea7b 100644
--- a/Swiften/Parser/PayloadParsers/PubSubDefaultParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubDefaultParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubDefault.h>
#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:
+ int level;
+ std::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 276ad34..adc36e9 100644
--- a/Swiften/Parser/PayloadParsers/PubSubErrorParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubErrorParser.h
@@ -1,35 +1,35 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubError.h>
-#include <Swiften/Parser/GenericPayloadParser.h>
#include <Swiften/Parser/EnumParser.h>
+#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..8ca1d7d 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.cpp
@@ -1,59 +1,54 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-
using namespace Swift;
-PubSubEventAssociateParser::PubSubEventAssociateParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubEventAssociateParser::PubSubEventAssociateParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 3aecdd5..4bb9bd9 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventAssociate.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.cpp
index 373d971..4452601 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.cpp
@@ -1,18 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.h>
#include <Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.h>
@@ -25,48 +24,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 = std::make_shared<PubSubEventDisassociateParser>(parsers);
+ }
+ if (element == "associate" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = std::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(std::dynamic_pointer_cast<PubSubEventDisassociate>(currentPayloadParser->getPayload()));
+ }
+ if (element == "associate" && ns == "http://jabber.org/protocol/pubsub#event") {
+ getPayloadInternal()->setAssociate(std::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 de65837..ffdafcf 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventCollection.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.cpp
index 97e5ad9..9bde91b 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.cpp
@@ -1,65 +1,61 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParsers/FormParser.h>
using namespace Swift;
-PubSubEventConfigurationParser::PubSubEventConfigurationParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubEventConfigurationParser::PubSubEventConfigurationParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 == 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 == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
+
+ if (level == 1) {
+ if (element == "x" && ns == "jabber:x:data") {
+ currentPayloadParser = std::make_shared<FormParser>();
+ }
+ }
+
+ 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);
- }
-
- 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(std::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 22cf70a..dddb7a4 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventConfiguration.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.cpp
index 9641a03..1569b90 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.cpp
@@ -1,18 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.h>
using namespace Swift;
@@ -24,42 +23,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 = std::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(std::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 9f24732..270430e 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventDelete.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.cpp
index 25ec3a9..4e72d85 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.cpp
@@ -1,59 +1,52 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-
using namespace Swift;
-PubSubEventDisassociateParser::PubSubEventDisassociateParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubEventDisassociateParser::PubSubEventDisassociateParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 bd0b904..5f7f1af 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventDisassociate.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventItemParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventItemParser.cpp
index e245e63..ba8f714 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventItemParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventItemParser.cpp
@@ -1,19 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubEventItemParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
using namespace Swift;
@@ -24,46 +22,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 23914fd..bd2e72e 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventItemParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventItemParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventItem.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.cpp
index 2aafb74..ae4f668 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.cpp
@@ -1,18 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/PubSubEventItemParser.h>
#include <Swiften/Parser/PayloadParsers/PubSubEventRetractParser.h>
@@ -25,48 +24,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 = std::make_shared<PubSubEventItemParser>(parsers);
+ }
+ if (element == "retract" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = std::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(std::dynamic_pointer_cast<PubSubEventItem>(currentPayloadParser->getPayload()));
+ }
+ if (element == "retract" && ns == "http://jabber.org/protocol/pubsub#event") {
+ getPayloadInternal()->addRetract(std::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 fb38deb..34b3669 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventItems.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventParser.cpp
index 34db2f8..d92730a 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventParser.cpp
@@ -1,24 +1,23 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubEventParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-#include <Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h>
-#include <Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h>
-#include <Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h>
-#include <Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.h>
#include <Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.h>
+#include <Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h>
+#include <Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h>
+#include <Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h>
+#include <Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h>
using namespace Swift;
@@ -29,53 +28,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 = std::make_shared<PubSubEventItemsParser>(parsers);
+ }
+ if (element == "collection" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = std::make_shared<PubSubEventCollectionParser>(parsers);
+ }
+ if (element == "purge" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = std::make_shared<PubSubEventPurgeParser>(parsers);
+ }
+ if (element == "configuration" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = std::make_shared<PubSubEventConfigurationParser>(parsers);
+ }
+ if (element == "delete" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = std::make_shared<PubSubEventDeleteParser>(parsers);
+ }
+ if (element == "subscription" && ns == "http://jabber.org/protocol/pubsub#event") {
+ currentPayloadParser = std::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(std::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 76b9b53..3b231b0 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEvent.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.cpp
index cdd3808..30a4d6c 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.cpp
@@ -1,59 +1,52 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-
using namespace Swift;
-PubSubEventPurgeParser::PubSubEventPurgeParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubEventPurgeParser::PubSubEventPurgeParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 f20a7cd..563283c 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventPurge.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.cpp
index 8ea236e..46f1922 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.cpp
@@ -1,59 +1,52 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-
using namespace Swift;
-PubSubEventRedirectParser::PubSubEventRedirectParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubEventRedirectParser::PubSubEventRedirectParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 99076de..603fbec 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventRedirect.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.cpp
index 7a4df14..226bb33 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.cpp
@@ -1,59 +1,53 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubEventRetractParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
using namespace Swift;
-PubSubEventRetractParser::PubSubEventRetractParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubEventRetractParser::PubSubEventRetractParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 f49faeb..141790b 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventRetract.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.cpp b/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.cpp
index 9308101..45c16f6 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.cpp
@@ -1,76 +1,70 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
-#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Base/DateTime.h>
#include <Swiften/Parser/EnumParser.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
using namespace Swift;
-PubSubEventSubscriptionParser::PubSubEventSubscriptionParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubEventSubscriptionParser::PubSubEventSubscriptionParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 == 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 >= 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);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ 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 73d8c6c..0d56a20 100644
--- a/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventSubscription.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubItemParser.cpp b/Swiften/Parser/PayloadParsers/PubSubItemParser.cpp
index a2b22ac..ff5bfc7 100644
--- a/Swiften/Parser/PayloadParsers/PubSubItemParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubItemParser.cpp
@@ -1,19 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubItemParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
using namespace Swift;
@@ -24,40 +22,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 36cdd00..c6e4ccf 100644
--- a/Swiften/Parser/PayloadParsers/PubSubItemParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubItemParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubItem.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubItemsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubItemsParser.cpp
index f07b6fa..2edfddb 100644
--- a/Swiften/Parser/PayloadParsers/PubSubItemsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubItemsParser.cpp
@@ -1,18 +1,18 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubItemsParser.h>
-#include <boost/optional.hpp>
#include <boost/lexical_cast.hpp>
+#include <boost/optional.hpp>
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/PubSubItemParser.h>
using namespace Swift;
@@ -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 = std::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(std::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 41d1188..ad6e746 100644
--- a/Swiften/Parser/PayloadParsers/PubSubItemsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubItemsParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubItems.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOptionsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOptionsParser.cpp
index 438d728..2098d8f 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOptionsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOptionsParser.cpp
@@ -1,73 +1,69 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubOptionsParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParsers/FormParser.h>
using namespace Swift;
-PubSubOptionsParser::PubSubOptionsParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubOptionsParser::PubSubOptionsParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 = std::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(std::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 d1458c6..ac14caf 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOptionsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOptionsParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOptions.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.cpp
index 3a8ceb8..d868ef6 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.cpp
@@ -1,66 +1,61 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
-#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/EnumParser.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
using namespace Swift;
-PubSubOwnerAffiliationParser::PubSubOwnerAffiliationParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubOwnerAffiliationParser::PubSubOwnerAffiliationParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ 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 7a95868..0a6503f 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerAffiliation.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.cpp
index df3813e..2f21b7a 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.cpp
@@ -1,18 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.h>
using namespace Swift;
@@ -24,42 +23,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 = std::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(std::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 dc78d61..52c7fa9 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerAffiliations.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.cpp
index 1cc8660..7fa6506 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.cpp
@@ -1,65 +1,61 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParsers/FormParser.h>
using namespace Swift;
-PubSubOwnerConfigureParser::PubSubOwnerConfigureParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubOwnerConfigureParser::PubSubOwnerConfigureParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 == 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 == 0) {
+ if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) {
+ getPayloadInternal()->setNode(*attributeValue);
+ }
+ }
+
+ if (level == 1) {
+ if (element == "x" && ns == "jabber:x:data") {
+ currentPayloadParser = std::make_shared<FormParser>();
+ }
+ }
+
+ 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);
- }
-
- 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(std::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 d2dca30..34000fa 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerConfigure.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.cpp
index a704411..e453230 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.cpp
@@ -1,61 +1,55 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParsers/FormParser.h>
using namespace Swift;
-PubSubOwnerDefaultParser::PubSubOwnerDefaultParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubOwnerDefaultParser::PubSubOwnerDefaultParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 = std::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(std::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 d036a30..528c297 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerDefault.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.cpp
index 9817793..c30e404 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.cpp
@@ -1,18 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.h>
using namespace Swift;
@@ -24,42 +23,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 = std::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(std::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 f9ab7cb..99a8c0e 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerDelete.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.cpp
index 71b1c16..e26f291 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.cpp
@@ -1,24 +1,23 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
+#include <Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h>
+#include <Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h>
#include <Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.h>
-#include <Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h>
#include <Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.h>
#include <Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.h>
-#include <Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h>
-#include <Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h>
+#include <Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h>
using namespace Swift;
@@ -29,53 +28,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 = std::make_shared<PubSubOwnerConfigureParser>(parsers);
+ }
+ if (element == "subscriptions" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ currentPayloadParser = std::make_shared<PubSubOwnerSubscriptionsParser>(parsers);
+ }
+ if (element == "default" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ currentPayloadParser = std::make_shared<PubSubOwnerDefaultParser>(parsers);
+ }
+ if (element == "purge" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ currentPayloadParser = std::make_shared<PubSubOwnerPurgeParser>(parsers);
+ }
+ if (element == "affiliations" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ currentPayloadParser = std::make_shared<PubSubOwnerAffiliationsParser>(parsers);
+ }
+ if (element == "delete" && ns == "http://jabber.org/protocol/pubsub#owner") {
+ currentPayloadParser = std::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(std::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 30e3bb8..35420f7 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerPubSub.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.cpp
index f417ec2..7c637cf 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.cpp
@@ -1,59 +1,53 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
using namespace Swift;
-PubSubOwnerPurgeParser::PubSubOwnerPurgeParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubOwnerPurgeParser::PubSubOwnerPurgeParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 e0f5c60..f85b2bb 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerPurge.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.cpp
index e4ad149..6d0b2a7 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.cpp
@@ -1,59 +1,52 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-
using namespace Swift;
-PubSubOwnerRedirectParser::PubSubOwnerRedirectParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubOwnerRedirectParser::PubSubOwnerRedirectParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 5211d6f..1197952 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerRedirect.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.cpp
index 9e2fdee..92b81f3 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.cpp
@@ -1,66 +1,60 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
-#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/EnumParser.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
using namespace Swift;
-PubSubOwnerSubscriptionParser::PubSubOwnerSubscriptionParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubOwnerSubscriptionParser::PubSubOwnerSubscriptionParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ 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 dc2a52d..74a61a2 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerSubscription.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.cpp
index 857bd87..6d5e43c 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.cpp
@@ -1,18 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.h>
using namespace Swift;
@@ -24,42 +23,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 = std::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(std::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 ddc2292..541d225 100644
--- a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerSubscriptions.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubParser.cpp b/Swiften/Parser/PayloadParsers/PubSubParser.cpp
index c6574a8..eef6e5e 100644
--- a/Swiften/Parser/PayloadParsers/PubSubParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubParser.cpp
@@ -1,31 +1,29 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-#include <Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
+#include <Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h>
#include <Swiften/Parser/PayloadParsers/PubSubConfigureParser.h>
-#include <Swiften/Parser/PayloadParsers/PubSubDefaultParser.h>
#include <Swiften/Parser/PayloadParsers/PubSubCreateParser.h>
-#include <Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h>
+#include <Swiften/Parser/PayloadParsers/PubSubDefaultParser.h>
+#include <Swiften/Parser/PayloadParsers/PubSubItemsParser.h>
#include <Swiften/Parser/PayloadParsers/PubSubOptionsParser.h>
#include <Swiften/Parser/PayloadParsers/PubSubPublishParser.h>
-#include <Swiften/Parser/PayloadParsers/PubSubOptionsParser.h>
-#include <Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h>
-#include <Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h>
-#include <Swiften/Parser/PayloadParsers/PubSubItemsParser.h>
#include <Swiften/Parser/PayloadParsers/PubSubRetractParser.h>
+#include <Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h>
+#include <Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h>
#include <Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.h>
+#include <Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h>
using namespace Swift;
@@ -36,90 +34,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 = std::make_shared<PubSubItemsParser>(parsers);
+ }
+ if (element == "create" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = std::make_shared<PubSubCreateParser>(parsers);
+ }
+ if (element == "publish" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = std::make_shared<PubSubPublishParser>(parsers);
+ }
+ if (element == "affiliations" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = std::make_shared<PubSubAffiliationsParser>(parsers);
+ }
+ if (element == "retract" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = std::make_shared<PubSubRetractParser>(parsers);
+ }
+ if (element == "options" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = std::make_shared<PubSubOptionsParser>(parsers);
+ }
+ if (element == "configure" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = std::make_shared<PubSubConfigureParser>(parsers);
+ }
+ if (element == "default" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = std::make_shared<PubSubDefaultParser>(parsers);
+ }
+ if (element == "subscriptions" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = std::make_shared<PubSubSubscriptionsParser>(parsers);
+ }
+ if (element == "subscribe" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = std::make_shared<PubSubSubscribeParser>(parsers);
+ }
+ if (element == "unsubscribe" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = std::make_shared<PubSubUnsubscribeParser>(parsers);
+ }
+ if (element == "subscription" && ns == "http://jabber.org/protocol/pubsub") {
+ currentPayloadParser = std::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 = std::dynamic_pointer_cast<PubSubOptions>(currentPayloadParser->getPayload());
+ }
+ else if (element == "configure" && ns == "http://jabber.org/protocol/pubsub") {
+ configurePayload = std::dynamic_pointer_cast<PubSubConfigure>(currentPayloadParser->getPayload());
+ }
+ else {
+ getPayloadInternal()->setPayload(std::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 (std::shared_ptr<PubSubCreate> create = std::dynamic_pointer_cast<PubSubCreate>(getPayloadInternal()->getPayload())) {
+ if (configurePayload) {
+ create->setConfigure(configurePayload);
+ }
+ }
+ if (std::shared_ptr<PubSubSubscribe> subscribe = std::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 0562046..1f40ca9 100644
--- a/Swiften/Parser/PayloadParsers/PubSubParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubParser.h
@@ -1,38 +1,38 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSub.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ std::shared_ptr<PubSubConfigure> configurePayload;
+ std::shared_ptr<PubSubOptions> optionsPayload;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubPublishParser.cpp b/Swiften/Parser/PayloadParsers/PubSubPublishParser.cpp
index 2b52edc..8c8db3d 100644
--- a/Swiften/Parser/PayloadParsers/PubSubPublishParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubPublishParser.cpp
@@ -1,18 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubPublishParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/PubSubItemParser.h>
using namespace Swift;
@@ -24,42 +23,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 = std::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(std::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 6dd039f..ad7dd11 100644
--- a/Swiften/Parser/PayloadParsers/PubSubPublishParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubPublishParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubPublish.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubRetractParser.cpp b/Swiften/Parser/PayloadParsers/PubSubRetractParser.cpp
index 909e82f..d5d5c0a 100644
--- a/Swiften/Parser/PayloadParsers/PubSubRetractParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubRetractParser.cpp
@@ -1,18 +1,15 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubRetractParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/PubSubItemParser.h>
using namespace Swift;
@@ -24,45 +21,49 @@ 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")) {
+ boost::optional<bool> notify;
+ if (attributeValue.is_initialized()) {
+ notify = (attributeValue.get() == "true" || attributeValue.get() == "1") ? true : false;
+ }
+ getPayloadInternal()->setNotify(notify);
+ }
+ }
- 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 = std::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(std::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 8d7b3fd..6bea498 100644
--- a/Swiften/Parser/PayloadParsers/PubSubRetractParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubRetractParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubRetract.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.cpp
index 64bea49..88b7758 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.cpp
@@ -1,57 +1,48 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-
using namespace Swift;
-PubSubSubscribeOptionsParser::PubSubSubscribeOptionsParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubSubscribeOptionsParser::PubSubSubscribeOptionsParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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 928e893..328818b 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubSubscribeOptions.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.cpp b/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.cpp
index 3f34fc7..1de39e7 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.cpp
@@ -1,64 +1,57 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-
using namespace Swift;
-PubSubSubscribeParser::PubSubSubscribeParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubSubscribeParser::PubSubSubscribeParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ 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 b4838d3..31221cb 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubSubscribe.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.cpp b/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.cpp
index b78c841..0f27cb2 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.cpp
@@ -1,19 +1,18 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
-#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/EnumParser.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.h>
using namespace Swift;
@@ -25,55 +24,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 = std::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(std::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 98baa3d..7075a99 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubSubscription.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.cpp b/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.cpp
index 85929a4..8b0fbef 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.cpp
@@ -1,18 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h>
using namespace Swift;
@@ -24,42 +23,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 = std::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(std::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 25a2c2e..2371a56 100644
--- a/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubSubscriptions.h>
#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;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.cpp b/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.cpp
index 1b1808e..ea3b46d 100644
--- a/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.cpp
+++ b/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.cpp
@@ -1,67 +1,62 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h>
#include <boost/optional.hpp>
-
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
-
using namespace Swift;
-PubSubUnsubscribeParser::PubSubUnsubscribeParser(PayloadParserFactoryCollection* parsers) : parsers(parsers), level(0) {
+PubSubUnsubscribeParser::PubSubUnsubscribeParser(PayloadParserFactoryCollection* /*parsers*/) : level(0) {
}
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);
- }
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
- if (level == 1) {
-
- currentPayloadParser.reset();
- }
- }
+ 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 914554e..e471130 100644
--- a/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h
+++ b/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h
@@ -1,34 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubUnsubscribe.h>
#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:
+ int level;
+ std::shared_ptr<PayloadParser> currentPayloadParser;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/RawXMLPayloadParser.cpp b/Swiften/Parser/PayloadParsers/RawXMLPayloadParser.cpp
index 801ee6a..97abce3 100644
--- a/Swiften/Parser/PayloadParsers/RawXMLPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/RawXMLPayloadParser.cpp
@@ -1,10 +1,11 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/RawXMLPayloadParser.h>
+
#include <Swiften/Parser/SerializingParser.h>
namespace Swift {
@@ -13,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 a363098..f7b7601 100644
--- a/Swiften/Parser/PayloadParsers/RawXMLPayloadParserFactory.h
+++ b/Swiften/Parser/PayloadParsers/RawXMLPayloadParserFactory.h
@@ -1,27 +1,28 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
#include <Swiften/Base/API.h>
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParsers/RawXMLPayloadParser.h>
-#include <string>
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 6835141..80d89d7 100644
--- a/Swiften/Parser/PayloadParsers/ResultSetParser.cpp
+++ b/Swiften/Parser/PayloadParsers/ResultSetParser.cpp
@@ -1,12 +1,14 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/ResultSetParser.h>
-#include <boost/optional.hpp>
+
#include <boost/lexical_cast.hpp>
+#include <boost/optional.hpp>
+
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParserFactoryCollection.h>
@@ -16,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 5277803..aa18ae6 100644
--- a/Swiften/Parser/PayloadParsers/ResultSetParser.h
+++ b/Swiften/Parser/PayloadParsers/ResultSetParser.h
@@ -1,36 +1,36 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/ResultSet.h>
#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 32be2c7..f99f592 100644
--- a/Swiften/Parser/PayloadParsers/RosterItemExchangeParser.cpp
+++ b/Swiften/Parser/PayloadParsers/RosterItemExchangeParser.cpp
@@ -4,7 +4,14 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Parser/PayloadParsers/RosterItemExchangeParser.h>
+
#include <Swiften/Parser/SerializingParser.h>
namespace Swift {
@@ -13,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..90fb518 100644
--- a/Swiften/Parser/PayloadParsers/RosterParser.cpp
+++ b/Swiften/Parser/PayloadParsers/RosterParser.cpp
@@ -1,104 +1,106 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/RosterParser.h>
+#include <cassert>
+
#include <boost/optional.hpp>
#include <Swiften/Parser/SerializingParser.h>
namespace Swift {
-RosterParser::RosterParser() : level_(TopLevel), inItem_(false), unknownContentParser_(0) {
+RosterParser::RosterParser() : level_(TopLevel), inItem_(false), unknownContentParser_(nullptr) {
}
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_ = nullptr;
+ }
+ 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 5cfd28d..502f400 100644
--- a/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp
+++ b/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp
@@ -5,12 +5,12 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "S5BProxyRequestParser.h"
+#include <Swiften/Parser/PayloadParsers/S5BProxyRequestParser.h>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
@@ -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 3e1bd55..0d79204 100644
--- a/Swiften/Parser/PayloadParsers/SearchPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/SearchPayloadParser.cpp
@@ -1,113 +1,115 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/SearchPayloadParser.h>
+#include <cassert>
+
#include <boost/cast.hpp>
-#include <Swiften/Parser/PayloadParsers/FormParserFactory.h>
#include <Swiften/Parser/PayloadParsers/FormParser.h>
+#include <Swiften/Parser/PayloadParsers/FormParserFactory.h>
namespace Swift {
-SearchPayloadParser::SearchPayloadParser() : level(TopLevel), formParser(NULL) {
- formParserFactory = new FormParserFactory();
+SearchPayloadParser::SearchPayloadParser() : level(TopLevel), formParser(nullptr) {
+ 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 = nullptr;
+ }
+ 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 22b6614..6e2319f 100644
--- a/Swiften/Parser/PayloadParsers/SecurityLabelParser.cpp
+++ b/Swiften/Parser/PayloadParsers/SecurityLabelParser.cpp
@@ -1,69 +1,72 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/SecurityLabelParser.h>
+
+#include <cassert>
+
#include <Swiften/Parser/SerializingParser.h>
namespace Swift {
-SecurityLabelParser::SecurityLabelParser() : level_(TopLevel), labelParser_(0) {
+SecurityLabelParser::SecurityLabelParser() : level_(TopLevel), labelParser_(nullptr) {
}
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_ = nullptr;
+ }
+ }
+ 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();
+std::shared_ptr<SecurityLabel> SecurityLabelParser::getLabelPayload() const {
+ return getPayloadInternal();
}
}
diff --git a/Swiften/Parser/PayloadParsers/SecurityLabelParser.h b/Swiften/Parser/PayloadParsers/SecurityLabelParser.h
index 857df6a..cc444a4 100644
--- a/Swiften/Parser/PayloadParsers/SecurityLabelParser.h
+++ b/Swiften/Parser/PayloadParsers/SecurityLabelParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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);
+ std::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 d5e3171..1897080 100644
--- a/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.cpp
+++ b/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.cpp
@@ -1,74 +1,76 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
-
#include <Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.h>
-#include <Swiften/Parser/PayloadParsers/SecurityLabelParserFactory.h>
+
+#include <cassert>
+#include <memory>
+
#include <Swiften/Parser/PayloadParsers/SecurityLabelParser.h>
+#include <Swiften/Parser/PayloadParsers/SecurityLabelParserFactory.h>
namespace Swift {
-SecurityLabelsCatalogParser::SecurityLabelsCatalogParser() : level_(TopLevel), labelParser_(0) {
- labelParserFactory_ = new SecurityLabelParserFactory();
+SecurityLabelsCatalogParser::SecurityLabelsCatalogParser() : level_(TopLevel), labelParser_(nullptr) {
+ 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_ = std::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_) {
+ std::shared_ptr<SecurityLabel> currentLabel = labelParser_->getLabelPayload();
+ assert(currentLabel);
+ currentItem_->setLabel(currentLabel);
+ delete labelParser_;
+ labelParser_ = nullptr;
+ }
+ 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..edfa86b 100644
--- a/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.h
+++ b/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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_;
+ std::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 b3888d6..ab5dbbe 100644
--- a/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp
+++ b/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp
@@ -5,15 +5,15 @@
*/
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.h>
-#include <boost/optional.hpp>
#include <boost/lexical_cast.hpp>
+#include <boost/optional.hpp>
#include <Swiften/Base/DateTime.h>
#include <Swiften/Base/Log.h>
@@ -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..ad66b3f 100644
--- a/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp
+++ b/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,112 +9,112 @@
#include <boost/lexical_cast.hpp>
#include <boost/cast.hpp>
+#include <cassert>
+
#include <Swiften/Parser/PayloadParsers/FormParserFactory.h>
#include <Swiften/Parser/PayloadParsers/FormParser.h>
-#include <Swiften/Base/foreach.h>
-
#define FILE_TRANSFER_NS "http://jabber.org/protocol/si/profile/file-transfer"
#define FEATURE_NEG_NS "http://jabber.org/protocol/feature-neg"
namespace Swift {
-StreamInitiationParser::StreamInitiationParser() : level(TopLevel), formParser(0), inFile(false), inFeature(false) {
- formParserFactory = new FormParserFactory();
+StreamInitiationParser::StreamInitiationParser() : level(TopLevel), formParser(nullptr), inFile(false), inFeature(false) {
+ 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 = std::dynamic_pointer_cast<FormField>(form->getField("stream-method"));
+ if (field) {
+ if (form->getType() == Form::FormType) {
+ for (const auto& option : field->getOptions()) {
+ getPayloadInternal()->addProvidedMethod(option.value);
+ }
+ }
+ else if (form->getType() == Form::SubmitType) {
+ if (!field->getValues().empty()) {
+ getPayloadInternal()->setRequestedMethod(field->getValues()[0]);
+ }
+ }
+ }
+ }
+ delete formParser;
+ formParser = nullptr;
+ }
+ }
}
void StreamInitiationParser::handleCharacterData(const std::string& data) {
- if (formParser) {
- formParser->handleCharacterData(data);
- }
- else {
- currentText += data;
- }
+ 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 ddd3a88..17a800e 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/BlockParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/BlockParserTest.cpp
@@ -4,69 +4,74 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/PayloadParsers/BlockParser.h>
-#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
-
+#include <Swiften/Elements/BlockListPayload.h>
#include <Swiften/Elements/BlockPayload.h>
#include <Swiften/Elements/UnblockPayload.h>
-#include <Swiften/Elements/BlockListPayload.h>
+#include <Swiften/Parser/PayloadParsers/BlockParser.h>
+#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
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 6fd38bc..b5b9995 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/CarbonsParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/CarbonsParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,121 +7,121 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Elements/Message.h>
-#include <Swiften/Elements/Thread.h>
-#include <Swiften/Elements/CarbonsEnable.h>
#include <Swiften/Elements/CarbonsDisable.h>
+#include <Swiften/Elements/CarbonsEnable.h>
+#include <Swiften/Elements/CarbonsPrivate.h>
#include <Swiften/Elements/CarbonsReceived.h>
#include <Swiften/Elements/CarbonsSent.h>
-#include <Swiften/Elements/CarbonsPrivate.h>
+#include <Swiften/Elements/Message.h>
+#include <Swiften/Elements/Thread.h>
+#include <Swiften/JID/JID.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
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);
+
+ std::shared_ptr<Forwarded> forwarded = received->getForwarded();
+ CPPUNIT_ASSERT(forwarded);
+
+ std::shared_ptr<Message> message = std::dynamic_pointer_cast<Message>(forwarded->getStanza());
+ CPPUNIT_ASSERT(message);
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.example/balcony"), message->getFrom());
+
+ std::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);
+
+ std::shared_ptr<Forwarded> forwarded = sent->getForwarded();
+ CPPUNIT_ASSERT(forwarded);
+
+ std::shared_ptr<Message> message = std::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 56ad448..fa8d014 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/CommandParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/CommandParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,80 +7,80 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
#include <Swiften/Elements/Command.h>
+#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
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..d93fd1f 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/DeliveryReceiptParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/DeliveryReceiptParserTest.cpp
@@ -4,6 +4,12 @@
* See http://www.opensource.org/licenses/bsd-license.php for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -15,29 +21,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 = std::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 = std::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..6e866fc 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/DiscoInfoParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/DiscoInfoParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 = std::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 = std::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 = std::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..977ef8e 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/DiscoItemsParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/DiscoItemsParserTest.cpp
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -13,30 +19,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>"));
+
+ std::shared_ptr<DiscoItems> payload = std::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 cbd416a..5402614 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/ErrorParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/ErrorParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,51 +7,51 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <Swiften/Elements/Delay.h>
#include <Swiften/Parser/PayloadParsers/ErrorParser.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
-#include <Swiften/Elements/Delay.h>
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 = std::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 = std::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(std::dynamic_pointer_cast<Delay>(payload->getPayload()));
+ }
};
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/FormParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/FormParserTest.cpp
index c9e685e..610c4f3 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/FormParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/FormParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,222 +7,225 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
#include <Swiften/Elements/Form.h>
+#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
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(payload);
+ 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(payload);
+ 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(payload);
+
+ 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());
+ std::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..a807d4e 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>"));
+
+ std::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()));
+
+ std::shared_ptr<IQ> iq = std::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>"));
+
+ std::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()));
+
+ std::shared_ptr<Message> message = std::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>"));
+
+ std::shared_ptr<Forwarded> payload = parser.getPayload<Forwarded>();
+ CPPUNIT_ASSERT(!!payload);
+ CPPUNIT_ASSERT(!payload->getDelay());
+
+ std::shared_ptr<Message> message = std::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>"));
+
+ std::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()));
+
+ std::shared_ptr<Presence> presence = std::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 5332a61..782cb32 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/IBBParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/IBBParserTest.cpp
@@ -1,40 +1,39 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/ByteArray.h>
-
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/Elements/IBB.h>
+#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
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 74da474..462247a 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/IdleParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/IdleParserTest.cpp
@@ -4,35 +4,41 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
-#include <Swiften/Elements/Presence.h>
-#include <Swiften/Elements/Idle.h>
#include <Swiften/Base/DateTime.h>
+#include <Swiften/Elements/Idle.h>
+#include <Swiften/Elements/Presence.h>
+#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
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 f9a9efd..6d08812 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/InBandRegistrationPayloadParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/InBandRegistrationPayloadParserTest.cpp
@@ -4,65 +4,71 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <Swiften/Elements/Form.h>
+#include <Swiften/Elements/InBandRegistrationPayload.h>
#include <Swiften/Parser/PayloadParsers/InBandRegistrationPayloadParser.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
-#include <Swiften/Elements/Form.h>
-#include <Swiften/Elements/InBandRegistrationPayload.h>
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..c502c8a 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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::fromString("192.168.4.1").get(), 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::fromString("24.24.24.1").get(), 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::fromString("192.169.1.10").get(), 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::fromString("134.102.201.180").get(), 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::fromString("2001:638:708:30c9:219:d1ff:fea4:a17d").get(), 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..6a8e2ed 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/MAMFinParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/MAMFinParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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' />"));
+
+ std::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>"));
+
+ std::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());
+ std::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..8750c2e 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/MAMQueryParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/MAMQueryParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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>"));
+
+
+ std::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());
+ std::shared_ptr<FormField> fieldType = payload->getForm()->getField("FORM_TYPE");
+ CPPUNIT_ASSERT(fieldType);
+ CPPUNIT_ASSERT_EQUAL(std::string("urn:xmpp:mam:0"), fieldType->getTextSingleValue());
+ std::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());
+ std::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>"));
+
+ std::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>"));
+ std::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>"));
+
+ std::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..15912b1 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>"));
+
+ std::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());
+
+ std::shared_ptr<Forwarded> forwarded = payload->getPayload();
+ CPPUNIT_ASSERT(forwarded->getDelay());
+ CPPUNIT_ASSERT_EQUAL(std::string("2010-07-10T23:08:25Z"), dateTimeToString(forwarded->getDelay()->getStamp()));
+
+ std::shared_ptr<Message> message = std::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..d403872 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/MUCAdminPayloadParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/MUCAdminPayloadParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 = std::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 7f5bb40..f0cf68d 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,87 +7,86 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Parser/PayloadParsers/MUCUserPayloadParser.h>
#include <Swiften/Elements/MUCDestroyPayload.h>
+#include <Swiften/Parser/PayloadParsers/MUCUserPayloadParser.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
using namespace Swift;
class MUCUserPayloadParserTest : public CppUnit::TestFixture
{
- CPPUNIT_TEST_SUITE(MUCUserPayloadParserTest);
- CPPUNIT_TEST(testParseEmpty);
- CPPUNIT_TEST(testParse);
- CPPUNIT_TEST(testParseDestroy);
- CPPUNIT_TEST(testParseInvite);
- CPPUNIT_TEST_SUITE_END();
-
- public:
- MUCUserPayloadParserTest() {}
-
- void testParse() {
- PayloadsParserTester parser;
-
- CPPUNIT_ASSERT(parser.parse("<x xmlns=\"http://jabber.org/protocol/muc#user\"><status code='110'/><item affiliation=\"owner\" role=\"visitor\"><actor jid=\"kev@tester.lit\"/><reason>malice</reason></item><status code='210'/></x>"));
-
- bool found110 = false;
- bool found210 = false;
-
- MUCUserPayload::ref payload = 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 = std::dynamic_pointer_cast<MUCUserPayload>(parser.getPayload());
+
+ for (const auto& status : payload->getStatusCodes()) {
+ if (status.code == 110) found110 = true;
+ if (status.code == 210) found210 = true;
+ }
+
+ MUCItem item = payload->getItems()[0];
+ CPPUNIT_ASSERT_EQUAL(MUCOccupant::Owner, item.affiliation.get());
+ CPPUNIT_ASSERT_EQUAL(MUCOccupant::Visitor, item.role.get());
+ CPPUNIT_ASSERT_EQUAL(JID("kev@tester.lit"), item.actor.get());
+ CPPUNIT_ASSERT_EQUAL(std::string("malice"), item.reason.get());
+ CPPUNIT_ASSERT(found110);
+ CPPUNIT_ASSERT(found210);
+ }
+
+ void testParseEmpty() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<x xmlns=\"http://jabber.org/protocol/muc#user\"/>"));
+
+ MUCUserPayload::ref payload = std::dynamic_pointer_cast<MUCUserPayload>(parser.getPayload());
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT(payload->getItems().empty());
+ }
+
+ void testParseDestroy() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<x xmlns=\"http://jabber.org/protocol/muc#user\"><destroy jid='alice@wonderland.lit'><reason>bert</reason></destroy></x>"));
+
+ MUCUserPayload::ref payload = std::dynamic_pointer_cast<MUCUserPayload>(parser.getPayload());
+ CPPUNIT_ASSERT(payload);
+ MUCDestroyPayload::ref destroy = std::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 = std::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 f9b4193..a85a692 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h
+++ b/Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h
@@ -1,14 +1,14 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Parser/UnitTest/ParserTester.h>
#include <Swiften/Parser/PayloadParser.h>
+#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 d9c30b8..2c1ff8e 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h
+++ b/Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h
@@ -1,66 +1,68 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <cassert>
+
+#include <Swiften/Elements/Payload.h>
+#include <Swiften/Parser/PayloadParser.h>
#include <Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h>
+#include <Swiften/Parser/PlatformXMLParserFactory.h>
#include <Swiften/Parser/XMLParser.h>
#include <Swiften/Parser/XMLParserClient.h>
-#include <Swiften/Parser/PlatformXMLParserFactory.h>
-#include <Swiften/Elements/Payload.h>
-#include <Swiften/Parser/PayloadParser.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();
- }
+ std::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>
+ std::shared_ptr<T> getPayload() const {
+ return std::dynamic_pointer_cast<T>(payloadParser->getPayload());
+ }
- private:
- XMLParser* xmlParser;
- FullPayloadParserFactoryCollection factories;
- boost::shared_ptr<PayloadParser> payloadParser;
- int level;
- };
+ private:
+ XMLParser* xmlParser;
+ FullPayloadParserFactoryCollection factories;
+ std::shared_ptr<PayloadParser> payloadParser;
+ int level;
+ };
}
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/PriorityParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/PriorityParserTest.cpp
index 285ac56..2c89f0f 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/PriorityParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/PriorityParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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());
- }
+ std::shared_ptr<Priority> payload = std::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());
- }
+ std::shared_ptr<Priority> payload = std::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 58f5a6e..06f3ae5 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/PrivateStorageParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/PrivateStorageParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,87 +9,87 @@
#include <Swiften/Elements/Storage.h>
#include <Swiften/Parser/PayloadParsers/PrivateStorageParser.h>
-#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h>
+#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
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>"));
+
+ std::shared_ptr<PrivateStorage> payload = std::dynamic_pointer_cast<PrivateStorage>(parser.getPayload());
+ CPPUNIT_ASSERT(payload);
+ std::shared_ptr<Storage> storage = std::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'/>"));
+
+ std::shared_ptr<PrivateStorage> payload = std::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>"));
+
+ std::shared_ptr<PrivateStorage> payload = std::dynamic_pointer_cast<PrivateStorage>(parser.getPayload());
+ CPPUNIT_ASSERT(payload);
+ std::shared_ptr<Storage> storage = std::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(!std::dynamic_pointer_cast<PrivateStorage>(testling.getPayload())->getPayload());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(PrivateStorageParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/PubSubRetractParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/PubSubRetractParserTest.cpp
new file mode 100644
index 0000000..91bc123
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/UnitTest/PubSubRetractParserTest.cpp
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
+#include <Swiften/Elements/ContainerPayload.h>
+#include <Swiften/Parser/PayloadParsers/PubSubRetractParser.h>
+#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
+
+using namespace Swift;
+
+class PubSubRetractParserTest : public CppUnit::TestFixture {
+ CPPUNIT_TEST_SUITE(PubSubRetractParserTest);
+ CPPUNIT_TEST(testParse);
+ CPPUNIT_TEST(testParseNotify);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testParse() {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<pubsub xmlns='http://jabber.org/protocol/pubsub'>"
+ "<retract node='princely_musings' xmlns='http://jabber.org/protocol/pubsub'>"
+ "<item id='ae890ac52d0df67ed7cfdf51b644e901' xmlns='http://jabber.org/protocol/pubsub'/>"
+ "</retract>"
+ "</pubsub>"));
+
+ auto payload = parser.getPayload<ContainerPayload<PubSubPayload>>();
+ std::shared_ptr<PubSubRetract> retract = std::dynamic_pointer_cast<PubSubRetract>(payload->getPayload());
+ CPPUNIT_ASSERT(retract);
+ CPPUNIT_ASSERT_EQUAL(std::string("princely_musings"), retract->getNode());
+ CPPUNIT_ASSERT_EQUAL(false, retract->isNotify().is_initialized());
+ }
+
+ void testParseNotify() {
+ {
+ PayloadsParserTester parser;
+
+ CPPUNIT_ASSERT(parser.parse("<pubsub xmlns='http://jabber.org/protocol/pubsub'>"
+ "<retract node='princely_musings' notify='true' xmlns='http://jabber.org/protocol/pubsub'>"
+ "<item id='ae890ac52d0df67ed7cfdf51b644e901' xmlns='http://jabber.org/protocol/pubsub'/>"
+ "</retract>"
+ "</pubsub>"));
+
+ auto payload = parser.getPayload<ContainerPayload<PubSubPayload>>();
+ std::shared_ptr<PubSubRetract> retract = std::dynamic_pointer_cast<PubSubRetract>(payload->getPayload());
+ CPPUNIT_ASSERT(retract);
+ CPPUNIT_ASSERT_EQUAL(std::string("princely_musings"), retract->getNode());
+ CPPUNIT_ASSERT_EQUAL(true, retract->isNotify().get());
+ }
+
+ {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse("<pubsub xmlns='http://jabber.org/protocol/pubsub'>"
+ "<retract node='princely_musings' notify='0' xmlns='http://jabber.org/protocol/pubsub'>"
+ "<item id='ae890ac52d0df67ed7cfdf51b644e901' xmlns='http://jabber.org/protocol/pubsub'/>"
+ "</retract>"
+ "</pubsub>"));
+
+ auto payload = parser.getPayload<ContainerPayload<PubSubPayload>>();
+ auto retract = std::dynamic_pointer_cast<PubSubRetract>(payload->getPayload());
+ CPPUNIT_ASSERT(retract);
+ CPPUNIT_ASSERT_EQUAL(std::string("princely_musings"), retract->getNode());
+ CPPUNIT_ASSERT_EQUAL(false, retract->isNotify().get());
+ }
+ }
+};
+
+CPPUNIT_TEST_SUITE_REGISTRATION(PubSubRetractParserTest);
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..6d77d4a 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/ReplaceTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/ReplaceTest.cpp
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -13,24 +19,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 = std::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 = std::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..da5d978 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/ResultSetParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/ResultSetParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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());
- }
+ std::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());
- }
+ std::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 492e0ec..5fe4168 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/SearchPayloadParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/SearchPayloadParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,175 +7,175 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
#include <Swiften/Elements/SearchPayload.h>
+#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
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 6909ec2..9b0679d 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,69 +7,69 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
#include <Swiften/Elements/StreamInitiation.h>
+#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
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 2d5d628..98a147f 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/UserLocationParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/UserLocationParserTest.cpp
@@ -4,101 +4,107 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/PayloadParsers/UserLocationParser.h>
-#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
+#include <Swiften/Base/DateTime.h>
#include <Swiften/Elements/UserLocation.h>
-#include <Swiften/Base/DateTime.h>
+#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
+#include <Swiften/Parser/PayloadParsers/UserLocationParser.h>
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.75, payload->getAltitude().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Near"), payload->getLocality().get());
+ CPPUNIT_ASSERT_EQUAL(1.670, payload->getLatitude().get());
+ CPPUNIT_ASSERT_EQUAL(0.95, 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.7578, payload->getLongitude().get());
+ CPPUNIT_ASSERT_EQUAL(5.66, payload->getError().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("67"), payload->getPostalCode().get());
+ CPPUNIT_ASSERT_EQUAL(12.89, 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.77, 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.75, payload->getAltitude().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("Near"), payload->getLocality().get());
+ CPPUNIT_ASSERT(!payload->getLatitude());
+ CPPUNIT_ASSERT_EQUAL(0.95, 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.7578, payload->getLongitude().get());
+ CPPUNIT_ASSERT_EQUAL(5.66, payload->getError().get());
+ CPPUNIT_ASSERT_EQUAL(std::string("67"), payload->getPostalCode().get());
+ CPPUNIT_ASSERT_EQUAL(12.89, 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 a1b284b..3783231 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/UserTuneParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/UserTuneParserTest.cpp
@@ -4,61 +4,67 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/PayloadParsers/UserTuneParser.h>
-#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
+#include <Swiften/Base/DateTime.h>
#include <Swiften/Elements/UserTune.h>
-#include <Swiften/Base/DateTime.h>
+#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
+#include <Swiften/Parser/PayloadParsers/UserTuneParser.h>
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 5c87f70..bc29921 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/VCardParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/VCardParserTest.cpp
@@ -1,207 +1,207 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/ByteArray.h>
-#include <QA/Checker/IO.h>
-
#include <boost/date_time/posix_time/posix_time.hpp>
+#include <QA/Checker/IO.h>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/PayloadParsers/VCardParser.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
+#include <Swiften/Parser/PayloadParsers/VCardParser.h>
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>"));
+
+ std::shared_ptr<VCard> payload = std::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 14707e3..11e8ded 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/VCardUpdateParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/VCardUpdateParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,31 +7,31 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/PayloadParsers/VCardUpdateParser.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
+#include <Swiften/Parser/PayloadParsers/VCardUpdateParser.h>
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..09d0e9a 100644
--- a/Swiften/Parser/PayloadParsers/UserLocationParser.cpp
+++ b/Swiften/Parser/PayloadParsers/UserLocationParser.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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<double>(currentText));
+ }
+ else if (element == "alt") {
+ getPayloadInternal()->setAltitude(boost::lexical_cast<double>(currentText));
+ }
+ else if (element == "area") {
+ getPayloadInternal()->setArea(currentText);
+ }
+ else if (element == "bearing") {
+ getPayloadInternal()->setBearing(boost::lexical_cast<double>(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<double>(currentText));
+ }
+ else if (element == "floor") {
+ getPayloadInternal()->setFloor(currentText);
+ }
+ else if (element == "lat") {
+ getPayloadInternal()->setLatitude(boost::lexical_cast<double>(currentText));
+ }
+ else if (element == "locality") {
+ getPayloadInternal()->setLocality(currentText);
+ }
+ else if (element == "lon") {
+ getPayloadInternal()->setLongitude(boost::lexical_cast<double>(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<double>(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 50bf644..1445d3e 100644
--- a/Swiften/Parser/PayloadParsers/UserLocationParser.h
+++ b/Swiften/Parser/PayloadParsers/UserLocationParser.h
@@ -1,31 +1,31 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericPayloadParser.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/UserLocation.h>
+#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 f1a3310..5a27273 100644
--- a/Swiften/Parser/PayloadParsers/UserTuneParser.h
+++ b/Swiften/Parser/PayloadParsers/UserTuneParser.h
@@ -1,31 +1,31 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericPayloadParser.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/UserTune.h>
+#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 c790c7b..f8779d1 100644
--- a/Swiften/Parser/PayloadParsers/VCardParser.cpp
+++ b/Swiften/Parser/PayloadParsers/VCardParser.cpp
@@ -1,288 +1,290 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/PayloadParsers/VCardParser.h>
-#include <Swiften/Base/foreach.h>
+
+#include <cassert>
+
#include <Swiften/Base/DateTime.h>
-#include <Swiften/StringCodecs/Base64.h>
#include <Swiften/Parser/SerializingParser.h>
+#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
-VCardParser::VCardParser() : unknownContentParser_(NULL) {
+VCardParser::VCardParser() : unknownContentParser_(nullptr) {
}
void VCardParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- elementStack_.push_back(element);
- std::string elementHierarchy = getElementHierarchy();
- if (elementHierarchy == "/vCard/EMAIL") {
- currentEMailAddress_ = VCard::EMailAddress();
- }
- if (elementHierarchy == "/vCard/TEL") {
- currentTelephone_ = VCard::Telephone();
- }
- if (elementHierarchy == "/vCard/ADR") {
- currentAddress_ = VCard::Address();
- }
- if (elementHierarchy == "/vCard/LABEL") {
- currentAddressLabel_ = VCard::AddressLabel();
- }
- if (elementHierarchy == "/vCard/ORG") {
- currentOrganization_ = VCard::Organization();
- }
- if (elementStack_.size() == 2) {
- assert(!unknownContentParser_);
- unknownContentParser_ = new SerializingParser();
- unknownContentParser_->handleStartElement(element, ns, attributes);
- }
- 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_ = nullptr;
+ }
+ 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;
+ for (const auto& element : elementStack_) {
+ result += "/" + element;
+ }
+ return result;
}
}
diff --git a/Swiften/Parser/PayloadParsers/VCardParser.h b/Swiften/Parser/PayloadParsers/VCardParser.h
index 0d163f4..5a47cbf 100644
--- a/Swiften/Parser/PayloadParsers/VCardParser.h
+++ b/Swiften/Parser/PayloadParsers/VCardParser.h
@@ -1,38 +1,37 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <Swiften/Base/API.h>
#include <Swiften/Elements/VCard.h>
#include <Swiften/Parser/GenericPayloadParser.h>
-#include <Swiften/Base/API.h>
-
namespace Swift {
- class SerializingParser;
-
- 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);
-
- 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_;
- };
+ class SerializingParser;
+
+ 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);
+
+ 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_;
+ };
}
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 a480813..d3a7211 100644
--- a/Swiften/Parser/PayloadParsers/WhiteboardParser.cpp
+++ b/Swiften/Parser/PayloadParsers/WhiteboardParser.cpp
@@ -4,312 +4,321 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Parser/PayloadParsers/WhiteboardParser.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardLineElement.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardRectElement.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardTextElement.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h>
+
+#include <memory>
+
+#include <boost/lexical_cast.hpp>
+#include <boost/optional.hpp>
+
+#include <Swiften/Elements/Whiteboard/WhiteboardColor.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardColor.h>
#include <Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardLineElement.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardRectElement.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardTextElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h>
-#include <boost/optional.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <boost/lexical_cast.hpp>
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 = std::make_shared<WhiteboardInsertOperation>();
+ operation = insertOp;
+ } else if (type == "update") {
+ WhiteboardUpdateOperation::ref updateOp = std::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 = std::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 = std::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 = std::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 = std::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 = std::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 = std::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 = std::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 = std::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 = std::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 = std::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 89848b5..2f22624 100644
--- a/Swiften/Parser/PayloadParsers/WhiteboardParser.h
+++ b/Swiften/Parser/PayloadParsers/WhiteboardParser.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,29 +13,29 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/WhiteboardPayload.h>
-#include <Swiften/Parser/GenericPayloadParser.h>
#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardOperation.h>
+#include <Swiften/Elements/WhiteboardPayload.h>
+#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 b6c0a92..82b8573 100644
--- a/Swiften/Parser/PlatformXMLParserFactory.h
+++ b/Swiften/Parser/PlatformXMLParserFactory.h
@@ -1,19 +1,19 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Parser/XMLParserFactory.h>
#include <Swiften/Base/API.h>
+#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 4fe3412..0235a12 100644
--- a/Swiften/Parser/PresenceParser.cpp
+++ b/Swiften/Parser/PresenceParser.cpp
@@ -1,52 +1,53 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <iostream>
+#include <Swiften/Parser/PresenceParser.h>
+
#include <boost/optional.hpp>
-#include <Swiften/Parser/PresenceParser.h>
+#include <Swiften/Base/Log.h>
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 {
+ SWIFT_LOG(error) << "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 09c1480..76753f8 100644
--- a/Swiften/Parser/PresenceParser.h
+++ b/Swiften/Parser/PresenceParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,15 +7,15 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericStanzaParser.h>
#include <Swiften/Elements/Presence.h>
+#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/SConscript b/Swiften/Parser/SConscript
index 03870e5..840cbda 100644
--- a/Swiften/Parser/SConscript
+++ b/Swiften/Parser/SConscript
@@ -6,114 +6,114 @@ myenv.MergeFlags(swiften_env.get("LIBXML_FLAGS", ""))
myenv.MergeFlags(swiften_env.get("EXPAT_FLAGS", ""))
sources = [
- "AttributeMap.cpp",
- "AuthRequestParser.cpp",
- "AuthChallengeParser.cpp",
- "AuthSuccessParser.cpp",
- "AuthResponseParser.cpp",
- "CompressParser.cpp",
- "ElementParser.cpp",
- "IQParser.cpp",
- "MessageParser.cpp",
- "PayloadParser.cpp",
- "StanzaAckParser.cpp",
- "BOSHBodyExtractor.cpp",
- "ComponentHandshakeParser.cpp",
- "PayloadParserFactory.cpp",
- "PayloadParserFactoryCollection.cpp",
- "PayloadParsers/BodyParser.cpp",
- "PayloadParsers/SubjectParser.cpp",
- "PayloadParsers/ThreadParser.cpp",
- "PayloadParsers/CarbonsEnableParser.cpp",
- "PayloadParsers/CarbonsDisableParser.cpp",
- "PayloadParsers/CarbonsPrivateParser.cpp",
- "PayloadParsers/CarbonsReceivedParser.cpp",
- "PayloadParsers/CarbonsSentParser.cpp",
- "PayloadParsers/ChatStateParser.cpp",
- "PayloadParsers/CapsInfoParser.cpp",
- "PayloadParsers/DiscoInfoParser.cpp",
- "PayloadParsers/DiscoItemsParser.cpp",
- "PayloadParsers/ErrorParser.cpp",
- "PayloadParsers/FormParser.cpp",
- "PayloadParsers/IBBParser.cpp",
- "PayloadParsers/JingleParser.cpp",
- "PayloadParsers/JingleReasonParser.cpp",
- "PayloadParsers/JingleContentPayloadParser.cpp",
- "PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp",
- "PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp",
- "PayloadParsers/JingleFileTransferDescriptionParser.cpp",
- "PayloadParsers/JingleFileTransferHashParser.cpp",
- "PayloadParsers/JingleFileTransferFileInfoParser.cpp",
- "PayloadParsers/StreamInitiationFileInfoParser.cpp",
- "PayloadParsers/CommandParser.cpp",
- "PayloadParsers/InBandRegistrationPayloadParser.cpp",
- "PayloadParsers/SearchPayloadParser.cpp",
- "PayloadParsers/FullPayloadParserFactoryCollection.cpp",
- "PayloadParsers/PriorityParser.cpp",
- "PayloadParsers/PrivateStorageParser.cpp",
- "PayloadParsers/RawXMLPayloadParser.cpp",
- "PayloadParsers/ResourceBindParser.cpp",
- "PayloadParsers/RosterItemExchangeParser.cpp",
- "PayloadParsers/RosterParser.cpp",
- "PayloadParsers/SecurityLabelParser.cpp",
- "PayloadParsers/SecurityLabelsCatalogParser.cpp",
- "PayloadParsers/SoftwareVersionParser.cpp",
- "PayloadParsers/StorageParser.cpp",
- "PayloadParsers/StatusParser.cpp",
- "PayloadParsers/StatusShowParser.cpp",
- "PayloadParsers/StreamInitiationParser.cpp",
- "PayloadParsers/BytestreamsParser.cpp",
- "PayloadParsers/VCardParser.cpp",
- "PayloadParsers/VCardUpdateParser.cpp",
- "PayloadParsers/DelayParser.cpp",
- "PayloadParsers/MUCUserPayloadParser.cpp",
- "PayloadParsers/MUCAdminPayloadParser.cpp",
- "PayloadParsers/MUCOwnerPayloadParser.cpp",
- "PayloadParsers/MUCDestroyPayloadParser.cpp",
- "PayloadParsers/MUCInvitationPayloadParser.cpp",
- "PayloadParsers/MUCItemParser.cpp",
- "PayloadParsers/NicknameParser.cpp",
- "PayloadParsers/ReplaceParser.cpp",
- "PayloadParsers/LastParser.cpp",
- "PayloadParsers/IdleParser.cpp",
- "PayloadParsers/S5BProxyRequestParser.cpp",
- "PayloadParsers/DeliveryReceiptParser.cpp",
- "PayloadParsers/DeliveryReceiptRequestParser.cpp",
- "PayloadParsers/UserLocationParser.cpp",
- "PayloadParsers/UserTuneParser.cpp",
- "PayloadParsers/WhiteboardParser.cpp",
- "PayloadParsers/PubSubErrorParserFactory.cpp",
- "PayloadParsers/ResultSetParser.cpp",
- "PayloadParsers/ForwardedParser.cpp",
- "PayloadParsers/MAMFinParser.cpp",
- "PayloadParsers/MAMResultParser.cpp",
- "PayloadParsers/MAMQueryParser.cpp",
- "PayloadParsers/IsodeIQDelegationParser.cpp",
- "PlatformXMLParserFactory.cpp",
- "PresenceParser.cpp",
- "SerializingParser.cpp",
- "StanzaParser.cpp",
- "StreamErrorParser.cpp",
- "StreamFeaturesParser.cpp",
- "StreamManagementEnabledParser.cpp",
- "StreamResumeParser.cpp",
- "StreamResumedParser.cpp",
- "Tree/ParserElement.cpp",
- "Tree/NullParserElement.cpp",
- "Tree/TreeReparser.cpp",
- "XMLParser.cpp",
- "XMLParserClient.cpp",
- "XMLParserFactory.cpp",
- "XMPPParser.cpp",
- "XMPPParserClient.cpp",
- ]
+ "AttributeMap.cpp",
+ "AuthRequestParser.cpp",
+ "AuthChallengeParser.cpp",
+ "AuthSuccessParser.cpp",
+ "AuthResponseParser.cpp",
+ "CompressParser.cpp",
+ "ElementParser.cpp",
+ "IQParser.cpp",
+ "MessageParser.cpp",
+ "PayloadParser.cpp",
+ "StanzaAckParser.cpp",
+ "BOSHBodyExtractor.cpp",
+ "ComponentHandshakeParser.cpp",
+ "PayloadParserFactory.cpp",
+ "PayloadParserFactoryCollection.cpp",
+ "PayloadParsers/BodyParser.cpp",
+ "PayloadParsers/SubjectParser.cpp",
+ "PayloadParsers/ThreadParser.cpp",
+ "PayloadParsers/CarbonsEnableParser.cpp",
+ "PayloadParsers/CarbonsDisableParser.cpp",
+ "PayloadParsers/CarbonsPrivateParser.cpp",
+ "PayloadParsers/CarbonsReceivedParser.cpp",
+ "PayloadParsers/CarbonsSentParser.cpp",
+ "PayloadParsers/ChatStateParser.cpp",
+ "PayloadParsers/CapsInfoParser.cpp",
+ "PayloadParsers/DiscoInfoParser.cpp",
+ "PayloadParsers/DiscoItemsParser.cpp",
+ "PayloadParsers/ErrorParser.cpp",
+ "PayloadParsers/FormParser.cpp",
+ "PayloadParsers/IBBParser.cpp",
+ "PayloadParsers/JingleParser.cpp",
+ "PayloadParsers/JingleReasonParser.cpp",
+ "PayloadParsers/JingleContentPayloadParser.cpp",
+ "PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp",
+ "PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp",
+ "PayloadParsers/JingleFileTransferDescriptionParser.cpp",
+ "PayloadParsers/JingleFileTransferHashParser.cpp",
+ "PayloadParsers/JingleFileTransferFileInfoParser.cpp",
+ "PayloadParsers/StreamInitiationFileInfoParser.cpp",
+ "PayloadParsers/CommandParser.cpp",
+ "PayloadParsers/InBandRegistrationPayloadParser.cpp",
+ "PayloadParsers/SearchPayloadParser.cpp",
+ "PayloadParsers/FullPayloadParserFactoryCollection.cpp",
+ "PayloadParsers/PriorityParser.cpp",
+ "PayloadParsers/PrivateStorageParser.cpp",
+ "PayloadParsers/RawXMLPayloadParser.cpp",
+ "PayloadParsers/ResourceBindParser.cpp",
+ "PayloadParsers/RosterItemExchangeParser.cpp",
+ "PayloadParsers/RosterParser.cpp",
+ "PayloadParsers/SecurityLabelParser.cpp",
+ "PayloadParsers/SecurityLabelsCatalogParser.cpp",
+ "PayloadParsers/SoftwareVersionParser.cpp",
+ "PayloadParsers/StorageParser.cpp",
+ "PayloadParsers/StatusParser.cpp",
+ "PayloadParsers/StatusShowParser.cpp",
+ "PayloadParsers/StreamInitiationParser.cpp",
+ "PayloadParsers/BytestreamsParser.cpp",
+ "PayloadParsers/VCardParser.cpp",
+ "PayloadParsers/VCardUpdateParser.cpp",
+ "PayloadParsers/DelayParser.cpp",
+ "PayloadParsers/MUCUserPayloadParser.cpp",
+ "PayloadParsers/MUCAdminPayloadParser.cpp",
+ "PayloadParsers/MUCOwnerPayloadParser.cpp",
+ "PayloadParsers/MUCDestroyPayloadParser.cpp",
+ "PayloadParsers/MUCInvitationPayloadParser.cpp",
+ "PayloadParsers/MUCItemParser.cpp",
+ "PayloadParsers/NicknameParser.cpp",
+ "PayloadParsers/ReplaceParser.cpp",
+ "PayloadParsers/LastParser.cpp",
+ "PayloadParsers/IdleParser.cpp",
+ "PayloadParsers/S5BProxyRequestParser.cpp",
+ "PayloadParsers/DeliveryReceiptParser.cpp",
+ "PayloadParsers/DeliveryReceiptRequestParser.cpp",
+ "PayloadParsers/UserLocationParser.cpp",
+ "PayloadParsers/UserTuneParser.cpp",
+ "PayloadParsers/WhiteboardParser.cpp",
+ "PayloadParsers/PubSubErrorParserFactory.cpp",
+ "PayloadParsers/ResultSetParser.cpp",
+ "PayloadParsers/ForwardedParser.cpp",
+ "PayloadParsers/MAMFinParser.cpp",
+ "PayloadParsers/MAMResultParser.cpp",
+ "PayloadParsers/MAMQueryParser.cpp",
+ "PayloadParsers/IsodeIQDelegationParser.cpp",
+ "PlatformXMLParserFactory.cpp",
+ "PresenceParser.cpp",
+ "SerializingParser.cpp",
+ "StanzaParser.cpp",
+ "StreamErrorParser.cpp",
+ "StreamFeaturesParser.cpp",
+ "StreamManagementEnabledParser.cpp",
+ "StreamResumeParser.cpp",
+ "StreamResumedParser.cpp",
+ "Tree/ParserElement.cpp",
+ "Tree/NullParserElement.cpp",
+ "Tree/TreeReparser.cpp",
+ "XMLParser.cpp",
+ "XMLParserClient.cpp",
+ "XMLParserFactory.cpp",
+ "XMPPParser.cpp",
+ "XMPPParserClient.cpp",
+ ]
if myenv.get("HAVE_EXPAT", 0) :
- myenv.Append(CPPDEFINES = "HAVE_EXPAT")
- sources += ["ExpatParser.cpp"]
+ myenv.Append(CPPDEFINES = "HAVE_EXPAT")
+ sources += ["ExpatParser.cpp"]
if myenv.get("HAVE_LIBXML", 0) :
- myenv.Append(CPPDEFINES = "HAVE_LIBXML")
- sources += ["LibXMLParser.cpp"]
+ myenv.Append(CPPDEFINES = "HAVE_LIBXML")
+ sources += ["LibXMLParser.cpp"]
objects = myenv.SwiftenObject(sources)
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
diff --git a/Swiften/Parser/SerializingParser.cpp b/Swiften/Parser/SerializingParser.cpp
index 4a7590f..85b0dd4 100644
--- a/Swiften/Parser/SerializingParser.cpp
+++ b/Swiften/Parser/SerializingParser.cpp
@@ -1,15 +1,15 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/SerializingParser.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <cassert>
+#include <memory>
#include <Swiften/Serializer/XML/XMLTextNode.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
@@ -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);
+ std::shared_ptr<XMLElement> element = std::make_shared<XMLElement>(tag, ns);
+ // FIXME: Ignoring attribute namespace
+ for (const auto& e : attributes.getEntries()) {
+ element->setAttribute(e.getAttribute().getName(), e.getValue());
+ }
+
+ if (elementStack_.empty()) {
+ rootElement_ = element;
+ }
+ else {
+ (*(elementStack_.end() - 1))->addNode(element);
+ }
+ elementStack_.push_back(element);
}
void SerializingParser::handleEndElement(const std::string&, const std::string&) {
- assert(!elementStack_.empty());
- elementStack_.pop_back();
+ 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(std::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 e6f8377..bc2d872 100644
--- a/Swiften/Parser/SerializingParser.h
+++ b/Swiften/Parser/SerializingParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,23 +7,24 @@
#pragma once
#include <string>
+
#include <Swiften/Base/API.h>
#include <Swiften/Parser/AttributeMap.h>
#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< std::shared_ptr<XMLElement> > elementStack_;
+ std::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 91aade1..7e5a75f 100644
--- a/Swiften/Parser/StanzaAckParser.h
+++ b/Swiften/Parser/StanzaAckParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,18 +7,18 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/StanzaAck.h>
+#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 039cf26..9766e98 100644
--- a/Swiften/Parser/StanzaAckRequestParser.h
+++ b/Swiften/Parser/StanzaAckRequestParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,12 +7,12 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/StanzaAckRequest.h>
+#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 fa65196..8be4103 100644
--- a/Swiften/Parser/StanzaParser.cpp
+++ b/Swiften/Parser/StanzaParser.cpp
@@ -1,15 +1,15 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/StanzaParser.h>
-#include <iostream>
-#include <boost/optional.hpp>
#include <cassert>
+#include <boost/optional.hpp>
+
#include <Swiften/Parser/PayloadParser.h>
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParserFactoryCollection.h>
@@ -17,69 +17,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()) {
+ std::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 68dbe6f..7b83e99 100644
--- a/Swiften/Parser/StanzaParser.h
+++ b/Swiften/Parser/StanzaParser.h
@@ -1,53 +1,54 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+#include <string>
+
#include <boost/noncopyable.hpp>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Base/API.h>
-#include <string>
#include <Swiften/Elements/Stanza.h>
-#include <Swiften/Parser/ElementParser.h>
#include <Swiften/Parser/AttributeMap.h>
+#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 std::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 std::shared_ptr<Stanza> getStanza() const {
+ return std::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_;
+ std::shared_ptr<PayloadParser> currentPayloadParser_;
+ };
}
diff --git a/Swiften/Parser/StartTLSFailureParser.h b/Swiften/Parser/StartTLSFailureParser.h
index 216449c..2f13e71 100644
--- a/Swiften/Parser/StartTLSFailureParser.h
+++ b/Swiften/Parser/StartTLSFailureParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,12 +7,12 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/StartTLSFailure.h>
+#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 0282456..f769d4d 100644
--- a/Swiften/Parser/StartTLSParser.h
+++ b/Swiften/Parser/StartTLSParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,12 +7,12 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/StartTLSRequest.h>
+#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 9ae5fd8..5af8de8 100644
--- a/Swiften/Parser/StreamFeaturesParser.h
+++ b/Swiften/Parser/StreamFeaturesParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,27 +7,28 @@
#pragma once
#include <string>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/StreamFeatures.h>
+#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 d0bbbd6..0f75071 100644
--- a/Swiften/Parser/StreamManagementEnabledParser.h
+++ b/Swiften/Parser/StreamManagementEnabledParser.h
@@ -1,28 +1,28 @@
/*
- * Copyright (c) 2010-2011 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Parser/GenericElementParser.h>
-#include <Swiften/Elements/StreamManagementEnabled.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Elements/StreamManagementEnabled.h>
+#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 af490b7..c87beee 100644
--- a/Swiften/Parser/StreamManagementFailedParser.h
+++ b/Swiften/Parser/StreamManagementFailedParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,12 +7,12 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/StreamManagementFailed.h>
+#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 a8659c1..d3d2498 100644
--- a/Swiften/Parser/StreamResumeParser.h
+++ b/Swiften/Parser/StreamResumeParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,22 +7,22 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/StreamResume.h>
+#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 66722bf..ca89597 100644
--- a/Swiften/Parser/StreamResumedParser.h
+++ b/Swiften/Parser/StreamResumedParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,22 +7,22 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/StreamResumed.h>
+#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 6c6464f..da6cfd1 100644
--- a/Swiften/Parser/TLSProceedParser.h
+++ b/Swiften/Parser/TLSProceedParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,12 +7,12 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/TLSProceed.h>
+#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.cpp b/Swiften/Parser/Tree/NullParserElement.cpp
index 4a2db8f..7b52926 100644
--- a/Swiften/Parser/Tree/NullParserElement.cpp
+++ b/Swiften/Parser/Tree/NullParserElement.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,6 +8,6 @@
namespace Swift {
-boost::shared_ptr<NullParserElement> NullParserElement::element = boost::make_shared<NullParserElement>();
+std::shared_ptr<NullParserElement> NullParserElement::element = std::make_shared<NullParserElement>();
}
diff --git a/Swiften/Parser/Tree/NullParserElement.h b/Swiften/Parser/Tree/NullParserElement.h
index 60d8353..320e098 100644
--- a/Swiften/Parser/Tree/NullParserElement.h
+++ b/Swiften/Parser/Tree/NullParserElement.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,16 +7,17 @@
#pragma once
#include <string>
+
#include <Swiften/Base/API.h>
#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 std::shared_ptr<NullParserElement> element;
+ };
}
diff --git a/Swiften/Parser/Tree/ParserElement.cpp b/Swiften/Parser/Tree/ParserElement.cpp
index 392029b..5415945 100644
--- a/Swiften/Parser/Tree/ParserElement.cpp
+++ b/Swiften/Parser/Tree/ParserElement.cpp
@@ -1,16 +1,16 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/Tree/ParserElement.h>
-#include <Swiften/Parser/Tree/NullParserElement.h>
-#include <iostream>
-#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
+#include <boost/lambda/lambda.hpp>
+
+#include <Swiften/Parser/Tree/NullParserElement.h>
namespace lambda = boost::lambda;
@@ -23,26 +23,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 = std::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 07cc153..38f2dee 100644
--- a/Swiften/Parser/Tree/ParserElement.h
+++ b/Swiften/Parser/Tree/ParserElement.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,43 +7,44 @@
#pragma once
+#include <memory>
#include <string>
#include <vector>
+
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Parser/AttributeMap.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
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 std::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 ac3ad0e..6993d73 100644
--- a/Swiften/Parser/Tree/TreeReparser.cpp
+++ b/Swiften/Parser/Tree/TreeReparser.cpp
@@ -1,48 +1,48 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/Tree/TreeReparser.h>
-#include <boost/lexical_cast.hpp>
-#include <utility>
#include <deque>
+#include <utility>
+
+#include <boost/lexical_cast.hpp>
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
-#include <Swiften/Parser/PayloadParserFactory.h>
-#include <Swiften/Parser/PayloadParser.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/MUCOccupant.h>
+#include <Swiften/Parser/PayloadParser.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
namespace Swift {
typedef std::pair<ParserElement::ref, bool> ElementState;
-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;
+std::shared_ptr<Payload> TreeReparser::parseTree(ParserElement::ref root, PayloadParserFactoryCollection* collection) {
+ PayloadParser* parser = collection->getPayloadParserFactory(root->getName(), root->getNamespace(), root->getAttributes())->createPayloadParser();
+ std::deque<ElementState > stack;
+ stack.push_back(ElementState(root, true));
+ while (!stack.empty()) {
+ ElementState current = stack.back();
+ stack.pop_back();
+ if (current.second) {
+ stack.push_back(ElementState(current.first, false));
+ parser->handleStartElement(current.first->getName(), current.first->getNamespace(), current.first->getAttributes());
+ for (const auto& child : current.first->getAllChildren()) {
+ stack.push_back(ElementState(child, true));
+ }
+ } else {
+ parser->handleCharacterData(current.first->getText());
+ parser->handleEndElement(current.first->getName(), current.first->getNamespace());
+ }
+
+ }
+
+ std::shared_ptr<Payload> payload = parser->getPayload();
+ delete parser;
+ return payload;
}
}
diff --git a/Swiften/Parser/Tree/TreeReparser.h b/Swiften/Parser/Tree/TreeReparser.h
index 80a326b..435922b 100644
--- a/Swiften/Parser/Tree/TreeReparser.h
+++ b/Swiften/Parser/Tree/TreeReparser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::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 19b0b58..f7ed80f 100644
--- a/Swiften/Parser/UnitTest/BOSHBodyExtractorTest.cpp
+++ b/Swiften/Parser/UnitTest/BOSHBodyExtractorTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,98 +7,98 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/PlatformXMLParserFactory.h>
#include <Swiften/Parser/BOSHBodyExtractor.h>
+#include <Swiften/Parser/PlatformXMLParserFactory.h>
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 c44326d..299fb50 100644
--- a/Swiften/Parser/UnitTest/ElementParserTester.h
+++ b/Swiften/Parser/UnitTest/ElementParserTester.h
@@ -1,14 +1,13 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-
#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 44242036..cd94ed8 100644
--- a/Swiften/Parser/UnitTest/GenericPayloadTreeParserTest.cpp
+++ b/Swiften/Parser/UnitTest/GenericPayloadTreeParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,9 +8,9 @@
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <Swiften/Base/Platform.h>
+#include <Swiften/Elements/RawXMLPayload.h>
#include <Swiften/Parser/GenericPayloadTreeParser.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h>
-#include <Swiften/Elements/RawXMLPayload.h>
using namespace Swift;
@@ -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 f28d557..a98eb51 100644
--- a/Swiften/Parser/UnitTest/ParserTester.h
+++ b/Swiften/Parser/UnitTest/ParserTester.h
@@ -1,48 +1,47 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-
-#include <Swiften/Parser/XMLParserClient.h>
#include <Swiften/Parser/PlatformXMLParserFactory.h>
#include <Swiften/Parser/XMLParser.h>
+#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 4129e86..f7234d9 100644
--- a/Swiften/Parser/UnitTest/PayloadParserFactoryCollectionTest.cpp
+++ b/Swiften/Parser/UnitTest/PayloadParserFactoryCollectionTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,97 +7,97 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
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 nullptr; }
+ std::string element;
+ };
};
CPPUNIT_TEST_SUITE_REGISTRATION(PayloadParserFactoryCollectionTest);
diff --git a/Swiften/Parser/UnitTest/PresenceParserTest.cpp b/Swiften/Parser/UnitTest/PresenceParserTest.cpp
index 6f4c305..2b2c242 100644
--- a/Swiften/Parser/UnitTest/PresenceParserTest.cpp
+++ b/Swiften/Parser/UnitTest/PresenceParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,107 +7,107 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/PresenceParser.h>
#include <Swiften/Parser/PayloadParserFactoryCollection.h>
+#include <Swiften/Parser/PresenceParser.h>
#include <Swiften/Parser/UnitTest/StanzaParserTester.h>
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 8f97ea5..4591640 100644
--- a/Swiften/Parser/UnitTest/StanzaAckParserTest.cpp
+++ b/Swiften/Parser/UnitTest/StanzaAckParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,47 +7,47 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/StanzaAckParser.h>
#include <Swiften/Parser/PayloadParserFactoryCollection.h>
+#include <Swiften/Parser/StanzaAckParser.h>
#include <Swiften/Parser/UnitTest/ElementParserTester.h>
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 d17ffef..6febdbc 100644
--- a/Swiften/Parser/UnitTest/StanzaParserTest.cpp
+++ b/Swiften/Parser/UnitTest/StanzaParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,206 +7,206 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Parser/StanzaParser.h>
+#include <Swiften/Elements/Payload.h>
+#include <Swiften/Elements/Stanza.h>
#include <Swiften/Parser/GenericPayloadParser.h>
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParserFactoryCollection.h>
-#include <Swiften/Elements/Stanza.h>
-#include <Swiften/Elements/Payload.h>
+#include <Swiften/Parser/StanzaParser.h>
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_ = std::make_shared<MyStanza>();
+ }
+
+ virtual std::shared_ptr<ToplevelElement> getElement() const {
+ return stanza_;
+ }
+
+ private:
+ std::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..4664df2 100644
--- a/Swiften/Parser/UnitTest/StreamFeaturesParserTest.cpp
+++ b/Swiften/Parser/UnitTest/StreamFeaturesParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 = std::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 = std::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 = std::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 = std::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..704a89f 100644
--- a/Swiften/Parser/UnitTest/StreamManagementEnabledParserTest.cpp
+++ b/Swiften/Parser/UnitTest/StreamManagementEnabledParserTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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\"/>"));
+
+ std::shared_ptr<StreamManagementEnabled> element = std::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 119fb6c..2424d4d 100644
--- a/Swiften/Parser/UnitTest/XMPPParserTest.cpp
+++ b/Swiften/Parser/UnitTest/XMPPParserTest.cpp
@@ -1,196 +1,197 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <string>
+#include <vector>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <vector>
-#include <Swiften/Elements/ProtocolHeader.h>
-#include <string>
-#include <Swiften/Parser/XMPPParser.h>
-#include <Swiften/Parser/ElementParser.h>
-#include <Swiften/Parser/XMPPParserClient.h>
-#include <Swiften/Parser/PayloadParserFactoryCollection.h>
-#include <Swiften/Parser/PlatformXMLParserFactory.h>
-#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/Message.h>
+#include <Swiften/Elements/Presence.h>
+#include <Swiften/Elements/ProtocolHeader.h>
#include <Swiften/Elements/StreamFeatures.h>
#include <Swiften/Elements/UnknownElement.h>
+#include <Swiften/Parser/ElementParser.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
+#include <Swiften/Parser/PlatformXMLParserFactory.h>
+#include <Swiften/Parser/XMPPParser.h>
+#include <Swiften/Parser/XMPPParserClient.h>
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, std::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;
+ std::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(std::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 ac9cc79..44c5464 100644
--- a/Swiften/Parser/UnknownElementParser.h
+++ b/Swiften/Parser/UnknownElementParser.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,12 +7,12 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Parser/GenericElementParser.h>
#include <Swiften/Elements/UnknownElement.h>
+#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..1553704 100644
--- a/Swiften/Parser/UnknownPayloadParser.h
+++ b/Swiften/Parser/UnknownPayloadParser.h
@@ -1,27 +1,27 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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 std::shared_ptr<Payload> getPayload() const {
+ return std::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 6789052..2b45a12 100644
--- a/Swiften/Parser/XMPPParser.cpp
+++ b/Swiften/Parser/XMPPParser.cpp
@@ -1,46 +1,44 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Parser/XMPPParser.h>
-#include <iostream>
#include <cassert>
+#include <string>
#include <Swiften/Elements/ProtocolHeader.h>
-#include <string>
-#include <Swiften/Parser/XMLParser.h>
-#include <Swiften/Parser/XMPPParserClient.h>
-#include <Swiften/Parser/XMPPParser.h>
+#include <Swiften/Parser/AuthChallengeParser.h>
+#include <Swiften/Parser/AuthFailureParser.h>
+#include <Swiften/Parser/AuthRequestParser.h>
+#include <Swiften/Parser/AuthResponseParser.h>
+#include <Swiften/Parser/AuthSuccessParser.h>
+#include <Swiften/Parser/ComponentHandshakeParser.h>
+#include <Swiften/Parser/CompressFailureParser.h>
+#include <Swiften/Parser/CompressParser.h>
+#include <Swiften/Parser/CompressedParser.h>
#include <Swiften/Parser/ElementParser.h>
-#include <Swiften/Parser/PresenceParser.h>
+#include <Swiften/Parser/EnableStreamManagementParser.h>
#include <Swiften/Parser/IQParser.h>
#include <Swiften/Parser/MessageParser.h>
-#include <Swiften/Parser/StreamFeaturesParser.h>
+#include <Swiften/Parser/PresenceParser.h>
+#include <Swiften/Parser/StanzaAckParser.h>
+#include <Swiften/Parser/StanzaAckRequestParser.h>
+#include <Swiften/Parser/StartTLSFailureParser.h>
+#include <Swiften/Parser/StartTLSParser.h>
#include <Swiften/Parser/StreamErrorParser.h>
-#include <Swiften/Parser/AuthRequestParser.h>
-#include <Swiften/Parser/AuthSuccessParser.h>
-#include <Swiften/Parser/AuthFailureParser.h>
-#include <Swiften/Parser/AuthChallengeParser.h>
-#include <Swiften/Parser/AuthResponseParser.h>
-#include <Swiften/Parser/EnableStreamManagementParser.h>
+#include <Swiften/Parser/StreamFeaturesParser.h>
#include <Swiften/Parser/StreamManagementEnabledParser.h>
#include <Swiften/Parser/StreamManagementFailedParser.h>
#include <Swiften/Parser/StreamResumeParser.h>
#include <Swiften/Parser/StreamResumedParser.h>
-#include <Swiften/Parser/StanzaAckParser.h>
-#include <Swiften/Parser/StanzaAckRequestParser.h>
-#include <Swiften/Parser/StartTLSParser.h>
-#include <Swiften/Parser/StartTLSFailureParser.h>
-#include <Swiften/Parser/CompressParser.h>
-#include <Swiften/Parser/CompressFailureParser.h>
-#include <Swiften/Parser/CompressedParser.h>
-#include <Swiften/Parser/UnknownElementParser.h>
#include <Swiften/Parser/TLSProceedParser.h>
-#include <Swiften/Parser/ComponentHandshakeParser.h>
+#include <Swiften/Parser/UnknownElementParser.h>
+#include <Swiften/Parser/XMLParser.h>
#include <Swiften/Parser/XMLParserFactory.h>
+#include <Swiften/Parser/XMPPParserClient.h>
// TODO: Whenever an error occurs in the handlers, stop the parser by returing
// a bool value, and stopping the XML parser
@@ -48,159 +46,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_(nullptr),
+ client_(client),
+ payloadParserFactories_(payloadParserFactories),
+ level_(0),
+ currentElementParser_(nullptr),
+ 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_ = nullptr;
+ }
+ }
+ }
}
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..09fae38 100644
--- a/Swiften/Parser/XMPPParser.h
+++ b/Swiften/Parser/XMPPParser.h
@@ -6,51 +6,52 @@
#pragma once
+#include <memory>
+
#include <boost/noncopyable.hpp>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Parser/AttributeMap.h>
#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..97c0c64 100644
--- a/Swiften/Parser/XMPPParserClient.h
+++ b/Swiften/Parser/XMPPParserClient.h
@@ -1,26 +1,26 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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(std::shared_ptr<ToplevelElement>) = 0;
+ virtual void handleStreamEnd() = 0;
+ };
}
diff --git a/Swiften/Presence/DirectedPresenceSender.cpp b/Swiften/Presence/DirectedPresenceSender.cpp
index c19d8a5..c1134c7 100644
--- a/Swiften/Presence/DirectedPresenceSender.cpp
+++ b/Swiften/Presence/DirectedPresenceSender.cpp
@@ -1,41 +1,40 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Presence/DirectedPresenceSender.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
DirectedPresenceSender::DirectedPresenceSender(PresenceSender* sender) : sender(sender) {
}
-void DirectedPresenceSender::sendPresence(boost::shared_ptr<Presence> presence) {
- if (!sender->isAvailable()) {
- return;
- }
+void DirectedPresenceSender::sendPresence(std::shared_ptr<Presence> presence) {
+ 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()) {
+ std::shared_ptr<Presence> presenceCopy(new Presence(*presence));
+ for (const auto& 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;
}
/**
@@ -44,14 +43,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) {
+ std::shared_ptr<Presence> presenceCopy((*lastSentUndirectedPresence)->clone());
+ presenceCopy->setTo(jid);
+ sender->sendPresence(presenceCopy);
+ }
+ }
}
/**
@@ -60,17 +59,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()) {
+ std::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 74c91bd..a397776 100644
--- a/Swiften/Presence/DirectedPresenceSender.h
+++ b/Swiften/Presence/DirectedPresenceSender.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -10,28 +10,28 @@
#include <boost/optional.hpp>
+#include <Swiften/Base/API.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/Presence/PresenceSender.h>
-#include <Swiften/Base/API.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..e5d2688 100644
--- a/Swiften/Presence/PayloadAddingPresenceSender.cpp
+++ b/Swiften/Presence/PayloadAddingPresenceSender.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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);
- }
+void PayloadAddingPresenceSender::setPayload(std::shared_ptr<Payload> payload) {
+ 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 fc240ef..3a55183 100644
--- a/Swiften/Presence/PayloadAddingPresenceSender.h
+++ b/Swiften/Presence/PayloadAddingPresenceSender.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,43 +7,43 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Presence/PresenceSender.h>
#include <Swiften/Elements/Payload.h>
+#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(std::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(std::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:
+ std::shared_ptr<Presence> lastSentPresence;
+ PresenceSender* sender;
+ std::shared_ptr<Payload> payload;
+ };
}
diff --git a/Swiften/Presence/PresenceOracle.cpp b/Swiften/Presence/PresenceOracle.cpp
index 8623529..1c9d0ea 100644
--- a/Swiften/Presence/PresenceOracle.cpp
+++ b/Swiften/Presence/PresenceOracle.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -10,7 +10,6 @@
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/StanzaChannel.h>
#include <Swiften/Elements/StatusShow.h>
#include <Swiften/Roster/XMPPRoster.h>
@@ -18,202 +17,198 @@
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;
+ }
+ for (const auto& jidPresence : i->second) {
+ if (jidPresence.second) {
+ results.push_back(jidPresence.second);
+ }
+ }
+ 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;
+
+ for (auto&& 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();
+ }
+ Presence::ref highest;
+ for (const auto& jidPresence : i->second) {
+ Presence::ref current = jidPresence.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..decc0ee 100644
--- a/Swiften/Presence/PresenceOracle.h
+++ b/Swiften/Presence/PresenceOracle.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,70 +9,71 @@
#include <map>
#include <string>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#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::signals2::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/SConscript b/Swiften/Presence/SConscript
index 33acbd3..c3e32f2 100644
--- a/Swiften/Presence/SConscript
+++ b/Swiften/Presence/SConscript
@@ -1,11 +1,11 @@
Import("swiften_env")
objects = swiften_env.SwiftenObject([
- "PresenceOracle.cpp",
- "PresenceSender.cpp",
- "DirectedPresenceSender.cpp",
- "PayloadAddingPresenceSender.cpp",
- "StanzaChannelPresenceSender.cpp",
- "SubscriptionManager.cpp",
- ])
+ "PresenceOracle.cpp",
+ "PresenceSender.cpp",
+ "DirectedPresenceSender.cpp",
+ "PayloadAddingPresenceSender.cpp",
+ "StanzaChannelPresenceSender.cpp",
+ "SubscriptionManager.cpp",
+ ])
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
diff --git a/Swiften/Presence/StanzaChannelPresenceSender.cpp b/Swiften/Presence/StanzaChannelPresenceSender.cpp
index 5132280..a96f40f 100644
--- a/Swiften/Presence/StanzaChannelPresenceSender.cpp
+++ b/Swiften/Presence/StanzaChannelPresenceSender.cpp
@@ -1,10 +1,11 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Presence/StanzaChannelPresenceSender.h>
+
#include <Swiften/Client/StanzaChannel.h>
namespace Swift {
@@ -13,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..83009e9 100644
--- a/Swiften/Presence/SubscriptionManager.cpp
+++ b/Swiften/Presence/SubscriptionManager.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,49 +8,48 @@
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Client/StanzaChannel.h>
namespace Swift {
SubscriptionManager::SubscriptionManager(StanzaChannel* channel) : stanzaChannel(channel) {
- stanzaChannel->onPresenceReceived.connect(boost::bind(&SubscriptionManager::handleIncomingPresence, this, _1));
+ 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 858702a..c1997bd 100644
--- a/Swiften/Presence/SubscriptionManager.h
+++ b/Swiften/Presence/SubscriptionManager.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,41 +7,42 @@
#pragma once
#include <map>
-
#include <string>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/Elements/Presence.h>
+
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Elements/Presence.h>
+#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::signals2::signal<void (const JID&, const std::string&, Presence::ref)> onPresenceSubscriptionRequest;
+
+ boost::signals2::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..38e67fb 100644
--- a/Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp
+++ b/Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp
@@ -1,9 +1,11 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -14,140 +16,135 @@
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 = std::unique_ptr<DummyStanzaChannel>(new DummyStanzaChannel());
+ testPresence = std::make_shared<Presence>();
+ testPresence->setStatus("Foo");
+ secondTestPresence = std::make_shared<Presence>();
+ secondTestPresence->setStatus("Bar");
+ stanzaChannelPresenceSender = std::unique_ptr<StanzaChannelPresenceSender>(new StanzaChannelPresenceSender(channel.get()));
+ }
+
+ void testSendPresence() {
+ std::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
+ testling->sendPresence(testPresence);
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size()));
+ std::shared_ptr<Presence> presence = std::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
+ CPPUNIT_ASSERT(testPresence == presence);
+ }
+
+ void testSendPresence_UndirectedPresenceWithDirectedPresenceReceivers() {
+ std::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()));
+ std::shared_ptr<Presence> presence = std::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
+ CPPUNIT_ASSERT(testPresence == presence);
+ presence = std::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() {
+ std::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()));
+ std::shared_ptr<Presence> presence = std::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
+ CPPUNIT_ASSERT(testPresence == presence);
+ }
+
+ void testAddDirectedPresenceReceiver() {
+ std::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()));
+ std::shared_ptr<Presence> presence = std::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() {
+ std::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() {
+ std::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()));
+ std::shared_ptr<Presence> presence = std::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() {
+ std::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(std::dynamic_pointer_cast<Presence>(channel->sentStanzas[0])->getType(), Presence::Unavailable);
+ CPPUNIT_ASSERT(channel->sentStanzas[1] == testPresence);
+ }
+
+ void testRemoveDirectedPresenceReceiver_WithoutSendingPresence() {
+ std::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.get());
+ }
+
+ private:
+ std::unique_ptr<DummyStanzaChannel> channel;
+ std::unique_ptr<StanzaChannelPresenceSender> stanzaChannelPresenceSender;
+ std::shared_ptr<Presence> testPresence;
+ std::shared_ptr<Presence> secondTestPresence;
};
CPPUNIT_TEST_SUITE_REGISTRATION(DirectedPresenceSenderTest);
diff --git a/Swiften/Presence/UnitTest/PayloadAddingPresenceSenderTest.cpp b/Swiften/Presence/UnitTest/PayloadAddingPresenceSenderTest.cpp
index b14c6d0..234f303 100644
--- a/Swiften/Presence/UnitTest/PayloadAddingPresenceSenderTest.cpp
+++ b/Swiften/Presence/UnitTest/PayloadAddingPresenceSenderTest.cpp
@@ -1,144 +1,146 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
#include <vector>
+
#include <boost/bind.hpp>
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
+#include <Swiften/Client/DummyStanzaChannel.h>
+#include <Swiften/Elements/Body.h>
#include <Swiften/Presence/PayloadAddingPresenceSender.h>
#include <Swiften/Presence/StanzaChannelPresenceSender.h>
-#include <Swiften/Elements/Body.h>
-#include <Swiften/Client/DummyStanzaChannel.h>
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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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:
+ std::shared_ptr<PayloadAddingPresenceSender> createSender() {
+ std::shared_ptr<PayloadAddingPresenceSender> sender(new PayloadAddingPresenceSender(presenceSender));
+ return sender;
+ }
- struct MyPayload : public Payload {
- typedef boost::shared_ptr<MyPayload> ref;
+ struct MyPayload : public Payload {
+ typedef std::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..86a7925 100644
--- a/Swiften/Presence/UnitTest/PresenceOracleTest.cpp
+++ b/Swiften/Presence/UnitTest/PresenceOracleTest.cpp
@@ -1,11 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/shared_ptr.hpp>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -19,230 +20,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() {
+ std::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() {
+ std::shared_ptr<Presence> sentPresence1(createPresence(user1));
+ std::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");
+
+ std::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() {
+ std::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 = std::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(std::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);
+ }
+
+ std::shared_ptr<Presence> createPresence(const JID& jid) {
+ std::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 7fc3820..eba5dd9 100644
--- a/Swiften/PubSub/PubSubManager.h
+++ b/Swiften/PubSub/PubSubManager.h
@@ -1,53 +1,53 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/Queries/PubSubRequest.h>
-#include <Swiften/PubSub/PubSubUtil.h>
+#include <Swiften/Base/Override.h>
+#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/PubSub.h>
-#include <Swiften/Elements/PubSubOwnerPubSub.h>
-#include <Swiften/Elements/PubSubCreate.h>
-#include <Swiften/Elements/PubSubSubscribe.h>
#include <Swiften/Elements/PubSubAffiliations.h>
+#include <Swiften/Elements/PubSubCreate.h>
#include <Swiften/Elements/PubSubDefault.h>
+#include <Swiften/Elements/PubSubEventPayload.h>
#include <Swiften/Elements/PubSubItems.h>
-#include <Swiften/Elements/PubSubPublish.h>
-#include <Swiften/Elements/PubSubRetract.h>
-#include <Swiften/Elements/PubSubSubscription.h>
-#include <Swiften/Elements/PubSubSubscriptions.h>
-#include <Swiften/Elements/PubSubUnsubscribe.h>
#include <Swiften/Elements/PubSubOwnerAffiliations.h>
#include <Swiften/Elements/PubSubOwnerConfigure.h>
#include <Swiften/Elements/PubSubOwnerDefault.h>
#include <Swiften/Elements/PubSubOwnerDelete.h>
+#include <Swiften/Elements/PubSubOwnerPubSub.h>
#include <Swiften/Elements/PubSubOwnerPurge.h>
#include <Swiften/Elements/PubSubOwnerSubscriptions.h>
-#include <Swiften/Elements/IQ.h>
-#include <Swiften/Elements/PubSubEventPayload.h>
-
+#include <Swiften/Elements/PubSubPublish.h>
+#include <Swiften/Elements/PubSubRetract.h>
+#include <Swiften/Elements/PubSubSubscribe.h>
+#include <Swiften/Elements/PubSubSubscription.h>
+#include <Swiften/Elements/PubSubSubscriptions.h>
+#include <Swiften/Elements/PubSubUnsubscribe.h>
+#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 std::shared_ptr< PubSubRequest<payload> > \
+ createRequest(IQ::Type, const JID&, std::shared_ptr<payload>) = 0;
namespace Swift {
- class JID;
+ class JID;
+
+ class SWIFTEN_API PubSubManager {
+ public:
+ virtual ~PubSubManager();
- class SWIFTEN_API PubSubManager {
- public:
- virtual ~PubSubManager();
-
- SWIFTEN_PUBSUB_FOREACH_PUBSUB_PAYLOAD_TYPE(
- SWIFTEN_PUBSUBMANAGER_DECLARE_CREATE_REQUEST)
+ SWIFTEN_PUBSUB_FOREACH_PUBSUB_PAYLOAD_TYPE(
+ SWIFTEN_PUBSUBMANAGER_DECLARE_CREATE_REQUEST)
- boost::signal<void (const JID&, const boost::shared_ptr<PubSubEventPayload>)> onEvent;
- };
+ boost::signals2::signal<void (const JID&, const std::shared_ptr<PubSubEventPayload>)> onEvent;
+ };
}
diff --git a/Swiften/PubSub/PubSubManagerImpl.cpp b/Swiften/PubSub/PubSubManagerImpl.cpp
index 7e73b86..12eb25c 100644
--- a/Swiften/PubSub/PubSubManagerImpl.cpp
+++ b/Swiften/PubSub/PubSubManagerImpl.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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());
- }
+void PubSubManagerImpl::handleMessageRecevied(std::shared_ptr<Message> message) {
+ if (std::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 d746aae..58c5fc0 100644
--- a/Swiften/PubSub/PubSubManagerImpl.h
+++ b/Swiften/PubSub/PubSubManagerImpl.h
@@ -1,41 +1,40 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
+#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 std::shared_ptr< PubSubRequest<payload> > \
+ createRequest(IQ::Type type, const JID& receiver, std::shared_ptr<payload> p) SWIFTEN_OVERRIDE { \
+ return std::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(std::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 7cc5a61..ac23092 100644
--- a/Swiften/PubSub/PubSubUtil.h
+++ b/Swiften/PubSub/PubSubUtil.h
@@ -1,27 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#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 eb116e9..5cb1765 100644
--- a/Swiften/QA/ClientTest/ClientTest.cpp
+++ b/Swiften/QA/ClientTest/ClientTest.cpp
@@ -1,98 +1,99 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/bind.hpp>
-#include <boost/thread.hpp>
#include <iostream>
+#include <thread>
+
+#include <boost/bind.hpp>
#include <Swiften/Client/Client.h>
-#include <Swiften/Network/TimerFactory.h>
-#include <Swiften/Network/BoostNetworkFactories.h>
+#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/EventLoop/SimpleEventLoop.h>
+#include <Swiften/Network/BoostNetworkFactories.h>
+#include <Swiften/Network/TimerFactory.h>
#include <Swiften/Roster/GetRosterRequest.h>
-#include <Swiften/Client/ClientXMLTracer.h>
using namespace Swift;
static SimpleEventLoop eventLoop;
static BoostNetworkFactories networkFactories(&eventLoop);
-static Client* client = 0;
+static Client* client = nullptr;
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();
+static void handleRosterReceived(std::shared_ptr<Payload>) {
+ 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/ClientTest/SConscript b/Swiften/QA/ClientTest/SConscript
index 15a68c6..812c472 100644
--- a/Swiften/QA/ClientTest/SConscript
+++ b/Swiften/QA/ClientTest/SConscript
@@ -3,15 +3,15 @@ import os
Import("env")
if env["TEST"] :
- myenv = env.Clone()
- myenv.UseFlags(myenv["SWIFTEN_FLAGS"])
- myenv.UseFlags(myenv["SWIFTEN_DEP_FLAGS"])
+ myenv = env.Clone()
+ myenv.UseFlags(myenv["SWIFTEN_FLAGS"])
+ myenv.UseFlags(myenv["SWIFTEN_DEP_FLAGS"])
- for i in ["SWIFT_CLIENTTEST_JID", "SWIFT_CLIENTTEST_PASS"]:
- if ARGUMENTS.get(i.lower(), False) :
- myenv["ENV"][i] = ARGUMENTS[i.lower()]
- elif os.environ.get(i, "") :
- myenv["ENV"][i] = os.environ[i]
+ for i in ["SWIFT_CLIENTTEST_JID", "SWIFT_CLIENTTEST_PASS"]:
+ if ARGUMENTS.get(i.lower(), False) :
+ myenv["ENV"][i] = ARGUMENTS[i.lower()]
+ elif os.environ.get(i, "") :
+ myenv["ENV"][i] = os.environ[i]
- tester = myenv.Program("ClientTest", ["ClientTest.cpp"])
- myenv.Test(tester, "system")
+ tester = myenv.Program("ClientTest", ["ClientTest.cpp"])
+ myenv.Test(tester, "system")
diff --git a/Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp b/Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp
index 4da2672..664a87b 100644
--- a/Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp
+++ b/Swiften/QA/ConcurrentFileTransferTest/ConcurrentFileTransferTest.cpp
@@ -1,81 +1,80 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <fstream>
-#include <string>
#include <map>
+#include <string>
-#include <boost/numeric/conversion/cast.hpp>
#include <boost/filesystem.hpp>
+#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/Base/sleep.h>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Base/BoostRandomGenerator.h>
+#include <Swiften/Base/Debug.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Client/ClientXMLTracer.h>
+#include <Swiften/Base/sleep.h>
#include <Swiften/Client/Client.h>
-#include <Swiften/EventLoop/SimpleEventLoop.h>
-#include <Swiften/Network/BoostNetworkFactories.h>
-#include <Swiften/Network/Timer.h>
-#include <Swiften/Network/TimerFactory.h>
+#include <Swiften/Client/ClientXMLTracer.h>
+#include <Swiften/Disco/ClientDiscoManager.h>
#include <Swiften/Disco/EntityCapsProvider.h>
#include <Swiften/Elements/Presence.h>
-#include <Swiften/FileTransfer/ReadBytestream.h>
-#include <Swiften/Base/BoostRandomGenerator.h>
+#include <Swiften/EventLoop/SimpleEventLoop.h>
#include <Swiften/FileTransfer/FileReadBytestream.h>
-#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
#include <Swiften/FileTransfer/FileTransferManager.h>
-#include <Swiften/Disco/ClientDiscoManager.h>
#include <Swiften/FileTransfer/FileWriteBytestream.h>
-#include <Swiften/Base/Debug.h>
+#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
+#include <Swiften/FileTransfer/ReadBytestream.h>
+#include <Swiften/Network/BoostNetworkFactories.h>
+#include <Swiften/Network/Timer.h>
+#include <Swiften/Network/TimerFactory.h>
using namespace Swift;
static const std::string CLIENT_NAME = "Swiften FT Test";
static const std::string CLIENT_NODE = "http://swift.im";
-static boost::shared_ptr<SimpleEventLoop> eventLoop;
-static boost::shared_ptr<BoostNetworkFactories> networkFactories;
+static std::shared_ptr<SimpleEventLoop> eventLoop;
+static std::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_;
+ std::shared_ptr<Client> clientA_;
+ std::map<std::string, ByteArray> clientASendFiles_;
- int clientBCandidates_;
- boost::shared_ptr<Client> clientB_;
+ int clientBCandidates_;
+ std::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/ConcurrentFileTransferTest/SConscript b/Swiften/QA/ConcurrentFileTransferTest/SConscript
index 1b4cdbc..94b37fd 100644
--- a/Swiften/QA/ConcurrentFileTransferTest/SConscript
+++ b/Swiften/QA/ConcurrentFileTransferTest/SConscript
@@ -3,15 +3,15 @@ import os
Import("env")
if env["TEST"] :
- myenv = env.Clone()
- myenv.UseFlags(myenv["SWIFTEN_FLAGS"])
- myenv.UseFlags(myenv["SWIFTEN_DEP_FLAGS"])
+ myenv = env.Clone()
+ myenv.UseFlags(myenv["SWIFTEN_FLAGS"])
+ myenv.UseFlags(myenv["SWIFTEN_DEP_FLAGS"])
- for i in ["SWIFT_FILETRANSFERTEST_JID", "SWIFT_FILETRANSFERTEST_PASS", "SWIFT_FILETRANSFERTEST2_JID", "SWIFT_FILETRANSFERTEST2_PASS"]:
- if ARGUMENTS.get(i.lower(), False) :
- myenv["ENV"][i] = ARGUMENTS[i.lower()]
- elif os.environ.get(i, "") :
- myenv["ENV"][i] = os.environ[i]
+ for i in ["SWIFT_FILETRANSFERTEST_JID", "SWIFT_FILETRANSFERTEST_PASS", "SWIFT_FILETRANSFERTEST2_JID", "SWIFT_FILETRANSFERTEST2_PASS"]:
+ if ARGUMENTS.get(i.lower(), False) :
+ myenv["ENV"][i] = ARGUMENTS[i.lower()]
+ elif os.environ.get(i, "") :
+ myenv["ENV"][i] = os.environ[i]
- tester = myenv.Program("ConcurrentFileTransferTest", ["ConcurrentFileTransferTest.cpp"])
- myenv.Test(tester, "system")
+ tester = myenv.Program("ConcurrentFileTransferTest", ["ConcurrentFileTransferTest.cpp"])
+ myenv.Test(tester, "system")
diff --git a/Swiften/QA/DNSSDTest/DNSSDTest.cpp b/Swiften/QA/DNSSDTest/DNSSDTest.cpp
index bd06445..ae2fafd 100644
--- a/Swiften/QA/DNSSDTest/DNSSDTest.cpp
+++ b/Swiften/QA/DNSSDTest/DNSSDTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 = std::make_shared<DNSSDQuerier>();
+ querier->start();
+ }
+
+ void tearDown() {
+ querier->stop();
+ querier.reset();
+ delete eventLoop;
+ }
+
+ void testPublish() {
+ std::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;
+ std::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();
+ std::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;
+ std::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/DNSSDTest/SConscript b/Swiften/QA/DNSSDTest/SConscript
index d35d06f..275a314 100644
--- a/Swiften/QA/DNSSDTest/SConscript
+++ b/Swiften/QA/DNSSDTest/SConscript
@@ -3,19 +3,19 @@ import os
Import("env")
if env["TEST"] :
- myenv = env.Clone()
- myenv.MergeFlags(myenv["CHECKER_FLAGS"])
- myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
- myenv.MergeFlags(myenv["CPPUNIT_FLAGS"])
- myenv.MergeFlags(myenv["BOOST_FLAGS"])
- myenv.MergeFlags(myenv["LIBIDN_FLAGS"])
- if myenv.get("HAVE_BONJOUR", 0) :
- myenv.Append(CPPDEFINES = "HAVE_BONJOUR")
- elif myenv.get("HAVE_AVAHI", 0) :
- myenv.Append(CPPDEFINES = ["HAVE_AVAHI"])
- myenv.MergeFlags(myenv["AVAHI_FLAGS"])
+ myenv = env.Clone()
+ myenv.MergeFlags(myenv["CHECKER_FLAGS"])
+ myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
+ myenv.MergeFlags(myenv["CPPUNIT_FLAGS"])
+ myenv.MergeFlags(myenv["BOOST_FLAGS"])
+ myenv.MergeFlags(myenv["LIBIDN_FLAGS"])
+ if myenv.get("HAVE_BONJOUR", 0) :
+ myenv.Append(CPPDEFINES = "HAVE_BONJOUR")
+ elif myenv.get("HAVE_AVAHI", 0) :
+ myenv.Append(CPPDEFINES = ["HAVE_AVAHI"])
+ myenv.MergeFlags(myenv["AVAHI_FLAGS"])
- tester = myenv.Program("DNSSDTest", [
- "DNSSDTest.cpp",
- ])
- myenv.Test(tester, "system")
+ tester = myenv.Program("DNSSDTest", [
+ "DNSSDTest.cpp",
+ ])
+ myenv.Test(tester, "system")
diff --git a/Swiften/QA/FileTransferTest/FileTransferTest.cpp b/Swiften/QA/FileTransferTest/FileTransferTest.cpp
index 7a50e9f..b627b30 100644
--- a/Swiften/QA/FileTransferTest/FileTransferTest.cpp
+++ b/Swiften/QA/FileTransferTest/FileTransferTest.cpp
@@ -13,7 +13,6 @@
#include <Swiften/Base/BoostRandomGenerator.h>
#include <Swiften/Base/Debug.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/sleep.h>
#include <Swiften/Client/Client.h>
#include <Swiften/Client/ClientXMLTracer.h>
@@ -35,366 +34,364 @@ using namespace Swift;
static const std::string CLIENT_NAME = "Swiften FT Test";
static const std::string CLIENT_NODE = "http://swift.im";
-static boost::shared_ptr<SimpleEventLoop> eventLoop;
-static boost::shared_ptr<BoostNetworkFactories> networkFactories;
+static std::shared_ptr<SimpleEventLoop> eventLoop;
+static std::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_ = std::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_ = std::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 (unsigned char& 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);
+ std::shared_ptr<FileWriteBytestream> out = std::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())) {
+ std::shared_ptr<FileReadBytestream> fileStream = std::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, std::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_;
+ std::shared_ptr<Client> sender_;
+ ClientXMLTracer* senderTracer_;
+ ByteArray sendData_;
+ OutgoingFileTransfer::ref outgoingFileTransfer_;
+ boost::filesystem::path sendFilePath_;
+ boost::optional<FileTransferError> senderError_;
+ bool senderIsDone_;
+
+ int receiverCandidates_;
+ std::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 = std::make_shared<SimpleEventLoop>();
+ networkFactories = std::make_shared<BoostNetworkFactories>(eventLoop.get());
- boost::shared_ptr<FileTransferTest> testRun = boost::make_shared<FileTransferTest>(senderCandidates, receiverCandidates);
+ std::shared_ptr<FileTransferTest> testRun = std::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("|"));
+ for (const auto& config : configurations) {
+ std::vector<std::string> split_config;
+ boost::split(split_config, config, boost::is_any_of(":"));
+ assert(split_config.size() == 2);
+
+ int senderCandidates = atoi(split_config[0].c_str());
+ int receiverCandidates = atoi(split_config[1].c_str());
+
+ if (!runTest(senderCandidates, receiverCandidates)) {
+ failedTests++;
+ failedTestPairs.push_back(std::pair<int, int>(senderCandidates, receiverCandidates));
+ }
+ }
+
+ for (auto&& failedTest : failedTestPairs) {
+ std::cout << "Failed test: " << "( " << failedTest.first << ", " << failedTest.second << ") " << std::endl;
+ }
+ }
+ else {
+ // test all configurations
+ for (int n = 0; n < (1 << 7); n++) {
+ int senderCandidates = n & 0xF;
+ int receiverCandidates = (n >> 4) & 0xF;
+ std::cout << "Run test " << n + 1 << " of " << (1 << 7) << ", (" << senderCandidates << ", " << receiverCandidates << ")" << std::endl;
+ if (!runTest(senderCandidates, receiverCandidates)) {
+ failedTests++;
+ failedTestPairs.push_back(std::pair<int, int>(senderCandidates, receiverCandidates));
+ }
+ }
+
+ for (auto&& failedTest : failedTestPairs) {
+ std::cout << "Failed test: " << "( " << failedTest.first << ", " << failedTest.second << ") " << std::endl;
+ }
+ }
+ }
+ else if (argc == 3) {
+ Log::setLogLevel(Log::debug);
+ int senderCandidates = atoi(argv[1]);
+ int receiverCandidates = atoi(argv[2]);
+ if (!runTest(senderCandidates, receiverCandidates)) {
+ failedTests++;
+ }
+ }
+ else {
+ std::cout << "Usage:" << std::endl;
+ std::cout << "\t- to test all combinations pass no arguments" << std::endl;
+ std::cout << "\t- to test a specific combination pass two integers describing sender and receiver candidates" << std::endl;
+ }
+ return failedTests;
}
diff --git a/Swiften/QA/FileTransferTest/SConscript b/Swiften/QA/FileTransferTest/SConscript
index 3275985..4b77674 100644
--- a/Swiften/QA/FileTransferTest/SConscript
+++ b/Swiften/QA/FileTransferTest/SConscript
@@ -3,18 +3,18 @@ import os
Import("env")
if env["TEST"] :
- myenv = env.Clone()
- myenv.UseFlags(myenv["SWIFTEN_FLAGS"])
- myenv.UseFlags(myenv["SWIFTEN_DEP_FLAGS"])
+ myenv = env.Clone()
+ myenv.UseFlags(myenv["SWIFTEN_FLAGS"])
+ myenv.UseFlags(myenv["SWIFTEN_DEP_FLAGS"])
- for i in ["SWIFT_FILETRANSFERTEST_JID", "SWIFT_FILETRANSFERTEST_PASS", "SWIFT_FILETRANSFERTEST2_JID", "SWIFT_FILETRANSFERTEST2_PASS"]:
- if ARGUMENTS.get(i.lower(), False) :
- myenv["ENV"][i] = ARGUMENTS[i.lower()]
- elif os.environ.get(i, "") :
- myenv["ENV"][i] = os.environ[i]
+ for i in ["SWIFT_FILETRANSFERTEST_JID", "SWIFT_FILETRANSFERTEST_PASS", "SWIFT_FILETRANSFERTEST2_JID", "SWIFT_FILETRANSFERTEST2_PASS"]:
+ if ARGUMENTS.get(i.lower(), False) :
+ myenv["ENV"][i] = ARGUMENTS[i.lower()]
+ elif os.environ.get(i, "") :
+ myenv["ENV"][i] = os.environ[i]
- # test in-band transfers, direct SOCKS5 bytestream transfers and proxied SOCKS5 bytestream transfers
- myenv["ENV"]["SWIFT_FILETRANSFERTEST_CONFIG"] = "1:1|2:2|4:4"
+ # test in-band transfers, direct SOCKS5 bytestream transfers and proxied SOCKS5 bytestream transfers
+ myenv["ENV"]["SWIFT_FILETRANSFERTEST_CONFIG"] = "1:1|2:2|4:4"
- tester = myenv.Program("FileTransferTest", ["FileTransferTest.cpp"])
- myenv.Test(tester, "system")
+ tester = myenv.Program("FileTransferTest", ["FileTransferTest.cpp"])
+ myenv.Test(tester, "system")
diff --git a/Swiften/QA/NetworkTest/BoostConnectionServerTest.cpp b/Swiften/QA/NetworkTest/BoostConnectionServerTest.cpp
index 67b4bfa..6982c0c 100644
--- a/Swiften/QA/NetworkTest/BoostConnectionServerTest.cpp
+++ b/Swiften/QA/NetworkTest/BoostConnectionServerTest.cpp
@@ -1,13 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
-
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -19,198 +18,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::fromString("127.0.0.1").get(), 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::fromString("127.0.0.1").get(), 9999));
+
+ while (!connectFinished_) {
+ Swift::sleep(10);
+ eventLoop_->processEvents();
+ }
+
+ CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
+
+ testling->stop();
+ }
+
+ void testIPv6Server() {
+ BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress::fromString("::1").get(), 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::fromString("::1").get(), 9999));
+
+ while (!connectFinished_) {
+ Swift::sleep(10);
+ eventLoop_->processEvents();
+ }
+
+ CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
+
+ testling->stop();
+ }
+
+ void testIPv4IPv6DualStackServer() {
+ BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress::fromString("::").get(), 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::fromString("127.0.0.1").get(), 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::fromString("::1").get(), 9999));
+
+ while (!connectFinished_) {
+ Swift::sleep(10);
+ eventLoop_->processEvents();
+ }
+
+ CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
+
+ testling->stop();
+ }
+
+ void testIPv6DualStackServerPeerAddress() {
+ BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress::fromString("::").get(), 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::fromString("127.0.0.1").get(), 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::fromString("::ffff:127.0.0.1").get() == 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::fromString("::1").get(), 9999));
+
+ while (!connectFinished_) {
+ Swift::sleep(10);
+ eventLoop_->processEvents();
+ }
+
+ CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
+ // The IPv6 local host is expected here.
+ CPPUNIT_ASSERT(HostAddress::fromString("::1").get() == remoteAddress_.get().getAddress());
+
+ testling->stop();
+ }
+
+ void handleStopped_(boost::optional<BoostConnectionServer::Error> e) {
+ stopped_ = true;
+ stoppedError_ = e;
+ }
+
+ void handleNewConnection(std::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..e0890bf 100755
--- a/Swiften/QA/NetworkTest/BoostConnectionTest.cpp
+++ b/Swiften/QA/NetworkTest/BoostConnectionTest.cpp
@@ -4,11 +4,10 @@
* See the COPYING file for more information.
*/
+#include <memory>
#include <string>
#include <boost/date_time/posix_time/posix_time_types.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -24,146 +23,157 @@
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_ = std::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_));
+ auto hostAddress = HostAddress::fromString(getenv("SWIFT_NETWORK_TEST_IPV4"));
+ CPPUNIT_ASSERT_EQUAL(true, hostAddress.is_initialized());
+ testling->connect(HostAddressPort(hostAddress.get(), 5222));
+ }
+ }
+
+ void testDestructor_PendingEvents() {
+ {
+ BoostConnection::ref testling(BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_));
+ auto hostAddress = HostAddress::fromString(getenv("SWIFT_NETWORK_TEST_IPV4"));
+ CPPUNIT_ASSERT_EQUAL(true, hostAddress.is_initialized());
+ testling->connect(HostAddressPort(hostAddress.get(), 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));
+ auto hostAddress = HostAddress::fromString(getenv("SWIFT_NETWORK_TEST_IPV4"));
+ CPPUNIT_ASSERT_EQUAL(true, hostAddress.is_initialized());
+ testling->connect(HostAddressPort(hostAddress.get(), 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));
+ auto hostAddress = HostAddress::fromString(getenv("SWIFT_NETWORK_TEST_IPV6"));
+ CPPUNIT_ASSERT_EQUAL(true, hostAddress.is_initialized());
+ testling->connect(HostAddressPort(hostAddress.get(), 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));
+
+ auto hostAddress = HostAddress::fromString(getenv("SWIFT_NETWORK_TEST_IPV4"));
+ CPPUNIT_ASSERT_EQUAL(true, hostAddress.is_initialized());
+ testling->connect(HostAddressPort(hostAddress.get(), 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(std::shared_ptr<SafeByteArray> data) {
+ append(receivedData_, *data);
+ }
+
+ void handleDisconnected() {
+ disconnected_ = true;
+ }
+
+ void handleConnectFinished() {
+ connectFinished_ = true;
+ }
+
+ private:
+ BoostIOServiceThread* boostIOServiceThread_;
+ std::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..95ebb6d 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 = std::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() {
+ std::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() {
+ std::shared_ptr<DomainNameAddressQuery> query(createAddressQuery("invalid.test.swift.im"));
+
+ query->run();
+ waitForResults();
+
+ CPPUNIT_ASSERT(addressQueryError);
+ }
+
+ void testResolveAddress_IPv6() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::shared_ptr<DomainNameAddressQuery> query(createAddressQuery("localhost"));
+
+ query->run();
+ waitForResults();
+
+ CPPUNIT_ASSERT(!addressQueryError);
+ CPPUNIT_ASSERT(std::find(addressQueryResult.begin(), addressQueryResult.end(), HostAddress::fromString("127.0.0.1").get()) != 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() {
+ std::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:
+ std::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& domain) {
+ std::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;
+ }
+
+ std::shared_ptr<DomainNameServiceQuery> createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) {
+ std::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;
+ std::shared_ptr<IDNConverter> idnConverter;
+ std::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/NetworkTest/SConscript b/Swiften/QA/NetworkTest/SConscript
index b090165..387bafc 100644
--- a/Swiften/QA/NetworkTest/SConscript
+++ b/Swiften/QA/NetworkTest/SConscript
@@ -3,20 +3,20 @@ import os
Import("env")
if env["TEST"] :
- myenv = env.Clone()
- if "test_ipv6" in ARGUMENTS :
- myenv.Append(CPPDEFINES = ["TEST_IPV6"])
- myenv.MergeFlags(myenv["CHECKER_FLAGS"])
- myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
- myenv.MergeFlags(myenv["SWIFTEN_DEP_FLAGS"])
- myenv.MergeFlags(myenv["CPPUNIT_FLAGS"])
+ myenv = env.Clone()
+ if "test_ipv6" in ARGUMENTS :
+ myenv.Append(CPPDEFINES = ["TEST_IPV6"])
+ myenv.MergeFlags(myenv["CHECKER_FLAGS"])
+ myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
+ myenv.MergeFlags(myenv["SWIFTEN_DEP_FLAGS"])
+ myenv.MergeFlags(myenv["CPPUNIT_FLAGS"])
- if env.get("unbound", False) :
- myenv.Append(CPPDEFINES = ["USE_UNBOUND"])
+ if env.get("unbound", False) :
+ myenv.Append(CPPDEFINES = ["USE_UNBOUND"])
- tester = myenv.Program("NetworkTest", [
- "BoostConnectionServerTest.cpp",
- "BoostConnectionTest.cpp",
- "DomainNameResolverTest.cpp",
- ])
- myenv.Test(tester, "system", is_checker = True)
+ tester = myenv.Program("NetworkTest", [
+ "BoostConnectionServerTest.cpp",
+ "BoostConnectionTest.cpp",
+ "DomainNameResolverTest.cpp",
+ ])
+ myenv.Test(tester, "system", is_checker = True)
diff --git a/Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp b/Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp
index ddaee01..53f9e60 100644
--- a/Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp
+++ b/Swiften/QA/ProxyProviderTest/ProxyProviderTest.cpp
@@ -4,32 +4,37 @@
* See Documentation/Licenses/BSD.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <iostream>
#include <Swiften/Network/PlatformProxyProvider.h>
-#include <Swiften/Base/foreach.h>
using namespace Swift;
int main(void)
{
- int ret = 0;
- HostAddressPort hap;
-
- std::cout << "constructing PlatfromProxyProvider instance ..." << std::endl;
- PlatformProxyProvider ppp;
-
- hap = ppp.getSOCKS5Proxy();
- std::cout << "SOCKS5 Proxy configured: " << hap.isValid() << std::endl;
- if(hap.isValid()) {
- std::cout << "SOCKS5 Proxy: " << hap.getAddress().toString() << ":" << hap.getPort() << std::endl;
- }
-
- hap = ppp.getHTTPConnectProxy();
- std::cout << "HTTPConnect Proxy configured: " << hap.isValid() << std::endl;
- if(hap.isValid()) {
- std::cout << "HTTPConnect Proxy: " << hap.getAddress().toString() << ":" << hap.getPort() << std::endl;
- }
-
- return ret;
+ 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/ProxyProviderTest/SConscript b/Swiften/QA/ProxyProviderTest/SConscript
index 2eb123d..3e28360 100644
--- a/Swiften/QA/ProxyProviderTest/SConscript
+++ b/Swiften/QA/ProxyProviderTest/SConscript
@@ -7,5 +7,5 @@ myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
myenv.MergeFlags(myenv["SWIFTEN_DEP_FLAGS"])
myenv.Program("ProxyProviderTest", [
- "ProxyProviderTest.cpp",
- ])
+ "ProxyProviderTest.cpp",
+ ])
diff --git a/Swiften/QA/ReconnectTest/ReconnectTest.cpp b/Swiften/QA/ReconnectTest/ReconnectTest.cpp
index cfb7f80..af3369c 100644
--- a/Swiften/QA/ReconnectTest/ReconnectTest.cpp
+++ b/Swiften/QA/ReconnectTest/ReconnectTest.cpp
@@ -1,20 +1,21 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <thread>
+
#include <boost/bind.hpp>
-#include <boost/thread.hpp>
#include <Swiften/Client/Client.h>
-#include <Swiften/Network/BoostTimer.h>
+#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/EventLoop/SimpleEventLoop.h>
-#include <Swiften/Roster/GetRosterRequest.h>
-#include <Swiften/Client/ClientXMLTracer.h>
#include <Swiften/Network/BoostIOServiceThread.h>
+#include <Swiften/Network/BoostTimer.h>
#include <Swiften/Network/MainBoostIOServiceThread.h>
+#include <Swiften/Roster/GetRosterRequest.h>
using namespace Swift;
@@ -25,49 +26,49 @@ Client* client_;
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();
+void handleTick(std::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;
+ std::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(std::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/ReconnectTest/SConscript b/Swiften/QA/ReconnectTest/SConscript
index 6db6a6f..a94af5e 100644
--- a/Swiften/QA/ReconnectTest/SConscript
+++ b/Swiften/QA/ReconnectTest/SConscript
@@ -3,23 +3,23 @@ import os
Import("env")
if env["TEST"] :
- myenv = env.Clone()
- myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
- myenv.MergeFlags(myenv["CPPUNIT_FLAGS"])
- myenv.MergeFlags(myenv["LIBIDN_FLAGS"])
- myenv.MergeFlags(myenv["BOOST_FLAGS"])
- myenv.MergeFlags(myenv.get("SQLITE_FLAGS", ""))
- myenv.MergeFlags(myenv["ZLIB_FLAGS"])
- myenv.MergeFlags(myenv["OPENSSL_FLAGS"])
- myenv.MergeFlags(myenv.get("LIBXML_FLAGS", ""))
- myenv.MergeFlags(myenv.get("EXPAT_FLAGS", ""))
- myenv.MergeFlags(myenv["PLATFORM_FLAGS"])
-# myenv.Append(LIBPATH = ["/opt/local/lib"])
-# myenv.Append(LIBS = ["efence"])
+ myenv = env.Clone()
+ myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
+ myenv.MergeFlags(myenv["CPPUNIT_FLAGS"])
+ myenv.MergeFlags(myenv["LIBIDN_FLAGS"])
+ myenv.MergeFlags(myenv["BOOST_FLAGS"])
+ myenv.MergeFlags(myenv.get("SQLITE_FLAGS", ""))
+ myenv.MergeFlags(myenv["ZLIB_FLAGS"])
+ myenv.MergeFlags(myenv["OPENSSL_FLAGS"])
+ myenv.MergeFlags(myenv.get("LIBXML_FLAGS", ""))
+ myenv.MergeFlags(myenv.get("EXPAT_FLAGS", ""))
+ myenv.MergeFlags(myenv["PLATFORM_FLAGS"])
+# myenv.Append(LIBPATH = ["/opt/local/lib"])
+# myenv.Append(LIBS = ["efence"])
- for i in ["SWIFT_CLIENTTEST_JID", "SWIFT_CLIENTTEST_PASS"]:
- if os.environ.get(i, "") :
- myenv["ENV"][i] = os.environ[i]
+ for i in ["SWIFT_CLIENTTEST_JID", "SWIFT_CLIENTTEST_PASS"]:
+ if os.environ.get(i, "") :
+ myenv["ENV"][i] = os.environ[i]
- tester = myenv.Program("ReconnectTest", ["ReconnectTest.cpp"])
- myenv.Test(tester, "system", is_checker = True)
+ tester = myenv.Program("ReconnectTest", ["ReconnectTest.cpp"])
+ myenv.Test(tester, "system", is_checker = True)
diff --git a/Swiften/QA/SConscript b/Swiften/QA/SConscript
index 2c588e5..2bb3e51 100644
--- a/Swiften/QA/SConscript
+++ b/Swiften/QA/SConscript
@@ -1,13 +1,13 @@
Import("swiften_env")
SConscript(dirs = [
- "NetworkTest",
-# "ReconnectTest",
- "ClientTest",
-# "DNSSDTest",
- "StorageTest",
- "TLSTest",
- "ScriptedTests",
- "ProxyProviderTest",
- "FileTransferTest",
- ])
+ "NetworkTest",
+# "ReconnectTest",
+ "ClientTest",
+# "DNSSDTest",
+ "StorageTest",
+ "TLSTest",
+ "ScriptedTests",
+ "ProxyProviderTest",
+ "FileTransferTest",
+ ])
diff --git a/Swiften/QA/ScriptedTests/SConscript b/Swiften/QA/ScriptedTests/SConscript
index 298c455..ae315fe 100644
--- a/Swiften/QA/ScriptedTests/SConscript
+++ b/Swiften/QA/ScriptedTests/SConscript
@@ -1,7 +1,7 @@
Import("env")
if env["TEST"] :
- env.ScriptTests([
- "SendMessage.lua",
- "MultipleClients.lua",
- ], "Swiften.QA.ScriptedTests", "system")
+ env.ScriptTests([
+ "SendMessage.lua",
+ "MultipleClients.lua",
+ ], "Swiften.QA.ScriptedTests", "system")
diff --git a/Swiften/QA/StorageTest/FileReadBytestreamTest.cpp b/Swiften/QA/StorageTest/FileReadBytestreamTest.cpp
index d70d9c9..e601de9 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() {
+ std::shared_ptr<FileReadBytestream> testling(createTestling());
- boost::shared_ptr< std::vector<unsigned char> > result = testling->read(10);
+ std::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() {
+ std::shared_ptr<FileReadBytestream> testling(createTestling());
- testling->read(10);
- boost::shared_ptr< std::vector<unsigned char> > result = testling->read(10);
+ testling->read(10);
+ std::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() {
+ std::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() {
+ std::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..7823519 100644
--- a/Swiften/QA/StorageTest/FileWriteBytestreamTest.cpp
+++ b/Swiften/QA/StorageTest/FileWriteBytestreamTest.cpp
@@ -6,53 +6,53 @@
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
+#include <boost/signals2.hpp>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <Swiften/Base/ByteArray.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/FileTransfer/FileWriteBytestream.h>
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");
+ std::shared_ptr<WriteBytestream> writeBytestream = std::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() {
+ std::shared_ptr<WriteBytestream> writeBytestream = std::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/SConscript b/Swiften/QA/StorageTest/SConscript
index fff2a2b..bb1a2c6 100644
--- a/Swiften/QA/StorageTest/SConscript
+++ b/Swiften/QA/StorageTest/SConscript
@@ -3,20 +3,20 @@ import os
Import("env")
if env["TEST"] :
- myenv = env.Clone()
- myenv.MergeFlags(myenv["CHECKER_FLAGS"])
- myenv.MergeFlags(myenv["SWIFTOOLS_FLAGS"])
- myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
- myenv.MergeFlags(myenv["CPPUNIT_FLAGS"])
- myenv.MergeFlags(myenv["BOOST_FLAGS"])
- myenv.MergeFlags(myenv["LIBIDN_FLAGS"])
- myenv.MergeFlags(myenv.get("EXPAT_FLAGS", {}))
- myenv.MergeFlags(myenv.get("LIBXML_FLAGS", {}))
- myenv.MergeFlags(myenv["PLATFORM_FLAGS"])
+ myenv = env.Clone()
+ myenv.MergeFlags(myenv["CHECKER_FLAGS"])
+ myenv.MergeFlags(myenv["SWIFTOOLS_FLAGS"])
+ myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
+ myenv.MergeFlags(myenv["CPPUNIT_FLAGS"])
+ myenv.MergeFlags(myenv["BOOST_FLAGS"])
+ myenv.MergeFlags(myenv["LIBIDN_FLAGS"])
+ myenv.MergeFlags(myenv.get("EXPAT_FLAGS", {}))
+ myenv.MergeFlags(myenv.get("LIBXML_FLAGS", {}))
+ myenv.MergeFlags(myenv["PLATFORM_FLAGS"])
- tester = myenv.Program("StorageTest", [
- #"VCardFileStorageTest.cpp",
- "FileReadBytestreamTest.cpp",
- "FileWriteBytestreamTest.cpp",
- ])
- myenv.Test(tester, "system", is_checker = True)
+ tester = myenv.Program("StorageTest", [
+ #"VCardFileStorageTest.cpp",
+ "FileReadBytestreamTest.cpp",
+ "FileWriteBytestreamTest.cpp",
+ ])
+ myenv.Test(tester, "system", is_checker = True)
diff --git a/Swiften/QA/StorageTest/VCardFileStorageTest.cpp b/Swiften/QA/StorageTest/VCardFileStorageTest.cpp
index e0a65a4..1be2490 100644
--- a/Swiften/QA/StorageTest/VCardFileStorageTest.cpp
+++ b/Swiften/QA/StorageTest/VCardFileStorageTest.cpp
@@ -1,113 +1,117 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+#include <sstream>
+
+#include <boost/algorithm/string.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/algorithm/string.hpp>
-#include <sstream>
-#include <Swiften/VCards/VCardFileStorage.h>
-#include <Swiften/JID/JID.h>
-#include "SwifTools/Application/PlatformApplicationPathProvider.h"
#include <Swiften/Elements/VCard.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/VCards/VCardFileStorage.h>
+
+#include <SwifTools/Application/PlatformApplicationPathProvider.h>
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() {
+ std::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::unique_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() {
+ std::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::unique_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() {
+ std::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 1d87994..abd004e 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_ = std::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) {
+ std::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(std::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() {
+ std::shared_ptr<TLSConnection> connection = std::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() {
+ std::shared_ptr<TLSConnection> connection = std::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() {
+ std::shared_ptr<TLSConnection> connection = std::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() {
+ std::shared_ptr<TLSConnection> connection = std::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() {
+ std::shared_ptr<TLSConnection> connection = std::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);
+ std::shared_ptr<TLSConnection> connection = std::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);
+ std::shared_ptr<TLSConnection> connection = std::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_;
+ std::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 1c3857a..b53cd2f 100644
--- a/Swiften/QA/TLSTest/CertificateTest.cpp
+++ b/Swiften/QA/TLSTest/CertificateTest.cpp
@@ -1,99 +1,97 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/ByteArray.h>
+#include <memory>
+
+#include <boost/bind.hpp>
#include <QA/Checker/IO.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/bind.hpp>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/TLS/CertificateFactory.h>
-#include "SwifTools/Application/PlatformApplicationPathProvider.h"
+
+#include <SwifTools/Application/PlatformApplicationPathProvider.h>
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 = std::unique_ptr<PlatformApplicationPathProvider>(new PlatformApplicationPathProvider("FileReadBytestreamTest"));
+ readByteArrayFromFile(certificateData, (pathProvider->getExecutableDir() / "jabber_org.crt"));
+ certificateFactory = std::unique_ptr<CertificateFactory>(new CERTIFICATE_FACTORY());
+ }
+
+ 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:
+ std::unique_ptr<PlatformApplicationPathProvider> pathProvider;
+ ByteArray certificateData;
+ std::unique_ptr<CertificateFactory> certificateFactory;
};
#ifdef HAVE_OPENSSL
diff --git a/Swiften/QA/TLSTest/SConscript b/Swiften/QA/TLSTest/SConscript
index 0ac50e6..b7bfc7d 100644
--- a/Swiften/QA/TLSTest/SConscript
+++ b/Swiften/QA/TLSTest/SConscript
@@ -3,22 +3,24 @@ import os
Import("env")
if env["TEST"] :
- myenv = env.Clone()
- myenv.MergeFlags(myenv["CHECKER_FLAGS"])
- myenv.MergeFlags(myenv["SWIFTOOLS_FLAGS"])
- myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
- myenv.MergeFlags(myenv["SWIFTEN_DEP_FLAGS"])
- myenv.MergeFlags(myenv["CPPUNIT_FLAGS"])
-
- if myenv.get("HAVE_OPENSSL", 0) :
- myenv.Append(CPPDEFINES = "HAVE_OPENSSL")
- elif myenv.get("HAVE_SCHANNEL", 0) :
- myenv.Append(CPPDEFINES = "HAVE_SCHANNEL")
- elif myenv.get("HAVE_SECURETRANSPORT", 0) :
- myenv.Append(CPPDEFINES = "HAVE_SECURETRANSPORT")
-
- tester = myenv.Program("TLSTest", [
- "CertificateTest.cpp",
- "CertificateErrorTest.cpp"
- ])
- myenv.Test(tester, "system") \ No newline at end of file
+ myenv = env.Clone()
+ myenv.MergeFlags(myenv["CHECKER_FLAGS"])
+ myenv.MergeFlags(myenv["SWIFTOOLS_FLAGS"])
+ myenv.MergeFlags(myenv["SWIFTEN_FLAGS"])
+ myenv.MergeFlags(myenv["SWIFTEN_DEP_FLAGS"])
+ myenv.MergeFlags(myenv["CPPUNIT_FLAGS"])
+
+ if myenv.get("HAVE_OPENSSL", 0) :
+ myenv.Append(CPPDEFINES = "HAVE_OPENSSL")
+ myenv.MergeFlags(myenv["OPENSSL_FLAGS"])
+ elif myenv.get("HAVE_SCHANNEL", 0) :
+ myenv.Append(CPPDEFINES = "HAVE_SCHANNEL")
+ elif myenv.get("HAVE_SECURETRANSPORT", 0) :
+ myenv.Append(CPPDEFINES = "HAVE_SECURETRANSPORT")
+
+ tester = myenv.Program("TLSTest", [
+ "CertificateTest.cpp",
+ # Reenable if either http://www.tls-o-matic.com/ is fixed or we have setup a replacement.
+ #"CertificateErrorTest.cpp"
+ ])
+ myenv.Test(tester, "system") \ No newline at end of file
diff --git a/Swiften/QA/TLSTest/jabber_org.crt b/Swiften/QA/TLSTest/jabber_org.crt
index f7d619f..5a9ddaa 100644
--- a/Swiften/QA/TLSTest/jabber_org.crt
+++ b/Swiften/QA/TLSTest/jabber_org.crt
Binary files differ
diff --git a/Swiften/Queries/DummyIQChannel.h b/Swiften/Queries/DummyIQChannel.h
index 11cc3dc..5ec68ca 100644
--- a/Swiften/Queries/DummyIQChannel.h
+++ b/Swiften/Queries/DummyIQChannel.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::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<std::shared_ptr<IQ> > iqs_;
+ };
}
diff --git a/Swiften/Queries/GenericRequest.h b/Swiften/Queries/GenericRequest.h
index d6cca1c..312ecf2 100644
--- a/Swiften/Queries/GenericRequest.h
+++ b/Swiften/Queries/GenericRequest.h
@@ -1,79 +1,80 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
#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 std::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,
+ std::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,
+ std::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(std::shared_ptr<Payload> payload, ErrorPayload::ref error) {
+ onResponse(std::dynamic_pointer_cast<PAYLOAD_TYPE>(payload), error);
+ }
- public:
- boost::shared_ptr<PAYLOAD_TYPE> getPayloadGeneric() const {
- return boost::dynamic_pointer_cast<PAYLOAD_TYPE>(getPayload());
- }
+ public:
+ std::shared_ptr<PAYLOAD_TYPE> getPayloadGeneric() const {
+ return std::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::signals2::signal<void (std::shared_ptr<PAYLOAD_TYPE>, ErrorPayload::ref)> onResponse;
+ };
}
diff --git a/Swiften/Queries/GetResponder.h b/Swiften/Queries/GetResponder.h
index df08f30..18dd694 100644
--- a/Swiften/Queries/GetResponder.h
+++ b/Swiften/Queries/GetResponder.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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&, std::shared_ptr<T>) { return false; }
+ };
}
diff --git a/Swiften/Queries/IQChannel.h b/Swiften/Queries/IQChannel.h
index 7f8e7dc..fe32d89 100644
--- a/Swiften/Queries/IQChannel.h
+++ b/Swiften/Queries/IQChannel.h
@@ -1,28 +1,29 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
-
+#include <memory>
#include <string>
+
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
#include <Swiften/Elements/IQ.h>
namespace Swift {
- class SWIFTEN_API IQChannel {
- public:
- virtual ~IQChannel();
+ class SWIFTEN_API IQChannel {
+ public:
+ virtual ~IQChannel();
+
+ virtual void sendIQ(std::shared_ptr<IQ>) = 0;
+ virtual std::string getNewIQID() = 0;
- virtual void sendIQ(boost::shared_ptr<IQ>) = 0;
- virtual std::string getNewIQID() = 0;
-
- virtual bool isAvailable() const = 0;
+ virtual bool isAvailable() const = 0;
- boost::signal<void (boost::shared_ptr<IQ>)> onIQReceived;
- };
+ boost::signals2::signal<void (std::shared_ptr<IQ>)> onIQReceived;
+ };
}
diff --git a/Swiften/Queries/IQHandler.cpp b/Swiften/Queries/IQHandler.cpp
index ec78ef6..bdfad30 100644
--- a/Swiften/Queries/IQHandler.cpp
+++ b/Swiften/Queries/IQHandler.cpp
@@ -1,10 +1,11 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Queries/IQHandler.h>
+
#include <Swiften/Queries/IQRouter.h>
namespace Swift {
diff --git a/Swiften/Queries/IQHandler.h b/Swiften/Queries/IQHandler.h
index b45e1e6..1bfdf0f 100644
--- a/Swiften/Queries/IQHandler.h
+++ b/Swiften/Queries/IQHandler.h
@@ -1,23 +1,23 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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(std::shared_ptr<IQ>) = 0;
+ };
}
diff --git a/Swiften/Queries/IQRouter.cpp b/Swiften/Queries/IQRouter.cpp
index b6b957e..286b65f 100644
--- a/Swiften/Queries/IQRouter.cpp
+++ b/Swiften/Queries/IQRouter.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,86 +9,85 @@
#include <boost/bind.hpp>
#include <Swiften/Base/Algorithm.h>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Queries/IQHandler.h>
-#include <Swiften/Queries/IQChannel.h>
#include <Swiften/Elements/ErrorPayload.h>
+#include <Swiften/Queries/IQChannel.h>
+#include <Swiften/Queries/IQHandler.h>
namespace Swift {
static void noop(IQHandler*) {}
IQRouter::IQRouter(IQChannel* channel) : channel_(channel), queueRemoves_(false) {
- channel->onIQReceived.connect(boost::bind(&IQRouter::handleIQ, this, _1));
+ 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;
+void IQRouter::handleIQ(std::shared_ptr<IQ> iq) {
+ queueRemoves_ = true;
+
+ bool handled = false;
+ // Go through the handlers in reverse order, to give precedence to the last added handler
+ std::vector<std::shared_ptr<IQHandler> >::const_reverse_iterator i = handlers_.rbegin();
+ std::vector<std::shared_ptr<IQHandler> >::const_reverse_iterator rend = handlers_.rend();
+ for (; i != rend; ++i) {
+ handled |= (*i)->handleIQ(iq);
+ if (handled) {
+ break;
+ }
+ }
+ if (!handled && (iq->getType() == IQ::Get || iq->getType() == IQ::Set) ) {
+ sendIQ(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::FeatureNotImplemented, ErrorPayload::Cancel));
+ }
+
+ processPendingRemoves();
+
+ queueRemoves_ = false;
}
void IQRouter::processPendingRemoves() {
- foreach(boost::shared_ptr<IQHandler> handler, queuedRemoves_) {
- erase(handlers_, handler);
- }
- queuedRemoves_.clear();
+ for (auto&& handler : queuedRemoves_) {
+ erase(handlers_, handler);
+ }
+ queuedRemoves_.clear();
}
void IQRouter::addHandler(IQHandler* handler) {
- addHandler(boost::shared_ptr<IQHandler>(handler, noop));
+ addHandler(std::shared_ptr<IQHandler>(handler, noop));
}
void IQRouter::removeHandler(IQHandler* handler) {
- removeHandler(boost::shared_ptr<IQHandler>(handler, noop));
+ removeHandler(std::shared_ptr<IQHandler>(handler, noop));
}
-void IQRouter::addHandler(boost::shared_ptr<IQHandler> handler) {
- handlers_.push_back(handler);
+void IQRouter::addHandler(std::shared_ptr<IQHandler> handler) {
+ handlers_.push_back(handler);
}
-void IQRouter::removeHandler(boost::shared_ptr<IQHandler> handler) {
- if (queueRemoves_) {
- queuedRemoves_.push_back(handler);
- }
- else {
- erase(handlers_, handler);
- }
+void IQRouter::removeHandler(std::shared_ptr<IQHandler> 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);
+void IQRouter::sendIQ(std::shared_ptr<IQ> 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 ac1beaf..eda7cfb 100644
--- a/Swiften/Queries/IQRouter.h
+++ b/Swiften/Queries/IQRouter.h
@@ -1,89 +1,89 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <vector>
+#include <memory>
#include <string>
+#include <vector>
#include <Swiften/Base/API.h>
#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(std::shared_ptr<IQHandler> handler);
+ void removeHandler(std::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(std::shared_ptr<IQ> iq);
+ std::string getNewIQID();
- /**
- * 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();
+ bool isAvailable();
- /**
- * 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;
- }
+ /**
+ * 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:
- void handleIQ(boost::shared_ptr<IQ> iq);
- void processPendingRemoves();
+ private:
+ void handleIQ(std::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_;
- };
+ private:
+ IQChannel* channel_;
+ JID jid_;
+ JID from_;
+ std::vector< std::shared_ptr<IQHandler> > handlers_;
+ std::vector< std::shared_ptr<IQHandler> > queuedRemoves_;
+ bool queueRemoves_;
+ };
}
diff --git a/Swiften/Queries/PubSubRequest.h b/Swiften/Queries/PubSubRequest.h
index 9cf4404..b439748 100644
--- a/Swiften/Queries/PubSubRequest.h
+++ b/Swiften/Queries/PubSubRequest.h
@@ -1,91 +1,92 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/Queries/Request.h>
#include <Swiften/Elements/ContainerPayload.h>
-#include <Swiften/PubSub/PubSubUtil.h>
#include <Swiften/Elements/PubSub.h>
-#include <Swiften/Elements/PubSubOwnerPubSub.h>
-#include <Swiften/Elements/PubSubCreate.h>
-#include <Swiften/Elements/PubSubSubscribe.h>
#include <Swiften/Elements/PubSubAffiliations.h>
+#include <Swiften/Elements/PubSubCreate.h>
#include <Swiften/Elements/PubSubDefault.h>
#include <Swiften/Elements/PubSubItems.h>
-#include <Swiften/Elements/PubSubPublish.h>
-#include <Swiften/Elements/PubSubRetract.h>
-#include <Swiften/Elements/PubSubSubscription.h>
-#include <Swiften/Elements/PubSubSubscriptions.h>
-#include <Swiften/Elements/PubSubUnsubscribe.h>
#include <Swiften/Elements/PubSubOwnerAffiliations.h>
#include <Swiften/Elements/PubSubOwnerConfigure.h>
#include <Swiften/Elements/PubSubOwnerDefault.h>
#include <Swiften/Elements/PubSubOwnerDelete.h>
+#include <Swiften/Elements/PubSubOwnerPubSub.h>
#include <Swiften/Elements/PubSubOwnerPurge.h>
#include <Swiften/Elements/PubSubOwnerSubscriptions.h>
+#include <Swiften/Elements/PubSubPublish.h>
+#include <Swiften/Elements/PubSubRetract.h>
+#include <Swiften/Elements/PubSubSubscribe.h>
+#include <Swiften/Elements/PubSubSubscription.h>
+#include <Swiften/Elements/PubSubSubscriptions.h>
+#include <Swiften/Elements/PubSubUnsubscribe.h>
+#include <Swiften/PubSub/PubSubUtil.h>
+#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,
+ std::shared_ptr<T> payload,
+ IQRouter* router) :
+ Request(type, receiver, router) {
+ std::shared_ptr<ContainerType> wrapper = std::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,
+ std::shared_ptr<T> payload,
+ IQRouter* router) :
+ Request(type, sender, receiver, router) {
+ std::shared_ptr<ContainerType> wrapper = std::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(
+ std::shared_ptr<Payload> payload, ErrorPayload::ref error) {
+ std::shared_ptr<ResponseType> result;
+ if (std::shared_ptr<ContainerType> container = std::dynamic_pointer_cast<ContainerType>(payload)) {
+ result = std::dynamic_pointer_cast<ResponseType>(container->getPayload());
+ }
+ onResponse(result, error);
+ }
- public:
- boost::signal<void (boost::shared_ptr<ResponseType>, ErrorPayload::ref)> onResponse;
- };
+ public:
+ boost::signals2::signal<void (std::shared_ptr<ResponseType>, ErrorPayload::ref)> onResponse;
+ };
}
diff --git a/Swiften/Queries/RawRequest.h b/Swiften/Queries/RawRequest.h
index 0d0336e..76c84f9 100644
--- a/Swiften/Queries/RawRequest.h
+++ b/Swiften/Queries/RawRequest.h
@@ -1,51 +1,52 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <typeinfo>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/Queries/Request.h>
-#include <Swiften/Elements/RawXMLPayload.h>
#include <Swiften/Elements/ErrorPayload.h>
+#include <Swiften/Elements/RawXMLPayload.h>
+#include <Swiften/Queries/Request.h>
#include <Swiften/Serializer/PayloadSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/ErrorSerializer.h>
#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 std::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::signals2::signal<void (const std::string&)> onResponse;
+
+ private:
+ RawRequest(IQ::Type type, const JID& receiver, const std::string& data, IQRouter* router) : Request(type, receiver, std::make_shared<RawXMLPayload>(data), router) {
+ }
+
+ virtual void handleResponse(std::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 dec1dfa..12eaae5 100644
--- a/Swiften/Queries/Request.cpp
+++ b/Swiften/Queries/Request.cpp
@@ -1,92 +1,93 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Queries/Request.h>
-#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/Elements/RawXMLPayload.h>
+
#include <Swiften/Base/Log.h>
+#include <Swiften/Elements/RawXMLPayload.h>
+#include <Swiften/Queries/IQRouter.h>
namespace Swift {
-Request::Request(IQ::Type type, const JID& receiver, boost::shared_ptr<Payload> payload, IQRouter* router) : router_(router), type_(type), receiver_(receiver), payload_(payload), sent_(false) {
+Request::Request(IQ::Type type, const JID& receiver, std::shared_ptr<Payload> payload, IQRouter* router) : router_(router), type_(type), receiver_(receiver), payload_(payload), sent_(false) {
}
Request::Request(IQ::Type type, const JID& receiver, IQRouter* router) : router_(router), type_(type), receiver_(receiver), sent_(false) {
}
-Request::Request(IQ::Type type, const JID& sender, const JID& receiver, boost::shared_ptr<Payload> payload, IQRouter* router) : router_(router), type_(type), sender_(sender), receiver_(receiver), payload_(payload), sent_(false) {
+Request::Request(IQ::Type type, const JID& sender, const JID& receiver, std::shared_ptr<Payload> payload, IQRouter* router) : router_(router), type_(type), sender_(sender), receiver_(receiver), payload_(payload), sent_(false) {
}
Request::Request(IQ::Type type, const JID& sender, const JID& receiver, IQRouter* router) : router_(router), type_(type), sender_(sender), receiver_(receiver), sent_(false) {
}
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_);
+ std::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 Request::handleIQ(std::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) {
+ std::shared_ptr<Payload> payload = iq->getPayloadOfSameType(payload_);
+ if (!payload && std::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(std::shared_ptr<Payload>(), errorPayload);
+ }
+ else {
+ handleResponse(std::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 707f81e..a62c103 100644
--- a/Swiften/Queries/Request.h
+++ b/Swiften/Queries/Request.h
@@ -1,106 +1,106 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <boost/optional.hpp>
-#include <boost/enable_shared_from_this.hpp>
+#include <memory>
#include <string>
+#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/IQHandler.h>
+#include <Swiften/Elements/ErrorPayload.h>
#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/Payload.h>
-#include <Swiften/Elements/ErrorPayload.h>
#include <Swiften/JID/JID.h>
+#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 std::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,
+ std::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,
+ std::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(std::shared_ptr<Payload> payload) {
+ payload_ = payload;
+ }
+
+ std::shared_ptr<Payload> getPayload() const {
+ return payload_;
+ }
+
+ virtual void handleResponse(std::shared_ptr<Payload>, std::shared_ptr<ErrorPayload>) = 0;
+
+ private:
+ bool handleIQ(std::shared_ptr<IQ>);
+ bool isCorrectSender(const JID& jid);
+
+ private:
+ IQRouter* router_;
+ IQ::Type type_;
+ JID sender_;
+ JID receiver_;
+ std::shared_ptr<Payload> payload_;
+ std::string id_;
+ bool sent_;
+ };
}
diff --git a/Swiften/Queries/Requests/EnableCarbonsRequest.h b/Swiften/Queries/Requests/EnableCarbonsRequest.h
new file mode 100644
index 0000000..7762e68
--- /dev/null
+++ b/Swiften/Queries/Requests/EnableCarbonsRequest.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#pragma once
+
+#include <memory>
+
+#include <Swiften/Base/API.h>
+#include <Swiften/Elements/CarbonsEnable.h>
+#include <Swiften/Queries/GenericRequest.h>
+
+namespace Swift {
+ class SWIFTEN_API EnableCarbonsRequest : public GenericRequest<CarbonsEnable> {
+ public:
+ typedef std::shared_ptr<EnableCarbonsRequest> ref;
+
+ static ref create(IQRouter* router) {
+ return ref(new EnableCarbonsRequest(router));
+ }
+
+ private:
+ EnableCarbonsRequest(IQRouter* router) : GenericRequest<CarbonsEnable>(IQ::Set, JID(), std::make_shared<CarbonsEnable>(), router) {
+ }
+ };
+}
diff --git a/Swiften/Queries/Requests/GetInBandRegistrationFormRequest.cpp b/Swiften/Queries/Requests/GetInBandRegistrationFormRequest.cpp
deleted file mode 100644
index d04e5c7..0000000
--- a/Swiften/Queries/Requests/GetInBandRegistrationFormRequest.cpp
+++ /dev/null
@@ -1,7 +0,0 @@
-/*
- * Copyright (c) 2010 Isode Limited.
- * All rights reserved.
- * See the COPYING file for more information.
- */
-
-#include <Swiften/Queries/Requests/GetInBandRegistrationFormRequest.h>
diff --git a/Swiften/Queries/Requests/GetInBandRegistrationFormRequest.h b/Swiften/Queries/Requests/GetInBandRegistrationFormRequest.h
index b952875..b187fa5 100644
--- a/Swiften/Queries/Requests/GetInBandRegistrationFormRequest.h
+++ b/Swiften/Queries/Requests/GetInBandRegistrationFormRequest.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,20 +7,20 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/InBandRegistrationPayload.h>
+#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 std::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 97711a6..5fb0de5 100644
--- a/Swiften/Queries/Requests/GetPrivateStorageRequest.h
+++ b/Swiften/Queries/Requests/GetPrivateStorageRequest.h
@@ -1,45 +1,45 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/Request.h>
-#include <Swiften/Elements/PrivateStorage.h>
#include <Swiften/Elements/ErrorPayload.h>
+#include <Swiften/Elements/PrivateStorage.h>
+#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 std::shared_ptr<GetPrivateStorageRequest<PAYLOAD_TYPE> > ref;
+
+ static ref create(IQRouter* router) {
+ return ref(new GetPrivateStorageRequest(router));
+ }
+
+ private:
+ GetPrivateStorageRequest(IQRouter* router) : Request(IQ::Get, JID(), std::make_shared<PrivateStorage>(std::make_shared<PAYLOAD_TYPE>()), router) {
+ }
+
+ virtual void handleResponse(std::shared_ptr<Payload> payload, ErrorPayload::ref error) {
+ std::shared_ptr<PrivateStorage> storage = std::dynamic_pointer_cast<PrivateStorage>(payload);
+ if (storage) {
+ onResponse(std::dynamic_pointer_cast<PAYLOAD_TYPE>(storage->getPayload()), error);
+ }
+ else {
+ onResponse(std::shared_ptr<PAYLOAD_TYPE>(), error);
+ }
+ }
+
+ public:
+ boost::signals2::signal<void (std::shared_ptr<PAYLOAD_TYPE>, ErrorPayload::ref)> onResponse;
+ };
}
diff --git a/Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h b/Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h
index 7a76fcc..0a3502f 100644
--- a/Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h
+++ b/Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h
@@ -1,33 +1,32 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/SecurityLabelsCatalog.h>
-
+#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 std::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(), std::make_shared<SecurityLabelsCatalog>(recipient), router) {
+ }
+ };
}
diff --git a/Swiften/Queries/Requests/GetSoftwareVersionRequest.h b/Swiften/Queries/Requests/GetSoftwareVersionRequest.h
index 1084a0b..5660dd8 100644
--- a/Swiften/Queries/Requests/GetSoftwareVersionRequest.h
+++ b/Swiften/Queries/Requests/GetSoftwareVersionRequest.h
@@ -1,32 +1,32 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/SoftwareVersion.h>
-#include <boost/smart_ptr/make_shared.hpp>
-
+#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 std::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, std::make_shared<SoftwareVersion>(), router) {
+ }
+ };
}
diff --git a/Swiften/Queries/Requests/SetPrivateStorageRequest.h b/Swiften/Queries/Requests/SetPrivateStorageRequest.h
index 9ab65f7..f1dc77a 100644
--- a/Swiften/Queries/Requests/SetPrivateStorageRequest.h
+++ b/Swiften/Queries/Requests/SetPrivateStorageRequest.h
@@ -1,39 +1,39 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/Request.h>
-#include <Swiften/Elements/PrivateStorage.h>
#include <Swiften/Elements/ErrorPayload.h>
+#include <Swiften/Elements/PrivateStorage.h>
+#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 std::shared_ptr<SetPrivateStorageRequest<PAYLOAD_TYPE> > ref;
+
+ static ref create(std::shared_ptr<PAYLOAD_TYPE> payload, IQRouter* router) {
+ return ref(new SetPrivateStorageRequest<PAYLOAD_TYPE>(payload, router));
+ }
+
+ private:
+ SetPrivateStorageRequest(std::shared_ptr<PAYLOAD_TYPE> payload, IQRouter* router) : Request(IQ::Set, JID(), std::make_shared<PrivateStorage>(payload), router) {
+ }
+
+ virtual void handleResponse(std::shared_ptr<Payload>, ErrorPayload::ref error) {
+ onResponse(error);
+ }
+
+ public:
+ boost::signals2::signal<void (ErrorPayload::ref)> onResponse;
+ };
}
diff --git a/Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.cpp b/Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.cpp
deleted file mode 100644
index d99ddca..0000000
--- a/Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.cpp
+++ /dev/null
@@ -1,7 +0,0 @@
-/*
- * Copyright (c) 2010 Isode Limited.
- * All rights reserved.
- * See the COPYING file for more information.
- */
-
-#include <Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.h>
diff --git a/Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.h b/Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.h
index e79562a..1cf28c5 100644
--- a/Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.h
+++ b/Swiften/Queries/Requests/SubmitInBandRegistrationFormRequest.h
@@ -1,37 +1,37 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/Request.h>
#include <Swiften/Elements/InBandRegistrationPayload.h>
-
+#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 std::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(std::shared_ptr<Payload> payload, ErrorPayload::ref error) {
+ onResponse(payload, error);
+ }
- public:
- boost::signal<void (boost::shared_ptr<Payload>, ErrorPayload::ref)> onResponse;
- };
+ public:
+ boost::signals2::signal<void (std::shared_ptr<Payload>, ErrorPayload::ref)> onResponse;
+ };
}
diff --git a/Swiften/Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp b/Swiften/Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp
index 5b0a704..8a4b9fc 100644
--- a/Swiften/Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp
+++ b/Swiften/Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp
@@ -1,109 +1,110 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/bind.hpp>
-#include <Swiften/Queries/Requests/GetPrivateStorageRequest.h>
-#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/Queries/DummyIQChannel.h>
#include <Swiften/Elements/Payload.h>
+#include <Swiften/Queries/DummyIQChannel.h>
+#include <Swiften/Queries/IQRouter.h>
+#include <Swiften/Queries/Requests/GetPrivateStorageRequest.h>
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 = std::unique_ptr<DummyIQChannel>(new DummyIQChannel());
+ router = std::unique_ptr<IQRouter>(new IQRouter(channel.get()));
+ }
+
+ void tearDown() {
+ router.reset();
+ }
+
+ void testSend() {
+ GetPrivateStorageRequest<MyPayload>::ref request = GetPrivateStorageRequest<MyPayload>::create(router.get());
+ 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());
+ std::shared_ptr<PrivateStorage> storage = channel->iqs_[0]->getPayload<PrivateStorage>();
+ CPPUNIT_ASSERT(storage);
+ std::shared_ptr<MyPayload> payload = std::dynamic_pointer_cast<MyPayload>(storage->getPayload());
+ CPPUNIT_ASSERT(payload);
+ }
+
+ void testHandleResponse() {
+ GetPrivateStorageRequest<MyPayload>::ref testling = GetPrivateStorageRequest<MyPayload>::create(router.get());
+ 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"), std::dynamic_pointer_cast<MyPayload>(responses[0])->text);
+ }
+
+ void testHandleResponse_Error() {
+ GetPrivateStorageRequest<MyPayload>::ref testling = GetPrivateStorageRequest<MyPayload>::create(router.get());
+ 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(std::shared_ptr<Payload> p, ErrorPayload::ref e) {
+ if (e) {
+ errors.push_back(*e);
+ }
+ else {
+ responses.push_back(p);
+ }
+ }
+
+ std::shared_ptr<IQ> createResponse(const std::string& id, const std::string& text) {
+ std::shared_ptr<IQ> iq(new IQ(IQ::Result));
+ std::shared_ptr<PrivateStorage> storage(new PrivateStorage());
+ storage->setPayload(std::make_shared<MyPayload>(text));
+ iq->addPayload(storage);
+ iq->setID(id);
+ return iq;
+ }
+
+ std::shared_ptr<IQ> createError(const std::string& id) {
+ std::shared_ptr<IQ> iq(new IQ(IQ::Error));
+ iq->setID(id);
+ return iq;
+ }
+
+ private:
+ std::unique_ptr<IQRouter> router;
+ std::unique_ptr<DummyIQChannel> channel;
+ std::vector< ErrorPayload > errors;
+ std::vector< std::shared_ptr<Payload> > responses;
};
CPPUNIT_TEST_SUITE_REGISTRATION(GetPrivateStorageRequestTest);
diff --git a/Swiften/Queries/Responder.h b/Swiften/Queries/Responder.h
index 8a201e6..0974adf 100644
--- a/Swiften/Queries/Responder.h
+++ b/Swiften/Queries/Responder.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,130 +7,130 @@
#pragma once
#include <Swiften/Base/API.h>
+#include <Swiften/Elements/ErrorPayload.h>
#include <Swiften/Queries/IQHandler.h>
#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/Elements/ErrorPayload.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, std::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, std::shared_ptr<PAYLOAD_TYPE> payload) = 0;
+
+ /**
+ * Convenience function for sending an IQ response.
+ */
+ void sendResponse(const JID& to, const std::string& id, std::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, std::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(std::shared_ptr<IQ> iq) {
+ if (iq->getType() == IQ::Set || iq->getType() == IQ::Get) {
+ std::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 6c10a2b..5071f6e 100644
--- a/Swiften/Queries/Responders/SoftwareVersionResponder.cpp
+++ b/Swiften/Queries/Responders/SoftwareVersionResponder.cpp
@@ -1,12 +1,13 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
-
#include <Swiften/Queries/Responders/SoftwareVersionResponder.h>
+
+#include <memory>
+
#include <Swiften/Queries/IQRouter.h>
namespace Swift {
@@ -15,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;
+bool SoftwareVersionResponder::handleGetRequest(const JID& from, const JID&, const std::string& id, std::shared_ptr<SoftwareVersion>) {
+ sendResponse(from, id, std::make_shared<SoftwareVersion>(client, version, os));
+ return true;
}
}
diff --git a/Swiften/Queries/Responders/SoftwareVersionResponder.h b/Swiften/Queries/Responders/SoftwareVersionResponder.h
index 4418333..4bb3425 100644
--- a/Swiften/Queries/Responders/SoftwareVersionResponder.h
+++ b/Swiften/Queries/Responders/SoftwareVersionResponder.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,24 +7,24 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/GetResponder.h>
#include <Swiften/Elements/SoftwareVersion.h>
+#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, std::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..e2842f4 100644
--- a/Swiften/Queries/SetResponder.h
+++ b/Swiften/Queries/SetResponder.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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&, std::shared_ptr<T>) { return false; }
+ };
}
diff --git a/Swiften/Queries/UnitTest/IQRouterTest.cpp b/Swiften/Queries/UnitTest/IQRouterTest.cpp
index 660e632..0acb87b 100644
--- a/Swiften/Queries/UnitTest/IQRouterTest.cpp
+++ b/Swiften/Queries/UnitTest/IQRouterTest.cpp
@@ -1,177 +1,178 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <boost/bind.hpp>
+#include <Swiften/Queries/DummyIQChannel.h>
#include <Swiften/Queries/IQHandler.h>
#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/Queries/DummyIQChannel.h>
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(std::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(std::make_shared<IQ>());
+ testling.removeHandler(&handler1);
+ channel_->onIQReceived(std::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(std::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(std::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(std::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(std::make_shared<IQ>());
+ channel_->onIQReceived(std::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(std::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(std::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(std::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(std::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(std::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 46532f5..b46f1d4 100644
--- a/Swiften/Queries/UnitTest/RequestTest.cpp
+++ b/Swiften/Queries/UnitTest/RequestTest.cpp
@@ -1,366 +1,367 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Queries/GenericRequest.h>
-#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/Queries/DummyIQChannel.h>
#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/RawXMLPayload.h>
+#include <Swiften/Queries/DummyIQChannel.h>
+#include <Swiften/Queries/GenericRequest.h>
+#include <Swiften/Queries/IQRouter.h>
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,
+ std::shared_ptr<Payload> payload,
+ IQRouter* router) :
+ Request(type, receiver, payload, router) {
+ }
+
+ virtual void handleResponse(std::shared_ptr<Payload> payload, ErrorPayload::ref error) {
+ onResponse(payload, error);
+ }
+
+ public:
+ boost::signals2::signal<void (std::shared_ptr<Payload>, ErrorPayload::ref)> onResponse;
+ };
+
+ public:
+ void setUp() {
+ channel_ = new DummyIQChannel();
+ router_ = new IQRouter(channel_);
+ payload_ = std::make_shared<MyPayload>("foo");
+ responsePayload_ = std::make_shared<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();
+
+ std::shared_ptr<IQ> error = createError(JID("foo@bar.com/baz"),"test-id");
+ std::shared_ptr<Payload> errorPayload = std::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_ = std::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_ = std::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_ = std::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();
+
+ std::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();
+
+ std::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(std::shared_ptr<Payload> p, ErrorPayload::ref e) {
+ if (e) {
+ receivedErrors.push_back(*e);
+ }
+ else {
+ std::shared_ptr<MyPayload> payload(std::dynamic_pointer_cast<MyPayload>(p));
+ CPPUNIT_ASSERT(payload);
+ CPPUNIT_ASSERT_EQUAL(std::string("bar"), payload->text_);
+ ++responsesReceived_;
+ }
+ }
+
+ void handleDifferentResponse(std::shared_ptr<Payload> p, ErrorPayload::ref e) {
+ CPPUNIT_ASSERT(!e);
+ CPPUNIT_ASSERT(!p);
+ ++responsesReceived_;
+ }
+
+ void handleRawXMLResponse(std::shared_ptr<Payload> p, ErrorPayload::ref e) {
+ CPPUNIT_ASSERT(!e);
+ CPPUNIT_ASSERT(p);
+ CPPUNIT_ASSERT(std::dynamic_pointer_cast<MyOtherPayload>(p));
+ ++responsesReceived_;
+ }
+
+ std::shared_ptr<IQ> createResponse(const JID& from, const std::string& id) {
+ std::shared_ptr<IQ> iq(new IQ(IQ::Result));
+ iq->setFrom(from);
+ iq->addPayload(responsePayload_);
+ iq->setID(id);
+ return iq;
+ }
+
+ std::shared_ptr<IQ> createError(const JID& from, const std::string& id) {
+ std::shared_ptr<IQ> iq(new IQ(IQ::Error));
+ iq->setFrom(from);
+ iq->setID(id);
+ return iq;
+ }
+
+ private:
+ IQRouter* router_;
+ DummyIQChannel* channel_;
+ std::shared_ptr<Payload> payload_;
+ std::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 4664eb9..94bfed1 100644
--- a/Swiften/Queries/UnitTest/ResponderTest.cpp
+++ b/Swiften/Queries/UnitTest/ResponderTest.cpp
@@ -1,157 +1,157 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <boost/bind.hpp>
-#include <Swiften/Queries/Responder.h>
-#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/Queries/DummyIQChannel.h>
#include <Swiften/Elements/SoftwareVersion.h>
+#include <Swiften/Queries/DummyIQChannel.h>
+#include <Swiften/Queries/IQRouter.h>
+#include <Swiften/Queries/Responder.h>
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_ = std::unique_ptr<DummyIQChannel>(new DummyIQChannel());
+ router_ = std::unique_ptr<IQRouter>(new IQRouter(channel_.get()));
+ payload_ = std::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() {
+ router_.reset();
+ }
+
+ void testConstructor() {
+ MyResponder testling(router_.get());
+
+ channel_->onIQReceived(createRequest(IQ::Set));
+
+ CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
+ }
+
+ void testStart() {
+ MyResponder testling(router_.get());
+
+ testling.start();
+ channel_->onIQReceived(createRequest(IQ::Set));
+
+ CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling.setPayloads_.size()));
+ }
+
+ void testStop() {
+ MyResponder testling(router_.get());
+
+ 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_.get());
+
+ 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_.get());
+
+ 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_.get());
+
+ 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_.get());
+
+ 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_.get());
+
+ CPPUNIT_ASSERT(!dynamic_cast<IQHandler*>(&testling)->handleIQ(std::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:
+ std::shared_ptr<IQ> createRequest(IQ::Type type) {
+ std::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, std::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, std::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<std::shared_ptr<SoftwareVersion> > getPayloads_;
+ std::vector<std::shared_ptr<SoftwareVersion> > setPayloads_;
+ };
- private:
- IQRouter* router_;
- DummyIQChannel* channel_;
- boost::shared_ptr<SoftwareVersion> payload_;
+ private:
+ std::unique_ptr<IQRouter> router_;
+ std::unique_ptr<DummyIQChannel> channel_;
+ std::shared_ptr<SoftwareVersion> payload_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ResponderTest);
diff --git a/Swiften/Roster/GetRosterRequest.h b/Swiften/Roster/GetRosterRequest.h
index 56ee2bb..1a0499f 100644
--- a/Swiften/Roster/GetRosterRequest.h
+++ b/Swiften/Roster/GetRosterRequest.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,28 +7,27 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/RosterPayload.h>
-
+#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 std::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(), std::make_shared<RosterPayload>(), router) {
+ }
+ };
}
diff --git a/Swiften/Roster/RosterMemoryStorage.cpp b/Swiften/Roster/RosterMemoryStorage.cpp
index abaac5e..1b72a85 100644
--- a/Swiften/Roster/RosterMemoryStorage.cpp
+++ b/Swiften/Roster/RosterMemoryStorage.cpp
@@ -1,23 +1,23 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Roster/RosterMemoryStorage.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
namespace Swift {
RosterMemoryStorage::RosterMemoryStorage() {
}
-void RosterMemoryStorage::setRoster(boost::shared_ptr<RosterPayload> r) {
- roster.reset();
- if (r) {
- roster = boost::make_shared<RosterPayload>(*r);
- }
+void RosterMemoryStorage::setRoster(std::shared_ptr<RosterPayload> r) {
+ roster.reset();
+ if (r) {
+ roster = std::make_shared<RosterPayload>(*r);
+ }
}
}
diff --git a/Swiften/Roster/RosterMemoryStorage.h b/Swiften/Roster/RosterMemoryStorage.h
index 9e1ca76..19e7802 100644
--- a/Swiften/Roster/RosterMemoryStorage.h
+++ b/Swiften/Roster/RosterMemoryStorage.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::shared_ptr<RosterPayload> getRoster() const {
+ return roster;
+ }
- virtual void setRoster(boost::shared_ptr<RosterPayload>);
+ virtual void setRoster(std::shared_ptr<RosterPayload>);
- private:
- boost::shared_ptr<RosterPayload> roster;
- };
+ private:
+ std::shared_ptr<RosterPayload> roster;
+ };
}
diff --git a/Swiften/Roster/RosterPushResponder.h b/Swiften/Roster/RosterPushResponder.h
index a54438b..00411df 100644
--- a/Swiften/Roster/RosterPushResponder.h
+++ b/Swiften/Roster/RosterPushResponder.h
@@ -1,34 +1,35 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/SetResponder.h>
#include <Swiften/Elements/RosterPayload.h>
+#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::signals2::signal<void (std::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, std::shared_ptr<RosterPayload> payload) {
+ if (getIQRouter()->isAccountJID(from)) {
+ onRosterReceived(payload);
+ sendResponse(from, id, std::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..1c1461d 100644
--- a/Swiften/Roster/RosterStorage.h
+++ b/Swiften/Roster/RosterStorage.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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 std::shared_ptr<RosterPayload> getRoster() const = 0;
+ virtual void setRoster(std::shared_ptr<RosterPayload>) = 0;
+ };
}
diff --git a/Swiften/Roster/SetRosterRequest.h b/Swiften/Roster/SetRosterRequest.h
index 95a9f65..0f71ab7 100644
--- a/Swiften/Roster/SetRosterRequest.h
+++ b/Swiften/Roster/SetRosterRequest.h
@@ -1,41 +1,41 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/Request.h>
#include <Swiften/Elements/RosterPayload.h>
-
+#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 std::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, std::shared_ptr<RosterPayload> payload, IQRouter* router) : Request(IQ::Set, to, std::shared_ptr<RosterPayload>(payload), router) {
+ }
- virtual void handleResponse(boost::shared_ptr<Payload> /*payload*/, ErrorPayload::ref error) {
- onResponse(error);
- }
+ virtual void handleResponse(std::shared_ptr<Payload> /*payload*/, ErrorPayload::ref error) {
+ onResponse(error);
+ }
- public:
- boost::signal<void (ErrorPayload::ref)> onResponse;
- };
+ public:
+ boost::signals2::signal<void (ErrorPayload::ref)> onResponse;
+ };
}
diff --git a/Swiften/Roster/UnitTest/XMPPRosterControllerTest.cpp b/Swiften/Roster/UnitTest/XMPPRosterControllerTest.cpp
index 21f197b..b646aba 100644
--- a/Swiften/Roster/UnitTest/XMPPRosterControllerTest.cpp
+++ b/Swiften/Roster/UnitTest/XMPPRosterControllerTest.cpp
@@ -1,360 +1,361 @@
/*
- * Copyright (c) 2010-2011 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Roster/UnitTest/XMPPRosterSignalHandler.h>
-#include <Swiften/Roster/XMPPRosterController.h>
+#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/RosterItemPayload.h>
#include <Swiften/Elements/RosterPayload.h>
-#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/Roster/XMPPRosterImpl.h>
#include <Swiften/Roster/RosterMemoryStorage.h>
+#include <Swiften/Roster/UnitTest/XMPPRosterSignalHandler.h>
+#include <Swiften/Roster/XMPPRosterController.h>
+#include <Swiften/Roster/XMPPRosterImpl.h>
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() {
+ std::shared_ptr<XMPPRosterController> testling(createController());
+
+ testling->requestRoster();
+ std::shared_ptr<RosterPayload> payload = std::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(), std::shared_ptr<RosterPayload>()));
+ }
+
+ void testAdd() {
+ XMPPRosterController controller(router_, xmppRoster_, rosterStorage_);
+
+ std::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() {
+ std::shared_ptr<XMPPRosterController> testling(createController());
+ testling->setUseVersioning(true);
+
+ testling->requestRoster();
+
+ std::shared_ptr<RosterPayload> roster = channel_->sentStanzas[0]->getPayload<RosterPayload>();
+ CPPUNIT_ASSERT(roster->getVersion());
+ CPPUNIT_ASSERT_EQUAL(std::string(""), *roster->getVersion());
+ }
+
+ void testGet_NoVersionInStorage() {
+ std::shared_ptr<XMPPRosterController> testling(createController());
+ testling->setUseVersioning(true);
+ rosterStorage_->setRoster(std::make_shared<RosterPayload>());
+
+ testling->requestRoster();
+
+ std::shared_ptr<RosterPayload> roster = channel_->sentStanzas[0]->getPayload<RosterPayload>();
+ CPPUNIT_ASSERT(roster->getVersion());
+ CPPUNIT_ASSERT_EQUAL(std::string(""), *roster->getVersion());
+ }
+
+ void testGet_VersionInStorage() {
+ std::shared_ptr<XMPPRosterController> testling(createController());
+ testling->setUseVersioning(true);
+ std::shared_ptr<RosterPayload> payload(new RosterPayload());
+ payload->setVersion("foover");
+ rosterStorage_->setRoster(payload);
+
+ testling->requestRoster();
+
+ std::shared_ptr<RosterPayload> roster = channel_->sentStanzas[0]->getPayload<RosterPayload>();
+ CPPUNIT_ASSERT(roster->getVersion());
+ CPPUNIT_ASSERT_EQUAL(std::string("foover"), *roster->getVersion());
+ }
+
+ void testGet_ServerDoesNotSupportVersion() {
+ std::shared_ptr<XMPPRosterController> testling(createController());
+ std::shared_ptr<RosterPayload> payload(new RosterPayload());
+ payload->setVersion("foover");
+ rosterStorage_->setRoster(payload);
+
+ testling->requestRoster();
+
+ std::shared_ptr<RosterPayload> roster = channel_->sentStanzas[0]->getPayload<RosterPayload>();
+ CPPUNIT_ASSERT(!roster->getVersion());
+ }
+
+ void testGet_ResponseWithoutNewVersion() {
+ std::shared_ptr<XMPPRosterController> testling(createController());
+ testling->setUseVersioning(true);
+ std::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(), std::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() {
+ std::shared_ptr<XMPPRosterController> testling(createController());
+ testling->setUseVersioning(true);
+ std::shared_ptr<RosterPayload> storedRoster(new RosterPayload());
+ storedRoster->setVersion("version10");
+ storedRoster->addItem(RosterItemPayload(jid1_, "Bob", RosterItemPayload::Both));
+ rosterStorage_->setRoster(storedRoster);
+ testling->requestRoster();
+
+ std::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() {
+ std::shared_ptr<XMPPRosterController> testling(createController());
+
+ std::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_);
+ std::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();
+
+ std::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_);
+ std::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();
+
+ std::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() {
+ std::shared_ptr<XMPPRosterController> testling(createController());
+ testling->setUseVersioning(true);
+ std::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(), std::shared_ptr<RosterPayload>()));
+
+ std::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_);
+ std::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();
+
+ std::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();
+
+ std::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();
+
+ std::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();
+
+ std::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();
+
+ std::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 2615db1..73e76d3 100644
--- a/Swiften/Roster/UnitTest/XMPPRosterImplTest.cpp
+++ b/Swiften/Roster/UnitTest/XMPPRosterImplTest.cpp
@@ -1,112 +1,108 @@
/*
- * Copyright (c) 2010-2011 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
+#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/bind.hpp>
#include <Swiften/Roster/UnitTest/XMPPRosterSignalHandler.h>
#include <Swiften/Roster/XMPPRosterImpl.h>
-
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();
-
- 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");
- }
+ CPPUNIT_TEST_SUITE(XMPPRosterImplTest);
+ CPPUNIT_TEST(testJIDAdded);
+ CPPUNIT_TEST(testJIDRemoved);
+ CPPUNIT_TEST(testJIDUpdated);
+ CPPUNIT_TEST_SUITE_END();
- void tearDown() {
- delete handler_;
- delete roster_;
- }
+ public:
+ void setUp() {
+ jid1_ = JID("a@b.c");
+ jid2_ = JID("b@c.d");
+ jid3_ = JID("c@d.e");
+ roster_ = std::unique_ptr<XMPPRosterImpl>(new XMPPRosterImpl());
+ handler_ = std::unique_ptr<XMPPRosterSignalHandler>(new XMPPRosterSignalHandler(roster_.get()));
+ groups1_.push_back("bobs");
+ groups1_.push_back("berts");
+ groups2_.push_back("ernies");
+ }
- 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:
+ std::unique_ptr<XMPPRosterImpl> roster_;
+ std::unique_ptr<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 76aa690..add34a0 100644
--- a/Swiften/Roster/UnitTest/XMPPRosterSignalHandler.cpp
+++ b/Swiften/Roster/UnitTest/XMPPRosterSignalHandler.cpp
@@ -1,28 +1,29 @@
/*
- * Copyright (c) 2010-2011 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Roster/UnitTest/XMPPRosterSignalHandler.h>
-#include <boost/bind.hpp>
#include <cassert>
+#include <boost/bind.hpp>
+
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 f55e749..0535578 100644
--- a/Swiften/Roster/UnitTest/XMPPRosterSignalHandler.h
+++ b/Swiften/Roster/UnitTest/XMPPRosterSignalHandler.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2011 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <vector>
#include <Swiften/Roster/XMPPRosterImpl.h>
@@ -15,50 +15,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 handleJIDAdded(const Swift::JID& jid) {
+ lastJID_ = jid;
+ lastEvent_ = Add;
+ eventCount++;
+ }
- void handleJIDRemoved(const Swift::JID& jid) {
- lastJID_ = jid;
- lastEvent_ = Remove;
- 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);
+ 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;
+ 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 d454516..ae2dbc7 100644
--- a/Swiften/Roster/XMPPRoster.h
+++ b/Swiften/Roster/XMPPRoster.h
@@ -1,97 +1,98 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/optional.hpp>
-#include <vector>
#include <set>
-#include <Swiften/Base/boost_bsignals.h>
-
#include <string>
+#include <vector>
+
+#include <boost/optional.hpp>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/RosterItemPayload.h>
+#include <Swiften/JID/JID.h>
#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::signals2::signal<void (const JID&)> onJIDAdded;
+
+ /**
+ * Emitted when the given JID is removed from the roster.
+ */
+ boost::signals2::signal<void (const JID&)> onJIDRemoved;
+
+ /**
+ * Emitted when the name or the groups of the roster item with the
+ * given JID changes.
+ */
+ boost::signals2::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::signals2::signal<void ()> onRosterCleared;
+
+ /**
+ * Emitted after the last contact of the initial roster request response
+ * was added.
+ */
+ boost::signals2::signal<void ()> onInitialRosterPopulated;
+ };
}
diff --git a/Swiften/Roster/XMPPRosterController.cpp b/Swiften/Roster/XMPPRosterController.cpp
index e958628..8ee9755 100644
--- a/Swiften/Roster/XMPPRosterController.cpp
+++ b/Swiften/Roster/XMPPRosterController.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,86 +7,85 @@
#include <Swiften/Roster/XMPPRosterController.h>
#include <boost/bind.hpp>
-#include <iostream>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Base/Log.h>
#include <Swiften/Elements/RosterItemPayload.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Roster/GetRosterRequest.h>
-#include <Swiften/Roster/XMPPRosterImpl.h>
#include <Swiften/Roster/RosterStorage.h>
+#include <Swiften/Roster/XMPPRosterImpl.h>
namespace Swift {
-
+
/**
* The controller does not gain ownership of these parameters.
*/
XMPPRosterController::XMPPRosterController(IQRouter* iqRouter, XMPPRosterImpl* xmppRoster, RosterStorage* rosterStorage) : iqRouter_(iqRouter), rosterPushResponder_(iqRouter), xmppRoster_(xmppRoster), rosterStorage_(rosterStorage), useVersioning(false) {
- rosterPushResponder_.onRosterReceived.connect(boost::bind(&XMPPRosterController::handleRosterReceived, this, _1, false, boost::shared_ptr<RosterPayload>()));
- rosterPushResponder_.start();
+ rosterPushResponder_.onRosterReceived.connect(boost::bind(&XMPPRosterController::handleRosterReceived, this, _1, false, std::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();
+ std::shared_ptr<RosterPayload> storedRoster = rosterStorage_->getRoster();
+ GetRosterRequest::ref rosterRequest;
+ if (useVersioning) {
+ std::string version = "";
+ if (storedRoster && storedRoster->getVersion()) {
+ version = *storedRoster->getVersion();
+ }
+ rosterRequest = GetRosterRequest::create(iqRouter_, version);
+ }
+ else {
+ rosterRequest = GetRosterRequest::create(iqRouter_);
+ }
+ rosterRequest->onResponse.connect(boost::bind(&XMPPRosterController::handleRosterReceived, this, _1, true, storedRoster));
+ rosterRequest->send();
}
-void XMPPRosterController::handleRosterReceived(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());
- }
+void XMPPRosterController::handleRosterReceived(std::shared_ptr<RosterPayload> rosterPayload, bool initial, std::shared_ptr<RosterPayload> previousRoster) {
+ if (rosterPayload) {
+ for (const auto& item : rosterPayload->getItems()) {
+ //Don't worry about the updated case, the XMPPRoster sorts that out.
+ if (item.getSubscription() == RosterItemPayload::Remove) {
+ xmppRoster_->removeContact(item.getJID());
+ } else {
+ xmppRoster_->addContact(item.getJID(), item.getName(), item.getGroups(), item.getSubscription());
+ }
+ }
+ }
+ else if (previousRoster) {
+ // The cached version hasn't changed; emit all items
+ for (const auto& item : previousRoster->getItems()) {
+ if (item.getSubscription() != RosterItemPayload::Remove) {
+ xmppRoster_->addContact(item.getJID(), item.getName(), item.getGroups(), item.getSubscription());
+ }
+ else {
+ SWIFT_LOG(error) << "Stored invalid roster item" << std::endl;
+ }
+ }
+ }
+ if (initial) {
+ xmppRoster_->onInitialRosterPopulated();
+ }
+ if (rosterPayload && rosterPayload->getVersion() && useVersioning) {
+ saveRoster(*rosterPayload->getVersion());
+ }
}
void XMPPRosterController::saveRoster(const std::string& version) {
- std::vector<XMPPRosterItem> items = xmppRoster_->getItems();
- 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();
+ std::shared_ptr<RosterPayload> roster(new RosterPayload());
+ roster->setVersion(version);
+ for (const auto& 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 90b1304..f952c60 100644
--- a/Swiften/Roster/XMPPRosterController.h
+++ b/Swiften/Roster/XMPPRosterController.h
@@ -1,47 +1,48 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <string>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
-#include <string>
#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/RosterPayload.h>
+#include <Swiften/JID/JID.h>
#include <Swiften/Roster/RosterPushResponder.h>
-#include <Swiften/Base/boost_bsignals.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(std::shared_ptr<RosterPayload> rosterPayload, bool initial, std::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..74f634f 100644
--- a/Swiften/Roster/XMPPRosterImpl.cpp
+++ b/Swiften/Roster/XMPPRosterImpl.cpp
@@ -1,13 +1,11 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Roster/XMPPRosterImpl.h>
-#include <Swiften/Base/foreach.h>
-
namespace Swift {
XMPPRosterImpl::XMPPRosterImpl() {
@@ -18,89 +16,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;
+ for (const auto& entry : entries_) {
+ result.push_back(entry.second);
+ }
+ return result;
}
boost::optional<XMPPRosterItem> XMPPRosterImpl::getItem(const JID& jid) const {
- std::map<JID, XMPPRosterItem>::const_iterator i = entries_.find(jid.toBare());
- if (i != entries_.end()) {
- return i->second;
- }
- else {
- return boost::optional<XMPPRosterItem>();
- }
+ std::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;
+ for (const auto& entry : entries_) {
+ std::vector<std::string> groups = entry.second.getGroups();
+ result.insert(groups.begin(), groups.end());
+ }
+ return result;
}
}
diff --git a/Swiften/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 3ea11ce..53b3781 100644
--- a/Swiften/Roster/XMPPRosterItem.h
+++ b/Swiften/Roster/XMPPRosterItem.h
@@ -1,54 +1,53 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-
-#include <vector>
#include <string>
+#include <vector>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Elements/RosterItemPayload.h>
+#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 6bc6675..b22a81d 100644
--- a/Swiften/SASL/ClientAuthenticator.h
+++ b/Swiften/SASL/ClientAuthenticator.h
@@ -1,54 +1,55 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/optional.hpp>
#include <string>
#include <vector>
+#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Base/SafeByteArray.h>
#include <Swiften/Base/ByteArray.h>
+#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 f27caec..a736a77 100644
--- a/Swiften/SASL/DIGESTMD5ClientAuthenticator.cpp
+++ b/Swiften/SASL/DIGESTMD5ClientAuthenticator.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,10 +8,10 @@
#include <cassert>
-#include <Swiften/StringCodecs/Hexify.h>
-#include <Swiften/Base/Concat.h>
#include <Swiften/Base/Algorithm.h>
+#include <Swiften/Base/Concat.h>
#include <Swiften/Crypto/CryptoProvider.h>
+#include <Swiften/StringCodecs/Hexify.h>
namespace Swift {
@@ -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 c94e53b..4a857d3 100644
--- a/Swiften/SASL/DIGESTMD5ClientAuthenticator.h
+++ b/Swiften/SASL/DIGESTMD5ClientAuthenticator.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,33 +7,33 @@
#pragma once
#include <map>
-
#include <string>
#include <vector>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/SafeByteArray.h>
#include <Swiften/SASL/ClientAuthenticator.h>
#include <Swiften/SASL/DIGESTMD5Properties.h>
-#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
- class CryptoProvider;
+ class CryptoProvider;
+
+ class SWIFTEN_API DIGESTMD5ClientAuthenticator : public ClientAuthenticator {
+ public:
+ DIGESTMD5ClientAuthenticator(const std::string& host, const std::string& nonce, 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> >&);
+ 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;
- };
+ 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 b47094f..1f33c8f 100644
--- a/Swiften/SASL/DIGESTMD5Properties.cpp
+++ b/Swiften/SASL/DIGESTMD5Properties.cpp
@@ -1,130 +1,131 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/SASL/DIGESTMD5Properties.h>
+
#include <Swiften/Base/Algorithm.h>
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 (unsigned char i : data) {
+ char c = static_cast<char>(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 d7be40b..a4d2d65 100644
--- a/Swiften/SASL/DIGESTMD5Properties.h
+++ b/Swiften/SASL/DIGESTMD5Properties.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,30 +7,31 @@
#pragma once
#include <map>
+#include <string>
+
#include <boost/optional.hpp>
-#include <string>
#include <Swiften/Base/API.h>
#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();
+
+ boost::optional<std::string> getValue(const std::string& key) const;
- void setValue(const std::string& key, const std::string& value);
+ void setValue(const std::string& key, const std::string& value);
- ByteArray serialize() const;
+ ByteArray serialize() const;
- static DIGESTMD5Properties parse(const ByteArray&);
+ static DIGESTMD5Properties parse(const ByteArray&);
- private:
- static bool isQuoted(const std::string& property);
+ private:
+ static bool isQuoted(const std::string& property);
- private:
- typedef std::multimap<std::string, ByteArray> DIGESTMD5PropertiesMap;
- DIGESTMD5PropertiesMap properties;
- };
+ 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 2b87ec3..e42e3fd 100644
--- a/Swiften/SASL/EXTERNALClientAuthenticator.h
+++ b/Swiften/SASL/EXTERNALClientAuthenticator.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,18 +7,18 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/SASL/ClientAuthenticator.h>
#include <Swiften/Base/ByteArray.h>
+#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 91727ea..11bd14c 100644
--- a/Swiften/SASL/PLAINClientAuthenticator.cpp
+++ b/Swiften/SASL/PLAINClientAuthenticator.cpp
@@ -1,10 +1,11 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/SASL/PLAINClientAuthenticator.h>
+
#include <Swiften/Base/Concat.h>
namespace Swift {
@@ -13,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 e04027b..64ef741 100644
--- a/Swiften/SASL/PLAINClientAuthenticator.h
+++ b/Swiften/SASL/PLAINClientAuthenticator.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,15 +7,15 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/SASL/ClientAuthenticator.h>
#include <Swiften/Base/ByteArray.h>
+#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 24644d5..a55f604 100644
--- a/Swiften/SASL/PLAINMessage.cpp
+++ b/Swiften/SASL/PLAINMessage.cpp
@@ -1,10 +1,11 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/SASL/PLAINMessage.h>
+
#include <Swiften/Base/Concat.h>
namespace Swift {
@@ -13,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 554e9f0..3c00402 100644
--- a/Swiften/SASL/SCRAMSHA1ClientAuthenticator.cpp
+++ b/Swiften/SASL/SCRAMSHA1ClientAuthenticator.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,30 +8,31 @@
#include <cassert>
#include <map>
+
#include <boost/lexical_cast.hpp>
+#include <Swiften/Base/Concat.h>
#include <Swiften/Crypto/CryptoProvider.h>
+#include <Swiften/IDN/IDNConverter.h>
#include <Swiften/StringCodecs/Base64.h>
#include <Swiften/StringCodecs/PBKDF2.h>
-#include <Swiften/IDN/IDNConverter.h>
-#include <Swiften/Base/Concat.h>
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 (char i : s) {
+ if (i == ',') {
+ result += "=2C";
+ }
+ else if (i == '=') {
+ result += "=3D";
+ }
+ else {
+ result += i;
+ }
+ }
+ return result;
}
@@ -39,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 b0cc098..5dc169a 100644
--- a/Swiften/SASL/SCRAMSHA1ClientAuthenticator.h
+++ b/Swiften/SASL/SCRAMSHA1ClientAuthenticator.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,48 +7,49 @@
#pragma once
#include <map>
+#include <string>
+
#include <boost/optional.hpp>
-#include <string>
+#include <Swiften/Base/API.h>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/SASL/ClientAuthenticator.h>
-#include <Swiften/Base/API.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/SConscript b/Swiften/SASL/SConscript
index 7e1fd07..6aa3e72 100644
--- a/Swiften/SASL/SConscript
+++ b/Swiften/SASL/SConscript
@@ -3,31 +3,31 @@ Import("swiften_env", "env")
myenv = swiften_env.Clone()
objects = myenv.SwiftenObject([
- "ClientAuthenticator.cpp",
- "EXTERNALClientAuthenticator.cpp",
- "PLAINClientAuthenticator.cpp",
- "PLAINMessage.cpp",
- "SCRAMSHA1ClientAuthenticator.cpp",
- "DIGESTMD5Properties.cpp",
- "DIGESTMD5ClientAuthenticator.cpp",
- ])
+ "ClientAuthenticator.cpp",
+ "EXTERNALClientAuthenticator.cpp",
+ "PLAINClientAuthenticator.cpp",
+ "PLAINMessage.cpp",
+ "SCRAMSHA1ClientAuthenticator.cpp",
+ "DIGESTMD5Properties.cpp",
+ "DIGESTMD5ClientAuthenticator.cpp",
+ ])
if myenv["PLATFORM"] == "win32" :
- objects += myenv.SwiftenObject([
- "WindowsServicePrincipalName.cpp",
- "WindowsAuthentication.cpp",
- "WindowsGSSAPIClientAuthenticator.cpp"
- ])
+ objects += myenv.SwiftenObject([
+ "WindowsServicePrincipalName.cpp",
+ "WindowsAuthentication.cpp",
+ "WindowsGSSAPIClientAuthenticator.cpp"
+ ])
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
env.Append(UNITTEST_SOURCES = [
- File("UnitTest/PLAINMessageTest.cpp"),
- File("UnitTest/PLAINClientAuthenticatorTest.cpp"),
- File("UnitTest/SCRAMSHA1ClientAuthenticatorTest.cpp"),
- File("UnitTest/DIGESTMD5PropertiesTest.cpp"),
- File("UnitTest/DIGESTMD5ClientAuthenticatorTest.cpp"),
- ])
+ File("UnitTest/PLAINMessageTest.cpp"),
+ File("UnitTest/PLAINClientAuthenticatorTest.cpp"),
+ File("UnitTest/SCRAMSHA1ClientAuthenticatorTest.cpp"),
+ File("UnitTest/DIGESTMD5PropertiesTest.cpp"),
+ File("UnitTest/DIGESTMD5ClientAuthenticatorTest.cpp"),
+ ])
if myenv["PLATFORM"] == "win32" :
- env.Append(UNITTEST_SOURCES = [
- File("UnitTest/WindowsServicePrincipalNameTest.cpp"),
- ])
+ env.Append(UNITTEST_SOURCES = [
+ File("UnitTest/WindowsServicePrincipalNameTest.cpp"),
+ ])
diff --git a/Swiften/SASL/UnitTest/DIGESTMD5ClientAuthenticatorTest.cpp b/Swiften/SASL/UnitTest/DIGESTMD5ClientAuthenticatorTest.cpp
index 2c29f07..d29af59 100644
--- a/Swiften/SASL/UnitTest/DIGESTMD5ClientAuthenticatorTest.cpp
+++ b/Swiften/SASL/UnitTest/DIGESTMD5ClientAuthenticatorTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,63 +9,62 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/SASL/DIGESTMD5ClientAuthenticator.h>
#include <Swiften/Base/ByteArray.h>
-
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/SASL/DIGESTMD5ClientAuthenticator.h>
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 = std::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:
+ std::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 f5fc5bd..070b4d9 100644
--- a/Swiften/SASL/UnitTest/PLAINClientAuthenticatorTest.cpp
+++ b/Swiften/SASL/UnitTest/PLAINClientAuthenticatorTest.cpp
@@ -1,39 +1,40 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/SASL/PLAINClientAuthenticator.h>
-
#include <QA/Checker/IO.h>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <Swiften/SASL/PLAINClientAuthenticator.h>
+
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 7b13a6d..271b827 100644
--- a/Swiften/SASL/UnitTest/PLAINMessageTest.cpp
+++ b/Swiften/SASL/UnitTest/PLAINMessageTest.cpp
@@ -1,70 +1,70 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/ByteArray.h>
#include <QA/Checker/IO.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/SASL/PLAINMessage.h>
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 f241c7e..7f408c6 100644
--- a/Swiften/SASL/UnitTest/SCRAMSHA1ClientAuthenticatorTest.cpp
+++ b/Swiften/SASL/UnitTest/SCRAMSHA1ClientAuthenticatorTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,225 +9,225 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/SASL/SCRAMSHA1ClientAuthenticator.h>
#include <Swiften/Base/ByteArray.h>
-#include <Swiften/IDN/IDNConverter.h>
-#include <Swiften/IDN/PlatformIDNConverter.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/IDN/IDNConverter.h>
+#include <Swiften/IDN/PlatformIDNConverter.h>
+#include <Swiften/SASL/SCRAMSHA1ClientAuthenticator.h>
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 = std::shared_ptr<IDNConverter>(PlatformIDNConverter::create());
+ crypto = std::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;
+ std::shared_ptr<IDNConverter> idnConverter;
+ std::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..b86381b 100644
--- a/Swiften/SASL/WindowsAuthentication.cpp
+++ b/Swiften/SASL/WindowsAuthentication.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 = std::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;
+std::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;
+ std::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;
+std::shared_ptr<boost::system::error_code> acquireCredentialsHandle(PCredHandle credentialsHandle) {
+ SECURITY_STATUS status;
+ std::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;
+std::shared_ptr<boost::system::error_code> freeCredentialsHandle(PCredHandle credentialsHandle) {
+ SECURITY_STATUS status;
+ std::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;
+std::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;
+ std::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 std::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;
+std::shared_ptr<boost::system::error_code> deleteSecurityContext(PCtxtHandle contextHandle) {
+ SECURITY_STATUS status;
+ std::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;
+std::shared_ptr<boost::system::error_code> completeAuthToken(const PCtxtHandle contextHandle, PSecBufferDesc token) {
+ SECURITY_STATUS status;
+ std::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;
+std::shared_ptr<boost::system::error_code> freeContextBuffer(PVOID contextBuffer) {
+ SECURITY_STATUS status;
+ std::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;
+std::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;
+ std::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;
+std::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;
+ std::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;
+std::shared_ptr<boost::system::error_code> queryContextAttributes(const PCtxtHandle contextHandle, ULONG attribute, PVOID buffer) {
+ SECURITY_STATUS status;
+ std::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..311c4c1 100644
--- a/Swiften/SASL/WindowsAuthentication.h
+++ b/Swiften/SASL/WindowsAuthentication.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,158 +13,158 @@
#include <Sspi.h>
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
#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 std::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 std::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 std::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 std::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 std::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 std::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 std::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 std::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 std::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 std::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 f602bff..aae437f 100644
--- a/Swiften/SASL/WindowsGSSAPIClientAuthenticator.cpp
+++ b/Swiften/SASL/WindowsGSSAPIClientAuthenticator.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(NULL);
+ 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..72616ed 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.
+ */
+ std::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_;
+ std::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/SConscript b/Swiften/SConscript
index e017376..a8fb88a 100644
--- a/Swiften/SConscript
+++ b/Swiften/SConscript
@@ -10,594 +10,595 @@ swiften_dep_modules = ["BOOST", "GCONF", "ICU", "LIBIDN", "ZLIB", "LDNS", "UNBOU
external_swiften_dep_modules = ["BOOST"]
if env["SCONS_STAGE"] == "flags" :
- env["SWIFTEN_DLL"] = env["swiften_dll"]
- env["SWIFTEN_VERSION"] = Version.getBuildVersion(env.Dir("#").abspath, "swift")
- version_match = re.match("(\d+)\.(\d+).*", env["SWIFTEN_VERSION"])
- if version_match :
- env["SWIFTEN_VERSION_MAJOR"] = int(version_match.group(1))
- env["SWIFTEN_VERSION_MINOR"] = int(version_match.group(2))
- else :
- env["SWIFTEN_VERSION_MAJOR"] = 0
- env["SWIFTEN_VERSION_MINOR"] = 0
- env["SWIFTEN_VERSION_PATCH"] = 0
- env["SWIFTEN_LIBRARY"] = "Swiften"
- env["SWIFTEN_LIBRARY_FILE"] = "Swiften"
- env["SWIFTEN_LIBRARY_ALIASES"] = []
-
- if env["SWIFTEN_DLL"] :
- if env["PLATFORM"] == "win32" :
- env["SWIFTEN_LIBRARY"] = env.subst("Swiften${SWIFTEN_VERSION_MAJOR}")
- env["SWIFTEN_LIBRARY_FILE"] = env.subst("${SWIFTEN_LIBRARY}.dll")
- elif env["PLATFORM"] == "darwin" :
- env["SWIFTEN_LIBRARY_FILE"] = env.subst("Swiften.${SWIFTEN_VERSION_MAJOR}.${SWIFTEN_VERSION_MINOR}")
- env["SWIFTEN_LIBRARY_ALIASES"] = ["libSwiften.dylib", env.subst("libSwiften.${SWIFTEN_VERSION_MAJOR}.dylib")]
- else :
- env["SWIFTEN_LIBRARY_FILE"] = env.subst("libSwiften.so.${SWIFTEN_VERSION_MAJOR}.${SWIFTEN_VERSION_MINOR}")
- env["SWIFTEN_LIBRARY_ALIASES"] = ["libSwiften.so", env.subst("libSwiften.so.${SWIFTEN_VERSION_MAJOR}")]
+ env["SWIFTEN_DLL"] = env["swiften_dll"]
+ env["SWIFTEN_VERSION"] = Version.getBuildVersion(env.Dir("#").abspath, "swift")
+ version_match = re.match("(\d+)\.(\d+).*", env["SWIFTEN_VERSION"])
+ if version_match :
+ env["SWIFTEN_VERSION_MAJOR"] = int(version_match.group(1))
+ env["SWIFTEN_VERSION_MINOR"] = int(version_match.group(2))
+ else :
+ env["SWIFTEN_VERSION_MAJOR"] = 0
+ env["SWIFTEN_VERSION_MINOR"] = 0
+ env["SWIFTEN_VERSION_PATCH"] = 0
+ env["SWIFTEN_LIBRARY"] = "Swiften"
+ env["SWIFTEN_LIBRARY_FILE"] = "Swiften"
+ env["SWIFTEN_LIBRARY_ALIASES"] = []
+
+ if env["SWIFTEN_DLL"] :
+ if env["PLATFORM"] == "win32" :
+ env["SWIFTEN_LIBRARY"] = env.subst("Swiften${SWIFTEN_VERSION_MAJOR}")
+ env["SWIFTEN_LIBRARY_FILE"] = env.subst("${SWIFTEN_LIBRARY}.dll")
+ elif env["PLATFORM"] == "darwin" :
+ env["SWIFTEN_LIBRARY_FILE"] = env.subst("Swiften.${SWIFTEN_VERSION_MAJOR}.${SWIFTEN_VERSION_MINOR}")
+ env["SWIFTEN_LIBRARY_ALIASES"] = ["libSwiften.dylib", env.subst("libSwiften.${SWIFTEN_VERSION_MAJOR}.dylib")]
+ else :
+ env["SWIFTEN_LIBRARY_FILE"] = env.subst("libSwiften.so.${SWIFTEN_VERSION_MAJOR}.${SWIFTEN_VERSION_MINOR}")
+ env["SWIFTEN_LIBRARY_ALIASES"] = ["libSwiften.so", env.subst("libSwiften.so.${SWIFTEN_VERSION_MAJOR}")]
- if env["SWIFTEN_DLL"] :
- env.AddMethod(lambda e,s : e.SharedObject(s), "SwiftenObject")
- else :
- env.AddMethod(lambda e,s : e.StaticObject(s), "SwiftenObject")
+ if env["SWIFTEN_DLL"] :
+ env.AddMethod(lambda e,s : e.SharedObject(s), "SwiftenObject")
+ else :
+ env.AddMethod(lambda e,s : e.StaticObject(s), "SwiftenObject")
- swiften_env = env.Clone()
- swiften_env["LIBPATH"] = [Dir(".")]
- swiften_env["LIBRUNPATH"] = [Dir(".")]
- swiften_env["LIBS"] = [swiften_env["SWIFTEN_LIBRARY"]]
- if not env["SWIFTEN_DLL"] :
- swiften_env.Append(CPPDEFINES = ["SWIFTEN_STATIC"])
- dep_env = env.Clone()
- for module in swiften_dep_modules :
- module_flags = env.get(module + "_FLAGS", {})
- if env.get(module + "_BUNDLED", False) :
- if module in external_swiften_dep_modules :
- swiften_env.UseFlags(module_flags)
- else :
- if module in external_swiften_dep_modules :
- dep_env.UseFlags(module_flags)
- else :
- # Expose only libraries
- dep_env.Append(LIBPATH = module_flags.get("LIBPATH", []))
- dep_env.Append(LIBS = module_flags.get("LIBS", []))
- dep_env.Append(FRAMEWORKS = module_flags.get("FRAMEWORKS", []))
- dep_env.UseFlags(dep_env["PLATFORM_FLAGS"])
+ swiften_env = env.Clone()
+ swiften_env["LIBPATH"] = [Dir(".")]
+ swiften_env["LIBRUNPATH"] = [Dir(".")]
+ swiften_env["LIBS"] = [swiften_env["SWIFTEN_LIBRARY"]]
+ if not env["SWIFTEN_DLL"] :
+ swiften_env.Append(CPPDEFINES = ["SWIFTEN_STATIC"])
+ dep_env = env.Clone()
+ for module in swiften_dep_modules :
+ module_flags = env.get(module + "_FLAGS", {})
+ if env.get(module + "_BUNDLED", False) :
+ if module in external_swiften_dep_modules :
+ swiften_env.UseFlags(module_flags)
+ else :
+ if module in external_swiften_dep_modules :
+ dep_env.UseFlags(module_flags)
+ else :
+ # Expose only libraries
+ dep_env.Append(LIBPATH = module_flags.get("LIBPATH", []))
+ dep_env.Append(LIBS = module_flags.get("LIBS", []))
+ dep_env.Append(FRAMEWORKS = module_flags.get("FRAMEWORKS", []))
+ dep_env.UseFlags(dep_env["PLATFORM_FLAGS"])
- if env.get("HAVE_SCHANNEL", 0) :
- dep_env.Append(LIBS = ["Winscard"])
+ if env.get("HAVE_SCHANNEL", 0) :
+ dep_env.Append(LIBS = ["Winscard"])
- for var, e in [("SWIFTEN_FLAGS", swiften_env), ("SWIFTEN_DEP_FLAGS", dep_env)] :
- env[var] = {
- "CPPDEFINES": e.get("CPPDEFINES", []),
- "CPPPATH": e.get("CPPPATH", []),
- "CPPFLAGS": e.get("CPPFLAGS", []),
- "LIBPATH": e.get("LIBPATH", []),
- "LIBRUNPATH": e.get("LIBRUNPATH", []),
- "LIBS": e.get("LIBS", []),
- "FRAMEWORKS": e.get("FRAMEWORKS", []),
- }
+ for var, e in [("SWIFTEN_FLAGS", swiften_env), ("SWIFTEN_DEP_FLAGS", dep_env)] :
+ env[var] = {
+ "CPPDEFINES": e.get("CPPDEFINES", []),
+ "CPPPATH": e.get("CPPPATH", []),
+ "CPPFLAGS": e.get("CPPFLAGS", []),
+ "LIBPATH": e.get("LIBPATH", []),
+ "LIBRUNPATH": e.get("LIBRUNPATH", []),
+ "LIBS": e.get("LIBS", []),
+ "FRAMEWORKS": e.get("FRAMEWORKS", []),
+ }
- if env["PLATFORM"] == "win32" :
- # 0x0600 = _WIN32_WINNT_VISTA, 0x06000000 = NTDDI_VISTA
- env.Append(CPPDEFINES = [("_WIN32_WINNT","0x0600") , ("NTDDI_VERSION","0x06000000")])
+ if env["PLATFORM"] == "win32" :
+ # 0x0600 = _WIN32_WINNT_VISTA, 0x06000000 = NTDDI_VISTA
+ env.Append(CPPDEFINES = [("_WIN32_WINNT","0x0600") , ("NTDDI_VERSION","0x06000000")])
################################################################################
# Build
################################################################################
if env["SCONS_STAGE"] == "build" :
- swiften_env = env.Clone()
- swiften_env.Append(CPPDEFINES = ["SWIFTEN_BUILDING"])
- for module in swiften_dep_modules :
- swiften_env.UseFlags(swiften_env.get(module + "_FLAGS", {}))
- if env.get(module + "_BUNDLED", False) :
- swiften_env.Append(SWIFTEN_OBJECTS = env.get(module + "_OBJECTS", []))
- swiften_env.UseFlags(swiften_env["PLATFORM_FLAGS"])
-
- if swiften_env["SWIFTEN_DLL"] :
- swiften_env.AddMethod(lambda e,l,o : e.SharedLibrary(l,o), "SwiftenLibrary")
- else :
- swiften_env.Append(CPPDEFINES = ["SWIFTEN_STATIC"])
- swiften_env.AddMethod(lambda e,l,o : e.StaticLibrary(l,o), "SwiftenLibrary")
- Export("swiften_env")
+ swiften_env = env.Clone()
+ swiften_env.Append(CPPDEFINES = ["SWIFTEN_BUILDING"])
+ for module in swiften_dep_modules :
+ swiften_env.UseFlags(swiften_env.get(module + "_FLAGS", {}))
+ if env.get(module + "_BUNDLED", False) :
+ swiften_env.Append(SWIFTEN_OBJECTS = env.get(module + "_OBJECTS", []))
+ swiften_env.UseFlags(swiften_env["PLATFORM_FLAGS"])
+
+ if swiften_env["SWIFTEN_DLL"] :
+ swiften_env.AddMethod(lambda e,l,o : e.SharedLibrary(l,o), "SwiftenLibrary")
+ else :
+ swiften_env.Append(CPPDEFINES = ["SWIFTEN_STATIC"])
+ swiften_env.AddMethod(lambda e,l,o : e.StaticLibrary(l,o), "SwiftenLibrary")
+ Export("swiften_env")
# TODO: Move all this to a submodule SConscript
- sources = [
- "Base/Debug.cpp",
- "Chat/ChatStateTracker.cpp",
- "Chat/ChatStateNotifier.cpp",
- "Client/ClientSessionStanzaChannel.cpp",
- "Client/CoreClient.cpp",
- "Client/Client.cpp",
- "Client/ClientXMLTracer.cpp",
- "Client/ClientSession.cpp",
- "Client/BlockList.cpp",
- "Client/BlockListImpl.cpp",
- "Client/ClientBlockListManager.cpp",
- "Client/MemoryStorages.cpp",
- "Client/NickResolver.cpp",
- "Client/NickManager.cpp",
- "Client/NickManagerImpl.cpp",
- "Client/Storages.cpp",
- "Client/XMLBeautifier.cpp",
- "Compress/ZLibCodecompressor.cpp",
- "Compress/ZLibDecompressor.cpp",
- "Compress/ZLibCompressor.cpp",
- "Elements/CarbonsEnable.cpp",
- "Elements/CarbonsDisable.cpp",
- "Elements/CarbonsPrivate.cpp",
- "Elements/CarbonsReceived.cpp",
- "Elements/CarbonsSent.cpp",
- "Elements/DiscoInfo.cpp",
- "Elements/Presence.cpp",
- "Elements/Form.cpp",
- "Elements/FormField.cpp",
- "Elements/FormPage.cpp",
- "Elements/FormSection.cpp",
- "Elements/FormText.cpp",
- "Elements/StreamFeatures.cpp",
- "Elements/Element.cpp",
- "Elements/ToplevelElement.cpp",
- "Elements/IQ.cpp",
- "Elements/Payload.cpp",
- "Elements/PubSubPayload.cpp",
- "Elements/PubSubOwnerPayload.cpp",
- "Elements/PubSubEventPayload.cpp",
- "Elements/RosterItemExchangePayload.cpp",
- "Elements/RosterPayload.cpp",
- "Elements/SecurityLabel.cpp",
- "Elements/Stanza.cpp",
- "Elements/StanzaAck.cpp",
- "Elements/StatusShow.cpp",
- "Elements/StreamManagementEnabled.cpp",
- "Elements/StreamResume.cpp",
- "Elements/StreamResumed.cpp",
- "Elements/UserLocation.cpp",
- "Elements/UserTune.cpp",
- "Elements/VCard.cpp",
- "Elements/MUCOccupant.cpp",
- "Elements/ResultSet.cpp",
- "Elements/Forwarded.cpp",
- "Elements/MAMResult.cpp",
- "Elements/MAMQuery.cpp",
- "Elements/MAMFin.cpp",
- "Elements/Thread.cpp",
- "Elements/IsodeIQDelegation.cpp",
- "Entity/Entity.cpp",
- "Entity/PayloadPersister.cpp",
- "MUC/MUC.cpp",
- "MUC/MUCImpl.cpp",
- "MUC/MUCManager.cpp",
- "MUC/MUCRegistry.cpp",
- "MUC/MUCBookmarkManager.cpp",
- "PubSub/PubSubManager.cpp",
- "PubSub/PubSubManagerImpl.cpp",
- "Queries/IQChannel.cpp",
- "Queries/IQHandler.cpp",
- "Queries/IQRouter.cpp",
- "Queries/Request.cpp",
- "Queries/Requests/GetInBandRegistrationFormRequest.cpp",
- "Queries/Requests/SubmitInBandRegistrationFormRequest.cpp",
- "Queries/Responders/SoftwareVersionResponder.cpp",
- "Roster/RosterStorage.cpp",
- "Roster/RosterMemoryStorage.cpp",
- "Roster/XMPPRoster.cpp",
- "Roster/XMPPRosterImpl.cpp",
- "Roster/XMPPRosterController.cpp",
- "Serializer/AuthRequestSerializer.cpp",
- "Serializer/AuthSuccessSerializer.cpp",
- "Serializer/AuthChallengeSerializer.cpp",
- "Serializer/AuthResponseSerializer.cpp",
- "Serializer/CompressRequestSerializer.cpp",
- "Serializer/ElementSerializer.cpp",
- "Serializer/MessageSerializer.cpp",
- "Serializer/StreamManagementEnabledSerializer.cpp",
- "Serializer/StreamResumeSerializer.cpp",
- "Serializer/StreamResumedSerializer.cpp",
- "Serializer/ComponentHandshakeSerializer.cpp",
- "Serializer/PayloadSerializer.cpp",
- "Serializer/PayloadSerializerCollection.cpp",
- "Serializer/PayloadSerializers/IBBSerializer.cpp",
- "Serializer/PayloadSerializers/CapsInfoSerializer.cpp",
- "Serializer/PayloadSerializers/CarbonsDisableSerializer.cpp",
- "Serializer/PayloadSerializers/CarbonsEnableSerializer.cpp",
- "Serializer/PayloadSerializers/CarbonsPrivateSerializer.cpp",
- "Serializer/PayloadSerializers/CarbonsSentSerializer.cpp",
- "Serializer/PayloadSerializers/CarbonsReceivedSerializer.cpp",
- "Serializer/PayloadSerializers/ChatStateSerializer.cpp",
- "Serializer/PayloadSerializers/DiscoInfoSerializer.cpp",
- "Serializer/PayloadSerializers/DiscoItemsSerializer.cpp",
- "Serializer/PayloadSerializers/ErrorSerializer.cpp",
- "Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp",
- "Serializer/PayloadSerializers/MUCPayloadSerializer.cpp",
- "Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp",
- "Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp",
- "Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp",
- "Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp",
- "Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp",
- "Serializer/PayloadSerializers/ResourceBindSerializer.cpp",
- "Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp",
- "Serializer/PayloadSerializers/RosterSerializer.cpp",
- "Serializer/PayloadSerializers/SecurityLabelSerializer.cpp",
- "Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp",
- "Serializer/PayloadSerializers/SoftwareVersionSerializer.cpp",
- "Serializer/PayloadSerializers/StreamInitiationSerializer.cpp",
- "Serializer/PayloadSerializers/BytestreamsSerializer.cpp",
- "Serializer/PayloadSerializers/VCardSerializer.cpp",
- "Serializer/PayloadSerializers/VCardUpdateSerializer.cpp",
- "Serializer/PayloadSerializers/StorageSerializer.cpp",
- "Serializer/PayloadSerializers/PrivateStorageSerializer.cpp",
- "Serializer/PayloadSerializers/DelaySerializer.cpp",
- "Serializer/PayloadSerializers/CommandSerializer.cpp",
- "Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp",
- "Serializer/PayloadSerializers/SearchPayloadSerializer.cpp",
- "Serializer/PayloadSerializers/FormSerializer.cpp",
- "Serializer/PayloadSerializers/NicknameSerializer.cpp",
- "Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp",
- "Serializer/PayloadSerializers/JinglePayloadSerializer.cpp",
- "Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp",
- "Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp",
- "Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp",
- "Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp",
- "Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp",
- "Serializer/PayloadSerializers/DeliveryReceiptSerializer.cpp",
- "Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.cpp",
- "Serializer/PayloadSerializers/UserLocationSerializer.cpp",
- "Serializer/PayloadSerializers/UserTuneSerializer.cpp",
- "Serializer/PayloadSerializers/WhiteboardSerializer.cpp",
- "Serializer/PayloadSerializers/ResultSetSerializer.cpp",
- "Serializer/PayloadSerializers/ForwardedSerializer.cpp",
- "Serializer/PayloadSerializers/MAMFinSerializer.cpp",
- "Serializer/PayloadSerializers/MAMResultSerializer.cpp",
- "Serializer/PayloadSerializers/MAMQuerySerializer.cpp",
- "Serializer/PayloadSerializers/IsodeIQDelegationSerializer.cpp",
- "Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp",
- "Serializer/PayloadSerializers/ThreadSerializer.cpp",
- "Serializer/PresenceSerializer.cpp",
- "Serializer/StanzaSerializer.cpp",
- "Serializer/StreamErrorSerializer.cpp",
- "Serializer/StreamFeaturesSerializer.cpp",
- "Serializer/XML/XMLElement.cpp",
- "Serializer/XML/XMLNode.cpp",
- "Serializer/XMPPSerializer.cpp",
- "Session/Session.cpp",
- "Session/SessionTracer.cpp",
- "Session/SessionStream.cpp",
- "Session/BasicSessionStream.cpp",
- "Session/BOSHSessionStream.cpp",
- "StringCodecs/Base64.cpp",
- "StringCodecs/Hexify.cpp",
- "Whiteboard/WhiteboardResponder.cpp",
- "Whiteboard/WhiteboardSession.cpp",
- "Whiteboard/IncomingWhiteboardSession.cpp",
- "Whiteboard/OutgoingWhiteboardSession.cpp",
- "Whiteboard/WhiteboardSessionManager.cpp",
- "Whiteboard/WhiteboardServer.cpp",
- "Whiteboard/WhiteboardClient.cpp",
- "Elements/Whiteboard/WhiteboardColor.cpp",
- "Whiteboard/WhiteboardTransformer.cpp",
- ]
-
- elements = [
- "PubSub", "PubSubAffiliations", "PubSubAffiliation", "PubSubConfigure", "PubSubCreate", "PubSubDefault",
- "PubSubItems", "PubSubItem", "PubSubOptions", "PubSubPublish", "PubSubRetract", "PubSubSubscribeOptions",
- "PubSubSubscribe", "PubSubSubscriptions", "PubSubSubscription", "PubSubUnsubscribe",
+ sources = [
+ "Base/Debug.cpp",
+ "Chat/ChatStateTracker.cpp",
+ "Chat/ChatStateNotifier.cpp",
+ "Client/ClientSessionStanzaChannel.cpp",
+ "Client/CoreClient.cpp",
+ "Client/Client.cpp",
+ "Client/ClientXMLTracer.cpp",
+ "Client/ClientSession.cpp",
+ "Client/BlockList.cpp",
+ "Client/BlockListImpl.cpp",
+ "Client/ClientBlockListManager.cpp",
+ "Client/MemoryStorages.cpp",
+ "Client/NickResolver.cpp",
+ "Client/NickManager.cpp",
+ "Client/NickManagerImpl.cpp",
+ "Client/Storages.cpp",
+ "Client/XMLBeautifier.cpp",
+ "Compress/ZLibCodecompressor.cpp",
+ "Compress/ZLibDecompressor.cpp",
+ "Compress/ZLibCompressor.cpp",
+ "Elements/CarbonsEnable.cpp",
+ "Elements/CarbonsDisable.cpp",
+ "Elements/CarbonsPrivate.cpp",
+ "Elements/CarbonsReceived.cpp",
+ "Elements/CarbonsSent.cpp",
+ "Elements/DiscoInfo.cpp",
+ "Elements/Presence.cpp",
+ "Elements/Form.cpp",
+ "Elements/FormField.cpp",
+ "Elements/FormPage.cpp",
+ "Elements/FormSection.cpp",
+ "Elements/FormText.cpp",
+ "Elements/StreamFeatures.cpp",
+ "Elements/Element.cpp",
+ "Elements/ToplevelElement.cpp",
+ "Elements/IQ.cpp",
+ "Elements/Payload.cpp",
+ "Elements/PubSubPayload.cpp",
+ "Elements/PubSubOwnerPayload.cpp",
+ "Elements/PubSubEventPayload.cpp",
+ "Elements/RosterItemExchangePayload.cpp",
+ "Elements/RosterPayload.cpp",
+ "Elements/SecurityLabel.cpp",
+ "Elements/Stanza.cpp",
+ "Elements/StanzaAck.cpp",
+ "Elements/StatusShow.cpp",
+ "Elements/StreamManagementEnabled.cpp",
+ "Elements/StreamResume.cpp",
+ "Elements/StreamResumed.cpp",
+ "Elements/UserLocation.cpp",
+ "Elements/UserTune.cpp",
+ "Elements/VCard.cpp",
+ "Elements/MUCOccupant.cpp",
+ "Elements/ResultSet.cpp",
+ "Elements/Forwarded.cpp",
+ "Elements/MAMResult.cpp",
+ "Elements/MAMQuery.cpp",
+ "Elements/MAMFin.cpp",
+ "Elements/Thread.cpp",
+ "Elements/IsodeIQDelegation.cpp",
+ "Entity/Entity.cpp",
+ "Entity/PayloadPersister.cpp",
+ "MUC/MUC.cpp",
+ "MUC/MUCImpl.cpp",
+ "MUC/MUCManager.cpp",
+ "MUC/MUCRegistry.cpp",
+ "MUC/MUCBookmarkManager.cpp",
+ "PubSub/PubSubManager.cpp",
+ "PubSub/PubSubManagerImpl.cpp",
+ "Queries/IQChannel.cpp",
+ "Queries/IQHandler.cpp",
+ "Queries/IQRouter.cpp",
+ "Queries/Request.cpp",
+ "Queries/Responders/SoftwareVersionResponder.cpp",
+ "Roster/RosterStorage.cpp",
+ "Roster/RosterMemoryStorage.cpp",
+ "Roster/XMPPRoster.cpp",
+ "Roster/XMPPRosterImpl.cpp",
+ "Roster/XMPPRosterController.cpp",
+ "Serializer/AuthRequestSerializer.cpp",
+ "Serializer/AuthSuccessSerializer.cpp",
+ "Serializer/AuthChallengeSerializer.cpp",
+ "Serializer/AuthResponseSerializer.cpp",
+ "Serializer/CompressRequestSerializer.cpp",
+ "Serializer/ElementSerializer.cpp",
+ "Serializer/MessageSerializer.cpp",
+ "Serializer/StreamManagementEnabledSerializer.cpp",
+ "Serializer/StreamResumeSerializer.cpp",
+ "Serializer/StreamResumedSerializer.cpp",
+ "Serializer/ComponentHandshakeSerializer.cpp",
+ "Serializer/PayloadSerializer.cpp",
+ "Serializer/PayloadSerializerCollection.cpp",
+ "Serializer/PayloadSerializers/IBBSerializer.cpp",
+ "Serializer/PayloadSerializers/CapsInfoSerializer.cpp",
+ "Serializer/PayloadSerializers/CarbonsDisableSerializer.cpp",
+ "Serializer/PayloadSerializers/CarbonsEnableSerializer.cpp",
+ "Serializer/PayloadSerializers/CarbonsPrivateSerializer.cpp",
+ "Serializer/PayloadSerializers/CarbonsSentSerializer.cpp",
+ "Serializer/PayloadSerializers/CarbonsReceivedSerializer.cpp",
+ "Serializer/PayloadSerializers/ChatStateSerializer.cpp",
+ "Serializer/PayloadSerializers/DiscoInfoSerializer.cpp",
+ "Serializer/PayloadSerializers/DiscoItemsSerializer.cpp",
+ "Serializer/PayloadSerializers/ErrorSerializer.cpp",
+ "Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp",
+ "Serializer/PayloadSerializers/MUCPayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/ResourceBindSerializer.cpp",
+ "Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp",
+ "Serializer/PayloadSerializers/RosterSerializer.cpp",
+ "Serializer/PayloadSerializers/SecurityLabelSerializer.cpp",
+ "Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp",
+ "Serializer/PayloadSerializers/SoftwareVersionSerializer.cpp",
+ "Serializer/PayloadSerializers/StreamInitiationSerializer.cpp",
+ "Serializer/PayloadSerializers/BytestreamsSerializer.cpp",
+ "Serializer/PayloadSerializers/VCardSerializer.cpp",
+ "Serializer/PayloadSerializers/VCardUpdateSerializer.cpp",
+ "Serializer/PayloadSerializers/StorageSerializer.cpp",
+ "Serializer/PayloadSerializers/PrivateStorageSerializer.cpp",
+ "Serializer/PayloadSerializers/DelaySerializer.cpp",
+ "Serializer/PayloadSerializers/CommandSerializer.cpp",
+ "Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/SearchPayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/FormSerializer.cpp",
+ "Serializer/PayloadSerializers/NicknameSerializer.cpp",
+ "Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp",
+ "Serializer/PayloadSerializers/JinglePayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp",
+ "Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp",
+ "Serializer/PayloadSerializers/DeliveryReceiptSerializer.cpp",
+ "Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.cpp",
+ "Serializer/PayloadSerializers/UserLocationSerializer.cpp",
+ "Serializer/PayloadSerializers/UserTuneSerializer.cpp",
+ "Serializer/PayloadSerializers/WhiteboardSerializer.cpp",
+ "Serializer/PayloadSerializers/ResultSetSerializer.cpp",
+ "Serializer/PayloadSerializers/ForwardedSerializer.cpp",
+ "Serializer/PayloadSerializers/MAMFinSerializer.cpp",
+ "Serializer/PayloadSerializers/MAMResultSerializer.cpp",
+ "Serializer/PayloadSerializers/MAMQuerySerializer.cpp",
+ "Serializer/PayloadSerializers/IsodeIQDelegationSerializer.cpp",
+ "Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp",
+ "Serializer/PayloadSerializers/ThreadSerializer.cpp",
+ "Serializer/PresenceSerializer.cpp",
+ "Serializer/StanzaSerializer.cpp",
+ "Serializer/StreamErrorSerializer.cpp",
+ "Serializer/StreamFeaturesSerializer.cpp",
+ "Serializer/XML/XMLElement.cpp",
+ "Serializer/XML/XMLNode.cpp",
+ "Serializer/XMPPSerializer.cpp",
+ "Session/Session.cpp",
+ "Session/SessionTracer.cpp",
+ "Session/SessionStream.cpp",
+ "Session/BasicSessionStream.cpp",
+ "Session/BOSHSessionStream.cpp",
+ "StringCodecs/Base64.cpp",
+ "StringCodecs/Hexify.cpp",
+ "Whiteboard/WhiteboardResponder.cpp",
+ "Whiteboard/WhiteboardSession.cpp",
+ "Whiteboard/IncomingWhiteboardSession.cpp",
+ "Whiteboard/OutgoingWhiteboardSession.cpp",
+ "Whiteboard/WhiteboardSessionManager.cpp",
+ "Whiteboard/WhiteboardServer.cpp",
+ "Whiteboard/WhiteboardClient.cpp",
+ "Elements/Whiteboard/WhiteboardColor.cpp",
+ "Whiteboard/WhiteboardTransformer.cpp",
+ ]
+
+ elements = [
+ "PubSub", "PubSubAffiliations", "PubSubAffiliation", "PubSubConfigure", "PubSubCreate", "PubSubDefault",
+ "PubSubItems", "PubSubItem", "PubSubOptions", "PubSubPublish", "PubSubRetract", "PubSubSubscribeOptions",
+ "PubSubSubscribe", "PubSubSubscriptions", "PubSubSubscription", "PubSubUnsubscribe",
- "PubSubEvent", "PubSubEventAssociate", "PubSubEventCollection", "PubSubEventConfiguration", "PubSubEventDelete",
- "PubSubEventDisassociate", "PubSubEventItem", "PubSubEventItems", "PubSubEventPurge", "PubSubEventRedirect",
- "PubSubEventRetract", "PubSubEventSubscription",
+ "PubSubEvent", "PubSubEventAssociate", "PubSubEventCollection", "PubSubEventConfiguration", "PubSubEventDelete",
+ "PubSubEventDisassociate", "PubSubEventItem", "PubSubEventItems", "PubSubEventPurge", "PubSubEventRedirect",
+ "PubSubEventRetract", "PubSubEventSubscription",
- "PubSubOwnerAffiliation", "PubSubOwnerAffiliations", "PubSubOwnerConfigure", "PubSubOwnerDefault",
- "PubSubOwnerDelete", "PubSubOwnerPubSub", "PubSubOwnerPurge", "PubSubOwnerRedirect",
- "PubSubOwnerSubscription", "PubSubOwnerSubscriptions",
+ "PubSubOwnerAffiliation", "PubSubOwnerAffiliations", "PubSubOwnerConfigure", "PubSubOwnerDefault",
+ "PubSubOwnerDelete", "PubSubOwnerPubSub", "PubSubOwnerPurge", "PubSubOwnerRedirect",
+ "PubSubOwnerSubscription", "PubSubOwnerSubscriptions",
- "PubSubError",
- ]
- for element in elements :
- sources += [
- "Elements/" + element + ".cpp",
- "Serializer/PayloadSerializers/" + element + "Serializer.cpp",
- "Parser/PayloadParsers/" + element + "Parser.cpp",
- ]
+ "PubSubError",
+ ]
+ for element in elements :
+ sources += [
+ "Elements/" + element + ".cpp",
+ "Serializer/PayloadSerializers/" + element + "Serializer.cpp",
+ "Parser/PayloadParsers/" + element + "Parser.cpp",
+ ]
- SConscript(dirs = [
- "Avatars",
- "Base",
- "IDN",
- "SASL",
- "TLS",
- "Crypto",
- "EventLoop",
- "Parser",
- "JID",
- "Jingle",
- "Disco",
- "VCards",
- "Network",
- "Presence",
- "FileTransfer",
- "History",
- "StreamStack",
- "LinkLocal",
- "StreamManagement",
- "Component",
- "AdHoc"
- ])
- if env["build_examples"] :
- SConscript(dirs = [
- "Config",
- "Examples"
- ])
- env.SConscript(test_only = True, dirs = [
- "QA",
- ])
+ SConscript(dirs = [
+ "Avatars",
+ "Base",
+ "IDN",
+ "SASL",
+ "TLS",
+ "Crypto",
+ "EventLoop",
+ "Parser",
+ "JID",
+ "Jingle",
+ "Disco",
+ "VCards",
+ "Network",
+ "Presence",
+ "FileTransfer",
+ "History",
+ "StreamStack",
+ "LinkLocal",
+ "StreamManagement",
+ "Component",
+ "AdHoc"
+ ])
+ if env["build_examples"] :
+ SConscript(dirs = [
+ "Config",
+ "Examples"
+ ])
+ env.SConscript(test_only = True, dirs = [
+ "QA",
+ ])
- myenv = swiften_env.Clone()
- if myenv["PLATFORM"] != "darwin" and myenv["PLATFORM"] != "win32" and myenv.get("HAVE_GCONF", 0) :
- env.MergeFlags(env["GCONF_FLAGS"])
+ myenv = swiften_env.Clone()
+ if myenv["PLATFORM"] != "darwin" and myenv["PLATFORM"] != "win32" and myenv.get("HAVE_GCONF", 0) :
+ env.MergeFlags(env["GCONF_FLAGS"])
- if myenv["SWIFTEN_DLL"] :
- if myenv["PLATFORM"] == "posix" :
- myenv.Append(LINKFLAGS = ["-Wl,-soname,libSwiften.so.$SWIFTEN_VERSION_MAJOR"])
- myenv["SHLIBSUFFIX"] = ""
- elif myenv["PLATFORM"] == "darwin" :
- myenv.Append(LINKFLAGS = ["-Wl,-install_name,${SHLIBPREFIX}Swiften.${SWIFTEN_VERSION_MAJOR}${SHLIBSUFFIX}", "-Wl,-compatibility_version,${SWIFTEN_VERSION_MAJOR}.${SWIFTEN_VERSION_MINOR}", "-Wl,-current_version,${SWIFTEN_VERSION_MAJOR}.${SWIFTEN_VERSION_MINOR}"])
- elif myenv["PLATFORM"] == "win32" :
- res_env = myenv.Clone()
- res_env.Append(CPPDEFINES = [
- ("SWIFTEN_LIBRARY_FILE", "\"\\\"${SWIFTEN_LIBRARY_FILE}\\\"\""),
- ("SWIFTEN_COPYRIGHT_YEAR", "\"\\\"2010-%s\\\"\"" % str(time.localtime()[0])),
- ("SWIFTEN_VERSION_MAJOR", "${SWIFTEN_VERSION_MAJOR}"),
- ("SWIFTEN_VERSION_MINOR", "${SWIFTEN_VERSION_MINOR}"),
- ("SWIFTEN_VERSION_PATCH", "${SWIFTEN_VERSION_PATCH}"),
- ])
- res = res_env.RES("Swiften.rc")
- # For some reason, SCons isn't picking up the dependency correctly
- # Adding it explicitly until i figure out why
- res_env.Depends(res, "Version.h")
- sources += res
+ if myenv["SWIFTEN_DLL"] :
+ if myenv["PLATFORM"] == "posix" :
+ myenv.Append(LINKFLAGS = ["-Wl,-soname,libSwiften.so.$SWIFTEN_VERSION_MAJOR"])
+ myenv["SHLIBSUFFIX"] = ""
+ elif myenv["PLATFORM"] == "darwin" :
+ myenv.Append(LINKFLAGS = ["-Wl,-install_name,${SHLIBPREFIX}Swiften.${SWIFTEN_VERSION_MAJOR}${SHLIBSUFFIX}", "-Wl,-compatibility_version,${SWIFTEN_VERSION_MAJOR}.${SWIFTEN_VERSION_MINOR}", "-Wl,-current_version,${SWIFTEN_VERSION_MAJOR}.${SWIFTEN_VERSION_MINOR}"])
+ elif myenv["PLATFORM"] == "win32" :
+ res_env = myenv.Clone()
+ res_env.Append(CPPDEFINES = [
+ ("SWIFTEN_LIBRARY_FILE", "\"\\\"${SWIFTEN_LIBRARY_FILE}\\\"\""),
+ ("SWIFTEN_COPYRIGHT_YEAR", "\"\\\"2010-%s\\\"\"" % str(time.localtime()[0])),
+ ("SWIFTEN_VERSION_MAJOR", "${SWIFTEN_VERSION_MAJOR}"),
+ ("SWIFTEN_VERSION_MINOR", "${SWIFTEN_VERSION_MINOR}"),
+ ("SWIFTEN_VERSION_PATCH", "${SWIFTEN_VERSION_PATCH}"),
+ ])
+ res = res_env.RES("Swiften.rc")
+ # For some reason, SCons isn't picking up the dependency correctly
+ # Adding it explicitly until i figure out why
+ res_env.Depends(res, "Version.h")
+ sources += res
- swiften_lib = myenv.SwiftenLibrary(swiften_env["SWIFTEN_LIBRARY_FILE"], sources + swiften_env["SWIFTEN_OBJECTS"])
- def symlink(env, target, source) :
- if os.path.exists(str(target[0])) :
- os.unlink(str(target[0]))
- os.symlink(source[0].get_contents(), str(target[0]))
- for alias in myenv["SWIFTEN_LIBRARY_ALIASES"] :
- myenv.Command(myenv.File(alias), [myenv.Value(swiften_lib[0].name), swiften_lib[0]], symlink)
+ swiften_lib = myenv.SwiftenLibrary(swiften_env["SWIFTEN_LIBRARY_FILE"], sources + swiften_env["SWIFTEN_OBJECTS"])
+ def symlink(env, target, source) :
+ if os.path.exists(str(target[0])) :
+ os.unlink(str(target[0]))
+ os.symlink(source[0].get_contents(), str(target[0]))
+ for alias in myenv["SWIFTEN_LIBRARY_ALIASES"] :
+ myenv.Command(myenv.File(alias), [myenv.Value(swiften_lib[0].name), swiften_lib[0]], symlink)
- env.Append(UNITTEST_SOURCES = [
- File("Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp"),
- File("Avatars/UnitTest/VCardAvatarManagerTest.cpp"),
- File("Avatars/UnitTest/CombinedAvatarProviderTest.cpp"),
- File("Avatars/UnitTest/AvatarManagerImplTest.cpp"),
- File("Base/UnitTest/IDGeneratorTest.cpp"),
- File("Base/UnitTest/SimpleIDGeneratorTest.cpp"),
- File("Base/UnitTest/StringTest.cpp"),
- File("Base/UnitTest/DateTimeTest.cpp"),
- File("Base/UnitTest/ByteArrayTest.cpp"),
- File("Base/UnitTest/URLTest.cpp"),
- File("Base/UnitTest/PathTest.cpp"),
- File("Chat/UnitTest/ChatStateNotifierTest.cpp"),
-# File("Chat/UnitTest/ChatStateTrackerTest.cpp"),
- File("Client/UnitTest/ClientSessionTest.cpp"),
- File("Client/UnitTest/NickResolverTest.cpp"),
- File("Client/UnitTest/ClientBlockListManagerTest.cpp"),
- File("Client/UnitTest/BlockListImplTest.cpp"),
- File("Compress/UnitTest/ZLibCompressorTest.cpp"),
- File("Compress/UnitTest/ZLibDecompressorTest.cpp"),
- File("Component/UnitTest/ComponentHandshakeGeneratorTest.cpp"),
- File("Component/UnitTest/ComponentConnectorTest.cpp"),
- File("Component/UnitTest/ComponentSessionTest.cpp"),
- File("Disco/UnitTest/CapsInfoGeneratorTest.cpp"),
- File("Disco/UnitTest/CapsManagerTest.cpp"),
- File("Disco/UnitTest/EntityCapsManagerTest.cpp"),
- File("Disco/UnitTest/JIDDiscoInfoResponderTest.cpp"),
- File("Disco/UnitTest/DiscoInfoResponderTest.cpp"),
- File("Elements/UnitTest/IQTest.cpp"),
- File("Elements/UnitTest/StanzaTest.cpp"),
- File("Elements/UnitTest/FormTest.cpp"),
- File("EventLoop/UnitTest/EventLoopTest.cpp"),
- File("EventLoop/UnitTest/SimpleEventLoopTest.cpp"),
-# File("History/UnitTest/SQLiteHistoryManagerTest.cpp"),
- File("JID/UnitTest/JIDTest.cpp"),
- File("LinkLocal/UnitTest/LinkLocalConnectorTest.cpp"),
- File("LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp"),
- File("LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp"),
- File("LinkLocal/UnitTest/LinkLocalServiceTest.cpp"),
- File("MUC/UnitTest/MUCTest.cpp"),
- File("MUC/UnitTest/MockMUC.cpp"),
- File("Network/UnitTest/HostAddressTest.cpp"),
- File("Network/UnitTest/ConnectorTest.cpp"),
- File("Network/UnitTest/ChainedConnectorTest.cpp"),
- File("Network/UnitTest/DomainNameServiceQueryTest.cpp"),
- File("Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp"),
- File("Network/UnitTest/BOSHConnectionTest.cpp"),
- File("Network/UnitTest/BOSHConnectionPoolTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/BlockParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/BodyParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/DiscoInfoParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/DiscoItemsParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/ErrorParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/FormParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/CommandParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/PriorityParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/RawXMLPayloadParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/ResourceBindParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/RosterItemExchangeParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/RosterParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/IBBParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/InBandRegistrationPayloadParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/JingleParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/SearchPayloadParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/SecurityLabelParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/SecurityLabelsCatalogParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/SoftwareVersionParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/StatusParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/StatusShowParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/VCardParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/StorageParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/PrivateStorageParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/VCardUpdateParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/ReplaceTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/MUCAdminPayloadParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/DeliveryReceiptParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/IdleParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/ResultSetParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/ForwardedParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/MAMFinParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/MAMResultParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/MAMQueryParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/CarbonsParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/UserTuneParserTest.cpp"),
- File("Parser/PayloadParsers/UnitTest/UserLocationParserTest.cpp"),
- File("Parser/UnitTest/BOSHBodyExtractorTest.cpp"),
- File("Parser/UnitTest/AttributeMapTest.cpp"),
- File("Parser/UnitTest/EnumParserTest.cpp"),
- File("Parser/UnitTest/IQParserTest.cpp"),
- File("Parser/UnitTest/GenericPayloadTreeParserTest.cpp"),
- File("Parser/UnitTest/MessageParserTest.cpp"),
- File("Parser/UnitTest/PayloadParserFactoryCollectionTest.cpp"),
- File("Parser/UnitTest/PresenceParserTest.cpp"),
- File("Parser/UnitTest/StanzaAckParserTest.cpp"),
- File("Parser/UnitTest/SerializingParserTest.cpp"),
- File("Parser/UnitTest/StanzaParserTest.cpp"),
- File("Parser/UnitTest/StreamFeaturesParserTest.cpp"),
- File("Parser/UnitTest/StreamManagementEnabledParserTest.cpp"),
- File("Parser/UnitTest/XMLParserTest.cpp"),
- File("Parser/UnitTest/XMPPParserTest.cpp"),
- File("Presence/UnitTest/PresenceOracleTest.cpp"),
- File("Presence/UnitTest/DirectedPresenceSenderTest.cpp"),
- File("Presence/UnitTest/PayloadAddingPresenceSenderTest.cpp"),
- File("Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp"),
- File("Queries/UnitTest/IQRouterTest.cpp"),
- File("Queries/UnitTest/RequestTest.cpp"),
- File("Queries/UnitTest/ResponderTest.cpp"),
- File("Roster/UnitTest/XMPPRosterImplTest.cpp"),
- File("Roster/UnitTest/XMPPRosterControllerTest.cpp"),
- File("Roster/UnitTest/XMPPRosterSignalHandler.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/BlockSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/CarbonsSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/CapsInfoSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/ChatStateSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/FormSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/DiscoInfoSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/ErrorSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/IBBSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/PrioritySerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/ResourceBindSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/RosterItemExchangeSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/RosterSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/SearchPayloadSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/SecurityLabelSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/SecurityLabelsCatalogSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/SoftwareVersionSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/StatusSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/StatusShowSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/StreamInitiationSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/InBandRegistrationPayloadSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/IsodeIQDelegationSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/VCardUpdateSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/StorageSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/PrivateStorageSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/ReplaceSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/MUCAdminPayloadSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/DeliveryReceiptSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/IdleSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/ResultSetSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/ForwardedSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/MAMFinSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/MAMResultSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/MAMQuerySerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/PubSubItemSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/PubSubItemsSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/UserTuneSerializerTest.cpp"),
- File("Serializer/PayloadSerializers/UnitTest/UserLocationSerializerTest.cpp"),
- File("Serializer/UnitTest/StreamFeaturesSerializerTest.cpp"),
- File("Serializer/UnitTest/AuthSuccessSerializerTest.cpp"),
- File("Serializer/UnitTest/AuthChallengeSerializerTest.cpp"),
- File("Serializer/UnitTest/AuthRequestSerializerTest.cpp"),
- File("Serializer/UnitTest/AuthResponseSerializerTest.cpp"),
- File("Serializer/UnitTest/XMPPSerializerTest.cpp"),
- File("Serializer/XML/UnitTest/XMLElementTest.cpp"),
- File("StreamManagement/UnitTest/StanzaAckRequesterTest.cpp"),
- File("StreamManagement/UnitTest/StanzaAckResponderTest.cpp"),
- File("StreamStack/UnitTest/StreamStackTest.cpp"),
- File("StreamStack/UnitTest/XMPPLayerTest.cpp"),
- File("StringCodecs/UnitTest/Base64Test.cpp"),
- File("StringCodecs/UnitTest/HexifyTest.cpp"),
- File("StringCodecs/UnitTest/PBKDF2Test.cpp"),
- File("TLS/UnitTest/ServerIdentityVerifierTest.cpp"),
- File("TLS/UnitTest/CertificateTest.cpp"),
- File("VCards/UnitTest/VCardManagerTest.cpp"),
- File("Whiteboard/UnitTest/WhiteboardServerTest.cpp"),
- File("Whiteboard/UnitTest/WhiteboardClientTest.cpp"),
- ])
-
- # Generate the Swiften header
- def relpath(path, start) :
- i = len(os.path.commonprefix([path, start]))
- return path[i+1:]
- swiften_header = "#pragma once\n"
- swiften_includes = []
- swiften_public_includes = []
- top_path = env.Dir("..").abspath
- for root, dirs, files in os.walk(env.Dir(".").abspath) :
- if root.endswith("UnitTest") :
- continue
- for file in files :
- if not file.endswith(".h") :
- continue
- include = relpath(os.path.join(root, file), top_path)
- if swiften_env["PLATFORM"] == "win32" :
- include = include.replace("\\", "/")
- swiften_includes.append(include)
- # Private modules
- if root.endswith("Config") :
- continue
+ env.Append(UNITTEST_SOURCES = [
+ File("Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp"),
+ File("Avatars/UnitTest/VCardAvatarManagerTest.cpp"),
+ File("Avatars/UnitTest/CombinedAvatarProviderTest.cpp"),
+ File("Avatars/UnitTest/AvatarManagerImplTest.cpp"),
+ File("Base/UnitTest/IDGeneratorTest.cpp"),
+ File("Base/UnitTest/SimpleIDGeneratorTest.cpp"),
+ File("Base/UnitTest/StringTest.cpp"),
+ File("Base/UnitTest/DateTimeTest.cpp"),
+ File("Base/UnitTest/ByteArrayTest.cpp"),
+ File("Base/UnitTest/URLTest.cpp"),
+ File("Base/UnitTest/PathTest.cpp"),
+ File("Chat/UnitTest/ChatStateNotifierTest.cpp"),
+# File("Chat/UnitTest/ChatStateTrackerTest.cpp"),
+ File("Client/UnitTest/ClientSessionTest.cpp"),
+ File("Client/UnitTest/NickResolverTest.cpp"),
+ File("Client/UnitTest/ClientBlockListManagerTest.cpp"),
+ File("Client/UnitTest/BlockListImplTest.cpp"),
+ File("Compress/UnitTest/ZLibCompressorTest.cpp"),
+ File("Compress/UnitTest/ZLibDecompressorTest.cpp"),
+ File("Component/UnitTest/ComponentHandshakeGeneratorTest.cpp"),
+ File("Component/UnitTest/ComponentConnectorTest.cpp"),
+ File("Component/UnitTest/ComponentSessionTest.cpp"),
+ File("Disco/UnitTest/CapsInfoGeneratorTest.cpp"),
+ File("Disco/UnitTest/CapsManagerTest.cpp"),
+ File("Disco/UnitTest/DiscoInfoResponderTest.cpp"),
+ File("Disco/UnitTest/EntityCapsManagerTest.cpp"),
+ File("Disco/UnitTest/FeatureOracleTest.cpp"),
+ File("Disco/UnitTest/JIDDiscoInfoResponderTest.cpp"),
+ File("Elements/UnitTest/IQTest.cpp"),
+ File("Elements/UnitTest/StanzaTest.cpp"),
+ File("Elements/UnitTest/FormTest.cpp"),
+ File("EventLoop/UnitTest/EventLoopTest.cpp"),
+ File("EventLoop/UnitTest/SimpleEventLoopTest.cpp"),
+# File("History/UnitTest/SQLiteHistoryManagerTest.cpp"),
+ File("JID/UnitTest/JIDTest.cpp"),
+ File("LinkLocal/UnitTest/LinkLocalConnectorTest.cpp"),
+ File("LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp"),
+ File("LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp"),
+ File("LinkLocal/UnitTest/LinkLocalServiceTest.cpp"),
+ File("MUC/UnitTest/MUCTest.cpp"),
+ File("MUC/UnitTest/MockMUC.cpp"),
+ File("Network/UnitTest/HostAddressTest.cpp"),
+ File("Network/UnitTest/ConnectorTest.cpp"),
+ File("Network/UnitTest/ChainedConnectorTest.cpp"),
+ File("Network/UnitTest/DomainNameServiceQueryTest.cpp"),
+ File("Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp"),
+ File("Network/UnitTest/BOSHConnectionTest.cpp"),
+ File("Network/UnitTest/BOSHConnectionPoolTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/BlockParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/BodyParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/DiscoInfoParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/DiscoItemsParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/ErrorParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/FormParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/CommandParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/PriorityParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/RawXMLPayloadParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/ResourceBindParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/RosterItemExchangeParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/RosterParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/IBBParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/InBandRegistrationPayloadParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/JingleParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/SearchPayloadParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/SecurityLabelParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/SecurityLabelsCatalogParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/SoftwareVersionParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/StatusParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/StatusShowParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/VCardParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/StorageParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/PrivateStorageParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/VCardUpdateParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/ReplaceTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/MUCAdminPayloadParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/MUCUserPayloadParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/DeliveryReceiptParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/IdleParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/ResultSetParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/ForwardedParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/MAMFinParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/MAMResultParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/MAMQueryParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/CarbonsParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/UserTuneParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/UserLocationParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/PubSubRetractParserTest.cpp"),
+ File("Parser/UnitTest/BOSHBodyExtractorTest.cpp"),
+ File("Parser/UnitTest/AttributeMapTest.cpp"),
+ File("Parser/UnitTest/EnumParserTest.cpp"),
+ File("Parser/UnitTest/IQParserTest.cpp"),
+ File("Parser/UnitTest/GenericPayloadTreeParserTest.cpp"),
+ File("Parser/UnitTest/MessageParserTest.cpp"),
+ File("Parser/UnitTest/PayloadParserFactoryCollectionTest.cpp"),
+ File("Parser/UnitTest/PresenceParserTest.cpp"),
+ File("Parser/UnitTest/StanzaAckParserTest.cpp"),
+ File("Parser/UnitTest/SerializingParserTest.cpp"),
+ File("Parser/UnitTest/StanzaParserTest.cpp"),
+ File("Parser/UnitTest/StreamFeaturesParserTest.cpp"),
+ File("Parser/UnitTest/StreamManagementEnabledParserTest.cpp"),
+ File("Parser/UnitTest/XMLParserTest.cpp"),
+ File("Parser/UnitTest/XMPPParserTest.cpp"),
+ File("Presence/UnitTest/PresenceOracleTest.cpp"),
+ File("Presence/UnitTest/DirectedPresenceSenderTest.cpp"),
+ File("Presence/UnitTest/PayloadAddingPresenceSenderTest.cpp"),
+ File("Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp"),
+ File("Queries/UnitTest/IQRouterTest.cpp"),
+ File("Queries/UnitTest/RequestTest.cpp"),
+ File("Queries/UnitTest/ResponderTest.cpp"),
+ File("Roster/UnitTest/XMPPRosterImplTest.cpp"),
+ File("Roster/UnitTest/XMPPRosterControllerTest.cpp"),
+ File("Roster/UnitTest/XMPPRosterSignalHandler.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/BlockSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/CarbonsSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/CapsInfoSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/ChatStateSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/FormSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/DiscoInfoSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/ErrorSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/IBBSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/PrioritySerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/ResourceBindSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/RosterItemExchangeSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/RosterSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/SearchPayloadSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/SecurityLabelSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/SecurityLabelsCatalogSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/SoftwareVersionSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/StatusSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/StatusShowSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/StreamInitiationSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/InBandRegistrationPayloadSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/IsodeIQDelegationSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/VCardUpdateSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/StorageSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/PrivateStorageSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/ReplaceSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/MUCAdminPayloadSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/DeliveryReceiptSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/IdleSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/ResultSetSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/ForwardedSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/MAMFinSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/MAMResultSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/MAMQuerySerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/PubSubItemSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/PubSubItemsSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/PubSubRetractSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/UserTuneSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/UserLocationSerializerTest.cpp"),
+ File("Serializer/UnitTest/StreamFeaturesSerializerTest.cpp"),
+ File("Serializer/UnitTest/AuthSuccessSerializerTest.cpp"),
+ File("Serializer/UnitTest/AuthChallengeSerializerTest.cpp"),
+ File("Serializer/UnitTest/AuthRequestSerializerTest.cpp"),
+ File("Serializer/UnitTest/AuthResponseSerializerTest.cpp"),
+ File("Serializer/UnitTest/XMPPSerializerTest.cpp"),
+ File("Serializer/XML/UnitTest/XMLElementTest.cpp"),
+ File("StreamManagement/UnitTest/StanzaAckRequesterTest.cpp"),
+ File("StreamManagement/UnitTest/StanzaAckResponderTest.cpp"),
+ File("StreamStack/UnitTest/StreamStackTest.cpp"),
+ File("StreamStack/UnitTest/XMPPLayerTest.cpp"),
+ File("StringCodecs/UnitTest/Base64Test.cpp"),
+ File("StringCodecs/UnitTest/HexifyTest.cpp"),
+ File("StringCodecs/UnitTest/PBKDF2Test.cpp"),
+ File("TLS/UnitTest/ServerIdentityVerifierTest.cpp"),
+ File("TLS/UnitTest/CertificateTest.cpp"),
+ File("VCards/UnitTest/VCardManagerTest.cpp"),
+ File("Whiteboard/UnitTest/WhiteboardServerTest.cpp"),
+ File("Whiteboard/UnitTest/WhiteboardClientTest.cpp"),
+ ])
+
+ # Generate the Swiften header
+ def relpath(path, start) :
+ i = len(os.path.commonprefix([path, start]))
+ return path[i+1:]
+ swiften_header = "#pragma once\n"
+ swiften_includes = []
+ swiften_public_includes = []
+ top_path = env.Dir("..").abspath
+ for root, dirs, files in os.walk(env.Dir(".").abspath) :
+ if root.endswith("UnitTest") :
+ continue
+ for file in files :
+ if not file.endswith(".h") :
+ continue
+ include = relpath(os.path.join(root, file), top_path)
+ if swiften_env["PLATFORM"] == "win32" :
+ include = include.replace("\\", "/")
+ swiften_includes.append(include)
+ # Private modules
+ if root.endswith("Config") :
+ continue
- # Library-specfifc private modules
- if root.endswith("OpenSSL") or root.endswith("Cocoa") or root.endswith("Qt") or root.endswith("Avahi") or root.endswith("Bonjour") :
- continue
+ # Library-specfifc private modules
+ if root.endswith("OpenSSL") or root.endswith("Cocoa") or root.endswith("Qt") or root.endswith("Avahi") or root.endswith("Bonjour") :
+ continue
- # Library-specific files
- if file.endswith("_Private.h") or file.startswith("Schannel") or file.startswith("CAPI") or file.startswith("MacOSX") or file.startswith("SecureTransport") or file.startswith("Windows") or file.endswith("_Windows.h") or file.startswith("SQLite") or file == "ICUConverter.h" or file == "UnboundDomainNameResolver.h" :
- continue
+ # Library-specific files
+ if file.endswith("_Private.h") or file.startswith("Schannel") or file.startswith("CAPI") or file.startswith("MacOSX") or file.startswith("SecureTransport") or file.startswith("Windows") or file.endswith("_Windows.h") or file.startswith("SQLite") or file == "ICUConverter.h" or file == "UnboundDomainNameResolver.h" :
+ continue
- # Specific headers we don't want to globally include
- if file == "Swiften.h" or file == "foreach.h" or file == "Log.h" or file == "format.h" :
- continue
- swiften_header += "#include <" + include + ">\n"
- swiften_public_includes.append(include)
- swiften_includes.append(include)
- swiften_env.WriteVal("Swiften.h", swiften_env.Value(swiften_header))
- swiften_includes.append("Swiften/Swiften.h")
+ # Specific headers we don't want to globally include
+ if file == "Swiften.h" or file == "foreach.h" or file == "Log.h" or file == "format.h" :
+ continue
+ swiften_header += "#include <" + include + ">\n"
+ swiften_public_includes.append(include)
+ swiften_includes.append(include)
+ swiften_env.WriteVal("Swiften.h", swiften_env.Value(swiften_header))
+ swiften_includes.append("Swiften/Swiften.h")
- version_header = "#pragma once\n\n"
- version_header += "#define SWIFTEN_VERSION 0x%02X%02X%02X\n" % (swiften_env["SWIFTEN_VERSION_MAJOR"], swiften_env["SWIFTEN_VERSION_MINOR"], swiften_env["SWIFTEN_VERSION_PATCH"])
- version_header += "#define SWIFTEN_VERSION_STRING \"%s\"\n" % swiften_env["SWIFTEN_VERSION"]
- swiften_env.WriteVal("Version.h", swiften_env.Value(version_header))
- swiften_includes.append("Swiften/Version.h")
+ version_header = "#pragma once\n\n"
+ version_header += "#define SWIFTEN_VERSION 0x%02X%02X%02X\n" % (swiften_env["SWIFTEN_VERSION_MAJOR"], swiften_env["SWIFTEN_VERSION_MINOR"], swiften_env["SWIFTEN_VERSION_PATCH"])
+ version_header += "#define SWIFTEN_VERSION_STRING \"%s\"\n" % swiften_env["SWIFTEN_VERSION"]
+ swiften_env.WriteVal("Version.h", swiften_env.Value(version_header))
+ swiften_includes.append("Swiften/Version.h")
- # Check headers
- if env["check_headers"] :
- test_env = swiften_env.Clone()
- for header in swiften_public_includes:
- program_text = "#include <%s>\n" % (header)
- filename = Dir('#/.sconf_temp').abspath + ("/%s.cpp" % (urllib.quote(header, '') ))
- text_file = open(filename, "w")
- text_file.write(program_text)
- text_file.close()
- test_obj = test_env.Object(File("#/.sconf_temp/%s.cpp" % (urllib.quote(header, '') )))
- test_env.Default(test_obj)
+ # Check headers
+ if env["check_headers"] :
+ test_env = swiften_env.Clone()
+ for header in swiften_public_includes:
+ program_text = "#include <%s>\n" % (header)
+ filename = Dir('#/.sconf_temp').abspath + ("/%s.cpp" % (urllib.quote(header, '') ))
+ text_file = open(filename, "w")
+ text_file.write(program_text)
+ text_file.close()
+ test_obj = test_env.Object(File("#/.sconf_temp/%s.cpp" % (urllib.quote(header, '') )))
+ test_env.Default(test_obj)
- # Install swiften
- if swiften_env.get("SWIFTEN_INSTALLDIR", "") :
- swiften_env.Install(os.path.join(swiften_env["SWIFTEN_INSTALLDIR"], "lib"), swiften_lib)
- for alias in myenv["SWIFTEN_LIBRARY_ALIASES"] :
- myenv.Command(myenv.File(os.path.join(swiften_env["SWIFTEN_INSTALLDIR"], "lib", alias)), [env.Value(swiften_lib[0].name), swiften_lib[0]], symlink)
- for include in swiften_includes :
- swiften_env.Install(os.path.join(swiften_env["SWIFTEN_INSTALLDIR"], "include", os.path.dirname(include)), "#/" + include)
+ # Install swiften
+ if swiften_env.get("SWIFTEN_INSTALLDIR", "") :
+ swiften_env.Install(os.path.join(swiften_env["SWIFTEN_INSTALLDIR"], "lib"), swiften_lib)
+ for alias in myenv["SWIFTEN_LIBRARY_ALIASES"] :
+ myenv.Command(myenv.File(os.path.join(swiften_env["SWIFTEN_INSTALLDIR"], "lib", alias)), [env.Value(swiften_lib[0].name), swiften_lib[0]], symlink)
+ for include in swiften_includes :
+ swiften_env.Install(os.path.join(swiften_env["SWIFTEN_INSTALLDIR"], "include", os.path.dirname(include)), "#/" + include)
diff --git a/Swiften/Serializer/AuthChallengeSerializer.cpp b/Swiften/Serializer/AuthChallengeSerializer.cpp
index 8ae7c7b..8f963ff 100644
--- a/Swiften/Serializer/AuthChallengeSerializer.cpp
+++ b/Swiften/Serializer/AuthChallengeSerializer.cpp
@@ -1,33 +1,33 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/AuthChallengeSerializer.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/Elements/AuthChallenge.h>
#include <Swiften/StringCodecs/Base64.h>
-#include <Swiften/Base/ByteArray.h>
namespace Swift {
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>");
+SafeByteArray AuthChallengeSerializer::serialize(std::shared_ptr<ToplevelElement> element) const {
+ std::shared_ptr<AuthChallenge> authChallenge(std::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..9bcf68b 100644
--- a/Swiften/Serializer/AuthChallengeSerializer.h
+++ b/Swiften/Serializer/AuthChallengeSerializer.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/AuthChallenge.h>
#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(std::shared_ptr<ToplevelElement> element) const;
+ };
}
diff --git a/Swiften/Serializer/AuthFailureSerializer.h b/Swiften/Serializer/AuthFailureSerializer.h
index 9c1d66e..a410e8c 100644
--- a/Swiften/Serializer/AuthFailureSerializer.h
+++ b/Swiften/Serializer/AuthFailureSerializer.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/AuthFailure.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(std::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 29b076d..2c9a4dd 100644
--- a/Swiften/Serializer/AuthRequestSerializer.cpp
+++ b/Swiften/Serializer/AuthRequestSerializer.cpp
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/AuthRequestSerializer.h>
+#include <Swiften/Base/Concat.h>
+#include <Swiften/Base/SafeByteArray.h>
#include <Swiften/Elements/AuthRequest.h>
#include <Swiften/StringCodecs/Base64.h>
-#include <Swiften/Base/SafeByteArray.h>
-#include <Swiften/Base/Concat.h>
namespace Swift {
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>"));
+SafeByteArray AuthRequestSerializer::serialize(std::shared_ptr<ToplevelElement> element) const {
+ std::shared_ptr<AuthRequest> authRequest(std::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..ae85cf6 100644
--- a/Swiften/Serializer/AuthRequestSerializer.h
+++ b/Swiften/Serializer/AuthRequestSerializer.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/AuthRequest.h>
#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(std::shared_ptr<ToplevelElement> element) const;
+ };
}
diff --git a/Swiften/Serializer/AuthResponseSerializer.cpp b/Swiften/Serializer/AuthResponseSerializer.cpp
index 818c6d4..9d3e2e0 100644
--- a/Swiften/Serializer/AuthResponseSerializer.cpp
+++ b/Swiften/Serializer/AuthResponseSerializer.cpp
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/AuthResponseSerializer.h>
+#include <Swiften/Base/Concat.h>
+#include <Swiften/Base/SafeByteArray.h>
#include <Swiften/Elements/AuthResponse.h>
#include <Swiften/StringCodecs/Base64.h>
-#include <Swiften/Base/SafeByteArray.h>
-#include <Swiften/Base/Concat.h>
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(std::shared_ptr<ToplevelElement> element) const {
+ std::shared_ptr<AuthResponse> authResponse(std::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..25ffbbb 100644
--- a/Swiften/Serializer/AuthResponseSerializer.h
+++ b/Swiften/Serializer/AuthResponseSerializer.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/AuthResponse.h>
#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(std::shared_ptr<ToplevelElement> element) const;
+ };
}
diff --git a/Swiften/Serializer/AuthSuccessSerializer.cpp b/Swiften/Serializer/AuthSuccessSerializer.cpp
index c09ecf0..48d512b 100644
--- a/Swiften/Serializer/AuthSuccessSerializer.cpp
+++ b/Swiften/Serializer/AuthSuccessSerializer.cpp
@@ -1,33 +1,33 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/AuthSuccessSerializer.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/Elements/AuthSuccess.h>
#include <Swiften/StringCodecs/Base64.h>
-#include <Swiften/Base/ByteArray.h>
namespace Swift {
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>");
+SafeByteArray AuthSuccessSerializer::serialize(std::shared_ptr<ToplevelElement> element) const {
+ std::shared_ptr<AuthSuccess> authSuccess(std::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..102e6a0 100644
--- a/Swiften/Serializer/AuthSuccessSerializer.h
+++ b/Swiften/Serializer/AuthSuccessSerializer.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/AuthSuccess.h>
#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(std::shared_ptr<ToplevelElement> element) const;
+ };
}
diff --git a/Swiften/Serializer/ComponentHandshakeSerializer.cpp b/Swiften/Serializer/ComponentHandshakeSerializer.cpp
index 0611b17..0e94917 100644
--- a/Swiften/Serializer/ComponentHandshakeSerializer.cpp
+++ b/Swiften/Serializer/ComponentHandshakeSerializer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,9 +13,9 @@ namespace Swift {
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>");
+SafeByteArray ComponentHandshakeSerializer::serialize(std::shared_ptr<ToplevelElement> element) const {
+ std::shared_ptr<ComponentHandshake> handshake(std::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..d6ee156 100644
--- a/Swiften/Serializer/ComponentHandshakeSerializer.h
+++ b/Swiften/Serializer/ComponentHandshakeSerializer.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/ComponentHandshake.h>
#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(std::shared_ptr<ToplevelElement> element) const;
+ };
}
diff --git a/Swiften/Serializer/CompressFailureSerializer.h b/Swiften/Serializer/CompressFailureSerializer.h
index e20d458..045c7d2 100644
--- a/Swiften/Serializer/CompressFailureSerializer.h
+++ b/Swiften/Serializer/CompressFailureSerializer.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/CompressFailure.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(std::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..9deb702 100644
--- a/Swiften/Serializer/CompressRequestSerializer.cpp
+++ b/Swiften/Serializer/CompressRequestSerializer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,13 +13,13 @@ namespace Swift {
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>");
+SafeByteArray CompressRequestSerializer::serialize(std::shared_ptr<ToplevelElement> element) const {
+ std::shared_ptr<CompressRequest> compressRequest(std::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;
+bool CompressRequestSerializer::canSerialize(std::shared_ptr<ToplevelElement> element) const {
+ return std::dynamic_pointer_cast<CompressRequest>(element) != nullptr;
}
}
diff --git a/Swiften/Serializer/CompressRequestSerializer.h b/Swiften/Serializer/CompressRequestSerializer.h
index 2ff349d..d768023 100644
--- a/Swiften/Serializer/CompressRequestSerializer.h
+++ b/Swiften/Serializer/CompressRequestSerializer.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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(std::shared_ptr<ToplevelElement> element) const;
+ virtual bool canSerialize(std::shared_ptr<ToplevelElement> element) const;
+ };
}
diff --git a/Swiften/Serializer/ElementSerializer.h b/Swiften/Serializer/ElementSerializer.h
index 8b24f2c..3bef58b 100644
--- a/Swiften/Serializer/ElementSerializer.h
+++ b/Swiften/Serializer/ElementSerializer.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Elements/ToplevelElement.h>
#include <Swiften/Base/SafeByteArray.h>
+#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(std::shared_ptr<ToplevelElement> element) const = 0;
+ virtual bool canSerialize(std::shared_ptr<ToplevelElement> element) const = 0;
+ };
}
diff --git a/Swiften/Serializer/EnableStreamManagementSerializer.h b/Swiften/Serializer/EnableStreamManagementSerializer.h
index f837e9f..ba92843 100644
--- a/Swiften/Serializer/EnableStreamManagementSerializer.h
+++ b/Swiften/Serializer/EnableStreamManagementSerializer.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/EnableStreamManagement.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(std::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..b5f4119 100644
--- a/Swiften/Serializer/GenericElementSerializer.h
+++ b/Swiften/Serializer/GenericElementSerializer.h
@@ -1,24 +1,24 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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(std::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(std::shared_ptr<ToplevelElement> element) const {
+ return !!std::dynamic_pointer_cast<T>(element);
+ }
+ };
}
diff --git a/Swiften/Serializer/GenericPayloadSerializer.h b/Swiften/Serializer/GenericPayloadSerializer.h
index f02ccda..804ccaf 100644
--- a/Swiften/Serializer/GenericPayloadSerializer.h
+++ b/Swiften/Serializer/GenericPayloadSerializer.h
@@ -1,28 +1,28 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#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(std::shared_ptr<Payload> element) const {
+ return serializePayload(std::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(std::shared_ptr<Payload> element) const {
+ return !!std::dynamic_pointer_cast<PAYLOAD_TYPE>(element);
+ }
- virtual std::string serializePayload(boost::shared_ptr<PAYLOAD_TYPE>) const = 0;
- };
+ virtual std::string serializePayload(std::shared_ptr<PAYLOAD_TYPE>) const = 0;
+ };
}
diff --git a/Swiften/Serializer/GenericStanzaSerializer.h b/Swiften/Serializer/GenericStanzaSerializer.h
index 319ea67..badd55c 100644
--- a/Swiften/Serializer/GenericStanzaSerializer.h
+++ b/Swiften/Serializer/GenericStanzaSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::shared_ptr<ToplevelElement> element) const {
+ return dynamic_cast<STANZA_TYPE*>(element.get()) != nullptr;
+ }
- virtual void setStanzaSpecificAttributes(
- boost::shared_ptr<ToplevelElement> stanza,
- XMLElement& element) const {
- setStanzaSpecificAttributesGeneric(
- boost::dynamic_pointer_cast<STANZA_TYPE>(stanza), element);
- }
+ virtual void setStanzaSpecificAttributes(
+ std::shared_ptr<ToplevelElement> stanza,
+ XMLElement& element) const {
+ setStanzaSpecificAttributesGeneric(
+ std::dynamic_pointer_cast<STANZA_TYPE>(stanza), element);
+ }
- virtual void setStanzaSpecificAttributesGeneric(
- boost::shared_ptr<STANZA_TYPE>,
- XMLElement&) const = 0;
- };
+ virtual void setStanzaSpecificAttributesGeneric(
+ std::shared_ptr<STANZA_TYPE>,
+ XMLElement&) const = 0;
+ };
}
diff --git a/Swiften/Serializer/IQSerializer.h b/Swiften/Serializer/IQSerializer.h
index 055ff86..1bdbb07 100644
--- a/Swiften/Serializer/IQSerializer.h
+++ b/Swiften/Serializer/IQSerializer.h
@@ -1,35 +1,35 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericStanzaSerializer.h>
#include <Swiften/Elements/IQ.h>
+#include <Swiften/Serializer/GenericStanzaSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/optional.hpp>
-
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(
+ std::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 e185f8d..774d9a3 100644
--- a/Swiften/Serializer/MessageSerializer.cpp
+++ b/Swiften/Serializer/MessageSerializer.cpp
@@ -1,33 +1,34 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/MessageSerializer.h>
+
#include <Swiften/Serializer/XML/XMLElement.h>
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");
- }
+ std::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 25adc52..812b647 100644
--- a/Swiften/Serializer/MessageSerializer.h
+++ b/Swiften/Serializer/MessageSerializer.h
@@ -1,27 +1,27 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericStanzaSerializer.h>
#include <Swiften/Elements/Message.h>
-
-#include <boost/optional.hpp>
+#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(
+ std::shared_ptr<Message> message,
+ XMLElement& element) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializer.h b/Swiften/Serializer/PayloadSerializer.h
index 696ec91..fe14e3d 100644
--- a/Swiften/Serializer/PayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializer.h
@@ -1,24 +1,24 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
#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(std::shared_ptr<Payload>) const = 0;
+ virtual std::string serialize(std::shared_ptr<Payload>) const = 0;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializerCollection.cpp b/Swiften/Serializer/PayloadSerializerCollection.cpp
index 7923c65..114512e 100644
--- a/Swiften/Serializer/PayloadSerializerCollection.cpp
+++ b/Swiften/Serializer/PayloadSerializerCollection.cpp
@@ -1,13 +1,15 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/bind.hpp>
+#include <Swiften/Serializer/PayloadSerializerCollection.h>
+
#include <algorithm>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <boost/bind.hpp>
+
#include <Swiften/Serializer/PayloadSerializer.h>
namespace Swift {
@@ -15,19 +17,22 @@ namespace Swift {
PayloadSerializerCollection::PayloadSerializerCollection() {
}
+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);
+PayloadSerializer* PayloadSerializerCollection::getPayloadSerializer(std::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 : nullptr);
}
}
diff --git a/Swiften/Serializer/PayloadSerializerCollection.h b/Swiften/Serializer/PayloadSerializerCollection.h
index d0cf20e..53b3135 100644
--- a/Swiften/Serializer/PayloadSerializerCollection.h
+++ b/Swiften/Serializer/PayloadSerializerCollection.h
@@ -1,30 +1,30 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <vector>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Payload.h>
namespace Swift {
- class PayloadSerializer;
-
+ class PayloadSerializer;
- class SWIFTEN_API PayloadSerializerCollection {
- public:
- PayloadSerializerCollection();
+ class SWIFTEN_API PayloadSerializerCollection {
+ public:
+ PayloadSerializerCollection();
+ virtual ~PayloadSerializerCollection();
- void addSerializer(PayloadSerializer* factory);
- void removeSerializer(PayloadSerializer* factory);
- PayloadSerializer* getPayloadSerializer(boost::shared_ptr<Payload>) const;
+ void addSerializer(PayloadSerializer* factory);
+ void removeSerializer(PayloadSerializer* factory);
+ PayloadSerializer* getPayloadSerializer(std::shared_ptr<Payload>) const;
- private:
- std::vector<PayloadSerializer*> serializers_;
- };
+ private:
+ std::vector<PayloadSerializer*> serializers_;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/BlockSerializer.h b/Swiften/Serializer/PayloadSerializers/BlockSerializer.h
index 48c8004..f034c46 100644
--- a/Swiften/Serializer/PayloadSerializers/BlockSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/BlockSerializer.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/JID/JID.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(std::shared_ptr<BLOCK_ELEMENT> payload) const {
+ XMLElement element(tag, "urn:xmpp:blocking");
+ const std::vector<JID>& items = payload->getItems();
+ for (const auto& i : items) {
+ std::shared_ptr<XMLElement> item = std::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 9ecc434..faad411 100644
--- a/Swiften/Serializer/PayloadSerializers/BodySerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/BodySerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,18 +7,18 @@
#pragma once
#include <Swiften/Base/API.h>
+#include <Swiften/Elements/Body.h>
#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
-#include <Swiften/Elements/Body.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(std::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 7909cb2..78bb0eb 100644
--- a/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp
@@ -1,41 +1,40 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
-
+#include <Swiften/Serializer/XML/XMLElement.h>
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(std::shared_ptr<Bytestreams> bytestreams) const {
+ XMLElement queryElement("query", "http://jabber.org/protocol/bytestreams");
+ queryElement.setAttribute("sid", bytestreams->getStreamID());
+ for (const auto& streamHost : bytestreams->getStreamHosts()) {
+ std::shared_ptr<XMLElement> streamHostElement(new XMLElement("streamhost"));
+ streamHostElement->setAttribute("host", streamHost.host);
+ streamHostElement->setAttribute("jid", streamHost.jid.toString());
+ streamHostElement->setAttribute("port", boost::lexical_cast<std::string>(streamHost.port));
+ queryElement.addNode(streamHostElement);
+ }
+
+ if (bytestreams->getUsedStreamHost()) {
+ std::shared_ptr<XMLElement> streamHostElement(new XMLElement("streamhost-used"));
+ streamHostElement->setAttribute("jid", *bytestreams->getUsedStreamHost());
+ queryElement.addNode(streamHostElement);
+ }
+ return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.h b/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.h
index 561a38f..533be61 100644
--- a/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,16 +7,16 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/Bytestreams.h>
+#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(std::shared_ptr<Bytestreams>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.cpp
index 87c45f6..19f8a27 100644
--- a/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.cpp
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Serializer/XML/XMLElement.h>
@@ -15,12 +15,12 @@ namespace Swift {
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();
+std::string CapsInfoSerializer::serializePayload(std::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();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.h b/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.h
index f09b3be..ac168e4 100644
--- a/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/CapsInfoSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/CapsInfo.h>
+#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(std::shared_ptr<CapsInfo>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.cpp
index e39d005..9938bd9 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::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..a6bf16f 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::shared_ptr<CarbonsDisable>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.cpp
index 0bc3822..424c6fc 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::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..eb0f6fa 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::shared_ptr<CarbonsEnable>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.cpp
index 1e77470..fb92017 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::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..d148a26 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::shared_ptr<CarbonsPrivate>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.cpp
index bf63a69..cc87929 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.cpp
@@ -1,26 +1,26 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.h>
-#include <boost/make_shared.hpp>
+#include <memory>
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(std::shared_ptr<CarbonsReceived> received) const {
+ XMLElement element("received", "urn:xmpp:carbons:2");
+ if (received->getForwarded()) {
+ element.addNode(std::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 9ce928d..017b187 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,21 +9,21 @@
#include <Swiften/Base/API.h>
#include <Swiften/Elements/CarbonsReceived.h>
#include <Swiften/Elements/Forwarded.h>
-#include <Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h>
#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#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(std::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..986edcb 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::shared_ptr<CarbonsSent> sent) const {
+ XMLElement element("sent", "urn:xmpp:carbons:2");
+ if (sent->getForwarded()) {
+ element.addNode(std::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 03d10ca..16db398 100644
--- a/Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.h
@@ -1,31 +1,31 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/CarbonsSent.h>
#include <Swiften/Elements/Forwarded.h>
-#include <Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h>
#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#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(std::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..17f8be0 100644
--- a/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -11,17 +11,17 @@ namespace Swift {
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 ChatStateSerializer::serializePayload(std::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;
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.h b/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.h
index 26b6d68..3b9f315 100644
--- a/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/ChatStateSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/ChatState.h>
+#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(std::shared_ptr<ChatState> error) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp
index 6cd8230..25a70f6 100644
--- a/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp
@@ -1,96 +1,94 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/CommandSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
+#include <Swiften/Serializer/XML/XMLTextNode.h>
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(std::shared_ptr<Command> command) const {
+ XMLElement commandElement("command", "http://jabber.org/protocol/commands");
+ commandElement.setAttribute("node", command->getNode());
- if (!command->getSessionID().empty()) {
- commandElement.setAttribute("sessionid", command->getSessionID());
- }
+ 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 += ">";
+ for (const auto& action : command->getAvailableActions()) {
+ actions += "<" + actionToString(action) + "/>";
+ }
+ actions += "</actions>";
+ commandElement.addNode(std::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);
- }
+ for (const auto& note : command->getNotes()) {
+ std::shared_ptr<XMLElement> noteElement(new XMLElement("note"));
+ std::string type;
+ switch (note.type) {
+ case Command::Note::Info: type = "info"; break;
+ case Command::Note::Warn: type = "warn"; break;
+ case Command::Note::Error: type = "error"; break;
+ }
+ if (!type.empty()) {
+ noteElement->setAttribute("type", type);
+ }
+ noteElement->addNode(std::make_shared<XMLTextNode>(note.note));
+ commandElement.addNode(noteElement);
+ }
- Form::ref form = command->getForm();
- if (form) {
- commandElement.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
- }
- return commandElement.serialize();
+ Form::ref form = command->getForm();
+ if (form) {
+ commandElement.addNode(std::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
+ }
+ return commandElement.serialize();
}
std::string CommandSerializer::actionToString(Command::Action action) const {
- std::string string;
- switch (action) {
- case Command::Cancel: string = "cancel"; break;
- case Command::Execute: string = "execute"; break;
- case Command::Complete: string = "complete"; break;
- case Command::Prev: string = "prev"; break;
- case Command::Next: string = "next"; break;
- case Command::NoAction: break;
- }
- 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 34b8d17..e1f0b24 100644
--- a/Swiften/Serializer/PayloadSerializers/CommandSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/CommandSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,17 +7,17 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/Command.h>
+#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(std::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 8d506f8..b168fdc 100644
--- a/Swiften/Serializer/PayloadSerializers/DelaySerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/DelaySerializer.cpp
@@ -1,30 +1,31 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/DelaySerializer.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/date_time/posix_time/posix_time.hpp>
+#include <Swiften/Base/DateTime.h>
#include <Swiften/Base/String.h>
#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Base/DateTime.h>
namespace Swift {
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();
+std::string DelaySerializer::serializePayload(std::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();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/DelaySerializer.h b/Swiften/Serializer/PayloadSerializers/DelaySerializer.h
index bfe53c3..86fde42 100644
--- a/Swiften/Serializer/PayloadSerializers/DelaySerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/DelaySerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,16 +7,16 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/Delay.h>
+#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(std::shared_ptr<Delay>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.cpp b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.cpp
index eeb0d90..8183b7f 100644
--- a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.cpp
@@ -4,19 +4,25 @@
* See http://www.opensource.org/licenses/bsd-license.php for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Base/Log.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
DeliveryReceiptRequestSerializer::DeliveryReceiptRequestSerializer() : GenericPayloadSerializer<DeliveryReceiptRequest>() {
}
-std::string DeliveryReceiptRequestSerializer::serializePayload(boost::shared_ptr<DeliveryReceiptRequest> /* request*/) const {
- XMLElement requestXML("request", "urn:xmpp:receipts");
- return requestXML.serialize();
+std::string DeliveryReceiptRequestSerializer::serializePayload(std::shared_ptr<DeliveryReceiptRequest> /* request*/) const {
+ XMLElement requestXML("request", "urn:xmpp:receipts");
+ return requestXML.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.h b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.h
index 784d9e1..a3e76eb 100644
--- a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.h
@@ -4,17 +4,23 @@
* See http://www.opensource.org/licenses/bsd-license.php for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
-#include <Swiften/Elements/DeliveryReceiptRequest.h>
#include <Swiften/Base/API.h>
+#include <Swiften/Elements/DeliveryReceiptRequest.h>
+#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(std::shared_ptr<DeliveryReceiptRequest> request) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.cpp b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.cpp
index a9033b2..d392d17 100644
--- a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.cpp
@@ -4,7 +4,14 @@
* See http://www.opensource.org/licenses/bsd-license.php for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.h>
+
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
@@ -12,10 +19,10 @@ namespace Swift {
DeliveryReceiptSerializer::DeliveryReceiptSerializer() : GenericPayloadSerializer<DeliveryReceipt>() {
}
-std::string DeliveryReceiptSerializer::serializePayload(boost::shared_ptr<DeliveryReceipt> receipt) const {
- XMLElement received("received", "urn:xmpp:receipts");
- received.setAttribute("id", receipt->getReceivedID());
- return received.serialize();
+std::string DeliveryReceiptSerializer::serializePayload(std::shared_ptr<DeliveryReceipt> receipt) const {
+ 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 92a531a..6153de1 100644
--- a/Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.h
@@ -4,17 +4,23 @@
* See http://www.opensource.org/licenses/bsd-license.php for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/DeliveryReceipt.h>
+#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(std::shared_ptr<DeliveryReceipt> receipt) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp b/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp
index 57f47e8..06cad2b 100644
--- a/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp
@@ -1,48 +1,46 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
namespace Swift {
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();
+std::string DiscoInfoSerializer::serializePayload(std::shared_ptr<DiscoInfo> discoInfo) const {
+ XMLElement queryElement("query", "http://jabber.org/protocol/disco#info");
+ if (!discoInfo->getNode().empty()) {
+ queryElement.setAttribute("node", discoInfo->getNode());
+ }
+ for (const auto& identity : discoInfo->getIdentities()) {
+ std::shared_ptr<XMLElement> identityElement(new XMLElement("identity"));
+ if (!identity.getLanguage().empty()) {
+ identityElement->setAttribute("xml:lang", identity.getLanguage());
+ }
+ identityElement->setAttribute("category", identity.getCategory());
+ identityElement->setAttribute("name", identity.getName());
+ identityElement->setAttribute("type", identity.getType());
+ queryElement.addNode(identityElement);
+ }
+ for (const auto& feature : discoInfo->getFeatures()) {
+ std::shared_ptr<XMLElement> featureElement(new XMLElement("feature"));
+ featureElement->setAttribute("var", feature);
+ queryElement.addNode(featureElement);
+ }
+ for (const auto& extension : discoInfo->getExtensions()) {
+ queryElement.addNode(std::make_shared<XMLRawTextNode>(FormSerializer().serialize(extension)));
+ }
+ return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h b/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h
index d248f03..21648d6 100644
--- a/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/DiscoInfo.h>
+#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(std::shared_ptr<DiscoInfo>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp
index 91a467c..a8eafef 100644
--- a/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.cpp
@@ -1,14 +1,13 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
@@ -16,21 +15,21 @@ namespace Swift {
DiscoItemsSerializer::DiscoItemsSerializer() : GenericPayloadSerializer<DiscoItems>() {
}
-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();
+std::string DiscoItemsSerializer::serializePayload(std::shared_ptr<DiscoItems> discoItems) const {
+ XMLElement queryElement("query", "http://jabber.org/protocol/disco#items");
+ if (!discoItems->getNode().empty()) {
+ queryElement.setAttribute("node", discoItems->getNode());
+ }
+ for (const auto& item : discoItems->getItems()) {
+ std::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
+ itemElement->setAttribute("name", item.getName());
+ itemElement->setAttribute("jid", item.getJID());
+ if (!item.getNode().empty()) {
+ itemElement->setAttribute("node", item.getNode());
+ }
+ queryElement.addNode(itemElement);
+ }
+ return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.h b/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.h
index 8af94d6..ca88cb0 100644
--- a/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/DiscoItemsSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,15 +7,15 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/DiscoItems.h>
+#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(std::shared_ptr<DiscoItems>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/ErrorSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ErrorSerializer.cpp
index 8bf1333..26686f0 100644
--- a/Swiften/Serializer/PayloadSerializers/ErrorSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/ErrorSerializer.cpp
@@ -1,70 +1,71 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/ErrorSerializer.h>
-#include <Swiften/Serializer/XML/XMLTextNode.h>
+
#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
ErrorSerializer::ErrorSerializer(PayloadSerializerCollection* serializers) : GenericPayloadSerializer<ErrorPayload>(), serializers(serializers) {
}
-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 ErrorSerializer::serializePayload(std::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 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 fe78f8a..df7791e 100644
--- a/Swiften/Serializer/PayloadSerializers/ErrorSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/ErrorSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,19 +7,19 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/ErrorPayload.h>
+#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(std::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 633ead6..f723ead 100644
--- a/Swiften/Serializer/PayloadSerializers/FormSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/FormSerializer.cpp
@@ -1,210 +1,209 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <iostream>
+#include <memory>
#include <string>
-#include <Swiften/Base/String.h>
#include <Swiften/Base/Algorithm.h>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Serializer/XML/XMLTextNode.h>
+#include <Swiften/Base/String.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+#include <Swiften/Serializer/XML/XMLTextNode.h>
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(std::shared_ptr<FormField> field, std::shared_ptr<XMLElement> parent) {
+ std::string value = std::dynamic_pointer_cast<T>(field)->getValue();
+ if (!value.empty()) {
+ std::shared_ptr<XMLElement> valueElement(new XMLElement("value"));
+ valueElement->addNode(XMLTextNode::create(value));
+ parent->addNode(valueElement);
+ }
+ }
}
namespace Swift {
FormSerializer::FormSerializer() : GenericPayloadSerializer<Form>() {}
-std::string FormSerializer::serializePayload(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();
+std::string FormSerializer::serializePayload(std::shared_ptr<Form> form) const {
+ if (!form) {
+ return "";
+ }
+
+ std::shared_ptr<XMLElement> formElement(new XMLElement("x", "jabber:x:data"));
+ std::string type;
+ switch (form->getType()) {
+ case Form::FormType: type = "form"; break;
+ case Form::SubmitType: type = "submit"; break;
+ case Form::CancelType: type = "cancel"; break;
+ case Form::ResultType: type = "result"; break;
+ }
+ formElement->setAttribute("type", type);
+ if (!form->getTitle().empty()) {
+ multiLineify(form->getTitle(), "title", formElement);
+ }
+ if (!form->getInstructions().empty()) {
+ multiLineify(form->getInstructions(), "instructions", formElement);
+ }
+ for (const auto& page : form->getPages()) {
+ formElement->addNode(pageToXML(page));
+ }
+ for (const auto& field : form->getFields()) {
+ formElement->addNode(fieldToXML(field, true));
+ }
+ if (!form->getReportedFields().empty()) {
+ std::shared_ptr<XMLElement> reportedElement(new XMLElement("reported"));
+ for (const auto& field : form->getReportedFields()) {
+ reportedElement->addNode(fieldToXML(field, true));
+ }
+ formElement->addNode(reportedElement);
+ }
+
+ for (const auto& item : form->getItems()) {
+ std::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
+ for (const auto& field : item) {
+ itemElement->addNode(fieldToXML(field, false));
+ }
+ formElement->addNode(itemElement);
+ }
+
+ for (const auto& text : form->getTextElements()) {
+ formElement->addNode(textToXML(text));
+ }
+
+ for (const auto& 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;
+std::shared_ptr<XMLElement> FormSerializer::textToXML(std::shared_ptr<FormText> text) const {
+ std::shared_ptr<XMLElement> textElement (new XMLElement("text"));
+ textElement->addNode(std::make_shared<XMLTextNode>(text->getTextString()));
+ return textElement;
}
-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;
+std::shared_ptr<XMLElement> FormSerializer::fieldRefToXML(const std::string& ref) const {
+ std::shared_ptr<XMLElement> fieldRefElement(new XMLElement("fieldref"));
+ fieldRefElement->setAttribute("var", ref);
+ return fieldRefElement;
}
-boost::shared_ptr<XMLElement> FormSerializer::pageToXML(boost::shared_ptr<FormPage> page) const {
- boost::shared_ptr<XMLElement> pageElement(new XMLElement("page"));
- pageElement->setAttribute("xmlns", page->getXMLNS());
- 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;
+std::shared_ptr<XMLElement> FormSerializer::pageToXML(std::shared_ptr<FormPage> page) const {
+ std::shared_ptr<XMLElement> pageElement(new XMLElement("page"));
+ pageElement->setAttribute("xmlns", "http://jabber.org/protocol/xdata-layout");
+ if (!page->getLabel().empty()) {
+ pageElement->setAttribute("label", page->getLabel());
+ }
+ for (const auto& text : page->getTextElements()) {
+ pageElement->addNode(textToXML(text));
+ }
+ for (const auto& field : page->getFields()) {
+ pageElement->addNode(fieldRefToXML(field->getName()));
+ fields_.push_back(field);
+ }
+ for (const auto& reportedRef: page->getReportedRefs()) {
+ (void)reportedRef;
+ pageElement->addNode(std::make_shared<XMLElement>("reportedref"));
+ }
+ for (const auto& 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;
+std::shared_ptr<XMLElement> FormSerializer::sectionToXML(std::shared_ptr<FormSection> section) const {
+ std::shared_ptr<XMLElement> sectionElement(new XMLElement("section"));
+ if (!section->getLabel().empty()) {
+ sectionElement->setAttribute("label", section->getLabel());
+ }
+ for (const auto& text : section->getTextElements()) {
+ sectionElement->addNode(textToXML(text));
+ }
+ for (const auto& field : section->getFields()) {
+ sectionElement->addNode(fieldRefToXML(field->getName()));
+ fields_.push_back(field);
+ }
+ for (const auto& reportedRef : section->getReportedRefs()) {
+ (void)reportedRef;
+ sectionElement->addNode(std::make_shared<XMLElement>("reportedref"));
+ }
+ for (const auto& 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;
+std::shared_ptr<XMLElement> FormSerializer::fieldToXML(std::shared_ptr<FormField> field, bool withTypeAttribute) const {
+ std::shared_ptr<XMLElement> fieldElement(new XMLElement("field"));
+ if (!field->getName().empty()) {
+ fieldElement->setAttribute("var", field->getName());
+ }
+ if (!field->getLabel().empty()) {
+ fieldElement->setAttribute("label", field->getLabel());
+ }
+ if (field->getRequired()) {
+ fieldElement->addNode(std::make_shared<XMLElement>("required"));
+ }
+ if (!field->getDescription().empty()) {
+ std::shared_ptr<XMLElement> descriptionElement(new XMLElement("desc"));
+ descriptionElement->addNode(std::make_shared<XMLTextNode>(field->getDescription()));
+ fieldElement->addNode(descriptionElement);
+ }
+
+ // Set the value and type
+ std::string fieldType;
+ switch (field->getType()) {
+ case FormField::UnknownType: fieldType = ""; break;
+ case FormField::BooleanType: fieldType = "boolean"; break;
+ case FormField::FixedType: fieldType = "fixed"; break;
+ case FormField::HiddenType: fieldType = "hidden"; break;
+ case FormField::ListSingleType: fieldType = "list-single"; break;
+ case FormField::TextMultiType: fieldType = "text-multi"; break;
+ case FormField::TextPrivateType: fieldType = "text-private"; break;
+ case FormField::TextSingleType: fieldType = "text-single"; break;
+ case FormField::JIDSingleType: fieldType = "jid-single"; break;
+ case FormField::JIDMultiType: fieldType = "jid-multi"; break;
+ case FormField::ListMultiType: fieldType = "list-multi"; break;
+ }
+ if (!fieldType.empty() && withTypeAttribute) {
+ fieldElement->setAttribute("type", fieldType);
+ }
+ for (const auto& value : field->getValues()) {
+ std::shared_ptr<XMLElement> valueElement = std::make_shared<XMLElement>("value");
+ valueElement->addNode(std::make_shared<XMLTextNode>(value));
+ fieldElement->addNode(valueElement);
+ }
+
+ for (const auto& option : field->getOptions()) {
+ std::shared_ptr<XMLElement> optionElement(new XMLElement("option"));
+ if (!option.label.empty()) {
+ optionElement->setAttribute("label", option.label);
+ }
+
+ std::shared_ptr<XMLElement> valueElement(new XMLElement("value"));
+ valueElement->addNode(XMLTextNode::create(option.value));
+ optionElement->addNode(valueElement);
+ fieldElement->addNode(optionElement);
+ }
+ return fieldElement;
}
-void FormSerializer::multiLineify(const std::string& text, const std::string& elementName, 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);
- }
+void FormSerializer::multiLineify(const std::string& text, const std::string& elementName, std::shared_ptr<XMLElement> element) const {
+ std::string unRdText(text);
+ erase(unRdText, '\r');
+ std::vector<std::string> lines = String::split(unRdText, '\n');
+ for (const auto& line : lines) {
+ std::shared_ptr<XMLElement> lineElement(new XMLElement(elementName));
+ lineElement->addNode(std::make_shared<XMLTextNode>(line));
+ element->addNode(lineElement);
+ }
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/FormSerializer.h b/Swiften/Serializer/PayloadSerializers/FormSerializer.h
index ad3f472..590fce4 100644
--- a/Swiften/Serializer/PayloadSerializers/FormSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/FormSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,27 +7,27 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/Form.h>
#include <Swiften/Elements/FormField.h>
#include <Swiften/Elements/FormPage.h>
#include <Swiften/Elements/FormSection.h>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
#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(std::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:
+ std::shared_ptr<XMLElement> textToXML(std::shared_ptr<FormText> textElement) const;
+ std::shared_ptr<XMLElement> fieldRefToXML(const std::string& ref) const;
+ std::shared_ptr<XMLElement> reportedRefToXML(std::shared_ptr<FormReportedRef> reportedRef) const;
+ std::shared_ptr<XMLElement> pageToXML(std::shared_ptr<FormPage> page) const;
+ std::shared_ptr<XMLElement> sectionToXML(std::shared_ptr<FormSection> section) const;
+ std::shared_ptr<XMLElement> fieldToXML(std::shared_ptr<FormField> field, bool withTypeAttribute) const;
+ void multiLineify(const std::string& text, const std::string& elementName, std::shared_ptr<XMLElement> parent) const;
+ mutable std::vector<std::shared_ptr<FormField> > fields_;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.cpp
index 12b4208..58660d7 100644
--- a/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.cpp
@@ -1,25 +1,27 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h>
+
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swiften/Elements/Delay.h>
#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Presence.h>
-#include <Swiften/Elements/Delay.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/GenericStanzaSerializer.h>
#include <Swiften/Serializer/IQSerializer.h>
#include <Swiften/Serializer/MessageSerializer.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/DelaySerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h>
#include <Swiften/Serializer/PresenceSerializer.h>
-
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -29,30 +31,30 @@ ForwardedSerializer::ForwardedSerializer(PayloadSerializerCollection* serializer
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();
+std::string ForwardedSerializer::serializePayload(std::shared_ptr<Forwarded> payload) const {
+ if (!payload) {
+ return "";
+ }
+
+ XMLElement element("forwarded", "urn:xmpp:forward:0");
+
+ if (payload->getDelay()) {
+ element.addNode(std::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*/
+ std::shared_ptr<IQ> iq;
+ std::shared_ptr<Message> message;
+ std::shared_ptr<Presence> presence;
+ const std::string ns = "jabber:client";
+ if ((iq = std::dynamic_pointer_cast<IQ>(payload->getStanza()))) {
+ element.addNode(std::make_shared<XMLRawTextNode>(safeByteArrayToString(IQSerializer(serializers_).serialize(iq, ns))));
+ } else if ((message = std::dynamic_pointer_cast<Message>(payload->getStanza()))) {
+ element.addNode(std::make_shared<XMLRawTextNode>(safeByteArrayToString(MessageSerializer(serializers_).serialize(message, ns))));
+ } else if ((presence = std::dynamic_pointer_cast<Presence>(payload->getStanza()))) {
+ element.addNode(std::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 5cdd4d1..f3eb6fb 100644
--- a/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h
@@ -1,28 +1,29 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/Forwarded.h>
#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(std::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 c84ee04..cf0b54c 100644
--- a/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp
+++ b/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp
@@ -1,14 +1,14 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
-#include <Swiften/Base/foreach.h>
+
+#include <Swiften/Elements/BlockListPayload.h>
#include <Swiften/Elements/BlockPayload.h>
#include <Swiften/Elements/UnblockPayload.h>
-#include <Swiften/Elements/BlockListPayload.h>
#include <Swiften/Serializer/PayloadSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/BlockSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/BodySerializer.h>
@@ -85,96 +85,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 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 PubSubSerializer(this));
+ serializers_.push_back(new PubSubEventSerializer(this));
+ serializers_.push_back(new PubSubOwnerPubSubSerializer(this));
+ serializers_.push_back(new PubSubErrorSerializer());
- serializers_.push_back(new PubSubSerializer(this));
- serializers_.push_back(new PubSubEventSerializer(this));
- serializers_.push_back(new PubSubOwnerPubSubSerializer(this));
- serializers_.push_back(new PubSubErrorSerializer());
+ serializers_.push_back(new ResultSetSerializer());
+ serializers_.push_back(new ForwardedSerializer(this));
+ serializers_.push_back(new MAMResultSerializer(this));
+ serializers_.push_back(new MAMQuerySerializer());
+ serializers_.push_back(new MAMFinSerializer());
- serializers_.push_back(new ResultSetSerializer());
- serializers_.push_back(new ForwardedSerializer(this));
- serializers_.push_back(new MAMResultSerializer(this));
- serializers_.push_back(new MAMQuerySerializer());
- serializers_.push_back(new MAMFinSerializer());
+ serializers_.push_back(new CarbonsDisableSerializer());
+ serializers_.push_back(new CarbonsEnableSerializer());
+ serializers_.push_back(new CarbonsPrivateSerializer());
+ serializers_.push_back(new CarbonsReceivedSerializer(this));
+ serializers_.push_back(new CarbonsSentSerializer(this));
- serializers_.push_back(new 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));
- serializers_.push_back(new IsodeIQDelegationSerializer(this));
-
- foreach(PayloadSerializer* serializer, serializers_) {
- addSerializer(serializer);
- }
+ for (auto serializer : serializers_) {
+ addSerializer(serializer);
+ }
}
FullPayloadSerializerCollection::~FullPayloadSerializerCollection() {
- foreach(PayloadSerializer* serializer, serializers_) {
- removeSerializer(serializer);
- delete serializer;
- }
- serializers_.clear();
+ for (auto 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 a9e7afa..e41ff8c 100644
--- a/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp
@@ -1,17 +1,16 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/IBBSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <cassert>
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/StringCodecs/Base64.h>
@@ -21,36 +20,36 @@ namespace Swift {
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 "";
+std::string IBBSerializer::serializePayload(std::shared_ptr<IBB> ibb) const {
+ switch(ibb->getAction()) {
+ case IBB::Data: {
+ XMLElement ibbElement("data", "http://jabber.org/protocol/ibb");
+ ibbElement.setAttribute("sid", ibb->getStreamID());
+ if (ibb->getSequenceNumber() >= 0) {
+ ibbElement.setAttribute("seq", boost::lexical_cast<std::string>(ibb->getSequenceNumber()));
+ }
+ ibbElement.addNode(std::make_shared<XMLTextNode>(Base64::encode(ibb->getData())));
+ return ibbElement.serialize();
+ }
+ case IBB::Open: {
+ XMLElement ibbElement("open", "http://jabber.org/protocol/ibb");
+ ibbElement.setAttribute("sid", ibb->getStreamID());
+ switch (ibb->getStanzaType()) {
+ case IBB::IQStanza: ibbElement.setAttribute("stanza", "iq"); break;
+ case IBB::MessageStanza: ibbElement.setAttribute("stanza", "message"); break;
+ }
+ assert(ibb->getBlockSize() > 0);
+ ibbElement.setAttribute("block-size", boost::lexical_cast<std::string>(ibb->getBlockSize()));
+ return ibbElement.serialize();
+ }
+ 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 06e658a..0ef1680 100644
--- a/Swiften/Serializer/PayloadSerializers/IBBSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/IBBSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/IBB.h>
+#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(std::shared_ptr<IBB>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/IdleSerializer.h b/Swiften/Serializer/PayloadSerializers/IdleSerializer.h
index 2c4150e..4e1a953 100644
--- a/Swiften/Serializer/PayloadSerializers/IdleSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/IdleSerializer.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,17 +13,17 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
-#include <Swiften/Elements/Idle.h>
#include <Swiften/Base/DateTime.h>
+#include <Swiften/Elements/Idle.h>
+#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(std::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 2fdcab2..04b7c56 100644
--- a/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp
@@ -1,113 +1,111 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
namespace Swift {
InBandRegistrationPayloadSerializer::InBandRegistrationPayloadSerializer() {
}
-std::string InBandRegistrationPayloadSerializer::serializePayload(boost::shared_ptr<InBandRegistrationPayload> registration) const {
- XMLElement registerElement("query", "jabber:iq:register");
+std::string InBandRegistrationPayloadSerializer::serializePayload(std::shared_ptr<InBandRegistrationPayload> registration) const {
+ XMLElement registerElement("query", "jabber:iq:register");
- if (registration->isRegistered()) {
- registerElement.addNode(XMLElement::ref(new XMLElement("registered")));
- }
+ if (registration->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(std::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 2a9a21f..d5f6cce 100644
--- a/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,14 +8,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/InBandRegistrationPayload.h>
+#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(std::shared_ptr<InBandRegistrationPayload>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.cpp b/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.cpp
index 7d6c64e..41c824f 100644
--- a/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.cpp
@@ -1,16 +1,17 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -21,13 +22,13 @@ IsodeIQDelegationSerializer::IsodeIQDelegationSerializer(PayloadSerializerCollec
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();
+std::string IsodeIQDelegationSerializer::serializePayload(std::shared_ptr<IsodeIQDelegation> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("delegate", "http://isode.com/iq_delegation");
+ element.addNode(std::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 e760adb..e7cfef9 100644
--- a/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/IsodeIQDelegation.h>
-#include <boost/shared_ptr.hpp>
+#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(std::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 2792a28..39eb149 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp
@@ -5,81 +5,76 @@
*/
/*
-* Copyright (c) 2014 Isode Limited.
-* All rights reserved.v3.
-* See the COPYING file for more information.
-*/
+ * Copyright (c) 2014-2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
#include <Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <boost/smart_ptr/intrusive_ptr.hpp>
+#include <memory>
#include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Serializer/XML/XMLNode.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-
#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h>
-
#include <Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLNode.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
JingleContentPayloadSerializer::JingleContentPayloadSerializer() {
}
-std::string JingleContentPayloadSerializer::serializePayload(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;
+std::string JingleContentPayloadSerializer::serializePayload(std::shared_ptr<JingleContentPayload> payload) const {
+ XMLElement payloadXML("content");
+ payloadXML.setAttribute("creator", creatorToString(payload->getCreator()));
+ payloadXML.setAttribute("name", payload->getName());
+
+ if (!payload->getDescriptions().empty()) {
+ // JingleFileTransferDescription
+ JingleFileTransferDescriptionSerializer ftSerializer;
+ JingleFileTransferDescription::ref filetransfer;
+
+ for (auto&& desc : payload->getDescriptions()) {
+ if ((filetransfer = std::dynamic_pointer_cast<JingleFileTransferDescription>(desc))) {
+ payloadXML.addNode(std::make_shared<XMLRawTextNode>(ftSerializer.serializePayload(filetransfer)));
+ }
+ }
+ }
+
+ if (!payload->getTransports().empty()) {
+ // JingleIBBTransportPayload
+ JingleIBBTransportPayloadSerializer ibbSerializer;
+ JingleIBBTransportPayload::ref ibb;
+
+ // JingleS5BTransportPayload
+ JingleS5BTransportPayloadSerializer s5bSerializer;
+ JingleS5BTransportPayload::ref s5b;
- foreach(JingleTransportPayload::ref transport, payload->getTransports()) {
- 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();
+ for (auto&& transport : payload->getTransports()) {
+ if ((ibb = std::dynamic_pointer_cast<JingleIBBTransportPayload>(transport))) {
+ payloadXML.addNode(std::make_shared<XMLRawTextNode>(ibbSerializer.serializePayload(ibb)));
+ } else if ((s5b = std::dynamic_pointer_cast<JingleS5BTransportPayload>(transport))) {
+ payloadXML.addNode(std::make_shared<XMLRawTextNode>(s5bSerializer.serializePayload(s5b)));
+ }
+ }
+ }
+ return payloadXML.serialize();
}
std::string JingleContentPayloadSerializer::creatorToString(JingleContentPayload::Creator creator) const {
- switch(creator) {
- case JingleContentPayload::InitiatorCreator:
- return "initiator";
- case JingleContentPayload::ResponderCreator:
- return "responder";
- case JingleContentPayload::UnknownCreator:
- SWIFT_LOG(error) << "Serializing unknown creator value.";
- return "ERROR ERROR ERROR";
- }
- assert(false);
- return "";
+ 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 4c74122..825a67c 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,19 +14,19 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/JingleContentPayload.h>
+#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(std::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 bbe1510..27e3b33 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp
@@ -5,39 +5,36 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/DateTime.h>
-#include <Swiften/StringCodecs/Base64.h>
-
-#include <Swiften/Serializer/XML/XMLNode.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-
-#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h>
+#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
JingleFileTransferDescriptionSerializer::JingleFileTransferDescriptionSerializer() {
}
-std::string JingleFileTransferDescriptionSerializer::serializePayload(boost::shared_ptr<JingleFileTransferDescription> payload) const {
- XMLElement description("description", "urn:xmpp:jingle:apps:file-transfer:4");
+std::string JingleFileTransferDescriptionSerializer::serializePayload(std::shared_ptr<JingleFileTransferDescription> payload) const {
+ 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;
+ std::shared_ptr<XMLRawTextNode> fileInfoXML = std::make_shared<XMLRawTextNode>(fileInfoSerializer.serialize(std::make_shared<JingleFileTransferFileInfo>(payload->getFileInfo())));
+ description.addNode(fileInfoXML);
+ return description.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h
index da8fa55..65e757b 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h
@@ -4,21 +4,27 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/JingleFileTransferDescription.h>
+#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(std::shared_ptr<JingleFileTransferDescription>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp
index 1a675d0..35a0a6e 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp
@@ -1,16 +1,15 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/DateTime.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
@@ -22,45 +21,45 @@ namespace Swift {
JingleFileTransferFileInfoSerializer::JingleFileTransferFileInfoSerializer() {
}
-std::string JingleFileTransferFileInfoSerializer::serializePayload(boost::shared_ptr<JingleFileTransferFileInfo> fileInfo) const {
+std::string JingleFileTransferFileInfoSerializer::serializePayload(std::shared_ptr<JingleFileTransferFileInfo> fileInfo) const {
- XMLElement fileElement("file", "");
+ XMLElement fileElement("file", "");
- if (fileInfo->getDate() != stringToDateTime("")) {
- fileElement.addNode(boost::make_shared<XMLElement>("date", "", dateTimeToString(fileInfo->getDate())));
- }
+ if (fileInfo->getDate() != stringToDateTime("")) {
+ fileElement.addNode(std::make_shared<XMLElement>("date", "", dateTimeToString(fileInfo->getDate())));
+ }
- if (!fileInfo->getDescription().empty()) {
- fileElement.addNode(boost::make_shared<XMLElement>("desc", "", fileInfo->getDescription()));
- }
+ if (!fileInfo->getDescription().empty()) {
+ fileElement.addNode(std::make_shared<XMLElement>("desc", "", fileInfo->getDescription()));
+ }
- if (!fileInfo->getMediaType().empty()) {
- fileElement.addNode(boost::make_shared<XMLElement>("media-type", "", fileInfo->getMediaType()));
- }
+ if (!fileInfo->getMediaType().empty()) {
+ fileElement.addNode(std::make_shared<XMLElement>("media-type", "", fileInfo->getMediaType()));
+ }
- if (!fileInfo->getName().empty()) {
- fileElement.addNode(boost::make_shared<XMLElement>("name", "", fileInfo->getName()));
- }
+ if (!fileInfo->getName().empty()) {
+ fileElement.addNode(std::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->getSupportsRangeRequests()) {
+ std::shared_ptr<XMLElement> range = std::make_shared<XMLElement>("range");
+ if (fileInfo->getRangeOffset() != 0) {
+ range->setAttribute("offset", boost::lexical_cast<std::string>(fileInfo->getRangeOffset()));
+ }
+ fileElement.addNode(range);
+ }
- if (fileInfo->getSize() > 0) {
- fileElement.addNode(boost::make_shared<XMLElement>("size", "", boost::lexical_cast<std::string>(fileInfo->getSize())));
- }
+ if (fileInfo->getSize() > 0) {
+ fileElement.addNode(std::make_shared<XMLElement>("size", "", boost::lexical_cast<std::string>(fileInfo->getSize())));
+ }
- foreach (JingleFileTransferFileInfo::HashElementMap::value_type hashElement, fileInfo->getHashes()) {
- 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);
- }
+ for (const auto& hashElement : fileInfo->getHashes()) {
+ std::shared_ptr<XMLElement> hash = std::make_shared<XMLElement>("hash", "urn:xmpp:hashes:1", Base64::encode(hashElement.second));
+ hash->setAttribute("algo", hashElement.first);
+ fileElement.addNode(hash);
+ }
- return fileElement.serialize();
+ return fileElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h
index 0c9f2de..6b80235 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,18 +7,17 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/JingleFileTransferFileInfo.h>
-
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
#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(std::shared_ptr<JingleFileTransferFileInfo>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp
index f416ddc..7629721 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp
@@ -5,44 +5,41 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h>
-#include <string>
#include <map>
+#include <memory>
+#include <string>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Serializer/XML/XMLNode.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.h>
namespace Swift {
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());
+std::string JingleFileTransferHashSerializer::serializePayload(std::shared_ptr<JingleFileTransferHash> payload) const {
+ // code for version urn:xmpp:jingle:apps:file-transfer:2
+ //XMLElement hash("hash", "urn:xmpp:jingle:apps:file-transfer:info:2", payload->getHash());
- // code for version urn:xmpp:jingle:apps:file-transfer:4
- XMLElement checksum("checksum", "urn:xmpp:jingle:apps:file-transfer:4");
+ // 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())));
+ std::shared_ptr<XMLRawTextNode> file = std::make_shared<XMLRawTextNode>(fileSerializer.serialize(std::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 2e75758..bb6eabc 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,17 +14,17 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/JingleFileTransferHash.h>
+#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(std::shared_ptr<JingleFileTransferHash>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp
index 61e093f..9930e44 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp
@@ -4,15 +4,20 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Serializer/XML/XMLNode.h>
#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
@@ -20,14 +25,14 @@ namespace Swift {
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());
+std::string JingleIBBTransportPayloadSerializer::serializePayload(std::shared_ptr<JingleIBBTransportPayload> payload) const {
+ XMLElement payloadXML("transport", "urn:xmpp:jingle:transports:ibb:1");
+ if (payload->getBlockSize()) {
+ payloadXML.setAttribute("block-size", boost::lexical_cast<std::string>(*payload->getBlockSize()));
+ }
+ payloadXML.setAttribute("sid", payload->getSessionID());
- return payloadXML.serialize();
+ return payloadXML.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h
index 42765ab..e94fb52 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,17 +14,17 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/JingleIBBTransportPayload.h>
+#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(std::shared_ptr<JingleIBBTransportPayload>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
index c6d6c12..aaac757 100644
--- a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
@@ -5,148 +5,143 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <boost/smart_ptr/intrusive_ptr.hpp>
+#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/Log.h>
-#include <Swiften/Serializer/XML/XMLNode.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-#include <Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h>
-
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
-
-#include <Swiften/Elements/JinglePayload.h>
#include <Swiften/Elements/JingleContentPayload.h>
-#include <Swiften/Elements/JingleIBBTransportPayload.h>
#include <Swiften/Elements/JingleFileTransferDescription.h>
#include <Swiften/Elements/JingleFileTransferHash.h>
+#include <Swiften/Elements/JingleIBBTransportPayload.h>
+#include <Swiften/Elements/JinglePayload.h>
+#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLNode.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
JinglePayloadSerializer::JinglePayloadSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
-std::string JinglePayloadSerializer::serializePayload(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());
+std::string JinglePayloadSerializer::serializePayload(std::shared_ptr<JinglePayload> payload) const {
+ XMLElement jinglePayload("jingle", "urn:xmpp:jingle:1");
+ jinglePayload.setAttribute("action", actionToString(payload->getAction()));
+ jinglePayload.setAttribute("initiator", payload->getInitiator());
+ jinglePayload.setAttribute("sid", payload->getSessionID());
+
+ std::vector<std::shared_ptr<Payload> > payloads = payload->getPayloads();
+ if (!payloads.empty()) {
+ for (auto&& subPayload : payloads) {
+ PayloadSerializer* serializer = serializers->getPayloadSerializer(subPayload);
+ if (serializer) {
+ jinglePayload.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(subPayload)));
+ }
+ }
+ }
+
+ if (payload->getReason().is_initialized()) {
+ std::shared_ptr<XMLElement> reason = std::make_shared<XMLElement>("reason");
+ reason->addNode(std::make_shared<XMLElement>(reasonTypeToString(payload->getReason()->type)));
+ if (!payload->getReason()->text.empty()) {
+ reason->addNode(std::make_shared<XMLElement>("desc", "", payload->getReason()->text));
+ }
+ jinglePayload.addNode(reason);
+ }
- 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();
+ 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 5ac266f..a846ebe 100644
--- a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h
@@ -4,28 +4,34 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/JinglePayload.h>
+#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(std::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 220d8dd..5e74d8e 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp
@@ -5,92 +5,91 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Serializer/XML/XMLNode.h>
+#include <Swiften/Base/Log.h>
#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-#include <Swiften/Base/Log.h>
namespace Swift {
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();
+std::string JingleS5BTransportPayloadSerializer::serializePayload(std::shared_ptr<JingleS5BTransportPayload> payload) const {
+ XMLElement payloadXML("transport", "urn:xmpp:jingle:transports:s5b:1");
+ payloadXML.setAttribute("sid", payload->getSessionID());
+ payloadXML.setAttribute("mode", modeToString(payload->getMode()));
+ if (!payload->getDstAddr().empty()) {
+ payloadXML.setAttribute("dstaddr", payload->getDstAddr());
+ }
+
+ for (const auto& candidate : payload->getCandidates()) {
+ std::shared_ptr<XMLElement> candidateXML = std::make_shared<XMLElement>("candidate");
+ candidateXML->setAttribute("cid", candidate.cid);
+ candidateXML->setAttribute("host", candidate.hostPort.getAddress().toString());
+ candidateXML->setAttribute("jid", candidate.jid.toString());
+ candidateXML->setAttribute("port", boost::lexical_cast<std::string>(candidate.hostPort.getPort()));
+ candidateXML->setAttribute("priority", boost::lexical_cast<std::string>(candidate.priority));
+ candidateXML->setAttribute("type", typeToString(candidate.type));
+ payloadXML.addNode(candidateXML);
+ }
+
+ if (payload->hasCandidateError()) {
+ payloadXML.addNode(std::make_shared<XMLElement>("candidate-error"));
+ }
+ if (payload->hasProxyError()) {
+ payloadXML.addNode(std::make_shared<XMLElement>("proxy-error"));
+ }
+
+ if (!payload->getActivated().empty()) {
+ std::shared_ptr<XMLElement> activatedXML = std::make_shared<XMLElement>("activated");
+ activatedXML->setAttribute("cid", payload->getActivated());
+ payloadXML.addNode(activatedXML);
+ }
+ if (!payload->getCandidateUsed().empty()) {
+ std::shared_ptr<XMLElement> candusedXML = std::make_shared<XMLElement>("candidate-used");
+ candusedXML->setAttribute("cid", payload->getCandidateUsed());
+ payloadXML.addNode(candusedXML);
+ }
+
+ return payloadXML.serialize();
}
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 d857129..cca2f4e 100644
--- a/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,21 +14,21 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/JingleS5BTransportPayload.h>
+#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(std::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 ac0fb8f..1710bc0 100644
--- a/Swiften/Serializer/PayloadSerializers/LastSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/LastSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,16 +9,16 @@
#include <boost/lexical_cast.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/Last.h>
+#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(std::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 38bab8c..6f40277 100644
--- a/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.cpp
@@ -1,16 +1,19 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h>
+
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+
#include <Swiften/Serializer/PayloadSerializerCollection.h>
-#include <Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -20,28 +23,28 @@ MAMFinSerializer::MAMFinSerializer() {
MAMFinSerializer::~MAMFinSerializer() {
}
-std::string MAMFinSerializer::serializePayload(boost::shared_ptr<MAMFin> payload) const {
- if (!payload) {
- return "";
- }
+std::string MAMFinSerializer::serializePayload(std::shared_ptr<MAMFin> payload) const {
+ 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(std::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 dbb5330..7e2a7c7 100644
--- a/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h
@@ -1,25 +1,26 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/MAMFin.h>
#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(std::shared_ptr<MAMFin>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.cpp b/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.cpp
index 45107d5..0b61c04 100644
--- a/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.cpp
@@ -1,18 +1,21 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h>
+
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h>
#include <Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -22,28 +25,28 @@ MAMQuerySerializer::MAMQuerySerializer() {
MAMQuerySerializer::~MAMQuerySerializer() {
}
-std::string MAMQuerySerializer::serializePayload(boost::shared_ptr<MAMQuery> payload) const {
- if (!payload) {
- return "";
- }
+std::string MAMQuerySerializer::serializePayload(std::shared_ptr<MAMQuery> payload) const {
+ 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(std::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(std::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 ca0fc25..6af979b 100644
--- a/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h
@@ -1,25 +1,26 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/MAMQuery.h>
#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(std::shared_ptr<MAMQuery>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.cpp
index 5e3666b..7ef2102 100644
--- a/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.cpp
@@ -1,16 +1,19 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h>
+
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -20,20 +23,20 @@ MAMResultSerializer::MAMResultSerializer(PayloadSerializerCollection* serializer
MAMResultSerializer::~MAMResultSerializer() {
}
-std::string MAMResultSerializer::serializePayload(boost::shared_ptr<MAMResult> payload) const {
- if (!payload) {
- return "";
- }
+std::string MAMResultSerializer::serializePayload(std::shared_ptr<MAMResult> payload) const {
+ 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(std::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 534f1b3..f4fc054 100644
--- a/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h
@@ -1,28 +1,29 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/MAMResult.h>
#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(std::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 39bd129..157c99e 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp
@@ -1,33 +1,29 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.h>
+#include <memory>
#include <sstream>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
-#include <Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h>
-
namespace Swift {
MUCAdminPayloadSerializer::MUCAdminPayloadSerializer() : GenericPayloadSerializer<MUCAdminPayload>() {
}
-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();
+std::string MUCAdminPayloadSerializer::serializePayload(std::shared_ptr<MUCAdminPayload> payload) const {
+ XMLElement mucElement("query", "http://jabber.org/protocol/muc#admin");
+ for (const auto& 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 db43435..c077d2e 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,17 +7,17 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/MUCAdminPayload.h>
+#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(std::shared_ptr<MUCAdminPayload> version) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp
index f6d8c8f..96116c7 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp
@@ -1,15 +1,13 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
@@ -18,17 +16,17 @@ namespace Swift {
MUCDestroyPayloadSerializer::MUCDestroyPayloadSerializer() : GenericPayloadSerializer<MUCDestroyPayload>() {
}
-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();
+std::string MUCDestroyPayloadSerializer::serializePayload(std::shared_ptr<MUCDestroyPayload> payload) const {
+ XMLElement mucElement("destroy", "");
+ if (!payload->getReason().empty()) {
+ XMLElement::ref reason = std::make_shared<XMLElement>("reason", "");
+ reason->addNode(std::make_shared<XMLTextNode>(payload->getReason()));
+ mucElement.addNode(reason);
+ }
+ if (payload->getNewVenue().isValid()) {
+ mucElement.setAttribute("jid", payload->getNewVenue().toString());
+ }
+ return mucElement.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.h
index dcbf68c..2ce8ccc 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,15 +7,15 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/MUCDestroyPayload.h>
+#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(std::shared_ptr<MUCDestroyPayload> version) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp
index aa18f8c..2004f4c 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp
@@ -1,46 +1,43 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
-#include <Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h>
-
namespace Swift {
MUCInvitationPayloadSerializer::MUCInvitationPayloadSerializer() : GenericPayloadSerializer<MUCInvitationPayload>() {
}
-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();
+std::string MUCInvitationPayloadSerializer::serializePayload(std::shared_ptr<MUCInvitationPayload> payload) const {
+ XMLElement mucElement("x", "jabber:x:conference");
+ if (payload->getIsContinuation()) {
+ mucElement.setAttribute("continue", "true");
+ }
+ if (payload->getJID().isValid()) {
+ mucElement.setAttribute("jid", payload->getJID().toString());
+ }
+ if (!payload->getPassword().empty()) {
+ mucElement.setAttribute("password", payload->getPassword());
+ }
+ if (!payload->getReason().empty()) {
+ mucElement.setAttribute("reason", payload->getReason());
+ }
+ if (!payload->getThread().empty()) {
+ mucElement.setAttribute("thread", payload->getThread());
+ }
+ if (payload->getIsImpromptu()) {
+ mucElement.addNode(std::make_shared<XMLElement>("impromptu", "http://swift.im/impromptu"));
+ }
+ return mucElement.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.h
index f395a4e..be21177 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.h
@@ -1,21 +1,21 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/MUCInvitationPayload.h>
+#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(std::shared_ptr<MUCInvitationPayload> version) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h b/Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h
index daa735b..22f7859 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h
@@ -1,69 +1,70 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <memory>
+
#include <Swiften/Elements/MUCItem.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#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 std::shared_ptr<XMLElement> itemToElement(const MUCItem& item) {
+ std::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) {
+ std::shared_ptr<XMLElement> actorElement(new XMLElement("actor"));
+ actorElement->setAttribute("jid", item.actor->toString());
+ itemElement->addNode(actorElement);
+ }
+ if (item.reason) {
+ std::shared_ptr<XMLElement> reasonElement(new XMLElement("reason"));
+ reasonElement->addNode(std::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..f385e91 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/XML/XMLElement.h>
@@ -17,16 +17,16 @@ namespace Swift {
MUCOwnerPayloadSerializer::MUCOwnerPayloadSerializer(PayloadSerializerCollection* serializers) : GenericPayloadSerializer<MUCOwnerPayload>(), serializers(serializers) {
}
-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();
+std::string MUCOwnerPayloadSerializer::serializePayload(std::shared_ptr<MUCOwnerPayload> mucOwner) const {
+ XMLElement mucElement("query", "http://jabber.org/protocol/muc#owner");
+ std::shared_ptr<Payload> payload = mucOwner->getPayload();
+ if (payload) {
+ PayloadSerializer* serializer = serializers->getPayloadSerializer(payload);
+ if (serializer) {
+ mucElement.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(payload)));
+ }
+ }
+ return mucElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.h
index ff55b78..8e2e856 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,17 +7,17 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/MUCOwnerPayload.h>
+#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(std::shared_ptr<MUCOwnerPayload> version) const;
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.cpp
index 909726a..4f0f637 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.cpp
@@ -1,57 +1,58 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.h>
-#include <boost/lexical_cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/date_time/posix_time/posix_time.hpp>
+#include <boost/lexical_cast.hpp>
+#include <Swiften/Base/String.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
-#include <Swiften/Base/String.h>
namespace Swift {
MUCPayloadSerializer::MUCPayloadSerializer() : GenericPayloadSerializer<MUCPayload>() {
}
-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();
+std::string MUCPayloadSerializer::serializePayload(std::shared_ptr<MUCPayload> muc) const {
+ XMLElement mucElement("x", "http://jabber.org/protocol/muc");
+ std::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();
+ std::shared_ptr<XMLElement> passwordElement(new XMLElement("password"));
+ passwordElement->addNode(std::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 77eba1c..6b0247d 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/MUCPayload.h>
+#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(std::shared_ptr<MUCPayload> version) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp
index e2a8dc3..f0f3cfa 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp
@@ -1,70 +1,67 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.h>
+#include <memory>
#include <sstream>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-#include <Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
MUCUserPayloadSerializer::MUCUserPayloadSerializer(PayloadSerializerCollection* serializers) : GenericPayloadSerializer<MUCUserPayload>(), serializers(serializers) {
}
-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));
- }
+std::string MUCUserPayloadSerializer::serializePayload(std::shared_ptr<MUCUserPayload> payload) const {
+ XMLElement mucElement("x", "http://jabber.org/protocol/muc#user");
+ for (const auto& statusCode : payload->getStatusCodes()) {
+ std::shared_ptr<XMLElement> statusElement(new XMLElement("status"));
+ std::ostringstream code;
+ code << statusCode.code;
+ statusElement->setAttribute("code", code.str());
+ mucElement.addNode(statusElement);
+ }
+ for (const auto& 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()) {
+ std::shared_ptr<XMLElement> passwordElement = std::make_shared<XMLElement>("password");
+ passwordElement->addNode(std::make_shared<XMLTextNode>(*payload->getPassword()));
+ }
- if (payload->getInvite()) {
- MUCUserPayload::Invite invite = *payload->getInvite();
- 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();
+ std::shared_ptr<XMLElement> inviteElement = std::make_shared<XMLElement>("invite");
+ if (invite.to.isValid()) {
+ inviteElement->setAttribute("to", invite.to.toString());
+ }
+ if (invite.from.isValid()) {
+ inviteElement->setAttribute("from", invite.from.toString());
+ }
+ if (!invite.reason.empty()) {
+ std::shared_ptr<XMLElement> reasonElement = std::make_shared<XMLElement>("reason");
+ reasonElement->addNode(std::make_shared<XMLTextNode>(invite.reason));
+ }
+ mucElement.addNode(inviteElement);
+ }
- 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();
+ std::shared_ptr<Payload> childPayload = payload->getPayload();
+ if (childPayload) {
+ PayloadSerializer* serializer = serializers->getPayloadSerializer(childPayload);
+ if (serializer) {
+ mucElement.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(childPayload)));
+ }
+ }
+ return mucElement.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.h
index 2d1b1e5..ea4b74b 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,18 +7,18 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/MUCUserPayload.h>
+#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(std::shared_ptr<MUCUserPayload> version) const;
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp b/Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp
index 303ef9a..7bd8931 100644
--- a/Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp
@@ -1,13 +1,12 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/NicknameSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
@@ -17,10 +16,10 @@ namespace Swift {
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();
+std::string NicknameSerializer::serializePayload(std::shared_ptr<Nickname> nick) const {
+ XMLElement nickElement("nick", "http://jabber.org/protocol/nick");
+ nickElement.addNode(std::make_shared<XMLTextNode>(nick->getNickname()));
+ return nickElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/NicknameSerializer.h b/Swiften/Serializer/PayloadSerializers/NicknameSerializer.h
index f1a6c9c..efea9c2 100644
--- a/Swiften/Serializer/PayloadSerializers/NicknameSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/NicknameSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,16 +7,16 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/Nickname.h>
+#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(std::shared_ptr<Nickname>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PrioritySerializer.h b/Swiften/Serializer/PayloadSerializers/PrioritySerializer.h
index bda5b2d..687d07f 100644
--- a/Swiften/Serializer/PayloadSerializers/PrioritySerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PrioritySerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,16 +9,16 @@
#include <boost/lexical_cast.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/Priority.h>
+#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(std::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 3e7a890..fc410fb 100644
--- a/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp
@@ -1,35 +1,33 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLTextNode.h>
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(std::shared_ptr<PrivateStorage> storage) const {
+ XMLElement storageElement("query", "jabber:iq:private");
+ std::shared_ptr<Payload> payload = storage->getPayload();
+ if (payload) {
+ PayloadSerializer* serializer = serializers->getPayloadSerializer(payload);
+ if (serializer) {
+ storageElement.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(payload)));
+ }
+ }
+ return storageElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.h b/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.h
index b11b60b..f2f9d90 100644
--- a/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,19 +7,19 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/PrivateStorage.h>
+#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(std::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..e72c304 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.cpp
@@ -1,45 +1,42 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
+#include <cassert>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
-
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubAffiliationSerializer::PubSubAffiliationSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubAffiliationSerializer::PubSubAffiliationSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubAffiliationSerializer::serializePayload(std::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();
}
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 a1c3bae..8862414 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h
@@ -1,31 +1,29 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubAffiliation.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubAffiliationSerializer : public GenericPayloadSerializer<PubSubAffiliation> {
- public:
- PubSubAffiliationSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubAffiliationSerializer();
+ class PayloadSerializerCollection;
- virtual std::string serializePayload(boost::shared_ptr<PubSubAffiliation>) const SWIFTEN_OVERRIDE;
+ class SWIFTEN_API PubSubAffiliationSerializer : public GenericPayloadSerializer<PubSubAffiliation> {
+ public:
+ PubSubAffiliationSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubAffiliationSerializer();
- private:
- static std::string serializeType(PubSubAffiliation::Type);
+ virtual std::string serializePayload(std::shared_ptr<PubSubAffiliation>) const SWIFTEN_OVERRIDE;
- private:
- PayloadSerializerCollection* serializers;
- };
+ private:
+ static std::string serializeType(PubSubAffiliation::Type);
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp
index 4003b6c..9c810da 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.cpp
@@ -1,18 +1,16 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -23,18 +21,18 @@ PubSubAffiliationsSerializer::PubSubAffiliationsSerializer(PayloadSerializerColl
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();
+std::string PubSubAffiliationsSerializer::serializePayload(std::shared_ptr<PubSubAffiliations> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("affiliations", "http://jabber.org/protocol/pubsub");
+ if (payload->getNode()) {
+ element.setAttribute("node", *payload->getNode());
+ }
+ for (const auto& item : payload->getAffiliations()) {
+ element.addNode(std::make_shared<XMLRawTextNode>(PubSubAffiliationSerializer(serializers).serialize(item)));
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h
index 7f786af..c51d70e 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubAffiliations.h>
-#include <boost/shared_ptr.hpp>
+#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(std::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..c0b651d 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.cpp
@@ -1,34 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <memory>
+
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
-PubSubConfigureSerializer::PubSubConfigureSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubConfigureSerializer::PubSubConfigureSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubConfigureSerializer::serializePayload(std::shared_ptr<PubSubConfigure> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("configure", "http://jabber.org/protocol/pubsub");
+ element.addNode(std::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 6db27b7..6a6241c 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubConfigure.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubConfigureSerializer : public GenericPayloadSerializer<PubSubConfigure> {
- public:
- PubSubConfigureSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubConfigureSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubConfigure>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubConfigureSerializer : public GenericPayloadSerializer<PubSubConfigure> {
+ public:
+ PubSubConfigureSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubConfigureSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubConfigure>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.cpp
index 0f9094d..a1efca3 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.cpp
@@ -1,33 +1,28 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-
-
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubCreateSerializer::PubSubCreateSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubCreateSerializer::PubSubCreateSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubCreateSerializer::serializePayload(std::shared_ptr<PubSubCreate> payload) const {
+ 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 b775948..876e26f 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubCreate.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubCreateSerializer : public GenericPayloadSerializer<PubSubCreate> {
- public:
- PubSubCreateSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubCreateSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubCreate>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubCreateSerializer : public GenericPayloadSerializer<PubSubCreate> {
+ public:
+ PubSubCreateSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubCreateSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubCreate>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.cpp
index c101623..e41e09e 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.cpp
@@ -1,44 +1,39 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-
-
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubDefaultSerializer::PubSubDefaultSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubDefaultSerializer::PubSubDefaultSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubDefaultSerializer::serializePayload(std::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();
}
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 22a70dd..4f5031b 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h
@@ -1,31 +1,29 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubDefault.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubDefaultSerializer : public GenericPayloadSerializer<PubSubDefault> {
- public:
- PubSubDefaultSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubDefaultSerializer();
+ class PayloadSerializerCollection;
- virtual std::string serializePayload(boost::shared_ptr<PubSubDefault>) const SWIFTEN_OVERRIDE;
+ class SWIFTEN_API PubSubDefaultSerializer : public GenericPayloadSerializer<PubSubDefault> {
+ public:
+ PubSubDefaultSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubDefaultSerializer();
- private:
- static std::string serializeType(PubSubDefault::Type);
+ virtual std::string serializePayload(std::shared_ptr<PubSubDefault>) const SWIFTEN_OVERRIDE;
- private:
- PayloadSerializerCollection* serializers;
- };
+ private:
+ static std::string serializeType(PubSubDefault::Type);
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.cpp
index 503db3e..1f98e7b 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.cpp
@@ -1,13 +1,15 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
+
+#include <cassert>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
@@ -17,95 +19,95 @@ PubSubErrorSerializer::PubSubErrorSerializer() {
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();
+std::string PubSubErrorSerializer::serializePayload(std::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();
}
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 d9387a6..6b0882e 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.h
@@ -1,28 +1,28 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubError.h>
+#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(std::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..1070c0b 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.cpp
@@ -1,33 +1,28 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-
-
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubEventAssociateSerializer::PubSubEventAssociateSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubEventAssociateSerializer::PubSubEventAssociateSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubEventAssociateSerializer::serializePayload(std::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();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h
index a7ac038..9348549 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventAssociate.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubEventAssociateSerializer : public GenericPayloadSerializer<PubSubEventAssociate> {
- public:
- PubSubEventAssociateSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventAssociateSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventAssociate>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubEventAssociateSerializer : public GenericPayloadSerializer<PubSubEventAssociate> {
+ public:
+ PubSubEventAssociateSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventAssociateSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubEventAssociate>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.cpp
index 96462d3..f492194 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.cpp
@@ -1,18 +1,19 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -23,17 +24,17 @@ PubSubEventCollectionSerializer::PubSubEventCollectionSerializer(PayloadSerializ
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();
+std::string PubSubEventCollectionSerializer::serializePayload(std::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(std::make_shared<XMLRawTextNode>(PubSubEventDisassociateSerializer(serializers).serialize(payload->getDisassociate())));
+ element.addNode(std::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 0495d5e..33144e9 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventCollection.h>
-#include <boost/shared_ptr.hpp>
+#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(std::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..a86cead 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.cpp
@@ -1,35 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <memory>
+
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
-PubSubEventConfigurationSerializer::PubSubEventConfigurationSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubEventConfigurationSerializer::PubSubEventConfigurationSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubEventConfigurationSerializer::serializePayload(std::shared_ptr<PubSubEventConfiguration> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("configuration", "http://jabber.org/protocol/pubsub#event");
+ element.setAttribute("node", payload->getNode());
+ element.addNode(std::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 f1fdcdb..a1e565c 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventConfiguration.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubEventConfigurationSerializer : public GenericPayloadSerializer<PubSubEventConfiguration> {
- public:
- PubSubEventConfigurationSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventConfigurationSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventConfiguration>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubEventConfigurationSerializer : public GenericPayloadSerializer<PubSubEventConfiguration> {
+ public:
+ PubSubEventConfigurationSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventConfigurationSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubEventConfiguration>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.cpp
index 5d9a6b4..daa9338 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.cpp
@@ -1,17 +1,18 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -22,14 +23,14 @@ PubSubEventDeleteSerializer::PubSubEventDeleteSerializer(PayloadSerializerCollec
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();
+std::string PubSubEventDeleteSerializer::serializePayload(std::shared_ptr<PubSubEventDelete> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("delete", "http://jabber.org/protocol/pubsub#event");
+ element.setAttribute("node", payload->getNode());
+ element.addNode(std::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 eca7a07..e02d44c 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventDelete.h>
-#include <boost/shared_ptr.hpp>
+#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(std::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..b90e76e 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.cpp
@@ -1,33 +1,28 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-
-
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubEventDisassociateSerializer::PubSubEventDisassociateSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubEventDisassociateSerializer::PubSubEventDisassociateSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubEventDisassociateSerializer::serializePayload(std::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();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h
index 72f8b8f..0d2d426 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventDisassociate.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubEventDisassociateSerializer : public GenericPayloadSerializer<PubSubEventDisassociate> {
- public:
- PubSubEventDisassociateSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventDisassociateSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventDisassociate>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubEventDisassociateSerializer : public GenericPayloadSerializer<PubSubEventDisassociate> {
+ public:
+ PubSubEventDisassociateSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventDisassociateSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubEventDisassociate>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp
index 01a58e3..2743ff6 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.cpp
@@ -1,17 +1,15 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -22,24 +20,24 @@ PubSubEventItemSerializer::PubSubEventItemSerializer(PayloadSerializerCollection
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();
+std::string PubSubEventItemSerializer::serializePayload(std::shared_ptr<PubSubEventItem> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("item", "http://jabber.org/protocol/pubsub#event");
+ if (payload->getNode()) {
+ element.setAttribute("node", *payload->getNode());
+ }
+ if (payload->getPublisher()) {
+ element.setAttribute("publisher", *payload->getPublisher());
+ }
+ for (const auto& item : payload->getData()) {
+ element.addNode(std::make_shared<XMLRawTextNode>(serializers->getPayloadSerializer(item)->serialize(item)));
+ }
+ if (payload->getID()) {
+ element.setAttribute("id", *payload->getID());
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h
index 04ace30..f292a53 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventItem.h>
-#include <boost/shared_ptr.hpp>
+#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(std::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..67d611b 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.cpp
@@ -1,19 +1,17 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -24,19 +22,19 @@ PubSubEventItemsSerializer::PubSubEventItemsSerializer(PayloadSerializerCollecti
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();
+std::string PubSubEventItemsSerializer::serializePayload(std::shared_ptr<PubSubEventItems> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("items", "http://jabber.org/protocol/pubsub#event");
+ element.setAttribute("node", payload->getNode());
+ for (const auto& item : payload->getItems()) {
+ element.addNode(std::make_shared<XMLRawTextNode>(PubSubEventItemSerializer(serializers).serialize(item)));
+ }
+ for (const auto& item : payload->getRetracts()) {
+ element.addNode(std::make_shared<XMLRawTextNode>(PubSubEventRetractSerializer(serializers).serialize(item)));
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h
index 2b35553..7220fde 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventItems.h>
-#include <boost/shared_ptr.hpp>
+#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(std::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..2125f59 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.cpp
@@ -1,33 +1,28 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-
-
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubEventPurgeSerializer::PubSubEventPurgeSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubEventPurgeSerializer::PubSubEventPurgeSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubEventPurgeSerializer::serializePayload(std::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();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h
index f4db1b7..161a733 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventPurge.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubEventPurgeSerializer : public GenericPayloadSerializer<PubSubEventPurge> {
- public:
- PubSubEventPurgeSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventPurgeSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventPurge>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubEventPurgeSerializer : public GenericPayloadSerializer<PubSubEventPurge> {
+ public:
+ PubSubEventPurgeSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventPurgeSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubEventPurge>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.cpp
index 80b4d94..771c923 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.cpp
@@ -1,33 +1,28 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-
-
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubEventRedirectSerializer::PubSubEventRedirectSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubEventRedirectSerializer::PubSubEventRedirectSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubEventRedirectSerializer::serializePayload(std::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();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h
index 5882570..1720847 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventRedirect.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubEventRedirectSerializer : public GenericPayloadSerializer<PubSubEventRedirect> {
- public:
- PubSubEventRedirectSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventRedirectSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventRedirect>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubEventRedirectSerializer : public GenericPayloadSerializer<PubSubEventRedirect> {
+ public:
+ PubSubEventRedirectSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventRedirectSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubEventRedirect>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.cpp
index 197c087..f938cd7 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.cpp
@@ -1,33 +1,28 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-
-
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubEventRetractSerializer::PubSubEventRetractSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubEventRetractSerializer::PubSubEventRetractSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubEventRetractSerializer::serializePayload(std::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();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h
index c2b7385..ff2f7e7 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventRetract.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubEventRetractSerializer : public GenericPayloadSerializer<PubSubEventRetract> {
- public:
- PubSubEventRetractSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventRetractSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventRetract>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubEventRetractSerializer : public GenericPayloadSerializer<PubSubEventRetract> {
+ public:
+ PubSubEventRetractSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventRetractSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubEventRetract>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp
index 8a7b881..51b8b46 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.cpp
@@ -1,51 +1,48 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h>
-#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h>
+#include <memory>
+
#include <Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
-PubSubEventSerializer::PubSubEventSerializer(PayloadSerializerCollection* serializers) : 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));
+PubSubEventSerializer::PubSubEventSerializer(PayloadSerializerCollection* serializers) {
+ pubsubSerializers.push_back(std::make_shared<PubSubEventSubscriptionSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubEventPurgeSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubEventCollectionSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubEventDeleteSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubEventItemsSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubEventConfigurationSerializer>(serializers));
}
PubSubEventSerializer::~PubSubEventSerializer() {
}
-std::string PubSubEventSerializer::serializePayload(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();
+std::string PubSubEventSerializer::serializePayload(std::shared_ptr<PubSubEvent> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("event", "http://jabber.org/protocol/pubsub#event");
+ std::shared_ptr<PubSubEventPayload> p = payload->getPayload();
+ for (const auto& serializer : pubsubSerializers) {
+ if (serializer->canSerialize(p)) {
+ element.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(p)));
+ }
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h
index 3c8e3cc..bebb101 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h
@@ -1,33 +1,30 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+#include <vector>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEvent.h>
-#include <boost/shared_ptr.hpp>
-#include <vector>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubEventSerializer : public GenericPayloadSerializer<PubSubEvent> {
- public:
- PubSubEventSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventSerializer();
+ class PayloadSerializerCollection;
- virtual std::string serializePayload(boost::shared_ptr<PubSubEvent>) const SWIFTEN_OVERRIDE;
+ class SWIFTEN_API PubSubEventSerializer : public GenericPayloadSerializer<PubSubEvent> {
+ public:
+ PubSubEventSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventSerializer();
- private:
-
+ virtual std::string serializePayload(std::shared_ptr<PubSubEvent>) const SWIFTEN_OVERRIDE;
- private:
- PayloadSerializerCollection* serializers;
- std::vector< boost::shared_ptr<PayloadSerializer> > pubsubSerializers;
- };
+ private:
+ std::vector< std::shared_ptr<PayloadSerializer> > pubsubSerializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.cpp
index a7240c8..e39e6ad 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.cpp
@@ -1,48 +1,44 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Base/DateTime.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubEventSubscriptionSerializer::PubSubEventSubscriptionSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubEventSubscriptionSerializer::PubSubEventSubscriptionSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubEventSubscriptionSerializer::serializePayload(std::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();
}
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 84f7856..7d85ba1 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h
@@ -1,31 +1,29 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubEventSubscription.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubEventSubscriptionSerializer : public GenericPayloadSerializer<PubSubEventSubscription> {
- public:
- PubSubEventSubscriptionSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubEventSubscriptionSerializer();
+ class PayloadSerializerCollection;
- virtual std::string serializePayload(boost::shared_ptr<PubSubEventSubscription>) const SWIFTEN_OVERRIDE;
+ class SWIFTEN_API PubSubEventSubscriptionSerializer : public GenericPayloadSerializer<PubSubEventSubscription> {
+ public:
+ PubSubEventSubscriptionSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubEventSubscriptionSerializer();
- private:
- static std::string serializeSubscriptionType(PubSubEventSubscription::SubscriptionType);
+ virtual std::string serializePayload(std::shared_ptr<PubSubEventSubscription>) const SWIFTEN_OVERRIDE;
- private:
- PayloadSerializerCollection* serializers;
- };
+ private:
+ static std::string serializeSubscriptionType(PubSubEventSubscription::SubscriptionType);
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp
index 93fa8e2..a202c88 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.cpp
@@ -1,17 +1,15 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -22,18 +20,18 @@ PubSubItemSerializer::PubSubItemSerializer(PayloadSerializerCollection* serializ
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();
+std::string PubSubItemSerializer::serializePayload(std::shared_ptr<PubSubItem> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("item", "http://jabber.org/protocol/pubsub");
+ for (const auto& item : payload->getData()) {
+ element.addNode(std::make_shared<XMLRawTextNode>(serializers->getPayloadSerializer(item)->serialize(item)));
+ }
+ if (!payload->getID().empty()) {
+ element.setAttribute("id", payload->getID());
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h
index 8b997b1..866d09b 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubItem.h>
-#include <boost/shared_ptr.hpp>
+#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(std::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..9786f51 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp
@@ -1,20 +1,19 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
+
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/Log.h>
+#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -25,25 +24,25 @@ PubSubItemsSerializer::PubSubItemsSerializer(PayloadSerializerCollection* serial
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();
+std::string PubSubItemsSerializer::serializePayload(std::shared_ptr<PubSubItems> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("items", "http://jabber.org/protocol/pubsub");
+ if (payload->getNode().empty()) {
+ SWIFT_LOG(warning) << "Serializing PubSubItems with empty node attribute";
+ }
+ element.setAttribute("node", payload->getNode());
+ for (const auto& item : payload->getItems()) {
+ element.addNode(std::make_shared<XMLRawTextNode>(PubSubItemSerializer(serializers).serialize(item)));
+ }
+ if (payload->getMaximumItems()) {
+ element.setAttribute("max_items", boost::lexical_cast<std::string>(*payload->getMaximumItems()));
+ }
+ if (payload->getSubscriptionID()) {
+ element.setAttribute("subid", *payload->getSubscriptionID());
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h
index 6fb8dab..51b0578 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubItems.h>
-#include <boost/shared_ptr.hpp>
+#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(std::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..5059a7c 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.cpp
@@ -1,39 +1,37 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <memory>
+
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
-PubSubOptionsSerializer::PubSubOptionsSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubOptionsSerializer::PubSubOptionsSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubOptionsSerializer::serializePayload(std::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(std::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 6aeafb0..0b7a9a7 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOptions.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubOptionsSerializer : public GenericPayloadSerializer<PubSubOptions> {
- public:
- PubSubOptionsSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOptionsSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubOptions>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubOptionsSerializer : public GenericPayloadSerializer<PubSubOptions> {
+ public:
+ PubSubOptionsSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOptionsSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubOptions>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.cpp
index efc9eef..1387b07 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.cpp
@@ -1,45 +1,43 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
+#include <cassert>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
-
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubOwnerAffiliationSerializer::PubSubOwnerAffiliationSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubOwnerAffiliationSerializer::PubSubOwnerAffiliationSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubOwnerAffiliationSerializer::serializePayload(std::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();
}
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 c667d37..ac6379a 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h
@@ -1,31 +1,29 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerAffiliation.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubOwnerAffiliationSerializer : public GenericPayloadSerializer<PubSubOwnerAffiliation> {
- public:
- PubSubOwnerAffiliationSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerAffiliationSerializer();
+ class PayloadSerializerCollection;
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerAffiliation>) const SWIFTEN_OVERRIDE;
+ class SWIFTEN_API PubSubOwnerAffiliationSerializer : public GenericPayloadSerializer<PubSubOwnerAffiliation> {
+ public:
+ PubSubOwnerAffiliationSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerAffiliationSerializer();
- private:
- static std::string serializeType(PubSubOwnerAffiliation::Type);
+ virtual std::string serializePayload(std::shared_ptr<PubSubOwnerAffiliation>) const SWIFTEN_OVERRIDE;
- private:
- PayloadSerializerCollection* serializers;
- };
+ private:
+ static std::string serializeType(PubSubOwnerAffiliation::Type);
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp
index 5e80747..b9f6bcc 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.cpp
@@ -1,18 +1,16 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -23,16 +21,16 @@ PubSubOwnerAffiliationsSerializer::PubSubOwnerAffiliationsSerializer(PayloadSeri
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();
+std::string PubSubOwnerAffiliationsSerializer::serializePayload(std::shared_ptr<PubSubOwnerAffiliations> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("affiliations", "http://jabber.org/protocol/pubsub#owner");
+ element.setAttribute("node", payload->getNode());
+ for (const auto& item : payload->getAffiliations()) {
+ element.addNode(std::make_shared<XMLRawTextNode>(PubSubOwnerAffiliationSerializer(serializers).serialize(item)));
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h
index 57e78f5..6c53189 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerAffiliations.h>
-#include <boost/shared_ptr.hpp>
+#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(std::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..a14b7ea 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.cpp
@@ -1,37 +1,33 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <memory>
+
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
-PubSubOwnerConfigureSerializer::PubSubOwnerConfigureSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubOwnerConfigureSerializer::PubSubOwnerConfigureSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubOwnerConfigureSerializer::serializePayload(std::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(std::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 3cce766..528f29e 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerConfigure.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubOwnerConfigureSerializer : public GenericPayloadSerializer<PubSubOwnerConfigure> {
- public:
- PubSubOwnerConfigureSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerConfigureSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerConfigure>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubOwnerConfigureSerializer : public GenericPayloadSerializer<PubSubOwnerConfigure> {
+ public:
+ PubSubOwnerConfigureSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerConfigureSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubOwnerConfigure>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.cpp
index 934f877..68d334d 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.cpp
@@ -1,34 +1,30 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <memory>
+
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
-PubSubOwnerDefaultSerializer::PubSubOwnerDefaultSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubOwnerDefaultSerializer::PubSubOwnerDefaultSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubOwnerDefaultSerializer::serializePayload(std::shared_ptr<PubSubOwnerDefault> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("default", "http://jabber.org/protocol/pubsub#owner");
+ element.addNode(std::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 a973847..e41900c 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerDefault.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubOwnerDefaultSerializer : public GenericPayloadSerializer<PubSubOwnerDefault> {
- public:
- PubSubOwnerDefaultSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerDefaultSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerDefault>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubOwnerDefaultSerializer : public GenericPayloadSerializer<PubSubOwnerDefault> {
+ public:
+ PubSubOwnerDefaultSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerDefaultSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubOwnerDefault>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.cpp
index 1594643..5d1c5a6 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.cpp
@@ -1,17 +1,18 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
+
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -22,14 +23,14 @@ PubSubOwnerDeleteSerializer::PubSubOwnerDeleteSerializer(PayloadSerializerCollec
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();
+std::string PubSubOwnerDeleteSerializer::serializePayload(std::shared_ptr<PubSubOwnerDelete> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("delete", "http://jabber.org/protocol/pubsub#owner");
+ element.setAttribute("node", payload->getNode());
+ element.addNode(std::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 3163e30..c06a916 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerDelete.h>
-#include <boost/shared_ptr.hpp>
+#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(std::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..b2dfd21 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.cpp
@@ -1,51 +1,48 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <memory>
+
+#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h>
-#include <Swiften/Base/foreach.h>
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));
+PubSubOwnerPubSubSerializer::PubSubOwnerPubSubSerializer(PayloadSerializerCollection* serializers) {
+ pubsubSerializers.push_back(std::make_shared<PubSubOwnerConfigureSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubOwnerSubscriptionsSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubOwnerDefaultSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubOwnerPurgeSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubOwnerAffiliationsSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubOwnerDeleteSerializer>(serializers));
}
PubSubOwnerPubSubSerializer::~PubSubOwnerPubSubSerializer() {
}
-std::string PubSubOwnerPubSubSerializer::serializePayload(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();
+std::string PubSubOwnerPubSubSerializer::serializePayload(std::shared_ptr<PubSubOwnerPubSub> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("pubsub", "http://jabber.org/protocol/pubsub#owner");
+ std::shared_ptr<PubSubOwnerPayload> p = payload->getPayload();
+ for (const auto& serializer : pubsubSerializers) {
+ if (serializer->canSerialize(p)) {
+ element.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(p)));
+ }
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h
index 44e24bc..b179c82 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h
@@ -1,33 +1,30 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+#include <vector>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerPubSub.h>
-#include <boost/shared_ptr.hpp>
-#include <vector>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubOwnerPubSubSerializer : public GenericPayloadSerializer<PubSubOwnerPubSub> {
- public:
- PubSubOwnerPubSubSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerPubSubSerializer();
+ class PayloadSerializerCollection;
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerPubSub>) const SWIFTEN_OVERRIDE;
+ class SWIFTEN_API PubSubOwnerPubSubSerializer : public GenericPayloadSerializer<PubSubOwnerPubSub> {
+ public:
+ PubSubOwnerPubSubSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerPubSubSerializer();
- private:
-
+ virtual std::string serializePayload(std::shared_ptr<PubSubOwnerPubSub>) const SWIFTEN_OVERRIDE;
- private:
- PayloadSerializerCollection* serializers;
- std::vector< boost::shared_ptr<PayloadSerializer> > pubsubSerializers;
- };
+ private:
+ std::vector< std::shared_ptr<PayloadSerializer> > pubsubSerializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.cpp
index 9d2f0c1..cbcccb9 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.cpp
@@ -1,33 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-
-
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubOwnerPurgeSerializer::PubSubOwnerPurgeSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubOwnerPurgeSerializer::PubSubOwnerPurgeSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubOwnerPurgeSerializer::serializePayload(std::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();
}
-
-
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h
index 5f2d5a0..32f6523 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerPurge.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubOwnerPurgeSerializer : public GenericPayloadSerializer<PubSubOwnerPurge> {
- public:
- PubSubOwnerPurgeSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerPurgeSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerPurge>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubOwnerPurgeSerializer : public GenericPayloadSerializer<PubSubOwnerPurge> {
+ public:
+ PubSubOwnerPurgeSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerPurgeSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubOwnerPurge>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.cpp
index 7628379..2d06a70 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.cpp
@@ -1,33 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-
-
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubOwnerRedirectSerializer::PubSubOwnerRedirectSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubOwnerRedirectSerializer::PubSubOwnerRedirectSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubOwnerRedirectSerializer::serializePayload(std::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();
}
-
-
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h
index ed0b870..cd78fc8 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerRedirect.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubOwnerRedirectSerializer : public GenericPayloadSerializer<PubSubOwnerRedirect> {
- public:
- PubSubOwnerRedirectSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerRedirectSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerRedirect>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubOwnerRedirectSerializer : public GenericPayloadSerializer<PubSubOwnerRedirect> {
+ public:
+ PubSubOwnerRedirectSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerRedirectSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubOwnerRedirect>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.cpp
index a639716..842df98 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.cpp
@@ -1,43 +1,40 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
+#include <cassert>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
-
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubOwnerSubscriptionSerializer::PubSubOwnerSubscriptionSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubOwnerSubscriptionSerializer::PubSubOwnerSubscriptionSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubOwnerSubscriptionSerializer::serializePayload(std::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();
}
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 e30b851..9f9e80d 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h
@@ -1,31 +1,29 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerSubscription.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubOwnerSubscriptionSerializer : public GenericPayloadSerializer<PubSubOwnerSubscription> {
- public:
- PubSubOwnerSubscriptionSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubOwnerSubscriptionSerializer();
+ class PayloadSerializerCollection;
- virtual std::string serializePayload(boost::shared_ptr<PubSubOwnerSubscription>) const SWIFTEN_OVERRIDE;
+ class SWIFTEN_API PubSubOwnerSubscriptionSerializer : public GenericPayloadSerializer<PubSubOwnerSubscription> {
+ public:
+ PubSubOwnerSubscriptionSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubOwnerSubscriptionSerializer();
- private:
- static std::string serializeSubscriptionType(PubSubOwnerSubscription::SubscriptionType);
+ virtual std::string serializePayload(std::shared_ptr<PubSubOwnerSubscription>) const SWIFTEN_OVERRIDE;
- private:
- PayloadSerializerCollection* serializers;
- };
+ private:
+ static std::string serializeSubscriptionType(PubSubOwnerSubscription::SubscriptionType);
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp
index 3b49329..a5940f6 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.cpp
@@ -1,18 +1,16 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -23,16 +21,16 @@ PubSubOwnerSubscriptionsSerializer::PubSubOwnerSubscriptionsSerializer(PayloadSe
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();
+std::string PubSubOwnerSubscriptionsSerializer::serializePayload(std::shared_ptr<PubSubOwnerSubscriptions> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("subscriptions", "http://jabber.org/protocol/pubsub#owner");
+ element.setAttribute("node", payload->getNode());
+ for (const auto& item : payload->getSubscriptions()) {
+ element.addNode(std::make_shared<XMLRawTextNode>(PubSubOwnerSubscriptionSerializer(serializers).serialize(item)));
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h
index 918536c..0c282b4 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubOwnerSubscriptions.h>
-#include <boost/shared_ptr.hpp>
+#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(std::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..ce8706d 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.cpp
@@ -1,18 +1,16 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -23,16 +21,16 @@ PubSubPublishSerializer::PubSubPublishSerializer(PayloadSerializerCollection* se
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();
+std::string PubSubPublishSerializer::serializePayload(std::shared_ptr<PubSubPublish> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("publish", "http://jabber.org/protocol/pubsub");
+ element.setAttribute("node", payload->getNode());
+ for (const auto& item : payload->getItems()) {
+ element.addNode(std::make_shared<XMLRawTextNode>(PubSubItemSerializer(serializers).serialize(item)));
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h
index c1faf0d..fb1af2e 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubPublish.h>
-#include <boost/shared_ptr.hpp>
+#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(std::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..c82089a 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.cpp
@@ -1,18 +1,16 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -23,17 +21,19 @@ PubSubRetractSerializer::PubSubRetractSerializer(PayloadSerializerCollection* se
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();
+std::string PubSubRetractSerializer::serializePayload(std::shared_ptr<PubSubRetract> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("retract", "http://jabber.org/protocol/pubsub");
+ element.setAttribute("node", payload->getNode());
+ for (const auto& item : payload->getItems()) {
+ element.addNode(std::make_shared<XMLRawTextNode>(PubSubItemSerializer(serializers).serialize(item)));
+ }
+ if (payload->isNotify().is_initialized()) {
+ element.setAttribute("notify", payload->isNotify().get() ? "true" : "false");
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h
index bcfff49..64737df 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h
@@ -1,31 +1,29 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubRetract.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubRetractSerializer : public GenericPayloadSerializer<PubSubRetract> {
- public:
- PubSubRetractSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubRetractSerializer();
+ class PayloadSerializerCollection;
- virtual std::string serializePayload(boost::shared_ptr<PubSubRetract>) const SWIFTEN_OVERRIDE;
+ class SWIFTEN_API PubSubRetractSerializer : public GenericPayloadSerializer<PubSubRetract> {
+ public:
+ PubSubRetractSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubRetractSerializer();
- private:
-
+ virtual std::string serializePayload(std::shared_ptr<PubSubRetract>) const SWIFTEN_OVERRIDE;
- private:
- PayloadSerializerCollection* serializers;
- };
+ private:
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp
index 2e75ecb..648c5a3 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSerializer.cpp
@@ -1,69 +1,66 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h>
-#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
PubSubSerializer::PubSubSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
- pubsubSerializers.push_back(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(std::make_shared<PubSubItemsSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubCreateSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubPublishSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubOptionsSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubAffiliationsSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubRetractSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubDefaultSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubSubscriptionsSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubSubscribeSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubUnsubscribeSerializer>(serializers));
+ pubsubSerializers.push_back(std::make_shared<PubSubSubscriptionSerializer>(serializers));
}
PubSubSerializer::~PubSubSerializer() {
}
-std::string PubSubSerializer::serializePayload(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();
+std::string PubSubSerializer::serializePayload(std::shared_ptr<PubSub> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("pubsub", "http://jabber.org/protocol/pubsub");
+ std::shared_ptr<PubSubPayload> p = payload->getPayload();
+ for (const auto& serializer : pubsubSerializers) {
+ if (serializer->canSerialize(p)) {
+ element.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(p)));
+ if (std::shared_ptr<PubSubCreate> create = std::dynamic_pointer_cast<PubSubCreate>(p)) {
+ element.addNode(std::make_shared<XMLRawTextNode>(std::make_shared<PubSubConfigureSerializer>(serializers)->serialize(create->getConfigure())));
+ }
+ if (std::shared_ptr<PubSubSubscribe> subscribe = std::dynamic_pointer_cast<PubSubSubscribe>(p)) {
+ element.addNode(std::make_shared<XMLRawTextNode>(std::make_shared<PubSubConfigureSerializer>(serializers)->serialize(subscribe->getOptions())));
+ }
+ }
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubSerializer.h
index 643b8b2..829f827 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSerializer.h
@@ -1,29 +1,30 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSub.h>
-#include <boost/shared_ptr.hpp>
+#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(std::shared_ptr<PubSub>) const SWIFTEN_OVERRIDE;
- private:
- std::vector< boost::shared_ptr<PayloadSerializer> > pubsubSerializers;
- PayloadSerializerCollection* serializers;
- };
+ private:
+ std::vector< std::shared_ptr<PayloadSerializer> > pubsubSerializers;
+ PayloadSerializerCollection* serializers;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.cpp
index 692158f..39550c2 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.cpp
@@ -1,33 +1,30 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <memory>
+
#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubSubscribeOptionsSerializer::PubSubSubscribeOptionsSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubSubscribeOptionsSerializer::PubSubSubscribeOptionsSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubSubscribeOptionsSerializer::serializePayload(std::shared_ptr<PubSubSubscribeOptions> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("subscribe-options", "http://jabber.org/protocol/pubsub");
+ element.addNode(payload->isRequired() ? std::make_shared<XMLElement>("required", "") : std::shared_ptr<XMLElement>());
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h
index bd640cf..fba02fe 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubSubscribeOptions.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubSubscribeOptionsSerializer : public GenericPayloadSerializer<PubSubSubscribeOptions> {
- public:
- PubSubSubscribeOptionsSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubSubscribeOptionsSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubSubscribeOptions>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubSubscribeOptionsSerializer : public GenericPayloadSerializer<PubSubSubscribeOptions> {
+ public:
+ PubSubSubscribeOptionsSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubSubscribeOptionsSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubSubscribeOptions>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.cpp
index f761531..d7970ba 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.cpp
@@ -1,36 +1,31 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-
-
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubSubscribeSerializer::PubSubSubscribeSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubSubscribeSerializer::PubSubSubscribeSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubSubscribeSerializer::serializePayload(std::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();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h
index 15eb9aa..b48e849 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubSubscribe.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubSubscribeSerializer : public GenericPayloadSerializer<PubSubSubscribe> {
- public:
- PubSubSubscribeSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubSubscribeSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubSubscribe>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubSubscribeSerializer : public GenericPayloadSerializer<PubSubSubscribe> {
+ public:
+ PubSubSubscribeSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubSubscribeSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubSubscribe>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.cpp
index a856f75..14e5e3f 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.cpp
@@ -1,17 +1,16 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -22,30 +21,30 @@ PubSubSubscriptionSerializer::PubSubSubscriptionSerializer(PayloadSerializerColl
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();
+std::string PubSubSubscriptionSerializer::serializePayload(std::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(std::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 fddfde6..5a5f847 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubSubscription.h>
-#include <boost/shared_ptr.hpp>
+#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(std::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..6e01881 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.cpp
@@ -1,18 +1,16 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
@@ -23,18 +21,18 @@ PubSubSubscriptionsSerializer::PubSubSubscriptionsSerializer(PayloadSerializerCo
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();
+std::string PubSubSubscriptionsSerializer::serializePayload(std::shared_ptr<PubSubSubscriptions> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("subscriptions", "http://jabber.org/protocol/pubsub");
+ if (payload->getNode()) {
+ element.setAttribute("node", *payload->getNode());
+ }
+ for (const auto& item : payload->getSubscriptions()) {
+ element.addNode(std::make_shared<XMLRawTextNode>(PubSubSubscriptionSerializer(serializers).serialize(item)));
+ }
+ return element.serialize();
}
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h
index d7bd8df..caeb3ef 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubSubscriptions.h>
-#include <boost/shared_ptr.hpp>
+#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(std::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..8a6d292 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.cpp
@@ -1,39 +1,32 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-
-
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-PubSubUnsubscribeSerializer::PubSubUnsubscribeSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+PubSubUnsubscribeSerializer::PubSubUnsubscribeSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string PubSubUnsubscribeSerializer::serializePayload(std::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();
}
-
-
diff --git a/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h
index 9a9ed4b..959bd9f 100644
--- a/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/PubSubUnsubscribe.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API PubSubUnsubscribeSerializer : public GenericPayloadSerializer<PubSubUnsubscribe> {
- public:
- PubSubUnsubscribeSerializer(PayloadSerializerCollection* serializers);
- virtual ~PubSubUnsubscribeSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<PubSubUnsubscribe>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API PubSubUnsubscribeSerializer : public GenericPayloadSerializer<PubSubUnsubscribe> {
+ public:
+ PubSubUnsubscribeSerializer(PayloadSerializerCollection* serializers);
+ virtual ~PubSubUnsubscribeSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<PubSubUnsubscribe>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/RawXMLPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/RawXMLPayloadSerializer.h
index 08314a5..1f07e37 100644
--- a/Swiften/Serializer/PayloadSerializers/RawXMLPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/RawXMLPayloadSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,16 +7,16 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/RawXMLPayload.h>
+#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(std::shared_ptr<RawXMLPayload> p) const {
+ return p->getRawXML();
+ }
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/ReplaceSerializer.h b/Swiften/Serializer/PayloadSerializers/ReplaceSerializer.h
index 9528964..3487b16 100644
--- a/Swiften/Serializer/PayloadSerializers/ReplaceSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/ReplaceSerializer.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,17 +13,17 @@
#pragma once
#include <Swiften/Base/API.h>
+#include <Swiften/Elements/Replace.h>
#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
-#include <Swiften/Elements/Replace.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(std::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..95a0084 100644
--- a/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.cpp
@@ -1,13 +1,12 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
@@ -17,19 +16,19 @@ namespace Swift {
ResourceBindSerializer::ResourceBindSerializer() : GenericPayloadSerializer<ResourceBind>() {
}
-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();
+std::string ResourceBindSerializer::serializePayload(std::shared_ptr<ResourceBind> resourceBind) const {
+ XMLElement bindElement("bind", "urn:ietf:params:xml:ns:xmpp-bind");
+ if (resourceBind->getJID().isValid()) {
+ std::shared_ptr<XMLElement> jidNode(new XMLElement("jid"));
+ jidNode->addNode(std::make_shared<XMLTextNode>(resourceBind->getJID().toString()));
+ bindElement.addNode(jidNode);
+ }
+ else if (!resourceBind->getResource().empty()) {
+ std::shared_ptr<XMLElement> resourceNode(new XMLElement("resource"));
+ resourceNode->addNode(std::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 0c13b4a..bea3ff1 100644
--- a/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/ResourceBind.h>
+#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(std::shared_ptr<ResourceBind>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.cpp
index e7672ab..3302863 100644
--- a/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.cpp
@@ -1,14 +1,17 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h>
+
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-#include <Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h>
using namespace Swift;
@@ -18,44 +21,44 @@ ResultSetSerializer::ResultSetSerializer() {
ResultSetSerializer::~ResultSetSerializer() {
}
-std::string ResultSetSerializer::serializePayload(boost::shared_ptr<ResultSet> payload) const {
- if (!payload) {
- return "";
- }
+std::string ResultSetSerializer::serializePayload(std::shared_ptr<ResultSet> payload) const {
+ 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(std::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(std::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(std::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()) {
+ std::shared_ptr<XMLElement> firstElement = std::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(std::make_shared<XMLElement>("last", "", *payload->getLastID()));
+ }
- if (payload->getBefore()) {
- element.addNode(boost::make_shared<XMLElement>("before", "", *payload->getBefore()));
- }
+ if (payload->getBefore()) {
+ element.addNode(std::make_shared<XMLElement>("before", "", *payload->getBefore()));
+ }
- if (payload->getAfter()) {
- element.addNode(boost::make_shared<XMLElement>("after", "", *payload->getAfter()));
- }
+ if (payload->getAfter()) {
+ element.addNode(std::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 400915b..e75b443 100644
--- a/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h
@@ -1,25 +1,26 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/ResultSet.h>
#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(std::shared_ptr<ResultSet>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp b/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp
index 39eaf7d..c7fdc5b 100644
--- a/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp
@@ -4,44 +4,48 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Serializer/XML/XMLTextNode.h>
-#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
RosterItemExchangeSerializer::RosterItemExchangeSerializer() : GenericPayloadSerializer<RosterItemExchangePayload>() {
}
-std::string RosterItemExchangeSerializer::serializePayload(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();
+std::string RosterItemExchangeSerializer::serializePayload(std::shared_ptr<RosterItemExchangePayload> roster) const {
+ XMLElement queryElement("x", "http://jabber.org/protocol/rosterx");
+ for (const auto& item : roster->getItems()) {
+ std::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
+ itemElement->setAttribute("jid", item.getJID());
+ itemElement->setAttribute("name", item.getName());
+
+ switch (item.getAction()) {
+ case RosterItemExchangePayload::Item::Add: itemElement->setAttribute("action", "add"); break;
+ case RosterItemExchangePayload::Item::Modify: itemElement->setAttribute("action", "modify"); break;
+ case RosterItemExchangePayload::Item::Delete: itemElement->setAttribute("action", "delete"); break;
+ }
+
+ for (const auto& group : item.getGroups()) {
+ std::shared_ptr<XMLElement> groupElement(new XMLElement("group"));
+ groupElement->addNode(std::make_shared<XMLTextNode>(group));
+ itemElement->addNode(groupElement);
+ }
+
+ queryElement.addNode(itemElement);
+ }
+
+ return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.h b/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.h
index 71a5b5d..6212998 100644
--- a/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.h
@@ -4,17 +4,23 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/RosterItemExchangePayload.h>
+#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(std::shared_ptr<RosterItemExchangePayload>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp b/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp
index e5cb2f2..e706542 100644
--- a/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp
@@ -1,61 +1,59 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/RosterSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Serializer/XML/XMLTextNode.h>
-#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
RosterSerializer::RosterSerializer() : GenericPayloadSerializer<RosterPayload>() {
}
-std::string RosterSerializer::serializePayload(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();
+std::string RosterSerializer::serializePayload(std::shared_ptr<RosterPayload> roster) const {
+ XMLElement queryElement("query", "jabber:iq:roster");
+ if (roster->getVersion()) {
+ queryElement.setAttribute("ver", *roster->getVersion());
+ }
+ for (const auto& item : roster->getItems()) {
+ std::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
+ itemElement->setAttribute("jid", item.getJID());
+ itemElement->setAttribute("name", item.getName());
+
+ switch (item.getSubscription()) {
+ case RosterItemPayload::To: itemElement->setAttribute("subscription", "to"); break;
+ case RosterItemPayload::From: itemElement->setAttribute("subscription", "from"); break;
+ case RosterItemPayload::Both: itemElement->setAttribute("subscription", "both"); break;
+ case RosterItemPayload::Remove: itemElement->setAttribute("subscription", "remove"); break;
+ case RosterItemPayload::None: itemElement->setAttribute("subscription", "none"); break;
+ }
+
+ if (item.getSubscriptionRequested()) {
+ itemElement->setAttribute("ask", "subscribe");
+ }
+
+ for (const auto& group : item.getGroups()) {
+ std::shared_ptr<XMLElement> groupElement(new XMLElement("group"));
+ groupElement->addNode(std::make_shared<XMLTextNode>(group));
+ itemElement->addNode(groupElement);
+ }
+
+ if (!item.getUnknownContent().empty()) {
+ itemElement->addNode(std::make_shared<XMLRawTextNode>(item.getUnknownContent()));
+ }
+
+
+ queryElement.addNode(itemElement);
+ }
+
+ return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/RosterSerializer.h b/Swiften/Serializer/PayloadSerializers/RosterSerializer.h
index cd1f4ad..834f723 100644
--- a/Swiften/Serializer/PayloadSerializers/RosterSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/RosterSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/RosterPayload.h>
+#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(std::shared_ptr<RosterPayload>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h b/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h
index 062e7c6..7058ac1 100644
--- a/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h
@@ -5,15 +5,16 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/S5BProxyRequest.h>
@@ -21,24 +22,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(std::shared_ptr<S5BProxyRequest> s5bProxyRequest) const {
+ XMLElement queryElement("query", "http://jabber.org/protocol/bytestreams");
+ if (s5bProxyRequest && s5bProxyRequest->getStreamHost()) {
+ std::shared_ptr<XMLElement> streamHost = std::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());
+ std::shared_ptr<XMLElement> activate = std::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 688276c..befd76d 100644
--- a/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp
@@ -1,63 +1,61 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
namespace Swift {
SearchPayloadSerializer::SearchPayloadSerializer() {
}
-std::string SearchPayloadSerializer::serializePayload(boost::shared_ptr<SearchPayload> searchPayload) const {
- XMLElement searchElement("query", "jabber:iq:search");
+std::string SearchPayloadSerializer::serializePayload(std::shared_ptr<SearchPayload> searchPayload) const {
+ XMLElement searchElement("query", "jabber:iq:search");
- if (searchPayload->getInstructions()) {
- searchElement.addNode(XMLElement::ref(new XMLElement("instructions", "", *searchPayload->getInstructions())));
- }
+ if (searchPayload->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)));
+ for (const auto& item : searchPayload->getItems()) {
+ XMLElement::ref itemElement(new XMLElement("item"));
+ itemElement->setAttribute("jid", item.jid);
+ itemElement->addNode(XMLElement::ref(new XMLElement("first", "", item.first)));
+ itemElement->addNode(XMLElement::ref(new XMLElement("last", "", item.last)));
+ itemElement->addNode(XMLElement::ref(new XMLElement("nick", "", item.nick)));
+ itemElement->addNode(XMLElement::ref(new XMLElement("email", "", item.email)));
- searchElement.addNode(itemElement);
- }
+ 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(std::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 c764de0..51f4227 100644
--- a/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,16 +8,16 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/SearchPayload.h>
+#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(std::shared_ptr<SearchPayload>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp b/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp
index 78cc605..b8faf73 100644
--- a/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp
@@ -1,46 +1,46 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
-
#include <Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h>
-#include <Swiften/Base/foreach.h>
+
+#include <memory>
+
+#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
SecurityLabelSerializer::SecurityLabelSerializer() : GenericPayloadSerializer<SecurityLabel>() {
}
-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();
+std::string SecurityLabelSerializer::serializePayload(std::shared_ptr<SecurityLabel> label) const {
+ XMLElement element("securitylabel", "urn:xmpp:sec-label:0");
+ if (!label->getDisplayMarking().empty()) {
+ std::shared_ptr<XMLElement> displayMarking(new XMLElement("displaymarking"));
+ if (!label->getForegroundColor().empty()) {
+ displayMarking->setAttribute("fgcolor", label->getForegroundColor());
+ }
+ if (!label->getBackgroundColor().empty()) {
+ displayMarking->setAttribute("bgcolor", label->getBackgroundColor());
+ }
+ displayMarking->addNode(std::make_shared<XMLTextNode>(label->getDisplayMarking()));
+ element.addNode(displayMarking);
+ }
+
+ std::shared_ptr<XMLElement> labelElement(new XMLElement("label"));
+ labelElement->addNode(std::make_shared<XMLRawTextNode>(label->getLabel()));
+ element.addNode(labelElement);
+
+ for (const auto& equivalentLabel : label->getEquivalentLabels()) {
+ std::shared_ptr<XMLElement> equivalentLabelElement(new XMLElement("equivalentlabel"));
+ equivalentLabelElement->addNode(std::make_shared<XMLRawTextNode>(equivalentLabel));
+ element.addNode(equivalentLabelElement);
+ }
+ return element.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h b/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h
index e9f3de3..b1eaaed 100644
--- a/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/SecurityLabel.h>
+#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(std::shared_ptr<SecurityLabel> version) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp b/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp
index 2c3dc06..36401a6 100644
--- a/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp
@@ -1,46 +1,46 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
-
#include <Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.h>
-#include <Swiften/Base/foreach.h>
+
+#include <memory>
+
+#include <Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
-#include <Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h>
namespace Swift {
SecurityLabelsCatalogSerializer::SecurityLabelsCatalogSerializer() : GenericPayloadSerializer<SecurityLabelsCatalog>() {
}
-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();
+std::string SecurityLabelsCatalogSerializer::serializePayload(std::shared_ptr<SecurityLabelsCatalog> catalog) const {
+ XMLElement element("catalog", "urn:xmpp:sec-label:catalog:2");
+ if (!catalog->getName().empty()) {
+ element.setAttribute("name", catalog->getName());
+ }
+ if (catalog->getTo().isValid()) {
+ element.setAttribute("to", catalog->getTo());
+ }
+ if (!catalog->getDescription().empty()) {
+ element.setAttribute("desc", catalog->getDescription());
+ }
+ for (const auto& item : catalog->getItems()) {
+ std::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
+ itemElement->setAttribute("selector", item.getSelector());
+ if (item.getIsDefault()) {
+ itemElement->setAttribute("default", "true");
+ }
+ if (item.getLabel()) {
+ std::string serializedLabel = SecurityLabelSerializer().serialize(item.getLabel());
+ itemElement->addNode(std::make_shared<XMLRawTextNode>(serializedLabel));
+ }
+ element.addNode(itemElement);
+ }
+ return element.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.h b/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.h
index 692dfcf..c3efc1e 100644
--- a/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/SecurityLabelsCatalog.h>
+#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(std::shared_ptr<SecurityLabelsCatalog> version) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.cpp b/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.cpp
index 8c0c605..2245030 100644
--- a/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -11,19 +11,19 @@ namespace Swift {
SoftwareVersionSerializer::SoftwareVersionSerializer() : GenericPayloadSerializer<SoftwareVersion>() {
}
-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 SoftwareVersionSerializer::serializePayload(std::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;
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.h b/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.h
index d4e7cba..7f0875b 100644
--- a/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/SoftwareVersionSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/SoftwareVersion.h>
+#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(std::shared_ptr<SoftwareVersion> version) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/StartSessionSerializer.h b/Swiften/Serializer/PayloadSerializers/StartSessionSerializer.h
index 1815955..12e6994 100644
--- a/Swiften/Serializer/PayloadSerializers/StartSessionSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/StartSessionSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::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 92c51d2..0e81a26 100644
--- a/Swiften/Serializer/PayloadSerializers/StatusSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/StatusSerializer.h
@@ -1,28 +1,28 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
+#include <Swiften/Elements/Status.h>
#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
-#include <Swiften/Elements/Status.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(std::shared_ptr<Status> status) const {
+ XMLElement element("status");
+ element.addNode(std::make_shared<XMLTextNode>(status->getText()));
+ return element.serialize();
+ }
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/StatusShowSerializer.h b/Swiften/Serializer/PayloadSerializers/StatusShowSerializer.h
index 33273ba..155b645 100644
--- a/Swiften/Serializer/PayloadSerializers/StatusShowSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/StatusShowSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,31 +7,31 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/StatusShow.h>
+#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(std::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..ffebcf4 100644
--- a/Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp
@@ -1,15 +1,13 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/StorageSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
@@ -18,35 +16,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(std::shared_ptr<Storage> storage) const {
+ XMLElement storageElement("storage", "storage:bookmarks");
+
+ for (const auto& room : storage->getRooms()) {
+ std::shared_ptr<XMLElement> conferenceElement(new XMLElement("conference"));
+ conferenceElement->setAttribute("name", room.name);
+ conferenceElement->setAttribute("jid", room.jid);
+ conferenceElement->setAttribute("autojoin", room.autoJoin ? "1" : "0");
+ if (!room.nick.empty()) {
+ std::shared_ptr<XMLElement> nickElement(new XMLElement("nick"));
+ nickElement->addNode(std::make_shared<XMLTextNode>(room.nick));
+ conferenceElement->addNode(nickElement);
+ }
+ if (room.password) {
+ std::shared_ptr<XMLElement> passwordElement(new XMLElement("password"));
+ passwordElement->addNode(std::make_shared<XMLTextNode>(*room.password));
+ conferenceElement->addNode(passwordElement);
+ }
+ storageElement.addNode(conferenceElement);
+ }
+
+ for (const auto& url : storage->getURLs()) {
+ std::shared_ptr<XMLElement> urlElement(new XMLElement("url"));
+ urlElement->setAttribute("name", url.name);
+ urlElement->setAttribute("url", url.url);
+ storageElement.addNode(urlElement);
+ }
+
+ return storageElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/StorageSerializer.h b/Swiften/Serializer/PayloadSerializers/StorageSerializer.h
index 68deff8..9f88fa1 100644
--- a/Swiften/Serializer/PayloadSerializers/StorageSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/StorageSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/Storage.h>
+#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(std::shared_ptr<Storage>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp
index 7b0cad8..ba296f9 100644
--- a/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp
@@ -4,53 +4,56 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Base/DateTime.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
-
-
namespace Swift {
StreamInitiationFileInfoSerializer::StreamInitiationFileInfoSerializer() {
}
-
-std::string StreamInitiationFileInfoSerializer::serializePayload(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();
+
+std::string StreamInitiationFileInfoSerializer::serializePayload(std::shared_ptr<StreamInitiationFileInfo> fileInfo) const {
+ XMLElement fileElement("file", "http://jabber.org/protocol/si/profile/file-transfer");
+
+ if (fileInfo->getDate() != stringToDateTime("")) {
+ fileElement.setAttribute("date", dateTimeToString(fileInfo->getDate()));
+ }
+ fileElement.setAttribute("hash", fileInfo->getHash());
+ if (fileInfo->getAlgo() != "md5") {
+ fileElement.setAttribute("algo", fileInfo->getAlgo());
+ }
+ if (!fileInfo->getName().empty()) {
+ fileElement.setAttribute("name", fileInfo->getName());
+ }
+ if (fileInfo->getSize() != 0) {
+ fileElement.setAttribute("size", boost::lexical_cast<std::string>(fileInfo->getSize()));
+ }
+ if (!fileInfo->getDescription().empty()) {
+ std::shared_ptr<XMLElement> desc = std::make_shared<XMLElement>("desc", "", fileInfo->getDescription());
+ fileElement.addNode(desc);
+ }
+ if (fileInfo->getSupportsRangeRequests()) {
+ std::shared_ptr<XMLElement> range = std::make_shared<XMLElement>("range");
+ if (fileInfo->getRangeOffset() != 0) {
+ range->setAttribute("offset", boost::lexical_cast<std::string>(fileInfo->getRangeOffset()));
+ }
+ fileElement.addNode(range);
+ }
+ return fileElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h
index 1f1e9d7..de54313 100644
--- a/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h
@@ -4,22 +4,27 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/StreamInitiationFileInfo.h>
-
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
#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(std::shared_ptr<StreamInitiationFileInfo>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
index bd44040..3faa5b7 100644
--- a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
@@ -1,16 +1,15 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <memory>
#include <boost/lexical_cast.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
@@ -25,51 +24,51 @@ namespace Swift {
StreamInitiationSerializer::StreamInitiationSerializer() {
}
-std::string StreamInitiationSerializer::serializePayload(boost::shared_ptr<StreamInitiation> streamInitiation) const {
- assert(streamInitiation->getIsFileTransfer());
+std::string StreamInitiationSerializer::serializePayload(std::shared_ptr<StreamInitiation> streamInitiation) const {
+ assert(streamInitiation->getIsFileTransfer());
- XMLElement siElement("si", "http://jabber.org/protocol/si");
- if (!streamInitiation->getID().empty()) {
- siElement.setAttribute("id", streamInitiation->getID());
- }
- siElement.setAttribute("profile", FILE_TRANSFER_NS);
+ 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();
+ std::shared_ptr<XMLElement> fileElement(new XMLElement("file", "http://jabber.org/protocol/si/profile/file-transfer"));
+ fileElement->setAttribute("name", file.getName());
+ if (file.getSize() != 0) {
+ fileElement->setAttribute("size", boost::lexical_cast<std::string>(file.getSize()));
+ }
+ if (!file.getDescription().empty()) {
+ std::shared_ptr<XMLElement> descElement(new XMLElement("desc"));
+ descElement->addNode(std::make_shared<XMLTextNode>(file.getDescription()));
+ fileElement->addNode(descElement);
+ }
+ siElement.addNode(fileElement);
+ }
- 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();
+ std::shared_ptr<XMLElement> featureElement(new XMLElement("feature", FEATURE_NEG_NS));
+ if (streamInitiation->getProvidedMethods().size() > 0) {
+ Form::ref form(new Form(Form::FormType));
+ FormField::ref field = std::make_shared<FormField>(FormField::ListSingleType);
+ field->setName("stream-method");
+ for (const auto& method : streamInitiation->getProvidedMethods()) {
+ field->addOption(FormField::Option("", method));
+ }
+ form->addField(field);
+ featureElement->addNode(std::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
+ }
+ else if (!streamInitiation->getRequestedMethod().empty()) {
+ Form::ref form(new Form(Form::SubmitType));
+ FormField::ref field = std::make_shared<FormField>(FormField::ListSingleType);
+ field->addValue(streamInitiation->getRequestedMethod());
+ field->setName("stream-method");
+ form->addField(field);
+ featureElement->addNode(std::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
+ }
+ siElement.addNode(featureElement);
+ return siElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.h b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.h
index 11aea16..73dbc39 100644
--- a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/StreamInitiation.h>
+#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(std::shared_ptr<StreamInitiation>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/SubjectSerializer.h b/Swiften/Serializer/PayloadSerializers/SubjectSerializer.h
index 580164b..20f95fd 100644
--- a/Swiften/Serializer/PayloadSerializers/SubjectSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/SubjectSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,18 +7,18 @@
#pragma once
#include <Swiften/Base/API.h>
+#include <Swiften/Elements/Subject.h>
#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
-#include <Swiften/Elements/Subject.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(std::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..5914cf2 100644
--- a/Swiften/Serializer/PayloadSerializers/ThreadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/ThreadSerializer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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(std::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 9aae887..07ecb82 100644
--- a/Swiften/Serializer/PayloadSerializers/ThreadSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/ThreadSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,16 +7,16 @@
#pragma once
#include <Swiften/Base/API.h>
+#include <Swiften/Elements/Thread.h>
#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
-#include <Swiften/Elements/Thread.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(std::shared_ptr<Thread> thread) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/BlockSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/BlockSerializerTest.cpp
index 7772381..9b9e00d 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/BlockSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/BlockSerializerTest.cpp
@@ -4,52 +4,58 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/PayloadSerializers/BlockSerializer.h>
#include <Swiften/Elements/BlockListPayload.h>
#include <Swiften/Elements/BlockPayload.h>
#include <Swiften/Elements/UnblockPayload.h>
#include <Swiften/JID/JID.h>
+#include <Swiften/Serializer/PayloadSerializers/BlockSerializer.h>
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");
+ std::shared_ptr<BlockListPayload> blocklist = std::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");
+ std::shared_ptr<BlockPayload> block = std::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");
+ std::shared_ptr<UnblockPayload> unblock = std::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..c4e3ad8 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/CapsInfoSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/CapsInfoSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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 1f0394d..9ac8416 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/CarbonsSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/CarbonsSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,130 +7,130 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
#include <Swiften/Elements/CarbonsDisable.h>
#include <Swiften/Elements/CarbonsEnable.h>
#include <Swiften/Elements/CarbonsPrivate.h>
#include <Swiften/Elements/CarbonsReceived.h>
#include <Swiften/Elements/CarbonsSent.h>
-#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Forwarded.h>
+#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Thread.h>
#include <Swiften/JID/JID.h>
+#include <Swiften/Serializer/PayloadSerializers/CarbonsDisableSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/CarbonsEnableSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/CarbonsPrivateSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/CarbonsReceivedSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/CarbonsSentSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/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(std::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(std::make_shared<CarbonsDisable>()));
+ }
+
+ /*
+ * Test serializing of example 12 in XEP-0280.
+ */
+ void testSerializeExample12() {
+ CarbonsReceivedSerializer testling(&serializers);
+
+ CarbonsReceived::ref received = std::make_shared<CarbonsReceived>();
+
+ std::shared_ptr<Forwarded> forwarded = std::make_shared<Forwarded>();
+
+ Message::ref message = std::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(std::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 = std::make_shared<CarbonsSent>();
+
+ std::shared_ptr<Forwarded> forwarded = std::make_shared<Forwarded>();
+
+ Message::ref message = std::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(std::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(std::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..018d2cc 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/ChatStateSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/ChatStateSerializerTest.cpp
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -13,42 +19,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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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 9282db4..7ed9421 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/DeliveryReceiptSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/DeliveryReceiptSerializerTest.cpp
@@ -4,41 +4,46 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <memory>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/DeliveryReceiptRequestSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/DeliveryReceiptSerializer.h>
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 = std::make_shared<DeliveryReceiptRequest>();
- boost::shared_ptr<DeliveryReceiptRequestSerializer> serializer = boost::make_shared<DeliveryReceiptRequestSerializer>();
- CPPUNIT_ASSERT_EQUAL(expected, serializer->serializePayload(receipt));
- }
+ std::shared_ptr<DeliveryReceiptRequestSerializer> serializer = std::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 = std::make_shared<DeliveryReceipt>("richard2-4.1.247");
- boost::shared_ptr<DeliveryReceiptSerializer> serializer = boost::make_shared<DeliveryReceiptSerializer>();
- CPPUNIT_ASSERT_EQUAL(expected, serializer->serializePayload(receipt));
- }
+ std::shared_ptr<DeliveryReceiptSerializer> serializer = std::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..318c3d7 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/DiscoInfoSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/DiscoInfoSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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;
+ std::shared_ptr<DiscoInfo> discoInfo(new DiscoInfo());
+ discoInfo->addFeature("http://jabber.org/protocol/caps");
+ discoInfo->addFeature("http://jabber.org/protocol/disco#info");
+ std::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 eb84ff2..68a72b8 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/ErrorSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/ErrorSerializerTest.cpp
@@ -1,45 +1,46 @@
/*
- * Copyright (c) 2010-2012 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <Swiften/Elements/Delay.h>
#include <Swiften/Serializer/PayloadSerializers/ErrorSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
-#include <Swiften/Elements/Delay.h>
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);
+ std::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);
+ std::shared_ptr<ErrorPayload> error = std::make_shared<ErrorPayload>();
+ error->setPayload(std::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 73c9db1..6534dce 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/FormSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/FormSerializerTest.cpp
@@ -1,298 +1,298 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/smart_ptr/make_shared.hpp>
-
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
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;
+ std::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;
+ std::shared_ptr<Form> form(new Form(Form::FormType));
+
+ FormPage::page page = std::make_shared<FormPage>();
+ page->setLabel("P1");
+ FormReportedRef::ref reportedRef = std::make_shared<FormReportedRef>();
+ page->addReportedRef(reportedRef);
+ FormText::text formText = std::make_shared<FormText>();
+ formText->setTextString("P1T1");
+ page->addTextElement(formText);
+ FormField::ref field = std::make_shared<FormField>(FormField::TextSingleType);
+ field->setName("P1F1");
+ field->setLabel("field one");
+ page->addField(field);
+
+ FormSection::section section = std::make_shared<FormSection>();
+ section->setLabel("P1S1");
+ formText = std::make_shared<FormText>();
+ formText->setTextString("P1S1T1");
+ section->addTextElement(formText);
+ field = std::make_shared<FormField>(FormField::TextSingleType);
+ field->setName("P1S1F1");
+ field->setLabel("field two");
+ section->addField(field);
+ page->addChildSection(section);
+ form->addPage(page);
+
+ page = std::make_shared<FormPage>();
+ page->setLabel("P2");
+ section = std::make_shared<FormSection>();
+ section->setLabel("P2S1");
+ FormSection::section subSection = std::make_shared<FormSection>();
+ subSection->setLabel("P2S2");
+ FormSection::section subSection2 = std::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;
+ std::shared_ptr<Form> form(new Form(Form::FormType));
+
+ FormField::ref field = std::make_shared<FormField>(FormField::HiddenType, "jabber:bot");
+ field->setName("FORM_TYPE");
+ form->addField(field);
+
+ form->addField(std::make_shared<FormField>(FormField::FixedType, "Section 1: Bot Info"));
+
+ field = std::make_shared<FormField>(FormField::TextSingleType);
+ field->setName("botname");
+ field->setLabel("The name of your bot");
+ form->addField(field);
+
+ field = std::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 = std::make_shared<FormField>(FormField::BooleanType, "1");
+ field->setName("public");
+ field->setLabel("Public bot?");
+ field->setRequired(true);
+ form->addField(field);
+
+ field = std::make_shared<FormField>(FormField::TextPrivateType);
+ field->setName("password");
+ field->setLabel("Password for special access");
+ form->addField(field);
+
+ field = std::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 = std::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 = std::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;
+ std::shared_ptr<Form> form(new Form(Form::ResultType));
+
+ FormField::ref field = std::make_shared<FormField>(FormField::HiddenType, "jabber:iq:search");
+ field->setName("FORM_TYPE");
+ form->addField(field);
+
+ // reported fields
+ field = std::make_shared<FormField>(FormField::TextSingleType);
+ field->setName("first");
+ field->setLabel("Given Name");
+ form->addReportedField(field);
+
+ field = std::make_shared<FormField>(FormField::TextSingleType);
+ field->setName("last");
+ field->setLabel("Family Name");
+ form->addReportedField(field);
+
+ field = std::make_shared<FormField>(FormField::JIDSingleType);
+ field->setName("jid");
+ field->setLabel("Jabber ID");
+ form->addReportedField(field);
+
+ field = std::make_shared<FormField>(FormField::ListSingleType);
+ field->setName("x-gender");
+ field->setLabel("Gender");
+ form->addReportedField(field);
+
+ Form::FormItem firstItem;
+ field = std::make_shared<FormField>(FormField::TextSingleType, "Benvolio");
+ field->setName("first");
+ firstItem.push_back(field);
+
+ field = std::make_shared<FormField>(FormField::TextSingleType, "Montague");
+ field->setName("last");
+ firstItem.push_back(field);
+
+ field = std::make_shared<FormField>(FormField::JIDSingleType, JID("benvolio@montague.net"));
+ field->setName("jid");
+ firstItem.push_back(field);
+
+ field = std::make_shared<FormField>(FormField::ListSingleType, "male");
+ field->setName("x-gender");
+ firstItem.push_back(field);
+
+ Form::FormItem secondItem;
+ field = std::make_shared<FormField>(FormField::TextSingleType, "Romeo");
+ field->setName("first");
+ secondItem.push_back(field);
+
+ field = std::make_shared<FormField>(FormField::TextSingleType, "Montague");
+ field->setName("last");
+ secondItem.push_back(field);
+
+ field = std::make_shared<FormField>(FormField::JIDSingleType, JID("romeo@montague.net"));
+ field->setName("jid");
+ secondItem.push_back(field);
+
+ field = std::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..b0f41d4 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/ForwardedSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/ForwardedSerializerTest.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -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);
+
+ std::shared_ptr<IQ> iq = IQ::createResult(JID("juliet@capulet.lit/balcony"), JID("romeo@montague.lit/orchard"), "id0");
+
+ std::shared_ptr<Forwarded> forwarded(std::make_shared<Forwarded>());
+ forwarded->setStanza(iq);
+ forwarded->setDelay(std::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);
+
+ std::shared_ptr<Message> message(std::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.");
+
+ std::shared_ptr<Forwarded> forwarded(std::make_shared<Forwarded>());
+ forwarded->setStanza(message);
+ forwarded->setDelay(std::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);
+
+ std::shared_ptr<Message> message(std::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.");
+
+ std::shared_ptr<Forwarded> forwarded(std::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);
+
+ std::shared_ptr<Presence> presence(std::make_shared<Presence>());
+ presence->setType(Presence::Subscribe);
+
+ std::shared_ptr<Forwarded> forwarded(std::make_shared<Forwarded>());
+ forwarded->setStanza(presence);
+ forwarded->setDelay(std::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 0d50101..84412c9 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/IBBSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/IBBSerializerTest.cpp
@@ -4,35 +4,41 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/PayloadSerializers/IBBSerializer.h>
-#include <Swiften/Elements/IBB.h>
#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Elements/IBB.h>
+#include <Swiften/Serializer/PayloadSerializers/IBBSerializer.h>
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;
+ std::shared_ptr<IBB> ibb = std::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 9700869..46598da 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/IdleSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/IdleSerializerTest.cpp
@@ -4,29 +4,35 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/make_shared.hpp>
-
#include <Swiften/Serializer/PayloadSerializers/IdleSerializer.h>
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 = std::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 357ffab..44ac7a1 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/InBandRegistrationPayloadSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/InBandRegistrationPayloadSerializerTest.cpp
@@ -1,62 +1,63 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.h>
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;
+ std::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;
+ std::shared_ptr<InBandRegistrationPayload> registration(new InBandRegistrationPayload());
+ registration->setInstructions("Use the enclosed form to register.");
+
+ std::shared_ptr<Form> form(new Form(Form::FormType));
+ form->setTitle("Contest Registration");
+
+ FormField::ref field = std::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 487febf..4a466ba 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/IsodeIQDelegationSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/IsodeIQDelegationSerializerTest.cpp
@@ -4,123 +4,129 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
-#include <Swiften/Elements/IsodeIQDelegation.h>
+#include <Swiften/Base/DateTime.h>
#include <Swiften/Elements/Delay.h>
#include <Swiften/Elements/Forwarded.h>
#include <Swiften/Elements/IQ.h>
+#include <Swiften/Elements/IsodeIQDelegation.h>
#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/Subject.h>
#include <Swiften/JID/JID.h>
-#include <Swiften/Base/DateTime.h>
+#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h>
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);
+ std::shared_ptr<IsodeIQDelegation> isodeIQDelegation = std::make_shared<IsodeIQDelegation>();
+
+ std::shared_ptr<IQ> iq = IQ::createResult(JID("juliet@capulet.lit/balcony"), JID("romeo@montague.lit/orchard"), "id0", std::make_shared<Subject>("text"));
+
+ std::shared_ptr<Forwarded> forwarded(std::make_shared<Forwarded>());
+ forwarded->setStanza(iq);
+ forwarded->setDelay(std::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);
+ std::shared_ptr<IsodeIQDelegation> isodeIQDelegation = std::make_shared<IsodeIQDelegation>();
+
+ std::shared_ptr<Message> message(std::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.");
+
+ std::shared_ptr<Forwarded> forwarded(std::make_shared<Forwarded>());
+ forwarded->setStanza(message);
+ forwarded->setDelay(std::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);
+ std::shared_ptr<IsodeIQDelegation> isodeIQDelegation = std::make_shared<IsodeIQDelegation>();
+
+ std::shared_ptr<Message> message(std::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.");
+
+ std::shared_ptr<Forwarded> forwarded(std::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);
+ std::shared_ptr<IsodeIQDelegation> isodeIQDelegation = std::make_shared<IsodeIQDelegation>();
+
+ std::shared_ptr<Presence> presence(std::make_shared<Presence>());
+ presence->setType(Presence::Subscribe);
+
+ std::shared_ptr<Forwarded> forwarded(std::make_shared<Forwarded>());
+ forwarded->setStanza(presence);
+ forwarded->setDelay(std::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 9d9996d..c259cce 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp
@@ -5,404 +5,403 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/Base/DateTime.h>
#include <Swiften/Elements/JingleFileTransferDescription.h>
#include <Swiften/Elements/JingleFileTransferFileInfo.h>
-#include <Swiften/Elements/JingleIBBTransportPayload.h>
-#include <Swiften/Elements/JingleS5BTransportPayload.h>
#include <Swiften/Elements/JingleFileTransferHash.h>
+#include <Swiften/Elements/JingleIBBTransportPayload.h>
#include <Swiften/Elements/JinglePayload.h>
-#include <Swiften/Base/DateTime.h>
+#include <Swiften/Elements/JingleS5BTransportPayload.h>
+#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h>
#include <Swiften/StringCodecs/Base64.h>
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();
+
+ std::shared_ptr<JinglePayloadSerializer> createTestling() {
+ return std::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 = std::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);
+
+ std::shared_ptr<StreamInitiationFileInfoSerializer> serializer = std::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 = std::make_shared<StreamInitiationFileInfo>();
+ fileInfo->setHash("552da749930852c69ae5d2141d3766b1");
+ fileInfo->setSupportsRangeRequests(true);
+ fileInfo->setRangeOffset(270336);
+
+ std::shared_ptr<StreamInitiationFileInfoSerializer> serializer = std::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 = std::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionInitiate);
+ payload->setSessionID("a73sjjvkla37jfea");
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+
+ JingleIBBTransportPayload::ref transport = std::make_shared<JingleIBBTransportPayload>();
+ transport->setBlockSize(4096);
+ transport->setSessionID("ch3d9s71");
+
+ JingleContentPayload::ref content = std::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 = std::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::TransportInfo);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+
+ JingleContentPayload::ref content = std::make_shared<JingleContentPayload>();
+ content->setCreator(JingleContentPayload::InitiatorCreator);
+ content->setName("ex");
+
+ JingleIBBTransportPayload::ref transport = std::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 = std::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 = std::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, std::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 = std::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionAccept);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("851ba2");
+
+ JingleContentPayload::ref content = std::make_shared<JingleContentPayload>();
+ content->setCreator(JingleContentPayload::InitiatorCreator);
+ content->setName("a-file-offer");
+
+ JingleFileTransferDescription::ref description = std::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 = std::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::TransportInfo);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+
+ JingleContentPayload::ref content = std::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 = std::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionInfo);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+
+ JingleFileTransferHash::ref hash = std::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 = std::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionInitiate);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+
+ JingleContentPayload::ref content = std::make_shared<JingleContentPayload>();
+ content->setCreator(JingleContentPayload::InitiatorCreator);
+ content->setName("ex");
+
+ JingleS5BTransportPayload::ref transport = std::make_shared<JingleS5BTransportPayload>();
+ transport->setMode(JingleS5BTransportPayload::TCPMode);
+ transport->setDstAddr("1a12fb7bc625e55f3ed5b29a53dbe0e4aa7d80ba");
+ transport->setSessionID("vj3hs98y");
+
+ JingleS5BTransportPayload::Candidate candidate1;
+ candidate1.cid = "hft54dqy";
+ candidate1.hostPort = HostAddressPort(HostAddress::fromString("192.168.4.1").get(), 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::fromString("24.24.24.1").get(), 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 7a73f30..198f73c 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/MAMFinSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MAMFinSerializerTest.cpp
@@ -1,64 +1,64 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h>
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");
+ std::shared_ptr<MAMFin> fin = std::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);
+ std::shared_ptr<MAMFin> fin = std::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);
+ std::shared_ptr<ResultSet> set = std::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 e3c1c83..cc46ef9 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/MAMQuerySerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MAMQuerySerializerTest.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -13,61 +13,61 @@
#include <Swiften/Elements/Delay.h>
#include <Swiften/Elements/MAMResult.h>
#include <Swiften/Elements/Message.h>
-#include <Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h>
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h>
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>());
+ std::shared_ptr<Form> parameters(std::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);
+ std::shared_ptr<FormField> fieldType = std::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);
+ std::shared_ptr<FormField> fieldStart = std::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);
+ std::shared_ptr<ResultSet> set = std::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);
+ std::shared_ptr<MAMQuery> query(std::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 875abdc..09bec39 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/MAMResultSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MAMResultSerializerTest.cpp
@@ -1,10 +1,10 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -13,50 +13,50 @@
#include <Swiften/Elements/Delay.h>
#include <Swiften/Elements/MAMResult.h>
#include <Swiften/Elements/Message.h>
-#include <Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h>
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);
+
+ std::shared_ptr<Message> message(std::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.");
+
+ std::shared_ptr<Forwarded> forwarded(std::make_shared<Forwarded>());
+ forwarded->setStanza(message);
+ forwarded->setDelay(std::make_shared<Delay>(stringToDateTime(std::string("2010-07-10T23:08:25Z"))));
+
+ std::shared_ptr<MAMResult> result(std::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 a14214b..5aeb9dd 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/MUCAdminPayloadSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MUCAdminPayloadSerializerTest.cpp
@@ -1,39 +1,39 @@
/*
- * Copyright (c) 2011 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/smart_ptr/make_shared.hpp>
-
#include <Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.h>
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;
+ std::shared_ptr<MUCAdminPayload> admin = std::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..d34ea38 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -12,15 +12,15 @@
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 "";
- }
+std::string PayloadsSerializer::serialize(std::shared_ptr<Payload> payload) {
+ 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 d385453..5e0f0c5 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.h
@@ -1,23 +1,23 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <string>
#include <Swiften/Elements/Payload.h>
-#include <string>
#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(std::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..87d7d0f 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/PrioritySerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/PrioritySerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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 824eb1e..4e77e7d 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/PrivateStorageSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/PrivateStorageSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,44 +7,44 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.h>
#include <Swiften/Elements/PrivateStorage.h>
#include <Swiften/Elements/Storage.h>
+#include <Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.h>
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;
+
+ std::shared_ptr<PrivateStorage> privateStorage(new PrivateStorage());
+ std::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 47d6d56..e8673b9 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemSerializerTest.cpp
@@ -1,59 +1,59 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <Swiften/Elements/PubSubItem.h>
#include <Swiften/Elements/RawXMLPayload.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h>
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\"/>");
+ std::shared_ptr<RawXMLPayload> payload(std::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");
+ std::shared_ptr<PubSubItem> item(std::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>());
+ std::shared_ptr<PubSubItem> item(std::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 0d28e13..0194553 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemsSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/PubSubItemsSerializerTest.cpp
@@ -1,77 +1,77 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <Swiften/Elements/PubSubItems.h>
#include <Swiften/Elements/RawXMLPayload.h>
-#include <Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h>
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\"/>");
+ std::shared_ptr<RawXMLPayload> payload1(std::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");
+ std::shared_ptr<PubSubItem> item1(std::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\"/>");
+ std::shared_ptr<RawXMLPayload> payload2(std::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");
+ std::shared_ptr<PubSubItem> item2(std::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);
+ std::shared_ptr<PubSubItems> items(std::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>());
+ std::shared_ptr<PubSubItems> items(std::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/PubSubRetractSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/PubSubRetractSerializerTest.cpp
new file mode 100644
index 0000000..f00eddc
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/PubSubRetractSerializerTest.cpp
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
+#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h>
+
+using namespace Swift;
+
+class PubSubRetractSerializerTest: public CppUnit::TestFixture {
+ CPPUNIT_TEST_SUITE(PubSubRetractSerializerTest);
+ CPPUNIT_TEST(testSerializeDefault);
+ CPPUNIT_TEST(testSerializeNotify);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ PubSubRetractSerializerTest() {}
+
+ std::shared_ptr<PubSubItem> somePubSubItem() {
+ auto item = std::make_shared<PubSubItem>();
+ item->setID("ae890ac52d0df67ed7cfdf51b644e901");
+ return item;
+ }
+
+ void testSerializeDefault() {
+ PubSubRetractSerializer testling(&serializer);
+ auto retract = std::make_shared<PubSubRetract>();
+ retract->setNode("princely_musings");
+ retract->setItems({somePubSubItem()});
+ CPPUNIT_ASSERT_EQUAL(std::string("<retract node=\"princely_musings\" xmlns=\"http://jabber.org/protocol/pubsub\"><item id=\"ae890ac52d0df67ed7cfdf51b644e901\" xmlns=\"http://jabber.org/protocol/pubsub\"/></retract>"), testling.serialize(retract));
+ }
+
+ void testSerializeNotify() {
+ PubSubRetractSerializer testling(&serializer);
+ auto retract = std::make_shared<PubSubRetract>();
+ retract->setNode("princely_musings");
+ retract->setItems({somePubSubItem()});
+ retract->setNotify(true);
+ CPPUNIT_ASSERT_EQUAL(std::string("<retract node=\"princely_musings\" notify=\"true\" xmlns=\"http://jabber.org/protocol/pubsub\"><item id=\"ae890ac52d0df67ed7cfdf51b644e901\" xmlns=\"http://jabber.org/protocol/pubsub\"/></retract>"), testling.serialize(retract));
+
+ retract = std::make_shared<PubSubRetract>();
+ retract->setNode("princely_musings");
+ retract->setItems({somePubSubItem()});
+ retract->setNotify(false);
+ CPPUNIT_ASSERT_EQUAL(std::string("<retract node=\"princely_musings\" notify=\"false\" xmlns=\"http://jabber.org/protocol/pubsub\"><item id=\"ae890ac52d0df67ed7cfdf51b644e901\" xmlns=\"http://jabber.org/protocol/pubsub\"/></retract>"), testling.serialize(retract));
+ }
+
+ private:
+ FullPayloadSerializerCollection serializer;
+};
+
+CPPUNIT_TEST_SUITE_REGISTRATION(PubSubRetractSerializerTest);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/ReplaceSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/ReplaceSerializerTest.cpp
index 6a51182..4aab334 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/ReplaceSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/ReplaceSerializerTest.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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..30cd6e7 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/ResourceBindSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/ResourceBindSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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;
+ std::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;
+ std::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 2750c9f..fecd3c5 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/ResultSetSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/ResultSetSerializerTest.cpp
@@ -1,118 +1,118 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
#include <Swiften/Elements/ResultSet.h>
+#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h>
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>());
+ std::shared_ptr<ResultSet> resultSet(std::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>());
+ std::shared_ptr<ResultSet> resultSet(std::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>());
+ std::shared_ptr<ResultSet> resultSet(std::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>());
+ std::shared_ptr<ResultSet> resultSet(std::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>());
+ std::shared_ptr<ResultSet> resultSet(std::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..652becb 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/RosterItemExchangeSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/RosterItemExchangeSerializerTest.cpp
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -13,42 +19,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;
+ std::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..0c576d2 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/RosterSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/RosterSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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;
+ std::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;
+ std::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;
+ std::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 d9b9aa6..3deca11 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/SearchPayloadSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/SearchPayloadSerializerTest.cpp
@@ -1,176 +1,177 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.h>
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());
+ std::shared_ptr<Form> form(new Form(Form::ResultType));
+
+ FormField::ref field = std::make_shared<FormField>(FormField::HiddenType, "jabber:iq:search");
+ field->setName("FORM_TYPE");
+ form->addField(field);
+
+ // reported fields
+ field = std::make_shared<FormField>(FormField::TextSingleType);
+ field->setName("first");
+ field->setLabel("Given Name");
+ form->addReportedField(field);
+
+ field = std::make_shared<FormField>(FormField::TextSingleType);
+ field->setName("last");
+ field->setLabel("Family Name");
+ form->addReportedField(field);
+
+ field = std::make_shared<FormField>(FormField::JIDSingleType);
+ field->setName("jid");
+ field->setLabel("Jabber ID");
+ form->addReportedField(field);
+
+ field = std::make_shared<FormField>(FormField::ListSingleType);
+ field->setName("x-gender");
+ field->setLabel("Gender");
+ form->addReportedField(field);
+
+ Form::FormItem firstItem;
+ field = std::make_shared<FormField>(FormField::TextSingleType, "Benvolio");
+ field->setName("first");
+ firstItem.push_back(field);
+
+ field = std::make_shared<FormField>(FormField::TextSingleType, "Montague");
+ field->setName("last");
+ firstItem.push_back(field);
+
+ field = std::make_shared<FormField>(FormField::TextSingleType, "benvolio@montague.net");
+ field->setName("jid");
+ firstItem.push_back(field);
+
+ field = std::make_shared<FormField>(FormField::ListSingleType, "male");
+ field->setName("x-gender");
+ firstItem.push_back(field);
+
+ Form::FormItem secondItem;
+ field = std::make_shared<FormField>(FormField::TextSingleType, "Romeo");
+ field->setName("first");
+ secondItem.push_back(field);
+
+ field = std::make_shared<FormField>(FormField::TextSingleType, "Montague");
+ field->setName("last");
+ secondItem.push_back(field);
+
+ field = std::make_shared<FormField>(FormField::TextSingleType, "romeo@montague.net");
+ field->setName("jid");
+ secondItem.push_back(field);
+
+ field = std::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..6b65fd4 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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;
+ std::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..c3a72a5 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelsCatalogSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/SecurityLabelsCatalogSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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;
+ std::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;
+ std::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..a20efb7 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/SoftwareVersionSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/SoftwareVersionSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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..03a3ef5 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/StatusSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/StatusSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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..eb3b221 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/StatusShowSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/StatusShowSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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;
+ std::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;
+ std::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;
+ std::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;
+ std::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;
+ std::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 6319975..33c63cb 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/StorageSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/StorageSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,65 +7,65 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.h>
#include <Swiften/Elements/Storage.h>
+#include <Swiften/Serializer/PayloadSerializers/UnitTest/PayloadsSerializer.h>
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;
+ std::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;
+ std::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..a38295c 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/StreamInitiationSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/StreamInitiationSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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;
+ std::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 e1e3131..1a3adb9 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/UserLocationSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/UserLocationSerializerTest.cpp
@@ -4,94 +4,101 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
-#include <Swiften/Elements/UserLocation.h>
#include <Swiften/Base/DateTime.h>
+#include <Swiften/Elements/UserLocation.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);
+ std::shared_ptr<UserLocation> userLocation(new UserLocation());
+ userLocation->setArea(boost::optional<std::string>("Barbaric"));
+ userLocation->setAltitude(5.75);
+ userLocation->setLocality(boost::optional<std::string>("Near"));
+ userLocation->setLatitude(boost::optional<double>(5.75));
+ userLocation->setAccuracy(5.75);
+ 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.75);
+ userLocation->setError(5.75);
+ userLocation->setPostalCode(boost::optional<std::string>("67"));
+ userLocation->setBearing(5.75);
+ userLocation->setText(boost::optional<std::string>("Hello"));
+ userLocation->setDatum(boost::optional<std::string>("Datee"));
+ userLocation->setStreet(boost::optional<std::string>("Highway"));
+ userLocation->setSpeed(5.75);
- 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);
+ std::shared_ptr<UserLocation> userLocation(new UserLocation());
+ userLocation->setArea(boost::optional<std::string>("Barbaric"));
+ userLocation->setAltitude(5.75);
+ userLocation->setLocality(boost::optional<std::string>("Near"));
+ userLocation->setAccuracy(5.75);
+ 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.75);
+ userLocation->setError(5.75);
+ userLocation->setPostalCode(boost::optional<std::string>("67"));
+ userLocation->setBearing(5.75);
+ 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 2306e9e..df79f0d 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/UserTuneSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/UserTuneSerializerTest.cpp
@@ -4,59 +4,66 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h>
-#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
-#include <Swiften/Elements/UserTune.h>
#include <Swiften/Base/DateTime.h>
+#include <Swiften/Elements/UserTune.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();
-
- 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>";
-
- 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);
-
- 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_TEST_SUITE(UserTuneSerializerTest);
+ CPPUNIT_TEST(testSerialize_withAllVariablesSet);
+ CPPUNIT_TEST(testSerialize_withSomeVariablesSet);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ void testSerialize_withAllVariablesSet() {
+ UserTuneSerializer testling(&serializers);
+ std::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>";
+
+ CPPUNIT_ASSERT_EQUAL(expectedResult, testling.serialize(userTune));
+ }
+
+ void testSerialize_withSomeVariablesSet() {
+ UserTuneSerializer testling(&serializers);
+ std::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>";
+
+ 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..49402ec 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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..e3fc5ff 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/VCardUpdateSerializerTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/VCardUpdateSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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;
+ std::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..e0e496c 100644
--- a/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.cpp
@@ -1,100 +1,98 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Base/DateTime.h>
+
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Base/DateTime.h>
#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-UserLocationSerializer::UserLocationSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+UserLocationSerializer::UserLocationSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string UserLocationSerializer::serializePayload(std::shared_ptr<UserLocation> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("geoloc", "http://jabber.org/protocol/geoloc");
+ if (payload->getArea()) {
+ element.addNode(std::make_shared<XMLElement>("area", "", *payload->getArea()));
+ }
+ if (payload->getAltitude()) {
+ element.addNode(std::make_shared<XMLElement>("alt", "", boost::lexical_cast<std::string>(*payload->getAltitude())));
+ }
+ if (payload->getLocality()) {
+ element.addNode(std::make_shared<XMLElement>("locality", "", *payload->getLocality()));
+ }
+ if (payload->getLatitude()) {
+ element.addNode(std::make_shared<XMLElement>("lat", "", boost::lexical_cast<std::string>(*payload->getLatitude())));
+ }
+ if (payload->getAccuracy()) {
+ element.addNode(std::make_shared<XMLElement>("accuracy", "", boost::lexical_cast<std::string>(*payload->getAccuracy())));
+ }
+ if (payload->getDescription()) {
+ element.addNode(std::make_shared<XMLElement>("description", "", *payload->getDescription()));
+ }
+ if (payload->getCountryCode()) {
+ element.addNode(std::make_shared<XMLElement>("countrycode", "", *payload->getCountryCode()));
+ }
+ if (payload->getTimestamp()) {
+ element.addNode(std::make_shared<XMLElement>("timestamp", "", dateTimeToString(*payload->getTimestamp())));
+ }
+ if (payload->getFloor()) {
+ element.addNode(std::make_shared<XMLElement>("floor", "", *payload->getFloor()));
+ }
+ if (payload->getBuilding()) {
+ element.addNode(std::make_shared<XMLElement>("building", "", *payload->getBuilding()));
+ }
+ if (payload->getRoom()) {
+ element.addNode(std::make_shared<XMLElement>("room", "", *payload->getRoom()));
+ }
+ if (payload->getCountry()) {
+ element.addNode(std::make_shared<XMLElement>("country", "", *payload->getCountry()));
+ }
+ if (payload->getRegion()) {
+ element.addNode(std::make_shared<XMLElement>("region", "", *payload->getRegion()));
+ }
+ if (payload->getURI()) {
+ element.addNode(std::make_shared<XMLElement>("uri", "", *payload->getURI()));
+ }
+ if (payload->getLongitude()) {
+ element.addNode(std::make_shared<XMLElement>("lon", "", boost::lexical_cast<std::string>(*payload->getLongitude())));
+ }
+ if (payload->getError()) {
+ element.addNode(std::make_shared<XMLElement>("error", "", boost::lexical_cast<std::string>(*payload->getError())));
+ }
+ if (payload->getPostalCode()) {
+ element.addNode(std::make_shared<XMLElement>("postalcode", "", *payload->getPostalCode()));
+ }
+ if (payload->getBearing()) {
+ element.addNode(std::make_shared<XMLElement>("bearing", "", boost::lexical_cast<std::string>(*payload->getBearing())));
+ }
+ if (payload->getText()) {
+ element.addNode(std::make_shared<XMLElement>("text", "", *payload->getText()));
+ }
+ if (payload->getDatum()) {
+ element.addNode(std::make_shared<XMLElement>("datum", "", *payload->getDatum()));
+ }
+ if (payload->getStreet()) {
+ element.addNode(std::make_shared<XMLElement>("street", "", *payload->getStreet()));
+ }
+ if (payload->getSpeed()) {
+ element.addNode(std::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 f0a0123..5d38997 100644
--- a/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/UserLocation.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API UserLocationSerializer : public GenericPayloadSerializer<UserLocation> {
- public:
- UserLocationSerializer(PayloadSerializerCollection* serializers);
- virtual ~UserLocationSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<UserLocation>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API UserLocationSerializer : public GenericPayloadSerializer<UserLocation> {
+ public:
+ UserLocationSerializer(PayloadSerializerCollection* serializers);
+ virtual ~UserLocationSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<UserLocation>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.cpp b/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.cpp
index fd6eebd..687b566 100644
--- a/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.cpp
@@ -1,54 +1,52 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#pragma clang diagnostic ignored "-Wunused-private-field"
-
#include <Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
+
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/XML/XMLElement.h>
using namespace Swift;
-UserTuneSerializer::UserTuneSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+UserTuneSerializer::UserTuneSerializer(PayloadSerializerCollection* /*serializers*/) {
}
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();
+std::string UserTuneSerializer::serializePayload(std::shared_ptr<UserTune> payload) const {
+ if (!payload) {
+ return "";
+ }
+ XMLElement element("tune", "http://jabber.org/protocol/tune");
+ if (payload->getRating()) {
+ element.addNode(std::make_shared<XMLElement>("rating", "", boost::lexical_cast<std::string>(*payload->getRating())));
+ }
+ if (payload->getTitle()) {
+ element.addNode(std::make_shared<XMLElement>("title", "", *payload->getTitle()));
+ }
+ if (payload->getTrack()) {
+ element.addNode(std::make_shared<XMLElement>("track", "", *payload->getTrack()));
+ }
+ if (payload->getArtist()) {
+ element.addNode(std::make_shared<XMLElement>("artist", "", *payload->getArtist()));
+ }
+ if (payload->getURI()) {
+ element.addNode(std::make_shared<XMLElement>("uri", "", *payload->getURI()));
+ }
+ if (payload->getSource()) {
+ element.addNode(std::make_shared<XMLElement>("source", "", *payload->getSource()));
+ }
+ if (payload->getLength()) {
+ element.addNode(std::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 88a4db0..06e9a0e 100644
--- a/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h
@@ -1,31 +1,26 @@
/*
- * Copyright (c) 2014 Isode Limited.
+ * Copyright (c) 2014-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/Override.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Base/Override.h>
#include <Swiften/Elements/UserTune.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
namespace Swift {
- class PayloadSerializerCollection;
-
- class SWIFTEN_API UserTuneSerializer : public GenericPayloadSerializer<UserTune> {
- public:
- UserTuneSerializer(PayloadSerializerCollection* serializers);
- virtual ~UserTuneSerializer();
-
- virtual std::string serializePayload(boost::shared_ptr<UserTune>) const SWIFTEN_OVERRIDE;
+ class PayloadSerializerCollection;
- private:
-
+ class SWIFTEN_API UserTuneSerializer : public GenericPayloadSerializer<UserTune> {
+ public:
+ UserTuneSerializer(PayloadSerializerCollection* serializers);
+ virtual ~UserTuneSerializer();
- private:
- PayloadSerializerCollection* serializers;
- };
+ virtual std::string serializePayload(std::shared_ptr<UserTune>) const SWIFTEN_OVERRIDE;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp b/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp
index aa05ef9..725d125 100644
--- a/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp
@@ -1,251 +1,249 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/VCardSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+#include <Swiften/Base/DateTime.h>
#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/StringCodecs/Base64.h>
-#include <Swiften/Base/DateTime.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
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();
+std::string VCardSerializer::serializePayload(std::shared_ptr<VCard> vcard) const {
+ XMLElement queryElement("vCard", "vcard-temp");
+ if (!vcard->getVersion().empty()) {
+ queryElement.addNode(std::make_shared<XMLElement>("VERSION", "", vcard->getVersion()));
+ }
+ if (!vcard->getFullName().empty()) {
+ queryElement.addNode(std::make_shared<XMLElement>("FN", "", vcard->getFullName()));
+ }
+ if (!vcard->getGivenName().empty() || !vcard->getFamilyName().empty() || !vcard->getMiddleName().empty() || !vcard->getPrefix().empty() || !vcard->getSuffix().empty()) {
+ std::shared_ptr<XMLElement> nameElement(new XMLElement("N"));
+ if (!vcard->getFamilyName().empty()) {
+ nameElement->addNode(std::make_shared<XMLElement>("FAMILY", "", vcard->getFamilyName()));
+ }
+ if (!vcard->getGivenName().empty()) {
+ nameElement->addNode(std::make_shared<XMLElement>("GIVEN", "", vcard->getGivenName()));
+ }
+ if (!vcard->getMiddleName().empty()) {
+ nameElement->addNode(std::make_shared<XMLElement>("MIDDLE", "", vcard->getMiddleName()));
+ }
+ if (!vcard->getPrefix().empty()) {
+ nameElement->addNode(std::make_shared<XMLElement>("PREFIX", "", vcard->getPrefix()));
+ }
+ if (!vcard->getSuffix().empty()) {
+ nameElement->addNode(std::make_shared<XMLElement>("SUFFIX", "", vcard->getSuffix()));
+ }
+ queryElement.addNode(nameElement);
+ }
+ for (const auto& emailAddress : vcard->getEMailAddresses()) {
+ std::shared_ptr<XMLElement> emailElement(new XMLElement("EMAIL"));
+ emailElement->addNode(std::make_shared<XMLElement>("USERID", "", emailAddress.address));
+ if (emailAddress.isHome) {
+ emailElement->addNode(std::make_shared<XMLElement>("HOME"));
+ }
+ if (emailAddress.isWork) {
+ emailElement->addNode(std::make_shared<XMLElement>("WORK"));
+ }
+ if (emailAddress.isInternet) {
+ emailElement->addNode(std::make_shared<XMLElement>("INTERNET"));
+ }
+ if (emailAddress.isPreferred) {
+ emailElement->addNode(std::make_shared<XMLElement>("PREF"));
+ }
+ if (emailAddress.isX400) {
+ emailElement->addNode(std::make_shared<XMLElement>("X400"));
+ }
+ queryElement.addNode(emailElement);
+ }
+ if (!vcard->getNickname().empty()) {
+ queryElement.addNode(std::make_shared<XMLElement>("NICKNAME", "", vcard->getNickname()));
+ }
+ if (!vcard->getPhoto().empty() || !vcard->getPhotoType().empty()) {
+ XMLElement::ref photoElement(new XMLElement("PHOTO"));
+ if (!vcard->getPhotoType().empty()) {
+ photoElement->addNode(std::make_shared<XMLElement>("TYPE", "", vcard->getPhotoType()));
+ }
+ if (!vcard->getPhoto().empty()) {
+ photoElement->addNode(std::make_shared<XMLElement>("BINVAL", "", Base64::encode(vcard->getPhoto())));
+ }
+ queryElement.addNode(photoElement);
+ }
+ if (!vcard->getBirthday().is_not_a_date_time()) {
+ queryElement.addNode(std::make_shared<XMLElement>("BDAY", "", dateTimeToString(vcard->getBirthday())));
+ }
+
+ for (const auto& telephone : vcard->getTelephones()) {
+ std::shared_ptr<XMLElement> telElement(new XMLElement("TEL"));
+ telElement->addNode(std::make_shared<XMLElement>("NUMBER", "", telephone.number));
+ if (telephone.isHome) {
+ telElement->addNode(std::make_shared<XMLElement>("HOME"));
+ }
+ if (telephone.isWork) {
+ telElement->addNode(std::make_shared<XMLElement>("WORK"));
+ }
+ if (telephone.isVoice) {
+ telElement->addNode(std::make_shared<XMLElement>("VOICE"));
+ }
+ if (telephone.isFax) {
+ telElement->addNode(std::make_shared<XMLElement>("FAX"));
+ }
+ if (telephone.isPager) {
+ telElement->addNode(std::make_shared<XMLElement>("PAGER"));
+ }
+ if (telephone.isMSG) {
+ telElement->addNode(std::make_shared<XMLElement>("MSG"));
+ }
+ if (telephone.isCell) {
+ telElement->addNode(std::make_shared<XMLElement>("CELL"));
+ }
+ if (telephone.isVideo) {
+ telElement->addNode(std::make_shared<XMLElement>("VIDEO"));
+ }
+ if (telephone.isBBS) {
+ telElement->addNode(std::make_shared<XMLElement>("BBS"));
+ }
+ if (telephone.isModem) {
+ telElement->addNode(std::make_shared<XMLElement>("MODEM"));
+ }
+ if (telephone.isISDN) {
+ telElement->addNode(std::make_shared<XMLElement>("ISDN"));
+ }
+ if (telephone.isPCS) {
+ telElement->addNode(std::make_shared<XMLElement>("PCS"));
+ }
+ if (telephone.isPreferred) {
+ telElement->addNode(std::make_shared<XMLElement>("PREF"));
+ }
+ queryElement.addNode(telElement);
+ }
+
+ for (const auto& address : vcard->getAddresses()) {
+ std::shared_ptr<XMLElement> adrElement = std::make_shared<XMLElement>("ADR");
+ if (!address.poBox.empty()) {
+ adrElement->addNode(std::make_shared<XMLElement>("POBOX", "", address.poBox));
+ }
+ if (!address.addressExtension.empty()) {
+ adrElement->addNode(std::make_shared<XMLElement>("EXTADD", "", address.addressExtension));
+ }
+ if (!address.street.empty()) {
+ adrElement->addNode(std::make_shared<XMLElement>("STREET", "", address.street));
+ }
+ if (!address.locality.empty()) {
+ adrElement->addNode(std::make_shared<XMLElement>("LOCALITY", "", address.locality));
+ }
+ if (!address.region.empty()) {
+ adrElement->addNode(std::make_shared<XMLElement>("REGION", "", address.region));
+ }
+ if (!address.postalCode.empty()) {
+ adrElement->addNode(std::make_shared<XMLElement>("PCODE", "", address.postalCode));
+ }
+ if (!address.country.empty()) {
+ adrElement->addNode(std::make_shared<XMLElement>("CTRY", "", address.country));
+ }
+
+ if (address.isHome) {
+ adrElement->addNode(std::make_shared<XMLElement>("HOME"));
+ }
+ if (address.isWork) {
+ adrElement->addNode(std::make_shared<XMLElement>("WORK"));
+ }
+ if (address.isPostal) {
+ adrElement->addNode(std::make_shared<XMLElement>("POSTAL"));
+ }
+ if (address.isParcel) {
+ adrElement->addNode(std::make_shared<XMLElement>("PARCEL"));
+ }
+ if (address.deliveryType == VCard::DomesticDelivery) {
+ adrElement->addNode(std::make_shared<XMLElement>("DOM"));
+ }
+ if (address.deliveryType == VCard::InternationalDelivery) {
+ adrElement->addNode(std::make_shared<XMLElement>("INTL"));
+ }
+ if (address.isPreferred) {
+ adrElement->addNode(std::make_shared<XMLElement>("PREF"));
+ }
+ queryElement.addNode(adrElement);
+ }
+
+ for (const auto& addressLabel : vcard->getAddressLabels()) {
+ std::shared_ptr<XMLElement> labelElement = std::make_shared<XMLElement>("LABEL");
+
+ for (const auto& line : addressLabel.lines) {
+ labelElement->addNode(std::make_shared<XMLElement>("LINE", "", line));
+ }
+
+ if (addressLabel.isHome) {
+ labelElement->addNode(std::make_shared<XMLElement>("HOME"));
+ }
+ if (addressLabel.isWork) {
+ labelElement->addNode(std::make_shared<XMLElement>("WORK"));
+ }
+ if (addressLabel.isPostal) {
+ labelElement->addNode(std::make_shared<XMLElement>("POSTAL"));
+ }
+ if (addressLabel.isParcel) {
+ labelElement->addNode(std::make_shared<XMLElement>("PARCEL"));
+ }
+ if (addressLabel.deliveryType == VCard::DomesticDelivery) {
+ labelElement->addNode(std::make_shared<XMLElement>("DOM"));
+ }
+ if (addressLabel.deliveryType == VCard::InternationalDelivery) {
+ labelElement->addNode(std::make_shared<XMLElement>("INTL"));
+ }
+ if (addressLabel.isPreferred) {
+ labelElement->addNode(std::make_shared<XMLElement>("PREF"));
+ }
+ queryElement.addNode(labelElement);
+ }
+
+ for (const auto& jid : vcard->getJIDs()) {
+ queryElement.addNode(std::make_shared<XMLElement>("JID", "", jid.toString()));
+ }
+
+ if (!vcard->getDescription().empty()) {
+ queryElement.addNode(std::make_shared<XMLElement>("DESC", "", vcard->getDescription()));
+ }
+
+ for (const auto& org : vcard->getOrganizations()) {
+ std::shared_ptr<XMLElement> orgElement = std::make_shared<XMLElement>("ORG");
+ if (!org.name.empty()) {
+ orgElement->addNode(std::make_shared<XMLElement>("ORGNAME", "", org.name));
+ }
+ if (!org.units.empty()) {
+ for (const auto& unit : org.units) {
+ orgElement->addNode(std::make_shared<XMLElement>("ORGUNIT", "", unit));
+ }
+ }
+ queryElement.addNode(orgElement);
+ }
+
+ for (const auto& title : vcard->getTitles()) {
+ queryElement.addNode(std::make_shared<XMLElement>("TITLE", "", title));
+ }
+
+ for (const auto& role : vcard->getRoles()) {
+ queryElement.addNode(std::make_shared<XMLElement>("ROLE", "", role));
+ }
+
+ for (const auto& url : vcard->getURLs()) {
+ queryElement.addNode(std::make_shared<XMLElement>("URL", "", url));
+ }
+
+ if (!vcard->getUnknownContent().empty()) {
+ queryElement.addNode(std::make_shared<XMLRawTextNode>(vcard->getUnknownContent()));
+ }
+ return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/VCardSerializer.h b/Swiften/Serializer/PayloadSerializers/VCardSerializer.h
index 8666e2e..ad83f9a 100644
--- a/Swiften/Serializer/PayloadSerializers/VCardSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/VCardSerializer.h
@@ -1,21 +1,20 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
-#include <Swiften/Elements/VCard.h>
-
#include <Swiften/Base/API.h>
+#include <Swiften/Elements/VCard.h>
+#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(std::shared_ptr<VCard>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp b/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp
index 0edca0a..607cf72 100644
--- a/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp
@@ -1,13 +1,12 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.h>
-#include <boost/shared_ptr.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
@@ -17,12 +16,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(std::shared_ptr<VCardUpdate> vcardUpdate) const {
+ XMLElement updateElement("x", "vcard-temp:x:update");
+ std::shared_ptr<XMLElement> photoElement(new XMLElement("photo"));
+ photoElement->addNode(std::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 4ad2d14..cea8ebd 100644
--- a/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Elements/VCardUpdate.h>
+#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(std::shared_ptr<VCardUpdate>) const;
+ };
}
diff --git a/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp b/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp
index 97dc94e..34fd149 100644
--- a/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp
@@ -4,197 +4,205 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.h>
-#include <iostream>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/lexical_cast.hpp>
-#include <Swiften/Serializer/XML/XMLTextNode.h>
+
+#include <Swiften/Base/Log.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h>
+#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 = std::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 = std::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 = std::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 = std::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 = std::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(std::make_shared<XMLTextNode>(text.getText()));
+ } catch (boost::bad_lexical_cast&) {
+ }
+ }
+
+ void WhiteboardElementSerializingVisitor::visit(WhiteboardEllipseElement& ellipse) {
+ element = std::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(std::shared_ptr<WhiteboardPayload> payload) const {
+ XMLElement element("wb", "http://swift.im/whiteboard");
+ if (payload->getType() == WhiteboardPayload::Data) {
+ XMLElement::ref operationNode = std::make_shared<XMLElement>("operation");
+ WhiteboardElementSerializingVisitor visitor;
+// payload->getElement()->accept(visitor);
+ WhiteboardInsertOperation::ref insertOp = std::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 = std::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 = std::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:
+ SWIFT_LOG(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 543d95e..1fde636 100644
--- a/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,39 +13,39 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/WhiteboardPayload.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardLineElement.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardFreehandPathElement.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardRectElement.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardLineElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardPolygonElement.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardRectElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardTextElement.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardElementVisitor.h>
+#include <Swiften/Elements/WhiteboardPayload.h>
#include <Swiften/Serializer/GenericPayloadSerializer.h>
#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(std::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 b903c02..fc398a4 100644
--- a/Swiften/Serializer/PresenceSerializer.cpp
+++ b/Swiften/Serializer/PresenceSerializer.cpp
@@ -1,34 +1,36 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/PresenceSerializer.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
+
+#include <memory>
+
#include <Swiften/Base/Log.h>
-#include <boost/shared_ptr.hpp>
+#include <Swiften/Serializer/XML/XMLElement.h>
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;
- }
+ std::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 d459fde..b0e1a4f 100644
--- a/Swiften/Serializer/PresenceSerializer.h
+++ b/Swiften/Serializer/PresenceSerializer.h
@@ -1,26 +1,26 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericStanzaSerializer.h>
#include <Swiften/Elements/Presence.h>
-
-#include <boost/optional.hpp>
+#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(
+ std::shared_ptr<Presence> presence,
+ XMLElement& element) const;
+ };
}
diff --git a/Swiften/Serializer/StanzaAckRequestSerializer.h b/Swiften/Serializer/StanzaAckRequestSerializer.h
index e8517b6..f738231 100644
--- a/Swiften/Serializer/StanzaAckRequestSerializer.h
+++ b/Swiften/Serializer/StanzaAckRequestSerializer.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/StanzaAckRequest.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(std::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 38e097b..f5a27dc 100644
--- a/Swiften/Serializer/StanzaAckSerializer.h
+++ b/Swiften/Serializer/StanzaAckSerializer.h
@@ -1,12 +1,13 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/lexical_cast.hpp>
#include <Swiften/Base/API.h>
@@ -15,17 +16,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(std::shared_ptr<ToplevelElement> element) const {
+ StanzaAck::ref stanzaAck(std::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 68e7cca..f2f5529 100644
--- a/Swiften/Serializer/StanzaSerializer.cpp
+++ b/Swiften/Serializer/StanzaSerializer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,59 +8,58 @@
#include <sstream>
#include <typeinfo>
-#include <iostream>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Elements/Stanza.h>
#include <Swiften/Serializer/PayloadSerializer.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
-#include <Swiften/Elements/Stanza.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
StanzaSerializer::StanzaSerializer(const std::string& tag, PayloadSerializerCollection* payloadSerializers, const boost::optional<std::string>& explicitNS) : tag_(tag), payloadSerializers_(payloadSerializers), explicitDefaultNS_(explicitNS) {
}
-SafeByteArray StanzaSerializer::serialize(boost::shared_ptr<ToplevelElement> element) const {
- if (explicitDefaultNS_) {
- return serialize(element, explicitDefaultNS_.get());
- }
- else {
- return serialize(element, "");
- }
+SafeByteArray StanzaSerializer::serialize(std::shared_ptr<ToplevelElement> element) const {
+ 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));
+SafeByteArray StanzaSerializer::serialize(std::shared_ptr<ToplevelElement> element, const std::string& xmlns) const {
+ std::shared_ptr<Stanza> stanza(std::dynamic_pointer_cast<Stanza>(element));
- XMLElement stanzaElement(tag_, explicitDefaultNS_ ? explicitDefaultNS_.get() : xmlns);
- if (stanza->getFrom().isValid()) {
- stanzaElement.setAttribute("from", stanza->getFrom());
- }
- if (stanza->getTo().isValid()) {
- stanzaElement.setAttribute("to", stanza->getTo());
- }
- if (!stanza->getID().empty()) {
- stanzaElement.setAttribute("id", stanza->getID());
- }
- setStanzaSpecificAttributes(stanza, stanzaElement);
+ 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;
+ for (const auto& payload : stanza->getPayloads()) {
+ PayloadSerializer* serializer = payloadSerializers_->getPayloadSerializer(payload);
+ if (serializer) {
+ serializedPayloads += serializer->serialize(payload);
+ }
+ else {
+ SWIFT_LOG(warning) << "Could not find serializer for " << typeid(*(payload.get())).name() << std::endl;
+ }
+ }
+ if (!serializedPayloads.empty()) {
+ stanzaElement.addNode(std::make_shared<XMLRawTextNode>(serializedPayloads));
+ }
- return createSafeByteArray(stanzaElement.serialize());
+ return createSafeByteArray(stanzaElement.serialize());
}
}
diff --git a/Swiften/Serializer/StanzaSerializer.h b/Swiften/Serializer/StanzaSerializer.h
index 61f9173..b2e051c 100644
--- a/Swiften/Serializer/StanzaSerializer.h
+++ b/Swiften/Serializer/StanzaSerializer.h
@@ -1,33 +1,34 @@
/*
- * Copyright (c) 2013-2015 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <string>
+
+#include <boost/optional.hpp>
+
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Stanza.h>
#include <Swiften/Serializer/ElementSerializer.h>
-#include <string>
-#include <boost/optional.hpp>
-
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(std::shared_ptr<ToplevelElement> element) const;
+ virtual SafeByteArray serialize(std::shared_ptr<ToplevelElement> element, const std::string& xmlns) const;
+ virtual void setStanzaSpecificAttributes(std::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..77f904c 100644
--- a/Swiften/Serializer/StartTLSFailureSerializer.h
+++ b/Swiften/Serializer/StartTLSFailureSerializer.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/StartTLSFailure.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(std::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..ee2a76f 100644
--- a/Swiften/Serializer/StartTLSRequestSerializer.h
+++ b/Swiften/Serializer/StartTLSRequestSerializer.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/StartTLSRequest.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(std::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..66a71ca 100644
--- a/Swiften/Serializer/StreamErrorSerializer.cpp
+++ b/Swiften/Serializer/StreamErrorSerializer.cpp
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/StreamErrorSerializer.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Serializer/XML/XMLElement.h>
@@ -15,45 +15,45 @@ namespace Swift {
StreamErrorSerializer::StreamErrorSerializer() : GenericElementSerializer<StreamError>() {
}
-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());
+SafeByteArray StreamErrorSerializer::serialize(std::shared_ptr<ToplevelElement> element) const {
+ StreamError::ref error = std::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(std::make_shared<XMLElement>(typeTag, "urn:ietf:params:xml:ns:xmpp-streams"));
+
+ if (!error->getText().empty()) {
+ errorElement.addNode(std::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 f7a8825..7277903 100644
--- a/Swiften/Serializer/StreamErrorSerializer.h
+++ b/Swiften/Serializer/StreamErrorSerializer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,14 +7,14 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Serializer/GenericElementSerializer.h>
#include <Swiften/Elements/StreamError.h>
+#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(std::shared_ptr<ToplevelElement> error) const;
+ };
}
diff --git a/Swiften/Serializer/StreamFeaturesSerializer.cpp b/Swiften/Serializer/StreamFeaturesSerializer.cpp
index fddfda9..2534db0 100644
--- a/Swiften/Serializer/StreamFeaturesSerializer.cpp
+++ b/Swiften/Serializer/StreamFeaturesSerializer.cpp
@@ -1,60 +1,59 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/StreamFeaturesSerializer.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
-#include <Swiften/Base/foreach.h>
namespace Swift {
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());
+SafeByteArray StreamFeaturesSerializer::serialize(std::shared_ptr<ToplevelElement> element) const {
+ std::shared_ptr<StreamFeatures> streamFeatures(std::dynamic_pointer_cast<StreamFeatures>(element));
+
+ XMLElement streamFeaturesElement("stream:features");
+ if (streamFeatures->hasStartTLS()) {
+ streamFeaturesElement.addNode(std::make_shared<XMLElement>("starttls", "urn:ietf:params:xml:ns:xmpp-tls"));
+ }
+ if (!streamFeatures->getCompressionMethods().empty()) {
+ std::shared_ptr<XMLElement> compressionElement(new XMLElement("compression", "http://jabber.org/features/compress"));
+ for (const auto& method : streamFeatures->getCompressionMethods()) {
+ std::shared_ptr<XMLElement> methodElement(new XMLElement("method"));
+ methodElement->addNode(std::make_shared<XMLTextNode>(method));
+ compressionElement->addNode(methodElement);
+ }
+ streamFeaturesElement.addNode(compressionElement);
+ }
+ if (!streamFeatures->getAuthenticationMechanisms().empty()) {
+ std::shared_ptr<XMLElement> mechanismsElement(new XMLElement("mechanisms", "urn:ietf:params:xml:ns:xmpp-sasl"));
+ for (const auto& mechanism : streamFeatures->getAuthenticationMechanisms()) {
+ std::shared_ptr<XMLElement> mechanismElement(new XMLElement("mechanism"));
+ mechanismElement->addNode(std::make_shared<XMLTextNode>(mechanism));
+ mechanismsElement->addNode(mechanismElement);
+ }
+ streamFeaturesElement.addNode(mechanismsElement);
+ }
+ if (streamFeatures->hasResourceBind()) {
+ streamFeaturesElement.addNode(std::make_shared<XMLElement>("bind", "urn:ietf:params:xml:ns:xmpp-bind"));
+ }
+ if (streamFeatures->hasSession()) {
+ streamFeaturesElement.addNode(std::make_shared<XMLElement>("session", "urn:ietf:params:xml:ns:xmpp-session"));
+ }
+ if (streamFeatures->hasStreamManagement()) {
+ streamFeaturesElement.addNode(std::make_shared<XMLElement>("sm", "urn:xmpp:sm:2"));
+ }
+ if (streamFeatures->hasRosterVersioning()) {
+ streamFeaturesElement.addNode(std::make_shared<XMLElement>("ver", "urn:xmpp:features:rosterver"));
+ }
+ return createSafeByteArray(streamFeaturesElement.serialize());
}
}
diff --git a/Swiften/Serializer/StreamFeaturesSerializer.h b/Swiften/Serializer/StreamFeaturesSerializer.h
index f98a86f..b1cc2f7 100644
--- a/Swiften/Serializer/StreamFeaturesSerializer.h
+++ b/Swiften/Serializer/StreamFeaturesSerializer.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/StreamFeatures.h>
#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(std::shared_ptr<ToplevelElement> element) const;
+ };
}
diff --git a/Swiften/Serializer/StreamManagementEnabledSerializer.cpp b/Swiften/Serializer/StreamManagementEnabledSerializer.cpp
index 3ee0772..4f4ca2e 100644
--- a/Swiften/Serializer/StreamManagementEnabledSerializer.cpp
+++ b/Swiften/Serializer/StreamManagementEnabledSerializer.cpp
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/StreamManagementEnabledSerializer.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Elements/StreamManagementEnabled.h>
#include <Swiften/Serializer/XML/XMLElement.h>
@@ -16,14 +16,14 @@ using namespace Swift;
StreamManagementEnabledSerializer::StreamManagementEnabledSerializer() : GenericElementSerializer<StreamManagementEnabled>() {
}
-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());
+SafeByteArray StreamManagementEnabledSerializer::serialize(std::shared_ptr<ToplevelElement> el) const {
+ std::shared_ptr<StreamManagementEnabled> e(std::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..f139dc8 100644
--- a/Swiften/Serializer/StreamManagementEnabledSerializer.h
+++ b/Swiften/Serializer/StreamManagementEnabledSerializer.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/StreamManagementEnabled.h>
#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(std::shared_ptr<ToplevelElement>) const;
+ };
}
diff --git a/Swiften/Serializer/StreamManagementFailedSerializer.h b/Swiften/Serializer/StreamManagementFailedSerializer.h
index 4489f97..29dd0ab 100644
--- a/Swiften/Serializer/StreamManagementFailedSerializer.h
+++ b/Swiften/Serializer/StreamManagementFailedSerializer.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/StreamManagementFailed.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(std::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 f63cb80..619ac9c 100644
--- a/Swiften/Serializer/StreamResumeSerializer.cpp
+++ b/Swiften/Serializer/StreamResumeSerializer.cpp
@@ -1,12 +1,13 @@
/*
- * Copyright (c) 2011-2014 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/StreamResumeSerializer.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/lexical_cast.hpp>
#include <Swiften/Elements/StreamResume.h>
@@ -17,12 +18,12 @@ using namespace Swift;
StreamResumeSerializer::StreamResumeSerializer() : GenericElementSerializer<StreamResume>() {
}
-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());
+SafeByteArray StreamResumeSerializer::serialize(std::shared_ptr<ToplevelElement> el) const {
+ std::shared_ptr<StreamResume> e(std::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..ad13b2b 100644
--- a/Swiften/Serializer/StreamResumeSerializer.h
+++ b/Swiften/Serializer/StreamResumeSerializer.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/StreamResume.h>
#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(std::shared_ptr<ToplevelElement>) const;
+ };
}
diff --git a/Swiften/Serializer/StreamResumedSerializer.cpp b/Swiften/Serializer/StreamResumedSerializer.cpp
index 55d91de..5b88ded 100644
--- a/Swiften/Serializer/StreamResumedSerializer.cpp
+++ b/Swiften/Serializer/StreamResumedSerializer.cpp
@@ -1,12 +1,13 @@
/*
- * Copyright (c) 2011-2014 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/StreamResumedSerializer.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/lexical_cast.hpp>
#include <Swiften/Elements/StreamResumed.h>
@@ -17,12 +18,12 @@ using namespace Swift;
StreamResumedSerializer::StreamResumedSerializer() : GenericElementSerializer<StreamResumed>() {
}
-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());
+SafeByteArray StreamResumedSerializer::serialize(std::shared_ptr<ToplevelElement> el) const {
+ std::shared_ptr<StreamResumed> e(std::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..324282b 100644
--- a/Swiften/Serializer/StreamResumedSerializer.h
+++ b/Swiften/Serializer/StreamResumedSerializer.h
@@ -1,22 +1,22 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/StreamResumed.h>
#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(std::shared_ptr<ToplevelElement>) const;
+ };
}
diff --git a/Swiften/Serializer/TLSProceedSerializer.h b/Swiften/Serializer/TLSProceedSerializer.h
index 7203042..f99aefd 100644
--- a/Swiften/Serializer/TLSProceedSerializer.h
+++ b/Swiften/Serializer/TLSProceedSerializer.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/TLSProceed.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(std::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 8c4e1be..d313b42 100644
--- a/Swiften/Serializer/UnitTest/AuthChallengeSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/AuthChallengeSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,50 +8,50 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/AuthChallengeSerializer.h>
-#include <Swiften/Elements/AuthChallenge.h>
#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Elements/AuthChallenge.h>
+#include <Swiften/Serializer/AuthChallengeSerializer.h>
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;
+ std::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;
+ std::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;
+ std::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 9c02793..2dc71fb 100644
--- a/Swiften/Serializer/UnitTest/AuthRequestSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/AuthRequestSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,50 +8,50 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/AuthRequestSerializer.h>
-#include <Swiften/Elements/AuthRequest.h>
#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Elements/AuthRequest.h>
+#include <Swiften/Serializer/AuthRequestSerializer.h>
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;
+ std::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;
+ std::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;
+ std::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 4dfb04d..1ee4b62 100644
--- a/Swiften/Serializer/UnitTest/AuthResponseSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/AuthResponseSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,50 +8,50 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/AuthResponseSerializer.h>
-#include <Swiften/Elements/AuthResponse.h>
#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Elements/AuthResponse.h>
+#include <Swiften/Serializer/AuthResponseSerializer.h>
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;
+ std::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;
+ std::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;
+ std::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 888dbc2..3c4bb1b 100644
--- a/Swiften/Serializer/UnitTest/AuthSuccessSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/AuthSuccessSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,50 +8,50 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/AuthSuccessSerializer.h>
-#include <Swiften/Elements/AuthSuccess.h>
#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Elements/AuthSuccess.h>
+#include <Swiften/Serializer/AuthSuccessSerializer.h>
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;
+ std::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;
+ std::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;
+ std::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 e8b847d..dd3d6c3 100644
--- a/Swiften/Serializer/UnitTest/StreamFeaturesSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/StreamFeaturesSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,51 +8,50 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/StreamFeaturesSerializer.h>
#include <Swiften/Elements/StreamFeatures.h>
-
+#include <Swiften/Serializer/StreamFeaturesSerializer.h>
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;
+ std::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 6d3c65c..93205fc 100644
--- a/Swiften/Serializer/UnitTest/XMPPSerializerTest.cpp
+++ b/Swiften/Serializer/UnitTest/XMPPSerializerTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,69 +7,69 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Serializer/XMPPSerializer.h>
#include <Swiften/Elements/AuthChallenge.h>
-#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Elements/ProtocolHeader.h>
+#include <Swiften/Serializer/PayloadSerializerCollection.h>
+#include <Swiften/Serializer/XMPPSerializer.h>
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() {
+ std::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() {
+ std::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() {
+ std::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 efb7917..ed3f8ab 100644
--- a/Swiften/Serializer/XML/UnitTest/XMLElementTest.cpp
+++ b/Swiften/Serializer/XML/UnitTest/XMLElementTest.cpp
@@ -1,14 +1,14 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/smart_ptr/make_shared.hpp>
-
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
@@ -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");
+ std::shared_ptr<XMLElement> barElement(new XMLElement("bar"));
+ barElement->addNode(std::make_shared<XMLTextNode>("Blo"));
+ testling.addNode(barElement);
+ std::shared_ptr<XMLElement> bazElement(new XMLElement("baz"));
+ bazElement->addNode(std::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..f2397ca 100644
--- a/Swiften/Serializer/XML/XMLElement.cpp
+++ b/Swiften/Serializer/XML/XMLElement.cpp
@@ -1,60 +1,58 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/XML/XMLElement.h>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
XMLElement::XMLElement(const std::string& tag, const std::string& xmlns, const std::string& text) : tag_(tag) {
- if (!xmlns.empty()) {
- setAttribute("xmlns", xmlns);
- }
- if (!text.empty()) {
- addNode(XMLTextNode::ref(new XMLTextNode(text)));
- }
+ 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_;
+ for (const auto& p : attributes_) {
+ result += " " + p.first + "=\"" + p.second + "\"";
+ }
+
+ if (!childNodes_.empty()) {
+ result += ">";
+ for (auto& node : childNodes_) {
+ result += node->serialize();
+ }
+ result += "</" + tag_ + ">";
+ }
+ else {
+ result += "/>";
+ }
+ return result;
}
void XMLElement::setAttribute(const std::string& attribute, const std::string& value) {
- std::string escapedValue(value);
- String::replaceAll(escapedValue, '&', "&amp;");
- String::replaceAll(escapedValue, '<', "&lt;");
- String::replaceAll(escapedValue, '>', "&gt;");
- String::replaceAll(escapedValue, '\'', "&apos;");
- String::replaceAll(escapedValue, '"', "&quot;");
- attributes_[attribute] = escapedValue;
+ 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);
- }
+void XMLElement::addNode(std::shared_ptr<XMLNode> node) {
+ if (node) {
+ childNodes_.push_back(node);
+ }
}
}
diff --git a/Swiften/Serializer/XML/XMLElement.h b/Swiften/Serializer/XML/XMLElement.h
index 8f5f3e4..54de041 100644
--- a/Swiften/Serializer/XML/XMLElement.h
+++ b/Swiften/Serializer/XML/XMLElement.h
@@ -1,35 +1,34 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <vector>
#include <map>
-
+#include <memory>
#include <string>
+#include <vector>
#include <Swiften/Base/API.h>
#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 std::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(std::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< std::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..44970bf 100644
--- a/Swiften/Serializer/XML/XMLTextNode.h
+++ b/Swiften/Serializer/XML/XMLTextNode.h
@@ -1,37 +1,37 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Base/String.h>
#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 std::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 2953f93..9cde777 100644
--- a/Swiften/Serializer/XMPPSerializer.cpp
+++ b/Swiften/Serializer/XMPPSerializer.cpp
@@ -1,111 +1,111 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Serializer/XMPPSerializer.h>
-#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <iostream>
#include <cassert>
+#include <memory>
+
+#include <boost/bind.hpp>
+#include <Swiften/Base/Log.h>
#include <Swiften/Elements/ProtocolHeader.h>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/Serializer/CompressRequestSerializer.h>
-#include <Swiften/Serializer/CompressFailureSerializer.h>
-#include <Swiften/Serializer/StreamErrorSerializer.h>
-#include <Swiften/Serializer/StreamFeaturesSerializer.h>
-#include <Swiften/Serializer/AuthRequestSerializer.h>
-#include <Swiften/Serializer/AuthFailureSerializer.h>
-#include <Swiften/Serializer/AuthSuccessSerializer.h>
#include <Swiften/Serializer/AuthChallengeSerializer.h>
+#include <Swiften/Serializer/AuthFailureSerializer.h>
+#include <Swiften/Serializer/AuthRequestSerializer.h>
#include <Swiften/Serializer/AuthResponseSerializer.h>
+#include <Swiften/Serializer/AuthSuccessSerializer.h>
+#include <Swiften/Serializer/ComponentHandshakeSerializer.h>
+#include <Swiften/Serializer/CompressFailureSerializer.h>
+#include <Swiften/Serializer/CompressRequestSerializer.h>
#include <Swiften/Serializer/EnableStreamManagementSerializer.h>
+#include <Swiften/Serializer/IQSerializer.h>
+#include <Swiften/Serializer/MessageSerializer.h>
+#include <Swiften/Serializer/PresenceSerializer.h>
+#include <Swiften/Serializer/StanzaAckRequestSerializer.h>
+#include <Swiften/Serializer/StanzaAckSerializer.h>
+#include <Swiften/Serializer/StartTLSFailureSerializer.h>
+#include <Swiften/Serializer/StartTLSRequestSerializer.h>
+#include <Swiften/Serializer/StreamErrorSerializer.h>
+#include <Swiften/Serializer/StreamFeaturesSerializer.h>
#include <Swiften/Serializer/StreamManagementEnabledSerializer.h>
+#include <Swiften/Serializer/StreamManagementFailedSerializer.h>
#include <Swiften/Serializer/StreamResumeSerializer.h>
#include <Swiften/Serializer/StreamResumedSerializer.h>
-#include <Swiften/Serializer/StreamManagementFailedSerializer.h>
-#include <Swiften/Serializer/StanzaAckSerializer.h>
-#include <Swiften/Serializer/StanzaAckRequestSerializer.h>
-#include <Swiften/Serializer/StartTLSRequestSerializer.h>
-#include <Swiften/Serializer/StartTLSFailureSerializer.h>
#include <Swiften/Serializer/TLSProceedSerializer.h>
-#include <Swiften/Serializer/MessageSerializer.h>
-#include <Swiften/Serializer/PresenceSerializer.h>
-#include <Swiften/Serializer/IQSerializer.h>
-#include <Swiften/Serializer/ComponentHandshakeSerializer.h>
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(std::make_shared<PresenceSerializer>(payloadSerializers, setExplictNSonTopLevelElements ? getDefaultNamespace() : boost::optional<std::string>()));
+ serializers_.push_back(std::make_shared<IQSerializer>(payloadSerializers, setExplictNSonTopLevelElements ? getDefaultNamespace() : boost::optional<std::string>()));
+ serializers_.push_back(std::make_shared<MessageSerializer>(payloadSerializers, setExplictNSonTopLevelElements ? getDefaultNamespace() : boost::optional<std::string>()));
+ serializers_.push_back(std::make_shared<CompressRequestSerializer>());
+ serializers_.push_back(std::make_shared<CompressFailureSerializer>());
+ serializers_.push_back(std::make_shared<AuthRequestSerializer>());
+ serializers_.push_back(std::make_shared<AuthFailureSerializer>());
+ serializers_.push_back(std::make_shared<AuthSuccessSerializer>());
+ serializers_.push_back(std::make_shared<AuthChallengeSerializer>());
+ serializers_.push_back(std::make_shared<AuthResponseSerializer>());
+ serializers_.push_back(std::make_shared<StartTLSRequestSerializer>());
+ serializers_.push_back(std::make_shared<StartTLSFailureSerializer>());
+ serializers_.push_back(std::make_shared<TLSProceedSerializer>());
+ serializers_.push_back(std::make_shared<StreamFeaturesSerializer>());
+ serializers_.push_back(std::make_shared<StreamErrorSerializer>());
+ serializers_.push_back(std::make_shared<EnableStreamManagementSerializer>());
+ serializers_.push_back(std::make_shared<StreamManagementEnabledSerializer>());
+ serializers_.push_back(std::make_shared<StreamManagementFailedSerializer>());
+ serializers_.push_back(std::make_shared<StreamResumeSerializer>());
+ serializers_.push_back(std::make_shared<StreamResumedSerializer>());
+ serializers_.push_back(std::make_shared<StanzaAckSerializer>());
+ serializers_.push_back(std::make_shared<StanzaAckRequestSerializer>());
+ serializers_.push_back(std::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("");
- }
+SafeByteArray XMPPSerializer::serializeElement(std::shared_ptr<ToplevelElement> element) const {
+ std::vector< std::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 {
+ SWIFT_LOG(warning) << "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 f9e3bf5..8c182e3 100644
--- a/Swiften/Serializer/XMPPSerializer.h
+++ b/Swiften/Serializer/XMPPSerializer.h
@@ -1,38 +1,38 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <string>
#include <vector>
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/ToplevelElement.h>
#include <Swiften/Elements/StreamType.h>
-#include <string>
+#include <Swiften/Elements/ToplevelElement.h>
#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(std::shared_ptr<ToplevelElement> stanza) const;
+ std::string serializeFooter() const;
+
+ private:
+ std::string getDefaultNamespace() const;
+
+ private:
+ StreamType type_;
+ std::vector< std::shared_ptr<ElementSerializer> > serializers_;
+ };
}
diff --git a/Swiften/Session/BOSHSessionStream.cpp b/Swiften/Session/BOSHSessionStream.cpp
index 7fb8b31..4c7bdee 100644
--- a/Swiften/Session/BOSHSessionStream.cpp
+++ b/Swiften/Session/BOSHSessionStream.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -12,7 +12,6 @@
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/StreamType.h>
#include <Swiften/EventLoop/EventLoop.h>
#include <Swiften/StreamStack/CompressionLayer.h>
@@ -27,123 +26,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,
+ std::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(nullptr)));
+ 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 = nullptr;
+ 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 = nullptr;
}
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);
+void BOSHSessionStream::writeElement(std::shared_ptr<ToplevelElement> 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();
+std::shared_ptr<CertificateVerificationError> BOSHSessionStream::getPeerCertificateVerificationError() const {
+ return connectionPool->getPeerCertificateVerificationError();
}
ByteArray BOSHSessionStream::getTLSFinishMessage() const {
- return ByteArray();
+ return ByteArray();
}
bool BOSHSessionStream::supportsZLibCompression() {
- return false;
+ return false;
}
void BOSHSessionStream::addZLibCompression() {
@@ -151,71 +150,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);
+void BOSHSessionStream::handleElementReceived(std::shared_ptr<ToplevelElement> element) {
+ onElementReceived(element);
}
void BOSHSessionStream::handleXMPPError() {
- available = false;
- onClosed(boost::make_shared<SessionStreamError>(SessionStreamError::ParseError));
+ available = false;
+ onClosed(std::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..0c26848 100644
--- a/Swiften/Session/BOSHSessionStream.h
+++ b/Swiften/Session/BOSHSessionStream.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2011-2015 Isode Limited.
+ * Copyright (c) 2011-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Base/SafeByteArray.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 std::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,
+ std::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(std::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 std::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(std::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 43f1c48..10c6ad0 100644
--- a/Swiften/Session/BasicSessionStream.cpp
+++ b/Swiften/Session/BasicSessionStream.cpp
@@ -1,212 +1,219 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/Session/BasicSessionStream.h>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/StreamStack/XMPPLayer.h>
-#include <Swiften/StreamStack/StreamStack.h>
-#include <Swiften/StreamStack/ConnectionLayer.h>
-#include <Swiften/StreamStack/WhitespacePingLayer.h>
#include <Swiften/StreamStack/CompressionLayer.h>
+#include <Swiften/StreamStack/ConnectionLayer.h>
+#include <Swiften/StreamStack/StreamStack.h>
#include <Swiften/StreamStack/TLSLayer.h>
-#include <Swiften/TLS/TLSContextFactory.h>
+#include <Swiften/StreamStack/WhitespacePingLayer.h>
+#include <Swiften/StreamStack/XMPPLayer.h>
#include <Swiften/TLS/TLSContext.h>
+#include <Swiften/TLS/TLSContextFactory.h>
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,
+ std::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(nullptr),
+ tlsLayer(nullptr),
+ whitespacePingLayer(nullptr),
+ tlsOptions_(tlsOptions) {
+ xmppLayer = new XMPPLayer(payloadParserFactories, payloadSerializers, xmlParserFactory, streamType);
+ xmppLayer->onStreamStart.connect(boost::bind(&BasicSessionStream::handleStreamStartReceived, this, _1));
+ xmppLayer->onStreamEnd.connect(boost::bind(&BasicSessionStream::handleStreamEndReceived, this));
+ 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->onStreamEnd.disconnect(boost::bind(&BasicSessionStream::handleStreamEndReceived, this));
+ 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);
+void BasicSessionStream::writeElement(std::shared_ptr<ToplevelElement> 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(std::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();
+std::shared_ptr<CertificateVerificationError> BasicSessionStream::getPeerCertificateVerificationError() const {
+ 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::handleStreamEndReceived() {
+ onStreamEndReceived();
}
-void BasicSessionStream::handleElementReceived(boost::shared_ptr<ToplevelElement> element) {
- onElementReceived(element);
+void BasicSessionStream::handleElementReceived(std::shared_ptr<ToplevelElement> element) {
+ onElementReceived(element);
}
void BasicSessionStream::handleXMPPError() {
- available = false;
- onClosed(boost::make_shared<SessionStreamError>(SessionStreamError::ParseError));
+ available = false;
+ onClosed(std::make_shared<SessionStreamError>(SessionStreamError::ParseError));
}
void BasicSessionStream::handleTLSConnected() {
- onTLSEncrypted();
+ onTLSEncrypted();
}
-void BasicSessionStream::handleTLSError(boost::shared_ptr<TLSError> error) {
- available = false;
- onClosed(error);
+void BasicSessionStream::handleTLSError(std::shared_ptr<TLSError> 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(std::make_shared<SessionStreamError>(SessionStreamError::ConnectionReadError));
+ }
+ else if (error) {
+ onClosed(std::make_shared<SessionStreamError>(SessionStreamError::ConnectionWriteError));
+ }
+ else {
+ onClosed(std::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..48b3d63 100644
--- a/Swiften/Session/BasicSessionStream.h
+++ b/Swiften/Session/BasicSessionStream.h
@@ -6,7 +6,7 @@
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Base/SafeByteArray.h>
@@ -17,78 +17,79 @@
#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,
+ std::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(std::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 std::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(std::shared_ptr<TLSError>);
+ void handleStreamStartReceived(const ProtocolHeader&);
+ void handleStreamEndReceived();
+ void handleElementReceived(std::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;
+ std::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 4dd8921..ebdb5d1 100644
--- a/Swiften/Session/Session.cpp
+++ b/Swiften/Session/Session.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,98 +8,98 @@
#include <boost/bind.hpp>
-#include <Swiften/StreamStack/XMPPLayer.h>
#include <Swiften/StreamStack/StreamStack.h>
+#include <Swiften/StreamStack/XMPPLayer.h>
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) {
+ std::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory) :
+ connection(connection),
+ payloadParserFactories(payloadParserFactories),
+ payloadSerializers(payloadSerializers),
+ xmlParserFactory(xmlParserFactory),
+ xmppLayer(nullptr),
+ connectionLayer(nullptr),
+ streamStack(nullptr),
+ 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);
+void Session::sendElement(std::shared_ptr<ToplevelElement> 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 c911fe6..23cc656 100644
--- a/Swiften/Session/Session.h
+++ b/Swiften/Session/Session.h
@@ -1,115 +1,115 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/boost_bsignals.h>
+#include <memory>
+
#include <boost/optional.hpp>
-#include <boost/enable_shared_from_this.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
+#include <Swiften/Base/SafeByteArray.h>
#include <Swiften/Elements/ToplevelElement.h>
+#include <Swiften/JID/JID.h>
#include <Swiften/Network/Connection.h>
#include <Swiften/StreamStack/ConnectionLayer.h>
-#include <Swiften/Base/SafeByteArray.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 std::enable_shared_from_this<Session> {
+ public:
+ enum SessionError {
+ ConnectionReadError,
+ ConnectionWriteError,
+ XMLError,
+ AuthenticationFailedError,
+ NoSupportedAuthMechanismsError,
+ UnexpectedElementError,
+ ResourceBindError,
+ SessionStartError,
+ TLSError,
+ ClientCertificateLoadError,
+ ClientCertificateError
+ };
+
+ Session(
+ std::shared_ptr<Connection> connection,
+ PayloadParserFactoryCollection* payloadParserFactories,
+ PayloadSerializerCollection* payloadSerializers,
+ XMLParserFactory* xmlParserFactory);
+ virtual ~Session();
+
+ void startSession();
+ void finishSession();
+
+ void sendElement(std::shared_ptr<ToplevelElement>);
+
+ const JID& getLocalJID() const {
+ return localJID;
+ }
+
+ const JID& getRemoteJID() const {
+ return remoteJID;
+ }
+
+ boost::signals2::signal<void (std::shared_ptr<ToplevelElement>)> onElementReceived;
+ boost::signals2::signal<void (const boost::optional<SessionError>&)> onSessionFinished;
+ boost::signals2::signal<void (const SafeByteArray&)> onDataWritten;
+ boost::signals2::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(std::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;
+ std::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 8513c1a..c5ec42a 100644
--- a/Swiften/Session/SessionStream.h
+++ b/Swiften/Session/SessionStream.h
@@ -1,91 +1,93 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/optional.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/Elements/ProtocolHeader.h>
-#include <Swiften/Elements/ToplevelElement.h>
#include <Swiften/Base/Error.h>
#include <Swiften/Base/SafeByteArray.h>
-#include <Swiften/TLS/CertificateWithKey.h>
+#include <Swiften/Elements/ProtocolHeader.h>
+#include <Swiften/Elements/ToplevelElement.h>
#include <Swiften/TLS/Certificate.h>
#include <Swiften/TLS/CertificateVerificationError.h>
+#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(std::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 std::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const = 0;
+
+ virtual ByteArray getTLSFinishMessage() const = 0;
+
+ boost::signals2::signal<void (const ProtocolHeader&)> onStreamStartReceived;
+ boost::signals2::signal<void ()> onStreamEndReceived;
+ boost::signals2::signal<void (std::shared_ptr<ToplevelElement>)> onElementReceived;
+ boost::signals2::signal<void (std::shared_ptr<Error>)> onClosed;
+ boost::signals2::signal<void ()> onTLSEncrypted;
+ boost::signals2::signal<void (const SafeByteArray&)> onDataRead;
+ boost::signals2::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 32ddc16..49b369d 100644
--- a/Swiften/Session/SessionTracer.cpp
+++ b/Swiften/Session/SessionTracer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,22 +7,23 @@
#include <Swiften/Session/SessionTracer.h>
#include <iostream>
+
#include <boost/bind.hpp>
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));
+SessionTracer::SessionTracer(std::shared_ptr<Session> session) : session(session) {
+ 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 4900fd6..8e73c16 100644
--- a/Swiften/Session/SessionTracer.h
+++ b/Swiften/Session/SessionTracer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,17 +9,17 @@
#include <string>
#include <Swiften/Base/API.h>
-#include <Swiften/Session/Session.h>
#include <Swiften/Base/SafeByteArray.h>
+#include <Swiften/Session/Session.h>
namespace Swift {
- class SWIFTEN_API SessionTracer {
- public:
- SessionTracer(boost::shared_ptr<Session> session);
+ class SWIFTEN_API SessionTracer {
+ public:
+ SessionTracer(std::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;
- };
+ std::shared_ptr<Session> session;
+ };
}
diff --git a/Swiften/StreamManagement/SConscript b/Swiften/StreamManagement/SConscript
index ce95fc7..8eab91b 100644
--- a/Swiften/StreamManagement/SConscript
+++ b/Swiften/StreamManagement/SConscript
@@ -1,8 +1,8 @@
Import("swiften_env")
sources = [
- "StanzaAckRequester.cpp",
- "StanzaAckResponder.cpp",
- ]
+ "StanzaAckRequester.cpp",
+ "StanzaAckResponder.cpp",
+ ]
swiften_env.Append(SWIFTEN_OBJECTS = swiften_env.SwiftenObject(sources))
diff --git a/Swiften/StreamManagement/StanzaAckRequester.cpp b/Swiften/StreamManagement/StanzaAckRequester.cpp
index 52ff6f0..8941f4a 100644
--- a/Swiften/StreamManagement/StanzaAckRequester.cpp
+++ b/Swiften/StreamManagement/StanzaAckRequester.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,8 +7,8 @@
#include <Swiften/StreamManagement/StanzaAckRequester.h>
#include <boost/numeric/conversion/cast.hpp>
-#include <iostream>
+#include <Swiften/Base/Log.h>
#include <Swiften/Elements/Message.h>
namespace Swift {
@@ -19,26 +19,26 @@ StanzaAckRequester::StanzaAckRequester() : lastHandledStanzasCount(0) {
}
-void StanzaAckRequester::handleStanzaSent(boost::shared_ptr<Stanza> stanza) {
- unackedStanzas.push_back(stanza);
- if (boost::dynamic_pointer_cast<Message>(stanza)) {
- onRequestAck();
- }
+void StanzaAckRequester::handleStanzaSent(std::shared_ptr<Stanza> stanza) {
+ unackedStanzas.push_back(stanza);
+ if (std::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()) {
+ SWIFT_LOG(warning) << "Server acked more stanzas than we sent" << std::endl;
+ break;
+ }
+ std::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 79f4da8..422efbd 100644
--- a/Swiften/StreamManagement/StanzaAckRequester.h
+++ b/Swiften/StreamManagement/StanzaAckRequester.h
@@ -1,34 +1,35 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
#include <deque>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Stanza.h>
-#include <Swiften/Base/boost_bsignals.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(std::shared_ptr<Stanza> stanza);
+ void handleAckReceived(unsigned int handledStanzasCount);
+
+ public:
+ boost::signals2::signal<void ()> onRequestAck;
+ boost::signals2::signal<void (std::shared_ptr<Stanza>)> onStanzaAcked;
+
+ private:
+ friend class StanzaAckRequesterTest;
+ unsigned int lastHandledStanzasCount;
+ std::deque<std::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 e2223f9..c90bbff 100644
--- a/Swiften/StreamManagement/StanzaAckResponder.h
+++ b/Swiften/StreamManagement/StanzaAckResponder.h
@@ -1,31 +1,32 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Stanza.h>
-#include <Swiften/Base/boost_bsignals.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::signals2::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 2b2803d..ce16e1f 100644
--- a/Swiften/StreamManagement/UnitTest/StanzaAckRequesterTest.cpp
+++ b/Swiften/StreamManagement/UnitTest/StanzaAckRequesterTest.cpp
@@ -1,163 +1,164 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
#include <boost/bind.hpp>
#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/StreamManagement/StanzaAckRequester.h>
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
+#include <Swiften/Elements/IQ.h>
#include <Swiften/Elements/Message.h>
#include <Swiften/Elements/Presence.h>
-#include <Swiften/Elements/IQ.h>
+#include <Swiften/StreamManagement/StanzaAckRequester.h>
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() {
+ std::shared_ptr<StanzaAckRequester> testling(createRequester());
+ testling->handleStanzaSent(createMessage("m1"));
+
+ CPPUNIT_ASSERT_EQUAL(1, acksRequested);
+ }
+
+ void testHandleStanzaSent_IQDoesNotRequestAck() {
+ std::shared_ptr<StanzaAckRequester> testling(createRequester());
+ testling->handleStanzaSent(createIQ("iq1"));
+
+ CPPUNIT_ASSERT_EQUAL(0, acksRequested);
+ }
+
+ void testHandleStanzaSent_PresenceDoesNotRequestAck() {
+ std::shared_ptr<StanzaAckRequester> testling(createRequester());
+ testling->handleStanzaSent(createPresence("p1"));
+
+ CPPUNIT_ASSERT_EQUAL(0, acksRequested);
+ }
+
+ void testHandleAckReceived_AcksStanza() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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(std::shared_ptr<Stanza> stanza) {
+ ackedStanzas.push_back(stanza);
+ }
+
+ private:
+ int acksRequested = 0;
+ std::vector< std::shared_ptr<Stanza> > ackedStanzas;
};
}
diff --git a/Swiften/StreamManagement/UnitTest/StanzaAckResponderTest.cpp b/Swiften/StreamManagement/UnitTest/StanzaAckResponderTest.cpp
index 92115e8..ffdabe9 100644
--- a/Swiften/StreamManagement/UnitTest/StanzaAckResponderTest.cpp
+++ b/Swiften/StreamManagement/UnitTest/StanzaAckResponderTest.cpp
@@ -1,96 +1,97 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <cppunit/extensions/HelperMacros.h>
-#include <cppunit/extensions/TestFactoryRegistry.h>
#include <boost/bind.hpp>
#include <boost/numeric/conversion/cast.hpp>
-#include <Swiften/StreamManagement/StanzaAckResponder.h>
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
#include <Swiften/Elements/Message.h>
+#include <Swiften/StreamManagement/StanzaAckResponder.h>
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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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 db43b60..04a9251 100644
--- a/Swiften/StreamStack/CompressionLayer.h
+++ b/Swiften/StreamStack/CompressionLayer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,46 +7,46 @@
#pragma once
#include <boost/noncopyable.hpp>
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/SafeByteArray.h>
-#include <Swiften/StreamStack/StreamLayer.h>
-#include <Swiften/Compress/ZLibException.h>
#include <Swiften/Compress/ZLibCompressor.h>
#include <Swiften/Compress/ZLibDecompressor.h>
+#include <Swiften/Compress/ZLibException.h>
+#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::signals2::signal<void ()> onError;
+
+ private:
+ ZLibCompressor compressor_;
+ ZLibDecompressor decompressor_;
+ };
}
diff --git a/Swiften/StreamStack/ConnectionLayer.cpp b/Swiften/StreamStack/ConnectionLayer.cpp
index 5bf07d0..b0c4deb 100644
--- a/Swiften/StreamStack/ConnectionLayer.cpp
+++ b/Swiften/StreamStack/ConnectionLayer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -10,16 +10,16 @@
namespace Swift {
-ConnectionLayer::ConnectionLayer(boost::shared_ptr<Connection> connection) : connection(connection) {
- connection->onDataRead.connect(boost::bind(&ConnectionLayer::handleDataRead, this, _1));
+ConnectionLayer::ConnectionLayer(std::shared_ptr<Connection> connection) : connection(connection) {
+ 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);
+void ConnectionLayer::handleDataRead(std::shared_ptr<SafeByteArray> data) {
+ writeDataToParentLayer(*data);
}
diff --git a/Swiften/StreamStack/ConnectionLayer.h b/Swiften/StreamStack/ConnectionLayer.h
index e89e24c..d1775ee 100644
--- a/Swiften/StreamStack/ConnectionLayer.h
+++ b/Swiften/StreamStack/ConnectionLayer.h
@@ -1,31 +1,31 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/Network/Connection.h>
#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(std::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(std::shared_ptr<SafeByteArray>);
- private:
- boost::shared_ptr<Connection> connection;
- };
+ private:
+ std::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..8e7ba02 100644
--- a/Swiften/StreamStack/HighLayer.cpp
+++ b/Swiften/StreamStack/HighLayer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -12,17 +12,17 @@
namespace Swift {
-HighLayer::HighLayer() : childLayer(NULL) {
+HighLayer::HighLayer() : childLayer(nullptr) {
}
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..c94dafe 100644
--- a/Swiften/StreamStack/LowLayer.cpp
+++ b/Swiften/StreamStack/LowLayer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -12,15 +12,15 @@
namespace Swift {
-LowLayer::LowLayer() : parentLayer(NULL) {
+LowLayer::LowLayer() : parentLayer(nullptr) {
}
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/SConscript b/Swiften/StreamStack/SConscript
index 06fcc03..0a8bab1 100644
--- a/Swiften/StreamStack/SConscript
+++ b/Swiften/StreamStack/SConscript
@@ -3,14 +3,14 @@ Import("swiften_env")
myenv = swiften_env.Clone()
sources = [
- "HighLayer.cpp",
- "LowLayer.cpp",
- "StreamStack.cpp",
- "ConnectionLayer.cpp",
- "TLSLayer.cpp",
- "WhitespacePingLayer.cpp",
- "XMPPLayer.cpp",
- ]
+ "HighLayer.cpp",
+ "LowLayer.cpp",
+ "StreamStack.cpp",
+ "ConnectionLayer.cpp",
+ "TLSLayer.cpp",
+ "WhitespacePingLayer.cpp",
+ "XMPPLayer.cpp",
+ ]
objects = myenv.SwiftenObject(sources)
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
diff --git a/Swiften/StreamStack/StreamLayer.h b/Swiften/StreamStack/StreamLayer.h
index b860c93..14a1ea6 100644
--- a/Swiften/StreamStack/StreamLayer.h
+++ b/Swiften/StreamStack/StreamLayer.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,12 +7,12 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/StreamStack/LowLayer.h>
#include <Swiften/StreamStack/HighLayer.h>
+#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 5cb96de..44a018d 100644
--- a/Swiften/StreamStack/StreamStack.cpp
+++ b/Swiften/StreamStack/StreamStack.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,31 +8,30 @@
#include <boost/bind.hpp>
-#include <Swiften/Base/foreach.h>
-#include <Swiften/StreamStack/XMPPLayer.h>
#include <Swiften/StreamStack/LowLayer.h>
#include <Swiften/StreamStack/StreamLayer.h>
+#include <Swiften/StreamStack/XMPPLayer.h>
namespace Swift {
StreamStack::StreamStack(XMPPLayer* xmppLayer, LowLayer* physicalLayer) : xmppLayer_(xmppLayer), physicalLayer_(physicalLayer) {
- physicalLayer_->setParentLayer(xmppLayer_);
- xmppLayer_->setChildLayer(physicalLayer_);
+ 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_);
- xmppLayer_->setChildLayer(newLayer);
- newLayer->setParentLayer(xmppLayer_);
-
- lowLayer->setParentLayer(newLayer);
- newLayer->setChildLayer(lowLayer);
+ lowLayer->setParentLayer(newLayer);
+ newLayer->setChildLayer(lowLayer);
- layers_.push_back(newLayer);
+ layers_.push_back(newLayer);
}
}
diff --git a/Swiften/StreamStack/StreamStack.h b/Swiften/StreamStack/StreamStack.h
index f19e418..b12a69f 100644
--- a/Swiften/StreamStack/StreamStack.h
+++ b/Swiften/StreamStack/StreamStack.h
@@ -1,47 +1,48 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Base/boost_bsignals.h>
+#include <memory>
#include <vector>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
#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 (auto& i : layers_) {
+ T* layer = dynamic_cast<T*>(i);
+ if (layer) {
+ return layer;
+ }
+ }
+ return nullptr;
+ }
+
+ private:
+ XMPPLayer* xmppLayer_;
+ LowLayer* physicalLayer_;
+ std::vector<StreamLayer*> layers_;
+ };
}
diff --git a/Swiften/StreamStack/TLSLayer.cpp b/Swiften/StreamStack/TLSLayer.cpp
index 15c4101..ced879e 100644
--- a/Swiften/StreamStack/TLSLayer.cpp
+++ b/Swiften/StreamStack/TLSLayer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,49 +8,49 @@
#include <boost/bind.hpp>
-#include <Swiften/TLS/TLSContextFactory.h>
#include <Swiften/TLS/TLSContext.h>
+#include <Swiften/TLS/TLSContextFactory.h>
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();
+std::shared_ptr<CertificateVerificationError> TLSLayer::getPeerCertificateVerificationError() const {
+ return context->getPeerCertificateVerificationError();
}
}
diff --git a/Swiften/StreamStack/TLSLayer.h b/Swiften/StreamStack/TLSLayer.h
index 0ab35d5..415a3f0 100644
--- a/Swiften/StreamStack/TLSLayer.h
+++ b/Swiften/StreamStack/TLSLayer.h
@@ -1,14 +1,15 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
#include <Swiften/Base/SafeByteArray.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/StreamStack/StreamLayer.h>
#include <Swiften/TLS/Certificate.h>
#include <Swiften/TLS/CertificateVerificationError.h>
@@ -17,33 +18,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;
+ std::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::signals2::signal<void (std::shared_ptr<TLSError>)> onError;
+ boost::signals2::signal<void ()> onConnected;
- private:
- TLSContext* context;
- };
+ private:
+ TLSContext* context;
+ };
}
diff --git a/Swiften/StreamStack/UnitTest/StreamStackTest.cpp b/Swiften/StreamStack/UnitTest/StreamStackTest.cpp
index b563b0c..f0f82c9 100644
--- a/Swiften/StreamStack/UnitTest/StreamStackTest.cpp
+++ b/Swiften/StreamStack/UnitTest/StreamStackTest.cpp
@@ -1,182 +1,183 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/ByteArray.h>
-#include <QA/Checker/IO.h>
-
+#include <memory>
#include <vector>
+
#include <boost/bind.hpp>
-#include <boost/smart_ptr.hpp>
+
+#include <QA/Checker/IO.h>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/Base/Concat.h>
-#include <Swiften/StreamStack/StreamStack.h>
-#include <Swiften/StreamStack/LowLayer.h>
-#include <Swiften/StreamStack/XMPPLayer.h>
-#include <Swiften/StreamStack/StreamLayer.h>
-#include <Swiften/Parser/PlatformXMLParserFactory.h>
#include <Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h>
+#include <Swiften/Parser/PlatformXMLParserFactory.h>
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/StreamStack/LowLayer.h>
+#include <Swiften/StreamStack/StreamLayer.h>
+#include <Swiften/StreamStack/StreamStack.h>
+#include <Swiften/StreamStack/XMPPLayer.h>
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_);
+ std::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_);
+ std::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("X"));
+ std::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));
+ std::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));
+ std::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("s"));
+ std::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));
+ std::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("X"));
+ testling.addLayer(xStream.get());
+
+ xmppStream_->writeData("foo");
+
+ CPPUNIT_ASSERT_EQUAL(1, dataWriteReceived_);
+ }
+
+ void handleElement(std::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 ae0f33f..6d1d537 100644
--- a/Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp
+++ b/Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp
@@ -1,141 +1,143 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <vector>
+
#include <boost/bind.hpp>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/Elements/ProtocolHeader.h>
-#include <Swiften/Elements/Presence.h>
#include <Swiften/Base/ByteArray.h>
-#include <Swiften/StreamStack/XMPPLayer.h>
-#include <Swiften/StreamStack/LowLayer.h>
-#include <Swiften/Parser/PlatformXMLParserFactory.h>
+#include <Swiften/Elements/Presence.h>
+#include <Swiften/Elements/ProtocolHeader.h>
#include <Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.h>
+#include <Swiften/Parser/PlatformXMLParserFactory.h>
#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/StreamStack/LowLayer.h>
+#include <Swiften/StreamStack/XMPPLayer.h>
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(std::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(std::shared_ptr<ToplevelElement>) {
+ ++elementsReceived_;
+ }
+
+ void handleElementAndReset(std::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..c9ffe92 100644
--- a/Swiften/StreamStack/WhitespacePingLayer.h
+++ b/Swiften/StreamStack/WhitespacePingLayer.h
@@ -6,35 +6,36 @@
#pragma once
+#include <memory>
+
#include <boost/noncopyable.hpp>
-#include <boost/shared_ptr.hpp>
#include <Swiften/Base/API.h>
#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;
+ std::shared_ptr<Timer> timer;
+ };
}
diff --git a/Swiften/StreamStack/XMPPLayer.cpp b/Swiften/StreamStack/XMPPLayer.cpp
index 5fdadf4..982d13f 100644
--- a/Swiften/StreamStack/XMPPLayer.cpp
+++ b/Swiften/StreamStack/XMPPLayer.cpp
@@ -1,99 +1,101 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/StreamStack/XMPPLayer.h>
+
+#include <Swiften/Elements/ProtocolHeader.h>
#include <Swiften/Parser/XMPPParser.h>
#include <Swiften/Serializer/XMPPSerializer.h>
-#include <Swiften/Elements/ProtocolHeader.h>
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));
+void XMPPLayer::writeElement(std::shared_ptr<ToplevelElement> 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);
+void XMPPLayer::handleElement(std::shared_ptr<ToplevelElement> stanza) {
+ onElement(stanza);
}
void XMPPLayer::handleStreamEnd() {
+ onStreamEnd();
}
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..f0b5afb 100644
--- a/Swiften/StreamStack/XMPPLayer.h
+++ b/Swiften/StreamStack/XMPPLayer.h
@@ -6,70 +6,72 @@
#pragma once
+#include <memory>
+
#include <boost/noncopyable.hpp>
-#include <boost/shared_ptr.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/SafeByteArray.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Elements/StreamType.h>
#include <Swiften/Elements/ToplevelElement.h>
#include <Swiften/Parser/XMPPParserClient.h>
#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(std::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::signals2::signal<void (const ProtocolHeader&)> onStreamStart;
+ boost::signals2::signal<void ()> onStreamEnd;
+ boost::signals2::signal<void (std::shared_ptr<ToplevelElement>)> onElement;
+ boost::signals2::signal<void (const SafeByteArray&)> onWriteData;
+ boost::signals2::signal<void (const SafeByteArray&)> onDataRead;
+ boost::signals2::signal<void ()> onError;
- private:
- void handleStreamStart(const ProtocolHeader&);
- void handleElement(boost::shared_ptr<ToplevelElement>);
- void handleStreamEnd();
+ private:
+ void handleStreamStart(const ProtocolHeader&);
+ void handleElement(std::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..7b5f402 100644
--- a/Swiften/StringCodecs/Base64.cpp
+++ b/Swiften/StringCodecs/Base64.cpp
@@ -1,101 +1,106 @@
/*
- * Copyright (c) 2013 Isode Limited.
+ * Copyright (c) 2013-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/StringCodecs/Base64.h>
+#include <stddef.h>
+
+#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
+
#pragma clang diagnostic ignored "-Wconversion"
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 205797c..fde27c0 100644
--- a/Swiften/StringCodecs/Base64.h
+++ b/Swiften/StringCodecs/Base64.h
@@ -1,12 +1,11 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <vector>
#include <string>
#include <Swiften/Base/API.h>
@@ -14,11 +13,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..907c240 100644
--- a/Swiften/StringCodecs/Hexify.cpp
+++ b/Swiften/StringCodecs/Hexify.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 char i : data) {
+ result << std::setw(2) << std::setfill('0') << boost::numeric_cast<unsigned int>(static_cast<unsigned char>(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 dddad6f..2177b5f 100644
--- a/Swiften/StringCodecs/PBKDF2.h
+++ b/Swiften/StringCodecs/PBKDF2.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,25 +7,25 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Base/SafeByteArray.h>
#include <Swiften/Base/Concat.h>
+#include <Swiften/Base/SafeByteArray.h>
#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 4914fb5..272514f 100644
--- a/Swiften/StringCodecs/UnitTest/Base64Test.cpp
+++ b/Swiften/StringCodecs/UnitTest/Base64Test.cpp
@@ -1,67 +1,67 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/ByteArray.h>
#include <QA/Checker/IO.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/StringCodecs/Base64.h>
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 0ff5b1b..7d349fa 100644
--- a/Swiften/StringCodecs/UnitTest/HexifyTest.cpp
+++ b/Swiften/StringCodecs/UnitTest/HexifyTest.cpp
@@ -1,38 +1,39 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <string>
+
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <Swiften/StringCodecs/Hexify.h>
-#include <string>
#include <Swiften/Base/ByteArray.h>
+#include <Swiften/StringCodecs/Hexify.h>
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 58ef1ba..43866cb 100644
--- a/Swiften/StringCodecs/UnitTest/PBKDF2Test.cpp
+++ b/Swiften/StringCodecs/UnitTest/PBKDF2Test.cpp
@@ -1,54 +1,53 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/ByteArray.h>
#include <QA/Checker/IO.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <Swiften/Base/ByteArray.h>
-#include <Swiften/StringCodecs/PBKDF2.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/StringCodecs/PBKDF2.h>
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 = std::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);
+ }
- 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;
+ private:
+ std::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 f492c50..a46b9f6 100644
--- a/Swiften/TLS/CAPICertificate.cpp
+++ b/Swiften/TLS/CAPICertificate.cpp
@@ -1,350 +1,351 @@
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Network/TimerFactory.h>
#include <Swiften/TLS/CAPICertificate.h>
-#include <Swiften/StringCodecs/Hexify.h>
-#include <Swiften/Base/Log.h>
-#include <boost/bind.hpp>
#include <boost/algorithm/string/predicate.hpp>
+#include <boost/bind.hpp>
+
+#include <Swiften/Base/Log.h>
+#include <Swiften/Network/TimerFactory.h>
+#include <Swiften/StringCodecs/Hexify.h>
// Size of the SHA1 hash
#define SHA1_HASH_LEN 20
#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; \
+ std::shared_ptr<boost::system::error_code> errorCode = std::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..0259db5 100644
--- a/Swiften/TLS/CAPICertificate.h
+++ b/Swiften/TLS/CAPICertificate.h
@@ -4,10 +4,16 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
#include <Swiften/Base/SafeByteArray.h>
#include <Swiften/TLS/CertificateWithKey.h>
#include <Swiften/Network/Timer.h>
@@ -17,52 +23,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::signals2::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_;
+ std::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..dbc61ad 100644
--- a/Swiften/TLS/Certificate.h
+++ b/Swiften/TLS/Certificate.h
@@ -1,46 +1,45 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
#include <vector>
-#include <boost/shared_ptr.hpp>
-
#include <Swiften/Base/API.h>
#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 std::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 744634f..dd2b3ec 100644
--- a/Swiften/TLS/CertificateTrustChecker.h
+++ b/Swiften/TLS/CertificateTrustChecker.h
@@ -1,12 +1,12 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
@@ -14,21 +14,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 f1596dc..02b4cca 100644
--- a/Swiften/TLS/CertificateVerificationError.h
+++ b/Swiften/TLS/CertificateVerificationError.h
@@ -1,43 +1,44 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <Swiften/Base/API.h>
#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 std::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..8414938 100644
--- a/Swiften/TLS/CertificateWithKey.h
+++ b/Swiften/TLS/CertificateWithKey.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::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..17ac8cc 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp
+++ b/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -19,92 +19,92 @@
namespace Swift {
-OpenSSLCertificate::OpenSSLCertificate(boost::shared_ptr<X509> cert) : cert(cert) {
- parse();
+OpenSSLCertificate::OpenSSLCertificate(std::shared_ptr<X509> cert) : cert(cert) {
+ 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 = std::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);
+ std::shared_ptr<GENERAL_NAMES> generalNames(reinterpret_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(extension)), GENERAL_NAMES_free);
+ std::shared_ptr<ASN1_OBJECT> xmppAddrObject(OBJ_txt2obj(ID_ON_XMPPADDR_OID, 1), ASN1_OBJECT_free);
+ std::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 2cc047a..186caea 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLCertificate.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLCertificate.h
@@ -1,70 +1,71 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+#include <string>
+
#include <openssl/ssl.h>
-#include <string>
#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(std::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;
+
+ std::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:
+ std::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..cd6b6bc 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContext.cpp
+++ b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,7 +13,7 @@
#include <vector>
#include <openssl/err.h>
#include <openssl/pkcs12.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
#if defined(SWIFTEN_PLATFORM_MACOSX)
#include <Security/Security.h>
@@ -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_set_default_verify_paths(context_);
#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(std::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(std::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(std::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;
+ std::shared_ptr<PKCS12Certificate> pkcs12Certificate = std::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());
+ std::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;
+ }
+ std::shared_ptr<X509> cert(certPtr, X509_free);
+ std::shared_ptr<EVP_PKEY> privateKey(privateKeyPtr, EVP_PKEY_free);
+ std::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) {
+ std::shared_ptr<X509> x509Cert(X509_dup(sk_X509_value(chain, i)), X509_free);
+
+ Certificate::ref cert = std::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>();
- }
+std::shared_ptr<CertificateVerificationError> OpenSSLContext::getPeerCertificateVerificationError() const {
+ int verifyResult = SSL_get_verify_result(handle_);
+ if (verifyResult != X509_V_OK) {
+ return std::make_shared<CertificateVerificationError>(getVerificationErrorTypeForResult(verifyResult));
+ }
+ else {
+ return std::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..e75b3c9 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContext.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLContext.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,48 +7,48 @@
#pragma once
#include <boost/noncopyable.hpp>
+#include <boost/signals2.hpp>
#include <openssl/ssl.h>
#include <Swiften/Base/ByteArray.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/TLS/CertificateWithKey.h>
#include <Swiften/TLS/TLSContext.h>
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;
+ std::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 4981170..9f7b2aa 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp
+++ b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp
@@ -1,34 +1,35 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/TLS/OpenSSL/OpenSSLContextFactory.h>
-#include <Swiften/TLS/OpenSSL/OpenSSLContext.h>
+
#include <Swiften/Base/Log.h>
+#include <Swiften/TLS/OpenSSL/OpenSSLContext.h>
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 89033ad..e121a1a 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h
@@ -1,23 +1,23 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/TLS/TLSContextFactory.h>
-
#include <cassert>
+#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 0fd3f56..4ed5040 100644
--- a/Swiften/TLS/PKCS12Certificate.h
+++ b/Swiften/TLS/PKCS12Certificate.h
@@ -1,61 +1,62 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <boost/filesystem/path.hpp>
+
#include <Swiften/Base/API.h>
#include <Swiften/Base/SafeByteArray.h>
#include <Swiften/TLS/CertificateWithKey.h>
-#include <boost/filesystem/path.hpp>
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 588e0e1..81f560b 100644
--- a/Swiften/TLS/PlatformTLSFactories.cpp
+++ b/Swiften/TLS/PlatformTLSFactories.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,48 +9,47 @@
#include <Swiften/Base/Platform.h>
#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) {
+PlatformTLSFactories::PlatformTLSFactories() : contextFactory(nullptr), certificateFactory(nullptr) {
#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/SConscript b/Swiften/TLS/SConscript
index f5eb053..68bf50b 100644
--- a/Swiften/TLS/SConscript
+++ b/Swiften/TLS/SConscript
@@ -1,43 +1,41 @@
Import("swiften_env")
objects = swiften_env.SwiftenObject([
- "Certificate.cpp",
- "CertificateFactory.cpp",
- "CertificateTrustChecker.cpp",
- "ServerIdentityVerifier.cpp",
- "TLSContext.cpp",
- "TLSContextFactory.cpp",
- ])
-
+ "Certificate.cpp",
+ "CertificateFactory.cpp",
+ "CertificateTrustChecker.cpp",
+ "ServerIdentityVerifier.cpp",
+ "TLSContext.cpp",
+ "TLSContextFactory.cpp",
+ ])
+
myenv = swiften_env.Clone()
if myenv.get("HAVE_OPENSSL", 0) :
- myenv.MergeFlags(myenv["OPENSSL_FLAGS"])
- objects += myenv.SwiftenObject([
- "OpenSSL/OpenSSLContext.cpp",
- "OpenSSL/OpenSSLCertificate.cpp",
- "OpenSSL/OpenSSLContextFactory.cpp",
- ])
- myenv.Append(CPPDEFINES = "HAVE_OPENSSL")
+ myenv.MergeFlags(myenv["OPENSSL_FLAGS"])
+ objects += myenv.SwiftenObject([
+ "OpenSSL/OpenSSLContext.cpp",
+ "OpenSSL/OpenSSLCertificate.cpp",
+ "OpenSSL/OpenSSLContextFactory.cpp",
+ ])
+ myenv.Append(CPPDEFINES = "HAVE_OPENSSL")
elif myenv.get("HAVE_SCHANNEL", 0) :
- swiften_env.Append(LIBS = ["Winscard"])
- objects += myenv.StaticObject([
- "CAPICertificate.cpp",
- "Schannel/SchannelContext.cpp",
- "Schannel/SchannelCertificate.cpp",
- "Schannel/SchannelContextFactory.cpp",
- ])
- myenv.Append(CPPDEFINES = "HAVE_SCHANNEL")
+ swiften_env.Append(LIBS = ["Winscard"])
+ objects += myenv.SwiftenObject([
+ "CAPICertificate.cpp",
+ "Schannel/SchannelContext.cpp",
+ "Schannel/SchannelCertificate.cpp",
+ "Schannel/SchannelContextFactory.cpp",
+ ])
+ myenv.Append(CPPDEFINES = "HAVE_SCHANNEL")
elif myenv.get("HAVE_SECURETRANSPORT", 0) :
- #swiften_env.Append(LIBS = ["Winscard"])
- objects += myenv.StaticObject([
- "SecureTransport/SecureTransportContext.mm",
- "SecureTransport/SecureTransportCertificate.mm",
- "SecureTransport/SecureTransportContextFactory.cpp",
- ])
- myenv.Append(CPPDEFINES = "HAVE_SECURETRANSPORT")
+ #swiften_env.Append(LIBS = ["Winscard"])
+ objects += myenv.SwiftenObject([
+ "SecureTransport/SecureTransportContext.mm",
+ "SecureTransport/SecureTransportCertificate.mm",
+ "SecureTransport/SecureTransportContextFactory.cpp",
+ ])
+ myenv.Append(CPPDEFINES = "HAVE_SECURETRANSPORT")
objects += myenv.SwiftenObject(["PlatformTLSFactories.cpp"])
-
-
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
diff --git a/Swiften/TLS/Schannel/SchannelCertificate.cpp b/Swiften/TLS/Schannel/SchannelCertificate.cpp
index 8aaec00..23c2479 100644
--- a/Swiften/TLS/Schannel/SchannelCertificate.cpp
+++ b/Swiften/TLS/Schannel/SchannelCertificate.cpp
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include "Swiften/TLS/Schannel/SchannelCertificate.h"
#include "Swiften/Base/ByteArray.h"
@@ -20,176 +26,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());
- // 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;
+ 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);
+ // std::shared_ptr<GENERAL_NAMES> generalNames(reinterpret_cast<GENERAL_NAMES*>(X509V3_EXT_d2i(extension)), GENERAL_NAMES_free);
+ // std::shared_ptr<ASN1_OBJECT> xmppAddrObject(OBJ_txt2obj(ID_ON_XMPPADDR_OID, 1), ASN1_OBJECT_free);
+ // std::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 395d3ec..d3bd66c 100644
--- a/Swiften/TLS/Schannel/SchannelCertificate.h
+++ b/Swiften/TLS/Schannel/SchannelCertificate.h
@@ -4,83 +4,89 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
-#include "Swiften/Base/String.h"
-#include "Swiften/TLS/Certificate.h"
-#include "Swiften/TLS/Schannel/SchannelUtil.h"
+#include <Swiften/Base/String.h>
+#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 std::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..5799157 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(std::make_shared<TLSError>(TLSError::UnknownError));
+ return;
+ }
+ }
+
+ pCertContext = findCertificateInStore( myCertStore_, certName_ );
+ if (pCertContext == NULL) {
+ indicateError(std::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(std::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(std::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 = std::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(std::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);
+void SchannelContext::indicateError(std::shared_ptr<TLSError> 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(std::make_shared<TLSError>(TLSError::UnknownError));
+ break;
+ }
+ else if (status == SEC_I_CONTEXT_EXPIRED) {
+ indicateError(std::make_shared<TLSError>(TLSError::UnknownError));
+ break;
+ }
+ else if (status != SEC_E_OK) {
+ indicateError(std::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(std::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;
- }
+ std::shared_ptr<CAPICertificate> capiCertificate = std::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(std::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(std::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(std::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_ ? std::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..a3748fe 100644
--- a/Swiften/TLS/Schannel/SchannelContext.h
+++ b/Swiften/TLS/Schannel/SchannelContext.h
@@ -5,14 +5,14 @@
*/
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
+#include <boost/signals2.hpp>
#include <Swiften/TLS/TLSContext.h>
#include <Swiften/TLS/Schannel/SchannelUtil.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 std::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(std::shared_ptr<TLSError> error);
+ //FIXME: Remove
+ void indicateError() {indicateError(std::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
+ std::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 c2587c5..f78d386 100644
--- a/Swiften/TLS/Schannel/SchannelContextFactory.cpp
+++ b/Swiften/TLS/Schannel/SchannelContextFactory.cpp
@@ -5,13 +5,14 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include "Swiften/TLS/Schannel/SchannelContextFactory.h"
-#include "Swiften/TLS/Schannel/SchannelContext.h"
+#include <Swiften/TLS/Schannel/SchannelContextFactory.h>
+
+#include <Swiften/TLS/Schannel/SchannelContext.h>
namespace Swift {
@@ -19,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..ec71d9d 100644
--- a/Swiften/TLS/Schannel/SchannelUtil.h
+++ b/Swiften/TLS/Schannel/SchannelUtil.h
@@ -4,6 +4,12 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#define SECURITY_WIN32
@@ -14,412 +20,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:
+ std::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:
+ std::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:
+ std::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:
+ std::shared_ptr<HandleContext> m_pHandle;
+ };
}
diff --git a/Swiften/TLS/SecureTransport/SecureTransportCertificate.h b/Swiften/TLS/SecureTransport/SecureTransportCertificate.h
index b8d3728..7faf3be 100644
--- a/Swiften/TLS/SecureTransport/SecureTransportCertificate.h
+++ b/Swiften/TLS/SecureTransport/SecureTransportCertificate.h
@@ -1,12 +1,13 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
#include <boost/type_traits.hpp>
#include <Security/SecCertificate.h>
@@ -17,29 +18,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_;
+ std::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 ed409bd..db0af89 100644
--- a/Swiften/TLS/SecureTransport/SecureTransportCertificate.mm
+++ b/Swiften/TLS/SecureTransport/SecureTransportCertificate.mm
@@ -19,123 +19,133 @@ 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
}
}
+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;
+}
+
+}
+
namespace Swift {
SecureTransportCertificate::SecureTransportCertificate(SecCertificateRef certificate) {
- assert(certificate);
- CFRetain(certificate);
- certificateHandle_ = boost::shared_ptr<SecCertificate>(certificate, CFRelease);
- parse();
+ assert(certificate);
+ CFRetain(certificate);
+ certificateHandle_ = std::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(nullptr, der.data(), static_cast<CFIndex>(der.size()), nullptr);
+ // certificate will take ownership of derData and free it on its release.
+ SecCertificateRef certificate = SecCertificateCreateWithData(nullptr, derData);
+ if (certificate) {
+ certificateHandle_ = std::shared_ptr<SecCertificate>(certificate, CFRelease);
+ parse();
+ }
}
SecureTransportCertificate::~SecureTransportCertificate() {
}
-#define NS2STDSTRING(a) (a == nil ? std::string() : std::string([a cStringUsingEncoding:NSUTF8StringEncoding]))
-
-
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:[NSString stringWithUTF8String:ID_ON_XMPPADDR_OID]]) {
- xmppAddresses_.push_back(NS2STDSTRING(entry[@"value"]));
- }
- else if ([entry[@"label"] isEqualToString:[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 = nullptr;
+
+ // The SecCertificateCopyValues function is not part of the iOS Secure Transport API.
+ CFDictionaryRef valueDict = SecCertificateCopyValues(certificateHandle_.get(), nullptr, &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 = nullptr;
+ 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..3942904 100644
--- a/Swiften/TLS/SecureTransport/SecureTransportContext.h
+++ b/Swiften/TLS/SecureTransport/SecureTransportContext.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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 std::shared_ptr<TLSError> nativeToTLSError(OSStatus error);
+ std::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(std::shared_ptr<TLSError> error, std::shared_ptr<CertificateVerificationError> certificateError);
+
+ private:
+ std::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..1ed636b 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;
+ std::shared_ptr<PKCS12Certificate> pkcs12 = std::dynamic_pointer_cast<PKCS12Certificate>(key);
+ if (!key) {
+ return nullptr;
+ }
+
+ SafeByteArray safePassword = pkcs12->getPassword();
+ CFIndex passwordSize = 0;
+ try {
+ passwordSize = boost::numeric_cast<CFIndex>(safePassword.size());
+ } catch (...) {
+ return nullptr;
+ }
+
+ CFMutableArrayRef certChain = CFArrayCreateMutable(nullptr, 0, nullptr);
+
+ OSStatus securityError = errSecSuccess;
+ CFStringRef password = CFStringCreateWithBytes(kCFAllocatorDefault, safePassword.data(), passwordSize, kCFStringEncodingUTF8, false);
+ const void* keys[] = { kSecImportExportPassphrase };
+ const void* values[] = { password };
+
+ CFDictionaryRef options = CFDictionaryCreate(nullptr, keys, values, 1, nullptr, nullptr);
+
+ CFArrayRef items = nullptr;
+ 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 = nullptr;
+ }
+ CFRelease(certChain);
+ certChain = nullptr;
+ }
+
+ 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_ = std::shared_ptr<SSLContext>(SSLCreateContext(nullptr, 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) {
+ std::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), std::make_shared<CertificateVerificationError>());
+ }
}
@@ -200,296 +200,308 @@ 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 = nullptr;
+ OSStatus error = SSLCopyPeerTrust(sslContext_.get(), &trust);
+ if (error != noErr) {
+ fatalError(std::make_shared<TLSError>(), std::make_shared<CertificateVerificationError>());
+ return;
+ }
+ std::shared_ptr<SecTrust> trustRef = std::shared_ptr<SecTrust>(trust, CFRelease);
+
+ if (checkCertificateRevocation_) {
+ error = SecTrustSetOptions(trust, kSecTrustOptionRequireRevPerCert | kSecTrustOptionFetchIssuerFromNet);
+ if (error != noErr) {
+ fatalError(std::make_shared<TLSError>(), std::make_shared<CertificateVerificationError>());
+ return;
+ }
+ }
+
+ SecTrustResultType trustResult;
+ error = SecTrustEvaluate(trust, &trustResult);
+ if (error != errSecSuccess) {
+ fatalError(std::make_shared<TLSError>(), std::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) {
+ std::shared_ptr<CFArray> certChainRef = std::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_ = std::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
+ }
+ break;
+ case kSecTrustResultInvalid:
+ verificationError_ = std::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
+ break;
+ case kSecTrustResultConfirm:
+ // TODO: Confirmation from the user is required before proceeding.
+ verificationError_ = std::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
+ break;
+ case kSecTrustResultDeny:
+ // The user specified that the certificate should not be trusted.
+ verificationError_ = std::make_shared<CertificateVerificationError>(CertificateVerificationError::Untrusted);
+ break;
+ case kSecTrustResultFatalTrustFailure:
+ // Trust denied; no simple fix is available.
+ verificationError_ = std::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
+ break;
+ case kSecTrustResultOtherError:
+ verificationError_ = std::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
+ 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(std::make_shared<TLSError>(), std::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(std::make_shared<TLSError>(), std::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;
+ std::shared_ptr<SecTrust> securityTrust;
+
+ SecTrustRef secTrust = nullptr;;
+ OSStatus error = SSLCopyPeerTrust(sslContext_.get(), &secTrust);
+ if (error == noErr) {
+ securityTrust = std::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(std::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;
+std::shared_ptr<TLSError> SecureTransportContext::nativeToTLSError(OSStatus /* error */) {
+ std::shared_ptr<TLSError> swiftenError;
+ swiftenError = std::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;
+std::shared_ptr<CertificateVerificationError> SecureTransportContext::CSSMErrorToVerificationError(OSStatus resultCode) {
+ std::shared_ptr<CertificateVerificationError> error;
+ switch(resultCode) {
+ case CSSMERR_TP_NOT_TRUSTED:
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_NOT_TRUSTED" << std::endl;
+ error = std::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 = std::make_shared<CertificateVerificationError>(CertificateVerificationError::NotYetValid);
+ break;
+ case CSSMERR_TP_CERT_EXPIRED:
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_EXPIRED" << std::endl;
+ error = std::make_shared<CertificateVerificationError>(CertificateVerificationError::Expired);
+ break;
+ case CSSMERR_TP_CERT_REVOKED:
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_REVOKED" << std::endl;
+ error = std::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 = std::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 = std::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 = std::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 = std::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);
+void SecureTransportContext::fatalError(std::shared_ptr<TLSError> error, std::shared_ptr<CertificateVerificationError> certificateError) {
+ 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..226e94b 100644
--- a/Swiften/TLS/ServerIdentityVerifier.cpp
+++ b/Swiften/TLS/ServerIdentityVerifier.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,88 +8,87 @@
#include <boost/algorithm/string.hpp>
-#include <Swiften/Base/foreach.h>
#include <Swiften/IDN/IDNConverter.h>
namespace Swift {
ServerIdentityVerifier::ServerIdentityVerifier(const JID& jid, IDNConverter* idnConverter) : domainValid(false) {
- domain = jid.getDomain();
- boost::optional<std::string> domainResult = idnConverter->getIDNAEncoded(domain);
- if (!!domainResult) {
- encodedDomain = *domainResult;
- domainValid = true;
- }
+ 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 == nullptr) {
+ return false;
+ }
+ // DNS names
+ std::vector<std::string> dnsNames = certificate->getDNSNames();
+ for (const auto& dnsName : dnsNames) {
+ if (matchesDomain(dnsName)) {
+ return true;
+ }
+ }
+ hasSAN |= !dnsNames.empty();
- // SRV names
- std::vector<std::string> srvNames = certificate->getSRVNames();
- foreach (const std::string& srvName, srvNames) {
- // 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();
+ for (const auto& srvName : srvNames) {
+ // Only match SRV names that begin with the service; this isn't required per
+ // spec, but we're being purist about this.
+ if (boost::starts_with(srvName, "_xmpp-client.") && matchesDomain(srvName.substr(std::string("_xmpp-client.").size(), srvName.npos))) {
+ return true;
+ }
+ }
+ hasSAN |= !srvNames.empty();
- // XmppAddr
- std::vector<std::string> xmppAddresses = certificate->getXMPPAddresses();
- foreach (const std::string& xmppAddress, xmppAddresses) {
- if (matchesAddress(xmppAddress)) {
- return true;
- }
- }
- hasSAN |= !xmppAddresses.empty();
+ // XmppAddr
+ std::vector<std::string> xmppAddresses = certificate->getXMPPAddresses();
+ for (const auto& xmppAddress : xmppAddresses) {
+ if (matchesAddress(xmppAddress)) {
+ return true;
+ }
+ }
+ hasSAN |= !xmppAddresses.empty();
- // CommonNames. Only check this if there was no SAN (according to spec).
- if (!hasSAN) {
- std::vector<std::string> commonNames = certificate->getCommonNames();
- foreach (const std::string& commonName, commonNames) {
- 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();
+ for (const auto& 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 79a3c17..f40c683 100644
--- a/Swiften/TLS/ServerIdentityVerifier.h
+++ b/Swiften/TLS/ServerIdentityVerifier.h
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-
+#include <memory>
#include <string>
+
#include <Swiften/Base/API.h>
#include <Swiften/JID/JID.h>
#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 88688c0..08cf1e3 100644
--- a/Swiften/TLS/SimpleCertificate.h
+++ b/Swiften/TLS/SimpleCertificate.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,71 +7,72 @@
#pragma once
#include <string>
+
#include <Swiften/Base/API.h>
#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 std::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 c5703e7..79e3485 100644
--- a/Swiften/TLS/TLSContext.h
+++ b/Swiften/TLS/TLSContext.h
@@ -1,44 +1,45 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <Swiften/Base/boost_bsignals.h>
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
#include <Swiften/Base/SafeByteArray.h>
#include <Swiften/TLS/Certificate.h>
-#include <Swiften/TLS/CertificateWithKey.h>
#include <Swiften/TLS/CertificateVerificationError.h>
+#include <Swiften/TLS/CertificateWithKey.h>
#include <Swiften/TLS/TLSError.h>
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::signals2::signal<void (const SafeByteArray&)> onDataForNetwork;
+ boost::signals2::signal<void (const SafeByteArray&)> onDataForApplication;
+ boost::signals2::signal<void (std::shared_ptr<TLSError>)> onError;
+ boost::signals2::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 27e4b03..ae775e6 100644
--- a/Swiften/TLS/TLSError.h
+++ b/Swiften/TLS/TLSError.h
@@ -1,32 +1,33 @@
/*
- * Copyright (c) 2012-2015 Isode Limited.
+ * Copyright (c) 2012-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <boost/shared_ptr.hpp>
#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 std::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 8e9c205..2483dae 100644
--- a/Swiften/TLS/UnitTest/CertificateTest.cpp
+++ b/Swiften/TLS/UnitTest/CertificateTest.cpp
@@ -1,34 +1,34 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/ByteArray.h>
+#include <memory>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/TLS/Certificate.h>
-#include <Swiften/TLS/SimpleCertificate.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/Crypto/CryptoProvider.h>
#include <Swiften/Crypto/PlatformCryptoProvider.h>
+#include <Swiften/TLS/Certificate.h>
+#include <Swiften/TLS/SimpleCertificate.h>
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 = std::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, std::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 a82cd2e..30fe423 100644
--- a/Swiften/TLS/UnitTest/ServerIdentityVerifierTest.cpp
+++ b/Swiften/TLS/UnitTest/ServerIdentityVerifierTest.cpp
@@ -1,178 +1,178 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
-#include <Swiften/Base/ByteArray.h>
+#include <vector>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <vector>
-#include <Swiften/TLS/ServerIdentityVerifier.h>
-#include <Swiften/TLS/SimpleCertificate.h>
+#include <Swiften/Base/ByteArray.h>
#include <Swiften/IDN/IDNConverter.h>
#include <Swiften/IDN/PlatformIDNConverter.h>
+#include <Swiften/TLS/ServerIdentityVerifier.h>
+#include <Swiften/TLS/SimpleCertificate.h>
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 = std::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;
+ std::shared_ptr<IDNConverter> idnConverter;
};
CPPUNIT_TEST_SUITE_REGISTRATION(ServerIdentityVerifierTest);
diff --git a/Swiften/VCards/GetVCardRequest.h b/Swiften/VCards/GetVCardRequest.h
index 47c302d..1b575c0 100644
--- a/Swiften/VCards/GetVCardRequest.h
+++ b/Swiften/VCards/GetVCardRequest.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,20 +7,20 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/VCard.h>
+#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 std::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, std::make_shared<VCard>(), router) {
+ }
+ };
}
diff --git a/Swiften/VCards/SConscript b/Swiften/VCards/SConscript
index c20c17d..d8189cb 100644
--- a/Swiften/VCards/SConscript
+++ b/Swiften/VCards/SConscript
@@ -1,7 +1,7 @@
Import("swiften_env")
objects = swiften_env.SwiftenObject([
- "VCardManager.cpp",
- "VCardStorage.cpp",
- ])
+ "VCardManager.cpp",
+ "VCardStorage.cpp",
+ ])
swiften_env.Append(SWIFTEN_OBJECTS = [objects])
diff --git a/Swiften/VCards/SetVCardRequest.h b/Swiften/VCards/SetVCardRequest.h
index d59c3bc..15cc78b 100644
--- a/Swiften/VCards/SetVCardRequest.h
+++ b/Swiften/VCards/SetVCardRequest.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -7,20 +7,20 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/VCard.h>
+#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 std::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..3d5338d 100644
--- a/Swiften/VCards/UnitTest/VCardManagerTest.cpp
+++ b/Swiften/VCards/UnitTest/VCardManagerTest.cpp
@@ -1,13 +1,13 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
+#include <memory>
#include <vector>
#include <boost/bind.hpp>
-#include <boost/smart_ptr/make_shared.hpp>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
@@ -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 = std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::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() {
+ std::shared_ptr<VCardManager> testling = createManager();
+ VCard::ref vcard = std::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() {
+ std::shared_ptr<VCardManager> testling = createManager();
+ VCard::ref vcard = std::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:
+ std::shared_ptr<VCardManager> createManager() {
+ std::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;
+ std::shared_ptr<CryptoProvider> crypto;
};
CPPUNIT_TEST_SUITE_REGISTRATION(VCardManagerTest);
diff --git a/Swiften/VCards/VCardManager.cpp b/Swiften/VCards/VCardManager.cpp
index 5fa44ae..95b96fa 100644
--- a/Swiften/VCards/VCardManager.cpp
+++ b/Swiften/VCards/VCardManager.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -22,68 +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);
- }
+ 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 8b3075a..d987862 100644
--- a/Swiften/VCards/VCardManager.h
+++ b/Swiften/VCards/VCardManager.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -9,56 +9,61 @@
#include <set>
#include <boost/date_time/posix_time/posix_time.hpp>
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Elements/VCard.h>
#include <Swiften/Elements/ErrorPayload.h>
+#include <Swiften/Elements/VCard.h>
+#include <Swiften/JID/JID.h>
#include <Swiften/VCards/SetVCardRequest.h>
-#include <Swiften/Base/boost_bsignals.h>
namespace Swift {
- class JID;
- class VCardStorage;
- class IQRouter;
+ class IQRouter;
+ class JID;
+ class VCardStorage;
+
+ class SWIFTEN_API VCardManager : public boost::signals2::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::signals2::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::signals2::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::signals2::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 989d46e..9a79edc 100644
--- a/Swiften/VCards/VCardMemoryStorage.h
+++ b/Swiften/VCards/VCardMemoryStorage.h
@@ -1,52 +1,51 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
-#include <boost/shared_ptr.hpp>
-
#include <map>
+#include <memory>
#include <Swiften/Base/API.h>
#include <Swiften/JID/JID.h>
#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 5e8cca5..2a4f04c 100644
--- a/Swiften/VCards/VCardStorage.cpp
+++ b/Swiften/VCards/VCardStorage.cpp
@@ -1,13 +1,13 @@
/*
- * Copyright (c) 2010-2013 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#include <Swiften/VCards/VCardStorage.h>
-#include <Swiften/StringCodecs/Hexify.h>
#include <Swiften/Crypto/CryptoProvider.h>
+#include <Swiften/StringCodecs/Hexify.h>
namespace Swift {
@@ -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 13554d0..632e9e3 100644
--- a/Swiften/VCards/VCardStorage.h
+++ b/Swiften/VCards/VCardStorage.h
@@ -1,35 +1,35 @@
/*
- * Copyright (c) 2010-2014 Isode Limited.
+ * Copyright (c) 2010-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
#pragma once
+#include <memory>
#include <string>
-#include <boost/shared_ptr.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <Swiften/Base/API.h>
#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 d64a0d2..462bf21 100644
--- a/Swiften/Whiteboard/IncomingWhiteboardSession.cpp
+++ b/Swiften/Whiteboard/IncomingWhiteboardSession.cpp
@@ -4,55 +4,62 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Whiteboard/IncomingWhiteboardSession.h>
-#include <Swiften/Elements/WhiteboardPayload.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h>
+#include <memory>
+
#include <Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h>
+#include <Swiften/Elements/WhiteboardPayload.h>
namespace Swift {
- IncomingWhiteboardSession::IncomingWhiteboardSession(const JID& jid, IQRouter* router) : WhiteboardSession(jid, router) {
- }
-
- 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::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);
- }
- }
-
- void IncomingWhiteboardSession::sendOperation(WhiteboardOperation::ref operation) {
- operation->setID(idGenerator.generateID());
- operation->setParentID(lastOpID);
- lastOpID = operation->getID();
-
- WhiteboardOperation::ref result = client.handleLocalOperationReceived(operation);
-
- if (result) {
- WhiteboardPayload::ref payload = boost::make_shared<WhiteboardPayload>();
- payload->setOperation(result);
- sendPayload(payload);
- }
- }
+ IncomingWhiteboardSession::IncomingWhiteboardSession(const JID& jid, IQRouter* router) : WhiteboardSession(jid, router) {
+ }
+
+ IncomingWhiteboardSession::~IncomingWhiteboardSession() {
+ }
+
+ void IncomingWhiteboardSession::accept() {
+ std::shared_ptr<WhiteboardPayload> payload = std::make_shared<WhiteboardPayload>(WhiteboardPayload::SessionAccept);
+ std::shared_ptr<GenericRequest<WhiteboardPayload> > request = std::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();
+ }
+
+ if (pairResult.server) {
+ WhiteboardPayload::ref payload = std::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();
+
+ WhiteboardOperation::ref result = client.handleLocalOperationReceived(operation);
+
+ if (result) {
+ WhiteboardPayload::ref payload = std::make_shared<WhiteboardPayload>();
+ payload->setOperation(result);
+ sendPayload(payload);
+ }
+ }
}
diff --git a/Swiften/Whiteboard/IncomingWhiteboardSession.h b/Swiften/Whiteboard/IncomingWhiteboardSession.h
index 54b5fb6..0f43cea 100644
--- a/Swiften/Whiteboard/IncomingWhiteboardSession.h
+++ b/Swiften/Whiteboard/IncomingWhiteboardSession.h
@@ -4,28 +4,35 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
+#include <memory>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Whiteboard/WhiteboardSession.h>
#include <Swiften/Whiteboard/WhiteboardClient.h>
-#include <boost/shared_ptr.hpp>
+#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 std::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 ad81daa..49f48aa 100644
--- a/Swiften/Whiteboard/OutgoingWhiteboardSession.cpp
+++ b/Swiften/Whiteboard/OutgoingWhiteboardSession.cpp
@@ -4,56 +4,63 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Whiteboard/OutgoingWhiteboardSession.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/bind.hpp>
-#include <Swiften/Elements/WhiteboardPayload.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h>
+#include <Swiften/Elements/WhiteboardPayload.h>
namespace Swift {
- OutgoingWhiteboardSession::OutgoingWhiteboardSession(const JID& jid, IQRouter* router) : WhiteboardSession(jid, router) {
- }
-
- 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::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();
-
- 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();
-
- server.handleLocalOperationReceived(operation);
- WhiteboardPayload::ref payload = boost::make_shared<WhiteboardPayload>();
- payload->setOperation(operation);
- sendPayload(payload);
- }
+ OutgoingWhiteboardSession::OutgoingWhiteboardSession(const JID& jid, IQRouter* router) : WhiteboardSession(jid, router) {
+ }
+
+ OutgoingWhiteboardSession::~OutgoingWhiteboardSession() {
+ }
+
+ void OutgoingWhiteboardSession::startSession() {
+ std::shared_ptr<WhiteboardPayload> payload = std::make_shared<WhiteboardPayload>(WhiteboardPayload::SessionRequest);
+ std::shared_ptr<GenericRequest<WhiteboardPayload> > request = std::make_shared<GenericRequest<WhiteboardPayload> >(IQ::Set, toJID_, payload, router_);
+ request->onResponse.connect(boost::bind(&OutgoingWhiteboardSession::handleRequestResponse, this, _1, _2));
+ request->send();
+ }
+
+ void OutgoingWhiteboardSession::handleRequestResponse(std::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();
+
+ WhiteboardPayload::ref payload = std::make_shared<WhiteboardPayload>();
+ payload->setOperation(op);
+ sendPayload(payload);
+ }
+
+ void OutgoingWhiteboardSession::sendOperation(WhiteboardOperation::ref operation) {
+ operation->setID(idGenerator.generateID());
+ operation->setParentID(lastOpID);
+ lastOpID = operation->getID();
+
+ server.handleLocalOperationReceived(operation);
+ WhiteboardPayload::ref payload = std::make_shared<WhiteboardPayload>();
+ payload->setOperation(operation);
+ sendPayload(payload);
+ }
}
diff --git a/Swiften/Whiteboard/OutgoingWhiteboardSession.h b/Swiften/Whiteboard/OutgoingWhiteboardSession.h
index 5db9c97..52fb1db 100644
--- a/Swiften/Whiteboard/OutgoingWhiteboardSession.h
+++ b/Swiften/Whiteboard/OutgoingWhiteboardSession.h
@@ -4,29 +4,36 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <Swiften/Whiteboard/WhiteboardSession.h>
-#include <Swiften/Whiteboard/WhiteboardServer.h>
-#include <boost/shared_ptr.hpp>
-#include <Swiften/Queries/GenericRequest.h>
+#include <memory>
+
#include <Swiften/Base/API.h>
+#include <Swiften/Queries/GenericRequest.h>
+#include <Swiften/Whiteboard/WhiteboardServer.h>
+#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 std::shared_ptr<OutgoingWhiteboardSession> ref;
+
+ public:
+ OutgoingWhiteboardSession(const JID& jid, IQRouter* router);
+ virtual ~OutgoingWhiteboardSession();
+ void startSession();
+
+ private:
+ void handleRequestResponse(std::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 09c25bb..fd26825 100644
--- a/Swiften/Whiteboard/UnitTest/WhiteboardClientTest.cpp
+++ b/Swiften/Whiteboard/UnitTest/WhiteboardClientTest.cpp
@@ -4,673 +4,680 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+
+#include <memory>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Whiteboard/WhiteboardClient.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h>
+#include <Swiften/Whiteboard/WhiteboardClient.h>
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, std::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 = std::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 = std::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 = std::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, std::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 = std::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 = std::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 = std::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ serverOp->setElement(eElement);
+ pairResult = client.handleServerOperationReceived(serverOp);
+ WhiteboardInsertOperation::ref result = std::dynamic_pointer_cast<WhiteboardInsertOperation>(pairResult.client);
+ CPPUNIT_ASSERT_EQUAL(serverOp, std::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, std::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 = std::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 = std::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 = std::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 = std::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, std::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 = std::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 = std::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 = std::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 = std::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 = std::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, std::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 = std::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 = std::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 = std::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 = std::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, std::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 = std::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 = std::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 = std::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 = std::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, std::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, std::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 = std::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 = std::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 = std::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 = std::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 = std::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 = std::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 = std::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
+ if (insertOp) {
+ CPPUNIT_ASSERT_EQUAL(element, insertOp->getElement());
+ }
+
+ WhiteboardUpdateOperation::ref updateOp = std::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 a7b9acc..e868968 100644
--- a/Swiften/Whiteboard/UnitTest/WhiteboardServerTest.cpp
+++ b/Swiften/Whiteboard/UnitTest/WhiteboardServerTest.cpp
@@ -4,125 +4,132 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+
+#include <memory>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Whiteboard/WhiteboardServer.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardEllipseElement.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h>
+#include <Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h>
+#include <Swiften/Whiteboard/WhiteboardServer.h>
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 = std::make_shared<WhiteboardInsertOperation>();
+ firstOp->setID("0");
+ server.handleLocalOperationReceived(firstOp);
+ WhiteboardInsertOperation::ref serverOp = std::make_shared<WhiteboardInsertOperation>();
+ serverOp->setID("b");
+ serverOp->setParentID("0");
+ serverOp->setPos(1);
+ server.handleLocalOperationReceived(serverOp);
+ WhiteboardInsertOperation::ref clientOp = std::make_shared<WhiteboardInsertOperation>();
+ WhiteboardEllipseElement::ref clientElement = std::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setID("a");
+ clientOp->setParentID("0");
+ clientOp->setPos(1);
+ clientOp->setElement(clientElement);
+ WhiteboardInsertOperation::ref op = std::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, std::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 = std::make_shared<WhiteboardInsertOperation>();
+ firstOp->setID("0");
+ server.handleLocalOperationReceived(firstOp);
+ WhiteboardDeleteOperation::ref serverOp = std::make_shared<WhiteboardDeleteOperation>();
+ serverOp->setID("b");
+ serverOp->setParentID("0");
+ serverOp->setPos(1);
+ server.handleLocalOperationReceived(serverOp);
+ WhiteboardUpdateOperation::ref clientOp = std::make_shared<WhiteboardUpdateOperation>();
+ WhiteboardEllipseElement::ref clientElement = std::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setID("a");
+ clientOp->setParentID("0");
+ clientOp->setPos(1);
+ clientOp->setElement(clientElement);
+ WhiteboardDeleteOperation::ref op = std::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 = std::make_shared<WhiteboardInsertOperation>();
+ firstOp->setID("0");
+ server.handleLocalOperationReceived(firstOp);
+ WhiteboardUpdateOperation::ref serverOp = std::make_shared<WhiteboardUpdateOperation>();
+ serverOp->setID("b");
+ serverOp->setParentID("0");
+ serverOp->setPos(1);
+ server.handleLocalOperationReceived(serverOp);
+ WhiteboardDeleteOperation::ref clientOp = std::make_shared<WhiteboardDeleteOperation>();
+ clientOp->setID("a");
+ clientOp->setParentID("0");
+ clientOp->setPos(1);
+ WhiteboardDeleteOperation::ref op = std::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 = std::make_shared<WhiteboardInsertOperation>();
+ firstOp->setID("0");
+ server.handleLocalOperationReceived(firstOp);
+ WhiteboardInsertOperation::ref serverOp = std::make_shared<WhiteboardInsertOperation>();
+ serverOp->setID("a");
+ serverOp->setParentID("0");
+ serverOp->setPos(1);
+ server.handleLocalOperationReceived(serverOp);
+ serverOp = std::make_shared<WhiteboardInsertOperation>();
+ serverOp->setID("b");
+ serverOp->setParentID("a");
+ serverOp->setPos(2);
+ server.handleLocalOperationReceived(serverOp);
+ serverOp = std::make_shared<WhiteboardInsertOperation>();
+ serverOp->setID("c");
+ serverOp->setParentID("b");
+ serverOp->setPos(3);
+ server.handleLocalOperationReceived(serverOp);
+ WhiteboardInsertOperation::ref clientOp = std::make_shared<WhiteboardInsertOperation>();
+ WhiteboardEllipseElement::ref clientElement = std::make_shared<WhiteboardEllipseElement>(0,0,0,0);
+ clientOp->setID("d");
+ clientOp->setParentID("0");
+ clientOp->setPos(1);
+ clientOp->setElement(clientElement);
+ WhiteboardInsertOperation::ref op = std::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, std::dynamic_pointer_cast<WhiteboardEllipseElement>(op->getElement()));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(WhiteboardServerTest);
diff --git a/Swiften/Whiteboard/WhiteboardClient.cpp b/Swiften/Whiteboard/WhiteboardClient.cpp
index c17b9f9..d7ed3ad 100644
--- a/Swiften/Whiteboard/WhiteboardClient.cpp
+++ b/Swiften/Whiteboard/WhiteboardClient.cpp
@@ -4,118 +4,126 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Whiteboard/WhiteboardClient.h>
-#include <Swiften/Whiteboard/WhiteboardTransformer.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
#include <iostream>
+#include <memory>
+
+#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 = std::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
+ if (insertOp) {
+ op = std::make_shared<WhiteboardInsertOperation>(*insertOp);
+ }
+ WhiteboardUpdateOperation::ref updateOp = std::dynamic_pointer_cast<WhiteboardUpdateOperation>(operation);
+ if (updateOp) {
+ op = std::make_shared<WhiteboardUpdateOperation>(*updateOp);
+ }
+ WhiteboardDeleteOperation::ref deleteOp = std::dynamic_pointer_cast<WhiteboardDeleteOperation>(operation);
+ if (deleteOp) {
+ op = std::make_shared<WhiteboardDeleteOperation>(*deleteOp);
+ }
+
+ if (!bridge_.empty()) {
+ op->setParentID(bridge_.back()->getID());
+ }
+ bridge_.push_back(op);
+
+ if (lastSentOperationID_.empty())
+ {
+ WhiteboardInsertOperation::ref insertOp = std::dynamic_pointer_cast<WhiteboardInsertOperation>(operation);
+ if (insertOp) {
+ op = std::make_shared<WhiteboardInsertOperation>(*insertOp);
+ }
+ WhiteboardUpdateOperation::ref updateOp = std::dynamic_pointer_cast<WhiteboardUpdateOperation>(operation);
+ if (updateOp) {
+ op = std::make_shared<WhiteboardUpdateOperation>(*updateOp);
+ }
+ WhiteboardDeleteOperation::ref deleteOp = std::dynamic_pointer_cast<WhiteboardDeleteOperation>(operation);
+ if (deleteOp) {
+ op = std::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 2cc46a6..15870c6 100644
--- a/Swiften/Whiteboard/WhiteboardClient.h
+++ b/Swiften/Whiteboard/WhiteboardClient.h
@@ -4,34 +4,41 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <Swiften/Base/API.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardOperation.h>
#include <list>
#include <utility>
+#include <Swiften/Base/API.h>
+#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 f72861f..f9df709 100644
--- a/Swiften/Whiteboard/WhiteboardResponder.cpp
+++ b/Swiften/Whiteboard/WhiteboardResponder.cpp
@@ -4,34 +4,41 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Whiteboard/WhiteboardResponder.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Whiteboard/WhiteboardSessionManager.h>
+#include <memory>
+
+#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Whiteboard/IncomingWhiteboardSession.h>
#include <Swiften/Whiteboard/WhiteboardSession.h>
-#include <Swiften/Queries/IQRouter.h>
+#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, std::shared_ptr<WhiteboardPayload> payload) {
+ if (payload->getType() == WhiteboardPayload::SessionRequest) {
+ if (sessionManager_->getSession(from)) {
+ sendError(from, id, ErrorPayload::Conflict, ErrorPayload::Cancel);
+ } else {
+ sendResponse(from, id, std::shared_ptr<WhiteboardPayload>());
+ IncomingWhiteboardSession::ref session = std::make_shared<IncomingWhiteboardSession>(from, router_);
+ sessionManager_->handleIncomingSession(session);
+ }
+ } else {
+ sendResponse(from, id, std::shared_ptr<WhiteboardPayload>());
+ WhiteboardSession::ref session = sessionManager_->getSession(from);
+ if (session != nullptr) {
+ session->handleIncomingAction(payload);
+ }
+ }
+ return true;
+ }
}
diff --git a/Swiften/Whiteboard/WhiteboardResponder.h b/Swiften/Whiteboard/WhiteboardResponder.h
index 23c6341..ac44664 100644
--- a/Swiften/Whiteboard/WhiteboardResponder.h
+++ b/Swiften/Whiteboard/WhiteboardResponder.h
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,20 +13,20 @@
#pragma once
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/SetResponder.h>
#include <Swiften/Elements/WhiteboardPayload.h>
+#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, std::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 94f8cff..4a2a315 100644
--- a/Swiften/Whiteboard/WhiteboardServer.cpp
+++ b/Swiften/Whiteboard/WhiteboardServer.cpp
@@ -4,46 +4,54 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Whiteboard/WhiteboardServer.h>
-#include <Swiften/Whiteboard/WhiteboardTransformer.h>
+
#include <iostream>
+#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 73e8d33..fcbdbe7 100644
--- a/Swiften/Whiteboard/WhiteboardServer.h
+++ b/Swiften/Whiteboard/WhiteboardServer.h
@@ -4,21 +4,27 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
+#include <list>
+
#include <Swiften/Base/API.h>
#include <Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h>
-#include <list>
-
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 cffcf07..c90475a 100644
--- a/Swiften/Whiteboard/WhiteboardSession.cpp
+++ b/Swiften/Whiteboard/WhiteboardSession.cpp
@@ -4,64 +4,69 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Whiteboard/WhiteboardSession.h>
-#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/Elements/WhiteboardPayload.h>
-#include <Swiften/Elements/ErrorPayload.h>
+#include <memory>
-#include <iostream>
+#include <Swiften/Elements/ErrorPayload.h>
+#include <Swiften/Elements/WhiteboardPayload.h>
+#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(std::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) {
+ std::shared_ptr<WhiteboardPayload> payload = std::make_shared<WhiteboardPayload>();
+ payload->setElement(element);
+ std::shared_ptr<GenericRequest<WhiteboardPayload> > request = std::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(std::shared_ptr<WhiteboardPayload> payload) {
+ std::shared_ptr<GenericRequest<WhiteboardPayload> > request = std::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()) {
+ std::shared_ptr<WhiteboardPayload> payload = std::make_shared<WhiteboardPayload>(WhiteboardPayload::SessionTerminate);
+ std::shared_ptr<GenericRequest<WhiteboardPayload> > request = std::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 14fa632..0871f94 100644
--- a/Swiften/Whiteboard/WhiteboardSession.h
+++ b/Swiften/Whiteboard/WhiteboardSession.h
@@ -4,52 +4,59 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
-#include <boost/shared_ptr.hpp>
+#include <memory>
+
+#include <boost/signals2.hpp>
#include <Swiften/Base/API.h>
-#include <Swiften/JID/JID.h>
-#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Base/IDGenerator.h>
-#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/Whiteboard/WhiteboardElement.h>
#include <Swiften/Elements/Whiteboard/WhiteboardOperation.h>
+#include <Swiften/JID/JID.h>
+#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 std::shared_ptr<WhiteboardSession> ref;
+
+ public:
+ WhiteboardSession(const JID& jid, IQRouter* router);
+ virtual ~WhiteboardSession();
+ void handleIncomingAction(std::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::signals2::signal< void(const WhiteboardElement::ref element)> onElementReceived;
+ boost::signals2::signal< void(const WhiteboardOperation::ref operation)> onOperationReceived;
+ boost::signals2::signal< void(const JID& contact)> onSessionTerminated;
+ boost::signals2::signal< void(const JID& contact)> onRequestAccepted;
+ boost::signals2::signal< void(const JID& contact)> onRequestRejected;
+
+ private:
+ virtual void handleIncomingOperation(WhiteboardOperation::ref operation) = 0;
+
+ protected:
+ void sendPayload(std::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 c8e9a6a..59f6c47 100644
--- a/Swiften/Whiteboard/WhiteboardSessionManager.cpp
+++ b/Swiften/Whiteboard/WhiteboardSessionManager.cpp
@@ -4,108 +4,115 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Whiteboard/WhiteboardSessionManager.h>
-#include <Swiften/Base/foreach.h>
-#include <boost/smart_ptr/make_shared.hpp>
+#include <memory>
+
#include <boost/bind.hpp>
+
+#include <Swiften/Disco/EntityCapsProvider.h>
+#include <Swiften/Presence/PresenceOracle.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Whiteboard/WhiteboardResponder.h>
-#include <Swiften/Presence/PresenceOracle.h>
-#include "Swiften/Disco/EntityCapsProvider.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 std::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 = std::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
+ for (const auto& pres : presences) {
+ if (pres->getPriority() > priority) {
+ // look up caps from the jid
+ DiscoInfo::ref info = capsProvider_->getCaps(pres->getFrom());
+ if (info && info->hasFeature(DiscoInfo::WhiteboardFeature)) {
+ priority = pres->getPriority();
+ fullReceipientJID = pres->getFrom();
+ }
+ }
+ }
+
+ return fullReceipientJID;
+ }
+
+ void WhiteboardSessionManager::deleteSessionEntry(const JID& contact) {
+ sessions_.erase(contact);
+ }
+
+ void WhiteboardSessionManager::handlePresenceReceived(Presence::ref presence) {
+ if (!presence->isAvailable()) {
+ WhiteboardSession::ref session = getSession(presence->getFrom());
+ if (session) {
+ session->cancel();
+ }
+ }
+ }
+
+ void WhiteboardSessionManager::handleAvailableChanged(bool available) {
+ if (!available) {
+ std::map<JID, WhiteboardSession::ref> sessionsCopy = sessions_;
+ std::map<JID, WhiteboardSession::ref>::iterator it;
+ for (it = sessionsCopy.begin(); it != sessionsCopy.end(); ++it) {
+ it->second->cancel();
+ }
+ }
+ }
}
diff --git a/Swiften/Whiteboard/WhiteboardSessionManager.h b/Swiften/Whiteboard/WhiteboardSessionManager.h
index d06b856..4f14665 100644
--- a/Swiften/Whiteboard/WhiteboardSessionManager.h
+++ b/Swiften/Whiteboard/WhiteboardSessionManager.h
@@ -4,51 +4,58 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
#include <map>
+#include <boost/signals2.hpp>
+
#include <Swiften/Base/API.h>
-#include <Swiften/Queries/IQRouter.h>
-#include <Swiften/JID/JID.h>
#include <Swiften/Client/StanzaChannel.h>
-#include <Swiften/Base/boost_bsignals.h>
-#include <Swiften/Whiteboard/WhiteboardSession.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Whiteboard/IncomingWhiteboardSession.h>
#include <Swiften/Whiteboard/OutgoingWhiteboardSession.h>
+#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::signals2::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, std::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 8b9c927..1d519f4 100644
--- a/Swiften/Whiteboard/WhiteboardTransformer.cpp
+++ b/Swiften/Whiteboard/WhiteboardTransformer.cpp
@@ -4,210 +4,217 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#include <Swiften/Whiteboard/WhiteboardTransformer.h>
-#include <boost/smart_ptr/make_shared.hpp>
+
+#include <memory>
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 = std::dynamic_pointer_cast<WhiteboardInsertOperation>(clientOp);
+ WhiteboardInsertOperation::ref serverInsert = std::dynamic_pointer_cast<WhiteboardInsertOperation>(serverOp);
+ WhiteboardUpdateOperation::ref clientUpdate = std::dynamic_pointer_cast<WhiteboardUpdateOperation>(clientOp);
+ WhiteboardUpdateOperation::ref serverUpdate = std::dynamic_pointer_cast<WhiteboardUpdateOperation>(serverOp);
+ WhiteboardDeleteOperation::ref clientDelete = std::dynamic_pointer_cast<WhiteboardDeleteOperation>(clientOp);
+ WhiteboardDeleteOperation::ref serverDelete = std::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 = std::make_shared<WhiteboardInsertOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+ result.second = std::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 = std::make_shared<WhiteboardUpdateOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+
+ if (clientOp->getPos() == serverOp->getPos()) {
+ result.second = std::make_shared<WhiteboardUpdateOperation>(*serverOp);
+ result.second->setID(clientOp->getID());
+ result.second->setParentID(serverOp->getID());
+ } else {
+ result.second = std::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 = std::make_shared<WhiteboardInsertOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+ result.second = std::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 = std::make_shared<WhiteboardUpdateOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+ result.second = std::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 = std::make_shared<WhiteboardDeleteOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+ result.second = std::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 = std::make_shared<WhiteboardDeleteOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+ result.second = std::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 = std::make_shared<WhiteboardInsertOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+ result.second = std::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 = std::make_shared<WhiteboardDeleteOperation>(*serverOp);
+ result.first->setParentID(clientOp->getID());
+ WhiteboardUpdateOperation::ref updateOp = std::make_shared<WhiteboardUpdateOperation>(*clientOp);
+ result.second = updateOp;
+ result.second->setParentID(serverOp->getID());
+ if (clientOp->getPos() == serverOp->getPos()) {
+ WhiteboardDeleteOperation::ref deleteOp = std::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 = std::make_shared<WhiteboardUpdateOperation>(*serverOp);
+ result.first = updateOp;
+ result.first->setParentID(clientOp->getID());
+ result.second = std::make_shared<WhiteboardDeleteOperation>(*clientOp);
+ result.second->setParentID(serverOp->getID());
+ if (clientOp->getPos() == serverOp->getPos()) {
+ WhiteboardDeleteOperation::ref deleteOp = std::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 5811f9f..399e299 100644
--- a/Swiften/Whiteboard/WhiteboardTransformer.h
+++ b/Swiften/Whiteboard/WhiteboardTransformer.h
@@ -4,25 +4,32 @@
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
#pragma once
+#include <utility>
+
+#include <Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h>
#include <Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h>
-#include <Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h>
-#include <utility>
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);
+ };
}