diff --git a/INSTALL b/INSTALL index 9e22624f78947a0bde6f54a249efd4d9dfc83137..59b9f8ebcd72f2a5496f2ace2c933c416db9ec14 100644 --- a/INSTALL +++ b/INSTALL @@ -1,6 +1,13 @@ INSTALLATION GUIDE * CORE INSTALLATION + + # Install dependencies (subject to change): + apt-get install gnome-doc-utils build-essential autoconf libtool + libasound2-dev libpulse-dev libsamplerate0-dev libcommoncpp2-dev + libccrtp-dev libzrtpcpp-dev libdbus-1-dev libdbus-c++-dev libyaml-dev + libpcre3-dev libgsm1-dev libspeex-dev libspeexdsp-dev libcelt-dev + # Go to the root of the application core directory cd daemon # Compile pjsip @@ -16,6 +23,10 @@ INSTALLATION GUIDE You are done with the core ! * GNOME CLIENT INSTALLATION + + # Install dependencies (subject to change): + apt-get install libnotify-dev libgtk2.0-dev libwebkit-dev libgnomeui-dev check + # Go to the root of the gnome client directory cd gnome ./autogen.sh diff --git a/NEWS b/NEWS index eceb88a204eeffb9cfbd41b0be2b64a88ac06bf1..622094a882577ce32fd05b19b2b1b09cd445b5ae 100644 --- a/NEWS +++ b/NEWS @@ -2,6 +2,8 @@ # SFLphone ################################################ +* 2011-11-18: 1.0.1 has been released + * 2011-09-30: 1.0.0 has been released * 2010-04-09: 0.9.8 rc1 has been released diff --git a/astylerc b/astylerc index 460124f66d7a1f71a6c4d0a168f9502e4755a059..20608435842d7696f67be15e5e3b12c5f98fb14e 100644 --- a/astylerc +++ b/astylerc @@ -5,12 +5,14 @@ # Savoir-faire Linux Inc # http://www.sflphone.org -style=k&r # Kernighan & Ritchie style formatting/indenting uses linux bracket -indent=spaces=4 # Use spaces instead of tabs for indentation -indent-classes # Indent 'class' and 'struct' blocks so that the blocks 'public:', 'protected:' and 'private:' are indented -indent-switches # Indent 'switch' blocks so that the 'case X:' statements are indented in the switch block -break-blocks # Pad empty lines around header blocks (e.g. 'if', 'while'...). +style=stroustrup # stroustrup style http://astyle.sourceforge.net/astyle.html#_style=stroustrup +indent=spaces=4 # Use spaces instead of tabs for indentation +indent-classes # Indent 'class' and 'struct' blocks so that the blocks 'public:', 'protected:' and 'private:' are indented +indent-switches # Indent 'switch' blocks so that the 'case X:' statements are indented in the switch block +break-blocks # Pad empty lines around header blocks (e.g. 'if', 'while'...). brackets=linux -unpad=paren -formatted --d +unpad-paren # Remove unwanted space around parentheses +pad-header # Insert space padding after paren headers only (e.g. 'if', 'for', 'while'...) +formatted # only display files that have changed +recursive # recursively enter subdirs +suffix=none # don't create backup files (that's what version control is for) diff --git a/daemon/README b/daemon/README index 3c4d8f924f6cef6d3c44a41de4e9602b28290085..afc3decbec4a968f7ab33d3032a2e2284bf0fe4d 100644 --- a/daemon/README +++ b/daemon/README @@ -74,7 +74,7 @@ How to compile -------------- # First compile the SIP library -cd libs/pjproject-1.0.3 +cd libs/pjproject ./autogen.sh ./configure --disable-ilbc-codec && make clean && make dep && make sudo make install diff --git a/daemon/configure.ac b/daemon/configure.ac index 304ab694b6e5a25205db4d51049f22f861f97d8b..0f700137936c340dfbbeef33c9234bdb97f0b2cd 100644 --- a/daemon/configure.ac +++ b/daemon/configure.ac @@ -3,7 +3,7 @@ dnl dnl Process this file with autoconf to produce a configure script. AC_PREREQ([2.65]) -AC_INIT([sflphone],[1.0.0],[sflphoneteam@savoirfairelinux.com],[sflphone]) +AC_INIT([sflphone],[1.0.1],[sflphoneteam@savoirfairelinux.com],[sflphone]) AC_COPYRIGHT([[Copyright (c) Savoir-Faire Linux 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011]]) AC_REVISION([$Revision$]) @@ -50,8 +50,6 @@ AC_CONFIG_FILES([src/Makefile \ src/audio/codecs/Makefile \ src/config/Makefile \ src/dbus/Makefile \ - src/plug-in/Makefile \ - src/plug-in/test/Makefile \ src/hooks/Makefile \ src/history/Makefile]) @@ -180,7 +178,7 @@ DBUS_CPP_REQUIRED_VERSION=0.6.0-pre1 PKG_CHECK_MODULES(DBUSCPP, dbus-c++-1,, AC_MSG_ERROR([You need the DBus-c++ libraries (version $DBUS_CPP_REQUIRED_VERSION or better)])) -CXXFLAGS="${CXXFLAGS} -g -Wno-return-type -Wall -Wextra -Wnon-virtual-dtor" +CXXFLAGS="${CXXFLAGS} -g -Wno-return-type -Wall -Wextra -Wnon-virtual-dtor -Weffc++ -Wfatal-errors" AC_CHECK_LIB([expat], XML_ParserCreate_MM, [AC_CHECK_HEADERS(expat.h, have_expat=true, have_expat=false)], diff --git a/daemon/libs/utilspp/Makefile.am b/daemon/libs/utilspp/Makefile.am index 2852c54fc302c2f9b9d48e837a62be9f69fd308b..403b7fc158899e61b14337c92505efb4f8e6b2ba 100644 --- a/daemon/libs/utilspp/Makefile.am +++ b/daemon/libs/utilspp/Makefile.am @@ -3,8 +3,8 @@ SUBDIRS = singleton noinst_LTLIBRARIES = libutilspp.la libutilspp_la_SOURCES = \ - NullType.hpp \ - Singleton.hpp \ - ThreadingSingle.hpp ThreadingSingle.inl + null_type.hpp \ + singleton.hpp \ + threading_single.hpp threading_single.inl libutilspp_la_LIBADD = ./singleton/libsingleton.la diff --git a/daemon/libs/utilspp/Singleton.hpp b/daemon/libs/utilspp/Singleton.hpp deleted file mode 100644 index 487cbebb5dcebcc2a1dbd7a2c7478e82e6737c78..0000000000000000000000000000000000000000 --- a/daemon/libs/utilspp/Singleton.hpp +++ /dev/null @@ -1,2 +0,0 @@ -#include "ThreadingSingle.hpp" -#include "singleton/SingletonHolder.hpp" diff --git a/daemon/libs/utilspp/NullType.hpp b/daemon/libs/utilspp/null_type.hpp similarity index 100% rename from daemon/libs/utilspp/NullType.hpp rename to daemon/libs/utilspp/null_type.hpp diff --git a/daemon/libs/utilspp/singleton.hpp b/daemon/libs/utilspp/singleton.hpp new file mode 100644 index 0000000000000000000000000000000000000000..649394f938addcb72c6cb317953dd20b4cf6c3a8 --- /dev/null +++ b/daemon/libs/utilspp/singleton.hpp @@ -0,0 +1,2 @@ +#include "threading_single.hpp" +#include "singleton/singleton_holder.hpp" diff --git a/daemon/libs/utilspp/singleton/Makefile.am b/daemon/libs/utilspp/singleton/Makefile.am index 66fdc6f012b1dc9be7b4ac50838245119b801f90..d494c4c5e8f963fd9a25b28abd8e576bbb0e78d9 100644 --- a/daemon/libs/utilspp/singleton/Makefile.am +++ b/daemon/libs/utilspp/singleton/Makefile.am @@ -1,19 +1,6 @@ noinst_LTLIBRARIES = libsingleton.la libsingleton_la_SOURCES = \ - CreationUsingNew.hpp CreationUsingNew.inl \ - LifetimeDefault.hpp LifetimeDefault.inl \ - SingletonHolder.hpp SingletonHolder.inl - - -#pkginclude_HEADERS = \ -# CreationStatic.hpp CreationStatic.inl \ -# CreationUsingNew.hpp CreationUsingNew.inl \ -# LifetimeDefault.hpp LifetimeDefault.inl \ -# LifetimeLibrary.hpp LifetimeLibrary.inl \ -# LifetimeWithLongevity.hpp LifetimeWithLongevity.inl \ -# PrivateMembers.hpp PrivateMembers.inl \ -# SingletonHolder.hpp SingletonHolder.inl - -#pkgincludedir=$(includedir)/utilspp/singleton - + creation_using_new.hpp creation_using_new.inl \ + lifetime_default.hpp lifetime_default.inl \ + singleton_holder.hpp singleton_holder.inl diff --git a/daemon/libs/utilspp/singleton/CreationUsingNew.hpp b/daemon/libs/utilspp/singleton/creation_using_new.hpp similarity index 91% rename from daemon/libs/utilspp/singleton/CreationUsingNew.hpp rename to daemon/libs/utilspp/singleton/creation_using_new.hpp index 2108d78f2717388f40b85625c08a6e4f1be2889b..de9c995d3d16ea4d1e9882067e6a44159c714539 100644 --- a/daemon/libs/utilspp/singleton/CreationUsingNew.hpp +++ b/daemon/libs/utilspp/singleton/creation_using_new.hpp @@ -21,8 +21,8 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#ifndef CREATION_USING_NEW_HPP -#define CREATION_USING_NEW_HPP +#ifndef __CREATION_USING_NEW_HPP__ +#define __CREATION_USING_NEW_HPP__ /** * This class is a creation policy for the utilspp::singleton_holder. The @@ -38,6 +38,5 @@ namespace utilspp }; } -#include "CreationUsingNew.inl" - -#endif +#include "creation_using_new.inl" +#endif // __CREATION_USING_NEW_HPP__ diff --git a/daemon/libs/utilspp/singleton/CreationUsingNew.inl b/daemon/libs/utilspp/singleton/creation_using_new.inl similarity index 100% rename from daemon/libs/utilspp/singleton/CreationUsingNew.inl rename to daemon/libs/utilspp/singleton/creation_using_new.inl diff --git a/daemon/libs/utilspp/singleton/LifetimeDefault.hpp b/daemon/libs/utilspp/singleton/lifetime_default.hpp similarity index 95% rename from daemon/libs/utilspp/singleton/LifetimeDefault.hpp rename to daemon/libs/utilspp/singleton/lifetime_default.hpp index ff830e76665c0243b107d6be49b5692dbbd69725..68a4342e76c6d6bcb6979d5d5862d7a613e21771 100644 --- a/daemon/libs/utilspp/singleton/LifetimeDefault.hpp +++ b/daemon/libs/utilspp/singleton/lifetime_default.hpp @@ -24,9 +24,6 @@ #ifndef LIFETIME_DEFAULT_HPP #define LIFETIME_DEFAULT_HPP -#include <stdexcept> -#include <cstdlib> - namespace utilspp { template< typename T > @@ -38,6 +35,6 @@ namespace utilspp }; } -#include "LifetimeDefault.inl" +#include "lifetime_default.inl" #endif diff --git a/daemon/libs/utilspp/singleton/LifetimeDefault.inl b/daemon/libs/utilspp/singleton/lifetime_default.inl similarity index 87% rename from daemon/libs/utilspp/singleton/LifetimeDefault.inl rename to daemon/libs/utilspp/singleton/lifetime_default.inl index a8e63f9fc43ede97e653513d336327ca93e242a7..8ff996e1db15d89bb9e4d3b7ac639bec5406af7b 100644 --- a/daemon/libs/utilspp/singleton/LifetimeDefault.inl +++ b/daemon/libs/utilspp/singleton/lifetime_default.inl @@ -21,8 +21,11 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#ifndef LIFETIME_DEFAULT_INL -#define LIFETIME_DEFAULT_INL +#ifndef __LIFETIME_DEFAULT_INL__ +#define __LIFETIME_DEFAULT_INL__ + +#include <cstdlib> +#include <stdexcept> template< typename T > void @@ -35,8 +38,7 @@ template< typename T > void utilspp::LifetimeDefault< T >::onDeadReference() { - throw std::logic_error( "Dead reference detected" ); + throw std::logic_error("Dead reference detected"); } - -#endif +#endif // __LIFETIME_DEFAULT_INL__ diff --git a/daemon/libs/utilspp/singleton/SingletonHolder.hpp b/daemon/libs/utilspp/singleton/singleton_holder.hpp similarity index 90% rename from daemon/libs/utilspp/singleton/SingletonHolder.hpp rename to daemon/libs/utilspp/singleton/singleton_holder.hpp index da62bc08385cd597d13a22d5f0561014c2d181df..da4118f3551173b432c75e1c6c6ba328f6bd88a4 100644 --- a/daemon/libs/utilspp/singleton/SingletonHolder.hpp +++ b/daemon/libs/utilspp/singleton/singleton_holder.hpp @@ -21,14 +21,12 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#ifndef SINGLETON_HOLDER_HPP -#define SINGLETON_HOLDER_HPP +#ifndef __SINGLETON_HOLDER_HPP__ +#define __SINGLETON_HOLDER_HPP__ -#include <cassert> - -#include "CreationUsingNew.hpp" -#include "LifetimeDefault.hpp" -#include "../ThreadingSingle.hpp" +#include "creation_using_new.hpp" +#include "lifetime_default.hpp" +#include "../threading_single.hpp" namespace utilspp { @@ -60,6 +58,6 @@ namespace utilspp } -#include "SingletonHolder.inl" +#include "singleton_holder.inl" #endif diff --git a/daemon/libs/utilspp/singleton/SingletonHolder.inl b/daemon/libs/utilspp/singleton/singleton_holder.inl similarity index 96% rename from daemon/libs/utilspp/singleton/SingletonHolder.inl rename to daemon/libs/utilspp/singleton/singleton_holder.inl index 36e31e3651c3a50aadb45bd2085105ee8404e6ba..d1a9e4f12bda144f1d218749fd7f9e0fb83032ce 100644 --- a/daemon/libs/utilspp/singleton/SingletonHolder.inl +++ b/daemon/libs/utilspp/singleton/singleton_holder.inl @@ -21,9 +21,10 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#ifndef SINGLETON_HOLDER_INL -#define SINGLETON_HOLDER_INL +#ifndef __SINGLETON_HOLDER_INL__ +#define __SINGLETON_HOLDER_INL__ +#include <cassert> template < class T, @@ -123,4 +124,4 @@ template < class > class M > bool utilspp::SingletonHolder< T, C, L, M >::mDestroyed; -#endif +#endif // __SINGLETON_HOLDER_INL__ diff --git a/daemon/libs/utilspp/ThreadingSingle.hpp b/daemon/libs/utilspp/threading_single.hpp similarity index 90% rename from daemon/libs/utilspp/ThreadingSingle.hpp rename to daemon/libs/utilspp/threading_single.hpp index 93e6432b2d1690b4310d72d6c0c5483a1a6ce36f..69dc04fbc7c936f9d8a01da684f53f27424af35d 100644 --- a/daemon/libs/utilspp/ThreadingSingle.hpp +++ b/daemon/libs/utilspp/threading_single.hpp @@ -21,10 +21,10 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#ifndef SINGLE_THREADED_HPP -#define SINGLE_THREADED_HPP +#ifndef __THREADING_SINGLE_HPP__ +#define __THREADING_SINGLE_HPP__ -#include "NullType.hpp" +#include "null_type.hpp" namespace utilspp { @@ -47,6 +47,6 @@ namespace utilspp }; } -#include "ThreadingSingle.inl" +#include "threading_single.inl" -#endif +#endif // __THREADING_SINGLE_HPP__ diff --git a/daemon/libs/utilspp/ThreadingSingle.inl b/daemon/libs/utilspp/threading_single.inl similarity index 94% rename from daemon/libs/utilspp/ThreadingSingle.inl rename to daemon/libs/utilspp/threading_single.inl index 633401fe4844c411e2095706380ca73691e1fce2..5285bf3af11b7907905aba9c414ea3478bbf859c 100644 --- a/daemon/libs/utilspp/ThreadingSingle.inl +++ b/daemon/libs/utilspp/threading_single.inl @@ -21,8 +21,8 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#ifndef SINGLE_THREADED_INL -#define SINGLE_THREADED_INL +#ifndef __THREADING_SINGLE_INL__ +#define __THREADING_SINGLE_INL__ template< typename T > inline @@ -47,4 +47,4 @@ void utilspp::ThreadingSingle< T >::mutex::unlock() {} -#endif +#endif // __THREADING_SINGLE_INL__ diff --git a/daemon/src/Makefile.am b/daemon/src/Makefile.am index 91e1c98e4c25350b3e19800e66efbae0da793195..8795e0063b0dc618c1684842d27c3f1faacac72a 100644 --- a/daemon/src/Makefile.am +++ b/daemon/src/Makefile.am @@ -5,7 +5,7 @@ libexec_PROGRAMS = sflphoned # all: indent -SUBDIRS = dbus audio config plug-in hooks history sip iax im +SUBDIRS = dbus audio config hooks history sip iax im sflphoned_SOURCES = main.cpp @@ -35,7 +35,7 @@ noinst_LTLIBRARIES = libsflphone.la noinst_HEADERS = \ global.h \ - Codec.h \ + codec.h \ conference.h \ voiplink.h \ preferences.h \ @@ -47,7 +47,8 @@ noinst_HEADERS = \ call.h \ logger.h \ numbercleaner.h \ - fileutils.h + fileutils.h \ + noncopyable.h libsflphone_la_LIBADD = \ $(top_builddir)/libs/utilspp/libutilspp.la \ @@ -58,7 +59,6 @@ libsflphone_la_LIBADD = \ ./audio/libaudio.la \ ./dbus/libdbus.la \ ./config/libconfig.la \ - ./plug-in/libplugin.la \ ./hooks/libhooks.la \ ./history/libhistory.la diff --git a/daemon/src/account.cpp b/daemon/src/account.cpp index a2c867d549993763146e01a0acb55e7365badc96..5501e3aa9423fb796202ab8670c909abefef8eb7 100644 --- a/daemon/src/account.cpp +++ b/daemon/src/account.cpp @@ -33,18 +33,22 @@ #include "account.h" #include "manager.h" -Account::Account (const std::string& accountID, const std::string &type) : - accountID_ (accountID) - , link_ (NULL) - , enabled_ (true) - , type_ (type) - , registrationState_ (Unregistered) - , codecOrder_ () - , codecStr_ ("") - , ringtonePath_ ("/usr/share/sflphone/ringtones/konga.ul") - , ringtoneEnabled_ (true) - , displayName_ ("") - , userAgent_ ("SFLphone") +Account::Account(const std::string& accountID, const std::string &type) : + accountID_(accountID) + , username_() + , hostname_() + , alias_() + , link_(NULL) + , enabled_(true) + , type_(type) + , registrationState_(Unregistered) + , codecOrder_() + , codecStr_() + , ringtonePath_("/usr/share/sflphone/ringtones/konga.ul") + , ringtoneEnabled_(true) + , displayName_("") + , userAgent_("SFLphone") + , mailBox_() { // Initialize the codec order, used when creating a new account loadDefaultCodecs(); @@ -54,7 +58,7 @@ Account::~Account() { } -void Account::setRegistrationState (const RegistrationState &state) +void Account::setRegistrationState(const RegistrationState &state) { if (state != registrationState_) { registrationState_ = state; @@ -71,20 +75,20 @@ void Account::loadDefaultCodecs() // Initialize codec std::vector <std::string> codecList; - codecList.push_back ("0"); - codecList.push_back ("3"); - codecList.push_back ("8"); - codecList.push_back ("9"); - codecList.push_back ("110"); - codecList.push_back ("111"); - codecList.push_back ("112"); - - setActiveCodecs (codecList); + codecList.push_back("0"); + codecList.push_back("3"); + codecList.push_back("8"); + codecList.push_back("9"); + codecList.push_back("110"); + codecList.push_back("111"); + codecList.push_back("112"); + + setActiveCodecs(codecList); } -void Account::setActiveCodecs (const std::vector <std::string> &list) +void Account::setActiveCodecs(const std::vector <std::string> &list) { // first clear the previously stored codecs codecOrder_.clear(); @@ -93,12 +97,12 @@ void Account::setActiveCodecs (const std::vector <std::string> &list) // we used the CodecOrder vector to save the order. for (std::vector<std::string>::const_iterator iter = list.begin(); iter != list.end(); ++iter) { - int payload = std::atoi (iter->c_str()); - codecOrder_.push_back ( (int) payload); + int payload = std::atoi(iter->c_str()); + codecOrder_.push_back((int) payload); } // update the codec string according to new codec selection - codecStr_ = ManagerImpl::serialize (list); + codecStr_ = ManagerImpl::serialize(list); } std::string Account::mapStateNumberToString(RegistrationState state) diff --git a/daemon/src/account.h b/daemon/src/account.h index b39b927521b7ef1e6955f2ed424e1e011d5572ae..76007b95f062ea114c0cc11bbd24d6cc99affc41 100644 --- a/daemon/src/account.h +++ b/daemon/src/account.h @@ -36,6 +36,7 @@ #include <vector> #include "global.h" +#include "noncopyable.h" #include "config/config.h" #include "config/serializable.h" @@ -143,12 +144,11 @@ static const char * const ringtonePathKey = "ringtonePath"; static const char * const ringtoneEnabledKey = "ringtoneEnabled"; static const char * const displayNameKey = "displayName"; -class Account : public Serializable -{ +class Account : public Serializable { public: - Account (const std::string& accountID, const std::string &type); + Account(const std::string& accountID, const std::string &type); /** * Virtual destructor @@ -159,15 +159,15 @@ class Account : public Serializable * Method called by the configuration engine to serialize instance's information * into configuration file. */ - virtual void serialize (Conf::YamlEmitter *emitter) = 0; + virtual void serialize(Conf::YamlEmitter *emitter) = 0; /** * Method called by the configuration engine to restore instance internal state * from configuration file. */ - virtual void unserialize (Conf::MappingNode *map) = 0; + virtual void unserialize(Conf::MappingNode *map) = 0; - virtual void setAccountDetails (std::map<std::string, std::string> details) = 0; + virtual void setAccountDetails(std::map<std::string, std::string> details) = 0; virtual std::map<std::string, std::string> getAccountDetails() const = 0; @@ -188,7 +188,7 @@ class Account : public Serializable * Get the voiplink pointer * @return VoIPLink* the pointer or 0 */ - VoIPLink* getVoIPLink() const { + VoIPLink* getVoIPLink() { return link_; } @@ -213,7 +213,7 @@ class Account : public Serializable return enabled_; } - void setEnabled (bool enable) { + void setEnabled(bool enable) { enabled_ = enable; } @@ -221,31 +221,31 @@ class Account : public Serializable * Set the registration state of the specified link * @param state The registration state of underlying VoIPLink */ - void setRegistrationState (const RegistrationState &state); + void setRegistrationState(const RegistrationState &state); /* They should be treated like macro definitions by the C++ compiler */ - std::string getUsername (void) const { + std::string getUsername() const { return username_; } - std::string getHostname (void) const { + std::string getHostname() const { return hostname_; } - void setHostname (const std::string &hostname) { + void setHostname(const std::string &hostname) { hostname_ = hostname; } - std::string getAlias (void) const { + std::string getAlias() const { return alias_; } - void setAlias (const std::string &alias) { + void setAlias(const std::string &alias) { alias_ = alias; } - std::string getType (void) const { + std::string getType() const { return type_; } - void setType (const std::string &type) { + void setType(const std::string &type) { type_ = type; } @@ -253,7 +253,7 @@ class Account : public Serializable * Accessor to data structures * @return CodecOrder& The list that reflects the user's choice */ - const CodecOrder& getActiveCodecs (void) const { + const CodecOrder& getActiveCodecs() const { return codecOrder_; } @@ -261,52 +261,48 @@ class Account : public Serializable * Update both the codec order structure and the codec string used for * SDP offer and configuration respectively */ - void setActiveCodecs (const std::vector <std::string>& list); + void setActiveCodecs(const std::vector <std::string>& list); - std::string getRingtonePath (void) const { + std::string getRingtonePath() const { return ringtonePath_; } - void setRingtonePath (const std::string &path) { + void setRingtonePath(const std::string &path) { ringtonePath_ = path; } - bool getRingtoneEnabled (void) const { + bool getRingtoneEnabled() const { return ringtoneEnabled_; } - void setRingtoneEnabled (bool enable) { + void setRingtoneEnabled(bool enable) { ringtoneEnabled_ = enable; } - std::string getDisplayName (void) const { + std::string getDisplayName() const { return displayName_; } - void setDisplayName (const std::string &name) { + void setDisplayName(const std::string &name) { displayName_ = name; } - std::string getMailBox (void) const { + std::string getMailBox() const { return mailBox_; } - void setMailBox (const std::string &mb) { + void setMailBox(const std::string &mb) { mailBox_ = mb; } private: - // copy constructor - Account (const Account& rh); - - // assignment operator - Account& operator= (const Account& rh); + NON_COPYABLE(Account); /** * Helper function used to load the default codec order from the codec factory * setActiveCodecs is called to sync both codecOrder_ and codecStr_ */ - void loadDefaultCodecs (void); + void loadDefaultCodecs(); protected: - static std::string mapStateNumberToString (RegistrationState state); + static std::string mapStateNumberToString(RegistrationState state); /** * Account ID are assign in constructor and shall not changed diff --git a/daemon/src/audio/alsa/alsalayer.cpp b/daemon/src/audio/alsa/alsalayer.cpp index 5363ba338f53e30c6933e13dd90068aa1dedb8c9..d903bb5cdb26ec3d2fcc7a403a22bc26ede9ee99 100644 --- a/daemon/src/audio/alsa/alsalayer.cpp +++ b/daemon/src/audio/alsa/alsalayer.cpp @@ -34,67 +34,65 @@ #include "eventthread.h" #include "audio/samplerateconverter.h" #include "managerimpl.h" +#include "noncopyable.h" #include "dbus/configurationmanager.h" -class AlsaThread : public ost::Thread -{ +class AlsaThread : public ost::Thread { public: - AlsaThread (AlsaLayer *alsa); + AlsaThread(AlsaLayer *alsa); - ~AlsaThread () { + ~AlsaThread() { terminate(); } - virtual void run (void); + virtual void run(); private: - AlsaThread (const AlsaThread& at); - AlsaThread& operator= (const AlsaThread& at); - + NON_COPYABLE(AlsaThread); AlsaLayer* alsa_; }; -AlsaThread::AlsaThread (AlsaLayer *alsa) +AlsaThread::AlsaThread(AlsaLayer *alsa) : Thread(), alsa_(alsa) { - setCancel (cancelDeferred); + setCancel(cancelDeferred); } /** * Reimplementation of run() */ -void AlsaThread::run (void) +void AlsaThread::run() { while (!testCancel()) { alsa_->audioCallback(); - Thread::sleep (20); + Thread::sleep(20); } } // Constructor -AlsaLayer::AlsaLayer () - : indexIn_ (audioPref.getCardin()) - , indexOut_ (audioPref.getCardout()) - , indexRing_ (audioPref.getCardring()) - , playbackHandle_ (NULL) - , ringtoneHandle_ (NULL) - , captureHandle_ (NULL) - , audioPlugin_ (audioPref.getPlugin()) - , IDSoundCards_ () - , is_playback_prepared_ (false) - , is_capture_prepared_ (false) - , is_playback_running_ (false) - , is_capture_running_ (false) - , is_playback_open_ (false) - , is_capture_open_ (false) - , audioThread_ (NULL) +AlsaLayer::AlsaLayer() + : indexIn_(audioPref.getCardin()) + , indexOut_(audioPref.getCardout()) + , indexRing_(audioPref.getCardring()) + , playbackHandle_(NULL) + , ringtoneHandle_(NULL) + , captureHandle_(NULL) + , audioPlugin_(audioPref.getPlugin()) + , IDSoundCards_() + , is_playback_prepared_(false) + , is_capture_prepared_(false) + , is_playback_running_(false) + , is_capture_running_(false) + , is_playback_open_(false) + , is_capture_open_(false) + , audioThread_(NULL) { } // Destructor -AlsaLayer::~AlsaLayer (void) +AlsaLayer::~AlsaLayer() { - delete audioThread_; + delete audioThread_; /* Then close the audio devices */ closeCaptureStream(); @@ -106,6 +104,7 @@ bool AlsaLayer::openDevice(snd_pcm_t **pcm, const std::string &dev, snd_pcm_stre { static const int MAX_RETRIES = 100; int err = snd_pcm_open(pcm, dev.c_str(), stream, 0); + // Retry if busy, since dmix plugin may not have released the device yet for (int tries = 0; tries < MAX_RETRIES and err == -EBUSY; ++tries) { usleep(10000); @@ -113,23 +112,23 @@ bool AlsaLayer::openDevice(snd_pcm_t **pcm, const std::string &dev, snd_pcm_stre } if (err < 0) { - _error("Alsa: couldn't open device %s : %s", dev.c_str(), - snd_strerror(err)); + ERROR("Alsa: couldn't open device %s : %s", dev.c_str(), + snd_strerror(err)); return false; } - if (!alsa_set_params(*pcm)) { - snd_pcm_close(*pcm); - return false; - } + if (!alsa_set_params(*pcm)) { + snd_pcm_close(*pcm); + return false; + } - return true; + return true; } void -AlsaLayer::startStream (void) +AlsaLayer::startStream() { - dcblocker_.reset(); + dcblocker_.reset(); if (is_playback_running_ and is_capture_running_) return; @@ -139,55 +138,57 @@ AlsaLayer::startStream (void) std::string pcmc; if (audioPlugin_ == PCM_DMIX_DSNOOP) { - pcmp = buildDeviceTopo (PCM_DMIX, indexOut_); - pcmr = buildDeviceTopo (PCM_DMIX, indexRing_); - pcmc = buildDeviceTopo (PCM_DSNOOP, indexIn_); + pcmp = buildDeviceTopo(PCM_DMIX, indexOut_); + pcmr = buildDeviceTopo(PCM_DMIX, indexRing_); + pcmc = buildDeviceTopo(PCM_DSNOOP, indexIn_); } else { - pcmp = buildDeviceTopo (audioPlugin_, indexOut_); - pcmr = buildDeviceTopo (audioPlugin_, indexRing_); - pcmc = buildDeviceTopo (audioPlugin_, indexIn_); + pcmp = buildDeviceTopo(audioPlugin_, indexOut_); + pcmr = buildDeviceTopo(audioPlugin_, indexRing_); + pcmc = buildDeviceTopo(audioPlugin_, indexIn_); } if (not is_capture_open_) { - is_capture_open_ = openDevice(&captureHandle_, pcmc, SND_PCM_STREAM_CAPTURE); + is_capture_open_ = openDevice(&captureHandle_, pcmc, SND_PCM_STREAM_CAPTURE); + if (not is_capture_open_) Manager::instance().getDbusManager()->getConfigurationManager()->errorAlert(ALSA_CAPTURE_DEVICE); } if (not is_playback_open_) { - is_playback_open_ = openDevice(&playbackHandle_, pcmp, SND_PCM_STREAM_PLAYBACK); - if (not is_playback_open_) + is_playback_open_ = openDevice(&playbackHandle_, pcmp, SND_PCM_STREAM_PLAYBACK); + + if (not is_playback_open_) Manager::instance().getDbusManager()->getConfigurationManager()->errorAlert(ALSA_PLAYBACK_DEVICE); - if (getIndexOut() != getIndexRing()) - if (!openDevice(&ringtoneHandle_, pcmr, SND_PCM_STREAM_PLAYBACK)) - Manager::instance().getDbusManager()->getConfigurationManager()->errorAlert(ALSA_PLAYBACK_DEVICE); + if (getIndexOut() != getIndexRing()) + if (!openDevice(&ringtoneHandle_, pcmr, SND_PCM_STREAM_PLAYBACK)) + Manager::instance().getDbusManager()->getConfigurationManager()->errorAlert(ALSA_PLAYBACK_DEVICE); } - prepareCaptureStream (); - preparePlaybackStream (); + prepareCaptureStream(); + preparePlaybackStream(); - startCaptureStream (); - startPlaybackStream (); + startCaptureStream(); + startPlaybackStream(); flushMain(); flushUrgent(); if (audioThread_ == NULL) { - audioThread_ = new AlsaThread (this); - audioThread_->start(); + audioThread_ = new AlsaThread(this); + audioThread_->start(); } isStarted_ = true; } void -AlsaLayer::stopStream (void) +AlsaLayer::stopStream() { isStarted_ = false; - delete audioThread_; - audioThread_ = NULL; + delete audioThread_; + audioThread_ = NULL; closeCaptureStream(); closePlaybackStream(); @@ -214,43 +215,43 @@ AlsaLayer::stopStream (void) * return the function return value */ #define ALSA_CALL(call, error) ({ \ - int err = call; \ - if (err < 0) \ - _error("ALSA: "error": %s", snd_strerror(err)); \ - err; \ + int err_code = call; \ + if (err_code < 0) \ + ERROR("ALSA: "error": %s", snd_strerror(err_code)); \ + err_code; \ }) -void AlsaLayer::stopCaptureStream (void) +void AlsaLayer::stopCaptureStream() { - if (captureHandle_ && ALSA_CALL(snd_pcm_drop (captureHandle_), "couldn't stop capture") >= 0) { - is_capture_running_ = false; - is_capture_prepared_ = false; + if (captureHandle_ && ALSA_CALL(snd_pcm_drop(captureHandle_), "couldn't stop capture") >= 0) { + is_capture_running_ = false; + is_capture_prepared_ = false; } } -void AlsaLayer::closeCaptureStream (void) +void AlsaLayer::closeCaptureStream() { if (is_capture_prepared_ and is_capture_running_) - stopCaptureStream (); + stopCaptureStream(); - if (is_capture_open_ && ALSA_CALL(snd_pcm_close (captureHandle_), "Couldn't close capture") >= 0) - is_capture_open_ = false; + if (is_capture_open_ && ALSA_CALL(snd_pcm_close(captureHandle_), "Couldn't close capture") >= 0) + is_capture_open_ = false; } -void AlsaLayer::startCaptureStream (void) +void AlsaLayer::startCaptureStream() { if (captureHandle_ and not is_capture_running_) - if (ALSA_CALL(snd_pcm_start (captureHandle_), "Couldn't start capture") >= 0) + if (ALSA_CALL(snd_pcm_start(captureHandle_), "Couldn't start capture") >= 0) is_capture_running_ = true; } -void AlsaLayer::stopPlaybackStream (void) +void AlsaLayer::stopPlaybackStream() { if (ringtoneHandle_ and is_playback_running_) - ALSA_CALL(snd_pcm_drop(ringtoneHandle_), "Couldn't stop ringtone"); + ALSA_CALL(snd_pcm_drop(ringtoneHandle_), "Couldn't stop ringtone"); if (playbackHandle_ and is_playback_running_) { - if (ALSA_CALL(snd_pcm_drop(playbackHandle_), "Couldn't stop playback") >= 0) { + if (ALSA_CALL(snd_pcm_drop(playbackHandle_), "Couldn't stop playback") >= 0) { is_playback_running_ = false; is_playback_prepared_ = false; } @@ -258,14 +259,14 @@ void AlsaLayer::stopPlaybackStream (void) } -void AlsaLayer::closePlaybackStream (void) +void AlsaLayer::closePlaybackStream() { if (is_playback_prepared_ and is_playback_running_) stopPlaybackStream(); if (is_playback_open_) { if (ringtoneHandle_) - ALSA_CALL(snd_pcm_close(ringtoneHandle_), "Couldn't stop ringtone"); + ALSA_CALL(snd_pcm_close(ringtoneHandle_), "Couldn't stop ringtone"); if (ALSA_CALL(snd_pcm_close(playbackHandle_), "Coulnd't close playback") >= 0) is_playback_open_ = false; @@ -273,28 +274,28 @@ void AlsaLayer::closePlaybackStream (void) } -void AlsaLayer::startPlaybackStream (void) +void AlsaLayer::startPlaybackStream() { if (playbackHandle_ and not is_playback_running_) - if (ALSA_CALL(snd_pcm_start(playbackHandle_), "Couldn't start playback") >= 0) + if (ALSA_CALL(snd_pcm_start(playbackHandle_), "Couldn't start playback") >= 0) is_playback_running_ = true; } -void AlsaLayer::prepareCaptureStream (void) +void AlsaLayer::prepareCaptureStream() { if (is_capture_open_ and not is_capture_prepared_) - if (ALSA_CALL(snd_pcm_prepare(captureHandle_), "Couldn't prepare capture") >= 0) + if (ALSA_CALL(snd_pcm_prepare(captureHandle_), "Couldn't prepare capture") >= 0) is_capture_prepared_ = true; } -void AlsaLayer::preparePlaybackStream (void) +void AlsaLayer::preparePlaybackStream() { if (is_playback_open_ and not is_playback_prepared_) - if (ALSA_CALL(snd_pcm_prepare(playbackHandle_), "Couldn't prepare playback") >= 0) + if (ALSA_CALL(snd_pcm_prepare(playbackHandle_), "Couldn't prepare playback") >= 0) is_playback_prepared_ = true; } -bool AlsaLayer::alsa_set_params (snd_pcm_t *pcm_handle) +bool AlsaLayer::alsa_set_params(snd_pcm_t *pcm_handle) { #define TRY(call, error) do { \ if (ALSA_CALL(call, error) < 0) \ @@ -308,27 +309,27 @@ bool AlsaLayer::alsa_set_params (snd_pcm_t *pcm_handle) unsigned int periods = 4; #define HW pcm_handle, hwparams /* hardware parameters */ - TRY(snd_pcm_hw_params_any (HW), "hwparams init"); - TRY(snd_pcm_hw_params_set_access (HW, SND_PCM_ACCESS_RW_INTERLEAVED), "access type"); - TRY(snd_pcm_hw_params_set_format (HW, SND_PCM_FORMAT_S16_LE), "sample format"); - TRY(snd_pcm_hw_params_set_rate_near (HW, &audioSampleRate_, NULL), "sample rate"); - TRY(snd_pcm_hw_params_set_channels (HW, 1), "channel count"); - TRY(snd_pcm_hw_params_set_period_size_near (HW, &periodSize, NULL), "period time"); - TRY(snd_pcm_hw_params_set_periods_near (HW, &periods, NULL), "periods number"); - TRY(snd_pcm_hw_params (HW), "hwparams"); + TRY(snd_pcm_hw_params_any(HW), "hwparams init"); + TRY(snd_pcm_hw_params_set_access(HW, SND_PCM_ACCESS_RW_INTERLEAVED), "access type"); + TRY(snd_pcm_hw_params_set_format(HW, SND_PCM_FORMAT_S16_LE), "sample format"); + TRY(snd_pcm_hw_params_set_rate_near(HW, &audioSampleRate_, NULL), "sample rate"); + TRY(snd_pcm_hw_params_set_channels(HW, 1), "channel count"); + TRY(snd_pcm_hw_params_set_period_size_near(HW, &periodSize, NULL), "period time"); + TRY(snd_pcm_hw_params_set_periods_near(HW, &periods, NULL), "periods number"); + TRY(snd_pcm_hw_params(HW), "hwparams"); #undef HW - _debug ("ALSA: %s using sampling rate %dHz", - (snd_pcm_stream(pcm_handle) == SND_PCM_STREAM_PLAYBACK) ? "playback" : "capture", - audioSampleRate_); + DEBUG("ALSA: %s using sampling rate %dHz", + (snd_pcm_stream(pcm_handle) == SND_PCM_STREAM_PLAYBACK) ? "playback" : "capture", + audioSampleRate_); snd_pcm_sw_params_t *swparams = NULL; snd_pcm_sw_params_alloca(&swparams); #define SW pcm_handle, swparams /* software parameters */ - snd_pcm_sw_params_current (SW); - TRY(snd_pcm_sw_params_set_start_threshold (SW, periodSize * 2), "start threshold"); - TRY(snd_pcm_sw_params (SW), "sw parameters"); + snd_pcm_sw_params_current(SW); + TRY(snd_pcm_sw_params_set_start_threshold(SW, periodSize * 2), "start threshold"); + TRY(snd_pcm_sw_params(SW), "sw parameters"); #undef SW return true; @@ -338,86 +339,86 @@ bool AlsaLayer::alsa_set_params (snd_pcm_t *pcm_handle) //TODO first frame causes broken pipe (underrun) because not enough data are send --> make the handle wait to be ready void -AlsaLayer::write (void* buffer, int length, snd_pcm_t * handle) +AlsaLayer::write(void* buffer, int length, snd_pcm_t * handle) { - snd_pcm_uframes_t frames = snd_pcm_bytes_to_frames (handle, length); + snd_pcm_uframes_t frames = snd_pcm_bytes_to_frames(handle, length); + + int err = snd_pcm_writei(handle, buffer , frames); - int err = snd_pcm_writei (handle, buffer , frames); if (err >= 0) - return; - - switch (err) { - - case -EPIPE: - case -ESTRPIPE: - case -EIO: - { - snd_pcm_status_t* status; - snd_pcm_status_alloca (&status); - - if (ALSA_CALL(snd_pcm_status (handle, status), "Cannot get playback handle status") >= 0) - if (snd_pcm_status_get_state (status) == SND_PCM_STATE_XRUN) { - stopPlaybackStream(); - preparePlaybackStream(); - startPlaybackStream(); - } - - ALSA_CALL(snd_pcm_writei (handle, buffer , frames), "XRUN handling failed"); - break; - } - - default: - _error("ALSA: unknown write error, dropping frames: %s", snd_strerror (err)); - stopPlaybackStream (); - break; - } + return; + + switch (err) { + + case -EPIPE: + case -ESTRPIPE: + case -EIO: { + snd_pcm_status_t* status; + snd_pcm_status_alloca(&status); + + if (ALSA_CALL(snd_pcm_status(handle, status), "Cannot get playback handle status") >= 0) + if (snd_pcm_status_get_state(status) == SND_PCM_STATE_XRUN) { + stopPlaybackStream(); + preparePlaybackStream(); + startPlaybackStream(); + } + + ALSA_CALL(snd_pcm_writei(handle, buffer , frames), "XRUN handling failed"); + break; + } + + default: + ERROR("ALSA: unknown write error, dropping frames: %s", snd_strerror(err)); + stopPlaybackStream(); + break; + } } int -AlsaLayer::read (void* buffer, int toCopy) +AlsaLayer::read(void* buffer, int toCopy) { - if (snd_pcm_state (captureHandle_) == SND_PCM_STATE_XRUN) { - prepareCaptureStream (); - startCaptureStream (); + if (snd_pcm_state(captureHandle_) == SND_PCM_STATE_XRUN) { + prepareCaptureStream(); + startCaptureStream(); } - snd_pcm_uframes_t frames = snd_pcm_bytes_to_frames (captureHandle_, toCopy); + snd_pcm_uframes_t frames = snd_pcm_bytes_to_frames(captureHandle_, toCopy); + + int err = snd_pcm_readi(captureHandle_, buffer, frames); - int err = snd_pcm_readi (captureHandle_, buffer, frames); if (err >= 0) - return snd_pcm_frames_to_bytes(captureHandle_, frames); - - switch (err) { - case -EPIPE: - case -ESTRPIPE: - case -EIO: - { - snd_pcm_status_t* status; - snd_pcm_status_alloca (&status); - - if (ALSA_CALL(snd_pcm_status(captureHandle_, status), "Get status failed") >= 0) - if (snd_pcm_status_get_state (status) == SND_PCM_STATE_XRUN) { - stopCaptureStream (); - prepareCaptureStream (); - startCaptureStream (); - } - - _error("ALSA: XRUN capture ignored (%s)", snd_strerror (err)); - break; - } - - case EPERM: - _error("ALSA: Can't capture, EPERM (%s)", snd_strerror (err)); - prepareCaptureStream (); - startCaptureStream (); - break; - } - - return 0; + return snd_pcm_frames_to_bytes(captureHandle_, frames); + + switch (err) { + case -EPIPE: + case -ESTRPIPE: + case -EIO: { + snd_pcm_status_t* status; + snd_pcm_status_alloca(&status); + + if (ALSA_CALL(snd_pcm_status(captureHandle_, status), "Get status failed") >= 0) + if (snd_pcm_status_get_state(status) == SND_PCM_STATE_XRUN) { + stopCaptureStream(); + prepareCaptureStream(); + startCaptureStream(); + } + + ERROR("ALSA: XRUN capture ignored (%s)", snd_strerror(err)); + break; + } + + case EPERM: + ERROR("ALSA: Can't capture, EPERM (%s)", snd_strerror(err)); + prepareCaptureStream(); + startCaptureStream(); + break; + } + + return 0; } std::string -AlsaLayer::buildDeviceTopo (const std::string &plugin, int card) +AlsaLayer::buildDeviceTopo(const std::string &plugin, int card) { std::stringstream ss; std::string pcm(plugin); @@ -431,18 +432,19 @@ AlsaLayer::buildDeviceTopo (const std::string &plugin, int card) } std::vector<std::string> -AlsaLayer::getSoundCardsInfo (int stream) +AlsaLayer::getSoundCardsInfo(int stream) { snd_ctl_t* handle; snd_ctl_card_info_t *info; snd_pcm_info_t* pcminfo; - snd_ctl_card_info_alloca (&info); - snd_pcm_info_alloca (&pcminfo); + snd_ctl_card_info_alloca(&info); + snd_pcm_info_alloca(&pcminfo); int numCard = -1 ; std::vector<std::string> cards_id; - if (snd_card_next (&numCard) < 0 || numCard < 0) + + if (snd_card_next(&numCard) < 0 || numCard < 0) return cards_id; do { @@ -450,30 +452,30 @@ AlsaLayer::getSoundCardsInfo (int stream) ss << numCard; std::string name = "hw:" + ss.str(); - if (snd_ctl_open (&handle, name.c_str(), 0) == 0) { - if (snd_ctl_card_info (handle, info) == 0) { - snd_pcm_info_set_device (pcminfo , 0); - snd_pcm_info_set_stream (pcminfo, (stream == SFL_PCM_CAPTURE) ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK); + if (snd_ctl_open(&handle, name.c_str(), 0) == 0) { + if (snd_ctl_card_info(handle, info) == 0) { + snd_pcm_info_set_device(pcminfo , 0); + snd_pcm_info_set_stream(pcminfo, (stream == SFL_PCM_CAPTURE) ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK); - if (snd_ctl_pcm_info (handle ,pcminfo) < 0) - _debug (" Cannot get info"); + if (snd_ctl_pcm_info(handle ,pcminfo) < 0) + DEBUG(" Cannot get info"); else { - _debug ("card %i : %s [%s]", - numCard, - snd_ctl_card_info_get_id (info), - snd_ctl_card_info_get_name (info)); - std::string description = snd_ctl_card_info_get_name (info); - description.append (" - "); - description.append (snd_pcm_info_get_name (pcminfo)); - cards_id.push_back (description); + DEBUG("card %i : %s [%s]", + numCard, + snd_ctl_card_info_get_id(info), + snd_ctl_card_info_get_name(info)); + std::string description = snd_ctl_card_info_get_name(info); + description.append(" - "); + description.append(snd_pcm_info_get_name(pcminfo)); + cards_id.push_back(description); // The number of the sound card is associated with a string description IDSoundCards_.push_back(HwIDPair(numCard , description)); } } - snd_ctl_close (handle); + snd_ctl_close(handle); } - } while (snd_card_next (&numCard) >= 0 && numCard >= 0); + } while (snd_card_next(&numCard) >= 0 && numCard >= 0); return cards_id; @@ -492,16 +494,16 @@ AlsaLayer::soundCardIndexExists(int card, int stream) name.append(ss.str()); if (snd_ctl_open(&handle, name.c_str(), 0) != 0) - return false; + return false; snd_pcm_info_set_stream(pcminfo , (stream == SFL_PCM_PLAYBACK) ? SND_PCM_STREAM_PLAYBACK : SND_PCM_STREAM_CAPTURE); - bool ret = snd_ctl_pcm_info(handle , pcminfo) >= 0; - snd_ctl_close(handle); - return ret; + bool ret = snd_ctl_pcm_info(handle , pcminfo) >= 0; + snd_ctl_close(handle); + return ret; } int -AlsaLayer::soundCardGetIndex (const std::string &description) +AlsaLayer::soundCardGetIndex(const std::string &description) { for (std::vector<HwIDPair>::const_iterator iter = IDSoundCards_.begin(); iter != IDSoundCards_.end(); ++iter) if (iter->second == description) @@ -511,54 +513,58 @@ AlsaLayer::soundCardGetIndex (const std::string &description) return 0; } -namespace +namespace { +void adjustVolume(SFLDataFormat *src , int samples, int volumePercentage) { - void adjustVolume (SFLDataFormat *src , int samples, int volumePercentage) - { - if (volumePercentage != 100) - for (int i = 0 ; i < samples; i++) - src[i] = src[i] * volumePercentage * 0.01; - } + if (volumePercentage != 100) + for (int i = 0 ; i < samples; i++) + src[i] = src[i] * volumePercentage * 0.01; +} } -void AlsaLayer::capture(void) +void AlsaLayer::capture() { unsigned int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); bool resample = audioSampleRate_ != mainBufferSampleRate; - int toGetSamples = snd_pcm_avail_update (captureHandle_); + int toGetSamples = snd_pcm_avail_update(captureHandle_); + if (toGetSamples < 0) - _error ("Audio: Mic error: %s", snd_strerror (toGetSamples)); + ERROR("Audio: Mic error: %s", snd_strerror(toGetSamples)); + if (toGetSamples <= 0) return; const int framesPerBufferAlsa = 2048; + if (toGetSamples > framesPerBufferAlsa) - toGetSamples = framesPerBufferAlsa; + toGetSamples = framesPerBufferAlsa; int toGetBytes = toGetSamples * sizeof(SFLDataFormat); - SFLDataFormat* in = (SFLDataFormat*) malloc (toGetBytes); + SFLDataFormat* in = (SFLDataFormat*) malloc(toGetBytes); + if (read(in, toGetBytes) != toGetBytes) { - _error("ALSA MIC : Couldn't read!"); - goto end; + ERROR("ALSA MIC : Couldn't read!"); + goto end; } - adjustVolume (in, toGetSamples, Manager::instance().getSpkrVolume()); + + adjustVolume(in, toGetSamples, Manager::instance().getSpkrVolume()); if (resample) { - int outSamples = toGetSamples * ((double) audioSampleRate_ / mainBufferSampleRate); - int outBytes = outSamples * sizeof (SFLDataFormat); - SFLDataFormat* rsmpl_out = (SFLDataFormat*) malloc (outBytes); - converter_->resample ( (SFLDataFormat*) in, rsmpl_out, mainBufferSampleRate, audioSampleRate_, toGetSamples); + int outSamples = toGetSamples * ((double) audioSampleRate_ / mainBufferSampleRate); + int outBytes = outSamples * sizeof(SFLDataFormat); + SFLDataFormat* rsmpl_out = (SFLDataFormat*) malloc(outBytes); + converter_->resample((SFLDataFormat*) in, rsmpl_out, mainBufferSampleRate, audioSampleRate_, toGetSamples); dcblocker_.process(rsmpl_out, rsmpl_out, outSamples); - Manager::instance().getMainBuffer()->putData (rsmpl_out, outBytes); - free (rsmpl_out); + Manager::instance().getMainBuffer()->putData(rsmpl_out, outBytes); + free(rsmpl_out); } else { dcblocker_.process(in, in, toGetSamples); - Manager::instance().getMainBuffer()->putData (in, toGetBytes); + Manager::instance().getMainBuffer()->putData(in, toGetBytes); } end: - free (in); + free(in); } void AlsaLayer::playback(int maxSamples) @@ -575,50 +581,53 @@ void AlsaLayer::playback(int maxSamples) AudioLoop *tone = Manager::instance().getTelephoneTone(); AudioLoop *file_tone = Manager::instance().getTelephoneFile(); - SFLDataFormat *out = (SFLDataFormat *) malloc (toPut); + SFLDataFormat *out = (SFLDataFormat *) malloc(toPut); - if (tone) - tone->getNext (out, maxSamples, spkrVolume); - else if (file_tone && !ringtoneHandle_) - file_tone->getNext (out, maxSamples, spkrVolume); - else - memset(out, 0, toPut); + if (tone) + tone->getNext(out, maxSamples, spkrVolume); + else if (file_tone && !ringtoneHandle_) + file_tone->getNext(out, maxSamples, spkrVolume); + else + memset(out, 0, toPut); - write (out, toPut, playbackHandle_); - free (out); - return; + write(out, toPut, playbackHandle_); + free(out); + return; } - // play the regular sound samples - - int maxNbBytesToGet = toPut; - // Compute maximal value to get from the ring buffer - double resampleFactor = 1.0; - if (resample) { - resampleFactor = (double) audioSampleRate_ / mainBufferSampleRate; - maxNbBytesToGet = (double) toGet / resampleFactor; - } - - if (toGet > maxNbBytesToGet) - toGet = maxNbBytesToGet; - - SFLDataFormat *out = (SFLDataFormat*) malloc (toGet); - Manager::instance().getMainBuffer()->getData (out, toGet); - adjustVolume(out, toGet / sizeof(SFLDataFormat), spkrVolume); - - if (resample) { - int inSamples = toGet / sizeof(SFLDataFormat); - int outSamples = inSamples * resampleFactor; - SFLDataFormat *rsmpl_out = (SFLDataFormat*) malloc (outSamples * sizeof(SFLDataFormat)); - converter_->resample (out, rsmpl_out, mainBufferSampleRate, audioSampleRate_, inSamples); - write (rsmpl_out, outSamples * sizeof(SFLDataFormat), playbackHandle_); - free (rsmpl_out); - } else { - write (out, toGet, playbackHandle_); - } - free (out); + + // play the regular sound samples + + int maxNbBytesToGet = toPut; + // Compute maximal value to get from the ring buffer + double resampleFactor = 1.0; + + if (resample) { + resampleFactor = (double) audioSampleRate_ / mainBufferSampleRate; + maxNbBytesToGet = (double) toGet / resampleFactor; + } + + if (toGet > maxNbBytesToGet) + toGet = maxNbBytesToGet; + + SFLDataFormat *out = (SFLDataFormat*) malloc(toGet); + Manager::instance().getMainBuffer()->getData(out, toGet); + adjustVolume(out, toGet / sizeof(SFLDataFormat), spkrVolume); + + if (resample) { + int inSamples = toGet / sizeof(SFLDataFormat); + int outSamples = inSamples * resampleFactor; + SFLDataFormat *rsmpl_out = (SFLDataFormat*) malloc(outSamples * sizeof(SFLDataFormat)); + converter_->resample(out, rsmpl_out, mainBufferSampleRate, audioSampleRate_, inSamples); + write(rsmpl_out, outSamples * sizeof(SFLDataFormat), playbackHandle_); + free(rsmpl_out); + } else { + write(out, toGet, playbackHandle_); + } + + free(out); } -void AlsaLayer::audioCallback (void) +void AlsaLayer::audioCallback() { if (!playbackHandle_ or !captureHandle_) return; @@ -627,46 +636,48 @@ void AlsaLayer::audioCallback (void) unsigned short spkrVolume = Manager::instance().getSpkrVolume(); - snd_pcm_wait (playbackHandle_, 20); + snd_pcm_wait(playbackHandle_, 20); - int playbackAvailSmpl = snd_pcm_avail_update (playbackHandle_); - int playbackAvailBytes = playbackAvailSmpl * sizeof (SFLDataFormat); + int playbackAvailSmpl = snd_pcm_avail_update(playbackHandle_); + int playbackAvailBytes = playbackAvailSmpl * sizeof(SFLDataFormat); int toGet = urgentRingBuffer_.AvailForGet(); + if (toGet > 0) { // Urgent data (dtmf, incoming call signal) come first. if (toGet > playbackAvailBytes) - toGet = playbackAvailBytes; - SFLDataFormat *out = (SFLDataFormat*) malloc (toGet); - urgentRingBuffer_.Get (out, toGet); + toGet = playbackAvailBytes; + + SFLDataFormat *out = (SFLDataFormat*) malloc(toGet); + urgentRingBuffer_.Get(out, toGet); adjustVolume(out, toGet / sizeof(SFLDataFormat), spkrVolume); - write (out, toGet, playbackHandle_); - free (out); + write(out, toGet, playbackHandle_); + free(out); // Consume the regular one as well (same amount of bytes) - Manager::instance().getMainBuffer()->discard (toGet); + Manager::instance().getMainBuffer()->discard(toGet); } else { - // regular audio data - playback(playbackAvailSmpl); + // regular audio data + playback(playbackAvailSmpl); } if (ringtoneHandle_) { AudioLoop *file_tone = Manager::instance().getTelephoneFile(); - int ringtoneAvailSmpl = snd_pcm_avail_update (ringtoneHandle_); - int ringtoneAvailBytes = ringtoneAvailSmpl*sizeof (SFLDataFormat); + int ringtoneAvailSmpl = snd_pcm_avail_update(ringtoneHandle_); + int ringtoneAvailBytes = ringtoneAvailSmpl*sizeof(SFLDataFormat); - SFLDataFormat *out = (SFLDataFormat *) malloc (ringtoneAvailBytes); + SFLDataFormat *out = (SFLDataFormat *) malloc(ringtoneAvailBytes); - if (file_tone) - file_tone->getNext (out, ringtoneAvailSmpl, spkrVolume); - else - memset (out, 0, ringtoneAvailBytes); + if (file_tone) + file_tone->getNext(out, ringtoneAvailSmpl, spkrVolume); + else + memset(out, 0, ringtoneAvailBytes); - write(out, ringtoneAvailBytes, ringtoneHandle_); - free(out); + write(out, ringtoneAvailBytes, ringtoneHandle_); + free(out); } // Additionally handle the mic's audio stream if (is_capture_running_) - capture(); + capture(); } diff --git a/daemon/src/audio/alsa/alsalayer.h b/daemon/src/audio/alsa/alsalayer.h index ed2febb2b86e0163b3b0f0c08b776fdcba1a7c92..083e7f2500b348783d1a4912588aac92cfca87dc 100644 --- a/daemon/src/audio/alsa/alsalayer.h +++ b/daemon/src/audio/alsa/alsalayer.h @@ -33,6 +33,7 @@ #define _ALSA_LAYER_H #include "audio/audiolayer.h" +#include "noncopyable.h" #include <alsa/asoundlib.h> class RingBuffer; @@ -47,32 +48,31 @@ class AlsaThread; /** Associate a sound card index to its string description */ typedef std::pair<int , std::string> HwIDPair; -class AlsaLayer : public AudioLayer -{ +class AlsaLayer : public AudioLayer { public: /** * Constructor */ - AlsaLayer (); + AlsaLayer(); /** * Destructor */ - ~AlsaLayer (void); + ~AlsaLayer(); /** * Start the capture stream and prepare the playback stream. * The playback starts accordingly to its threshold * ALSA Library API */ - void startStream (void); + void startStream(); /** * Stop the playback and capture streams. * Drops the pending frames and put the capture and playback handles to PREPARED state * ALSA Library API */ - void stopStream (void); + void stopStream(); /** * Concatenate two strings. Used to build a valid pcm device name. @@ -80,7 +80,7 @@ class AlsaLayer : public AudioLayer * @param card the sound card number * @return std::string the concatenated string */ - std::string buildDeviceTopo (const std::string &plugin, int card); + std::string buildDeviceTopo(const std::string &plugin, int card); /** * Scan the sound card available on the system @@ -90,7 +90,7 @@ class AlsaLayer : public AudioLayer * SFL_PCM_BOTH * @return std::vector<std::string> The vector containing the string description of the card */ - std::vector<std::string> getSoundCardsInfo (int stream); + std::vector<std::string> getSoundCardsInfo(int stream); /** * Check if the given index corresponds to an existing sound card and supports the specified streaming mode @@ -109,12 +109,12 @@ class AlsaLayer : public AudioLayer * @param description The string description * @return int Its index */ - int soundCardGetIndex (const std::string &description); + int soundCardGetIndex(const std::string &description); void playback(int maxSamples); - void capture(void); + void capture(); - void audioCallback (void); + void audioCallback(); /** * Get the index of the audio card for capture @@ -135,10 +135,10 @@ class AlsaLayer : public AudioLayer } /** - * Get the index of the audio card for ringtone (could be differnet from playback) - * @return int The index of the card used for ringtone - * 0 for the first available card on the system, 1 ... - */ + * Get the index of the audio card for ringtone (could be differnet from playback) + * @return int The index of the card used for ringtone + * 0 for the first available card on the system, 1 ... + */ int getIndexRing() const { return indexRing_; } @@ -168,28 +168,23 @@ class AlsaLayer : public AudioLayer */ int indexRing_; - - // Copy Constructor - AlsaLayer (const AlsaLayer& rh); - - // Assignment Operator - AlsaLayer& operator= (const AlsaLayer& rh); + NON_COPYABLE(AlsaLayer); /** * Drop the pending frames and close the capture device * ALSA Library API */ - void closeCaptureStream (void); - void stopCaptureStream (void); - void startCaptureStream (void); - void prepareCaptureStream (void); + void closeCaptureStream(); + void stopCaptureStream(); + void startCaptureStream(); + void prepareCaptureStream(); - void closePlaybackStream (void); - void stopPlaybackStream (void); - void startPlaybackStream (void); - void preparePlaybackStream (void); + void closePlaybackStream(); + void stopPlaybackStream(); + void startPlaybackStream(); + void preparePlaybackStream(); - bool alsa_set_params (snd_pcm_t *pcm_handle); + bool alsa_set_params(snd_pcm_t *pcm_handle); /** * Copy a data buffer in the internal ring buffer @@ -197,7 +192,7 @@ class AlsaLayer : public AudioLayer * @param buffer The data to be copied * @param length The size of the buffer */ - void write (void* buffer, int length, snd_pcm_t *handle); + void write(void* buffer, int length, snd_pcm_t *handle); /** * Read data from the internal ring buffer @@ -206,7 +201,7 @@ class AlsaLayer : public AudioLayer * @param toCopy The number of bytes to get * @return int The number of frames actually read */ - int read (void* buffer, int toCopy); + int read(void* buffer, int toCopy); /** * Handles to manipulate playback stream diff --git a/daemon/src/audio/audiolayer.cpp b/daemon/src/audio/audiolayer.cpp index f568abdd749a68f128c927e6d6b5bf30cf5d5a9b..285f31978bc3864374dca74f8a7940b8b462d717 100644 --- a/daemon/src/audio/audiolayer.cpp +++ b/daemon/src/audio/audiolayer.cpp @@ -34,70 +34,71 @@ #include "audio/dcblocker.h" #include "manager.h" -AudioLayer::AudioLayer () - : isStarted_ (false) - , urgentRingBuffer_ (SIZEBUF, Call::DEFAULT_ID) - , audioSampleRate_(Manager::instance().getMainBuffer()->getInternalSamplingRate()) - , mutex_ () - , audioPref(Manager::instance().audioPreference) - , converter_ (new SamplerateConverter(audioSampleRate_)) - , lastNotificationTime_ (0) +AudioLayer::AudioLayer() + : isStarted_(false) + , urgentRingBuffer_(SIZEBUF, Call::DEFAULT_ID) + , audioSampleRate_(Manager::instance().getMainBuffer()->getInternalSamplingRate()) + , mutex_() + , dcblocker_() + , audioPref(Manager::instance().audioPreference) + , converter_(new SamplerateConverter(audioSampleRate_)) + , lastNotificationTime_(0) { urgentRingBuffer_.createReadPointer(); } -AudioLayer::~AudioLayer () +AudioLayer::~AudioLayer() { - delete converter_; + delete converter_; } -void AudioLayer::flushMain (void) +void AudioLayer::flushMain() { - ost::MutexLock guard (mutex_); + ost::MutexLock guard(mutex_); // should pass call id Manager::instance().getMainBuffer()->flushAllBuffers(); } -void AudioLayer::flushUrgent (void) +void AudioLayer::flushUrgent() { - ost::MutexLock guard (mutex_); + ost::MutexLock guard(mutex_); urgentRingBuffer_.flushAll(); } -void AudioLayer::putUrgent (void* buffer, int toCopy) +void AudioLayer::putUrgent(void* buffer, int toCopy) { - ost::MutexLock guard (mutex_); - urgentRingBuffer_.Put (buffer, toCopy); + ost::MutexLock guard(mutex_); + urgentRingBuffer_.Put(buffer, toCopy); } // Notify (with a beep) an incoming call when there is already a call in progress void AudioLayer::notifyincomingCall() { if (!Manager::instance().incomingCallWaiting()) - return; + return; - time_t now = time(NULL); + time_t now = time(NULL); - // Notify maximum once every 5 seconds - if (difftime(now, lastNotificationTime_) < 5) - return; + // Notify maximum once every 5 seconds + if (difftime(now, lastNotificationTime_) < 5) + return; - lastNotificationTime_ = now; + lastNotificationTime_ = now; - // Enable notification only if more than one call - if (!Manager::instance().hasCurrentCall()) - return; + // Enable notification only if more than one call + if (!Manager::instance().hasCurrentCall()) + return; - Tone tone ("440/160", getSampleRate()); - unsigned int nbSample = tone.getSize(); - SFLDataFormat buf[nbSample]; - tone.getNext (buf, nbSample); + Tone tone("440/160", getSampleRate()); + unsigned int nbSample = tone.getSize(); + SFLDataFormat buf[nbSample]; + tone.getNext(buf, nbSample); - /* Put the data in the urgent ring buffer */ - Manager::instance().audioLayerMutexLock(); - flushUrgent(); - putUrgent (buf, sizeof buf); - Manager::instance().audioLayerMutexUnlock(); + /* Put the data in the urgent ring buffer */ + Manager::instance().audioLayerMutexLock(); + flushUrgent(); + putUrgent(buf, sizeof buf); + Manager::instance().audioLayerMutexUnlock(); } diff --git a/daemon/src/audio/audiolayer.h b/daemon/src/audio/audiolayer.h index a3243ee9b0c79765236b36651502d474bb145f45..cc36e453745a342178cee867df424bfcca88dabb 100644 --- a/daemon/src/audio/audiolayer.h +++ b/daemon/src/audio/audiolayer.h @@ -31,8 +31,8 @@ * as that of the covered work. */ -#ifndef _AUDIO_LAYER_H -#define _AUDIO_LAYER_H +#ifndef __AUDIO_LAYER_H__ +#define __AUDIO_LAYER_H__ #include <cc++/thread.h> // for ost::Mutex #include <sys/time.h> @@ -41,6 +41,7 @@ #include "ringbuffer.h" #include "dcblocker.h" #include "samplerateconverter.h" +#include "noncopyable.h" /** * @file audiolayer.h @@ -50,44 +51,34 @@ class MainBuffer; namespace ost { - class Time; +class Time; } -class AudioLayer -{ +class AudioLayer { private: - //copy constructor - AudioLayer (const AudioLayer& rh); - - // assignment operator - AudioLayer& operator= (const AudioLayer& rh); + NON_COPYABLE(AudioLayer); public: - /** - * Constructor - */ - AudioLayer (); - - /** - * Destructor - */ - virtual ~AudioLayer (void); + AudioLayer(); + virtual ~AudioLayer(); /** * Start the capture stream and prepare the playback stream. * The playback starts accordingly to its threshold * ALSA Library API */ - virtual void startStream (void) = 0; + virtual void startStream() = 0; /** * Stop the playback and capture streams. * Drops the pending frames and put the capture and playback handles to PREPARED state * ALSA Library API */ - virtual void stopStream (void) = 0; + virtual void stopStream() = 0; - bool isStarted(void) const { return isStarted_; } + bool isStarted() const { + return isStarted_; + } /** * Send a chunk of data to the hardware buffer to start the playback @@ -95,11 +86,11 @@ class AudioLayer * @param buffer The buffer containing the data to be played ( ringtones ) * @param toCopy The size of the buffer */ - void putUrgent (void* buffer, int toCopy); + void putUrgent(void* buffer, int toCopy); - void flushMain (void); + void flushMain(); - void flushUrgent (void); + void flushUrgent(); /** @@ -114,14 +105,14 @@ class AudioLayer /** * Get the mutex lock for the entire audio layer */ - ost::Mutex* getMutexLock (void) { + ost::Mutex* getMutexLock() { return &mutex_; } - void notifyincomingCall (void); + void notifyincomingCall(); protected: - + /** * Wether or not the audio layer stream is started */ @@ -142,15 +133,11 @@ class AudioLayer * Lock for the entire audio layer */ ost::Mutex mutex_; - DcBlocker dcblocker_; - AudioPreference &audioPref; - SamplerateConverter *converter_; private: - /** * Time of the last incoming call notification */ diff --git a/daemon/src/audio/audioloop.cpp b/daemon/src/audio/audioloop.cpp index 445060a62a1f07c24fa3b92d61e961fc337832f1..7e1d41d4e1a389a667fde5ca899f7ec50e5924b1 100644 --- a/daemon/src/audio/audioloop.cpp +++ b/daemon/src/audio/audioloop.cpp @@ -37,50 +37,49 @@ #include <cstring> #include <cassert> -AudioLoop::AudioLoop() :_buffer (0), _size (0), _pos (0), _sampleRate (0) +AudioLoop::AudioLoop() : buffer_(0), size_(0), pos_(0), sampleRate_(0) { } AudioLoop::~AudioLoop() { - delete [] _buffer; + delete [] buffer_; } void -AudioLoop::getNext (SFLDataFormat* output, size_t total_samples, short volume) +AudioLoop::getNext(SFLDataFormat* output, size_t total_samples, short volume) { - size_t pos = _pos; + size_t pos = pos_; - assert(_size); - - if(_size == 0) { - _error("AudioLoop: Error: Audio loop size is 0"); - return; + if (size_ == 0) { + ERROR("AudioLoop: Error: Audio loop size is 0"); + return; } while (total_samples) { size_t samples = total_samples; - if (samples > (_size-pos)) { - samples = _size-pos; - } + if (samples > (size_ - pos)) + samples = size_ - pos; + + // short->char conversion + memcpy(output, buffer_ + pos, samples * sizeof(SFLDataFormat)); - memcpy(output, _buffer+pos, samples*sizeof (SFLDataFormat)); // short>char conversion + if (volume != 100) { + double gain = volume * 0.01; - if (volume!=100) { - for (size_t i=0; i<samples; i++) { - *output = (*output * volume) /100; + for (size_t i = 0; i < samples; i++) { + *output *= gain; output++; } - } else { + } else output += samples; // this is the destination... - } - pos = (pos + samples) % _size; + pos = (pos + samples) % size_; total_samples -= samples; } - _pos = pos; + pos_ = pos; } diff --git a/daemon/src/audio/audioloop.h b/daemon/src/audio/audioloop.h index 58e8f83c211561c92e0123d33c5d418d10d6e62c..cc6cc653fbe85e4df52c35e415667f70f497c20f 100644 --- a/daemon/src/audio/audioloop.h +++ b/daemon/src/audio/audioloop.h @@ -33,25 +33,18 @@ #ifndef __AUDIOLOOP_H__ #define __AUDIOLOOP_H__ -#include <string> -#include "global.h" // for int16 declaration +#include "global.h" // for SFLDataFormat +#include "noncopyable.h" /** * @file audioloop.h * @brief Loop on a sound file */ -class AudioLoop -{ +class AudioLoop { public: - /** - * Constructor - */ AudioLoop(); - /** - * Virtual destructor - */ virtual ~AudioLoop(); /** @@ -61,44 +54,39 @@ class AudioLoop * @param nb of int16 to send * @param volume The volume */ - void getNext (SFLDataFormat* output, size_t samples, short volume=100); + void getNext(SFLDataFormat* output, size_t samples, short volume=100); /** * Reset the pointer position */ void reset() { - _pos = 0; + pos_ = 0; } /** * Accessor to the size of the buffer * @return unsigned int The size */ - size_t getSize() { - return _size; + size_t getSize() const { + return size_; } protected: /** The data buffer */ - SFLDataFormat* _buffer; + SFLDataFormat* buffer_; /** Number of samples inside the buffer */ - size_t _size; + size_t size_; /** current position, set to 0, when initialize */ - size_t _pos; + size_t pos_; /** Sample rate */ - unsigned int _sampleRate; + unsigned int sampleRate_; private: - - // Copy Constructor - AudioLoop (const AudioLoop& rh); - - // Assignment Operator - AudioLoop& operator= (const AudioLoop& rh); + NON_COPYABLE(AudioLoop); }; #endif // __AUDIOLOOP_H__ diff --git a/daemon/src/audio/audiorecord.cpp b/daemon/src/audio/audiorecord.cpp index f84c602d27deb18cd6c6f17325beeb1aa9457739..dcfe03fdde815d10fbcf4c94c39ca249cf6460ab 100644 --- a/daemon/src/audio/audiorecord.cpp +++ b/daemon/src/audio/audiorecord.cpp @@ -51,86 +51,68 @@ struct wavhdr { }; -AudioRecord::AudioRecord() : fp (NULL) - , channels_ (1) - , byteCounter_ (0) - , sndSmplRate_ (8000) - , nbSamplesMic_ (0) - , nbSamplesSpk_ (0) - , nbSamplesMax_ (3000) - , recordingEnabled_ (false) - , mixBuffer_ (NULL) - , micBuffer_ (NULL) - , spkBuffer_ (NULL) +AudioRecord::AudioRecord() : fileHandle_(NULL) + , fileType_(FILE_INVALID) + , channels_(1) + , byteCounter_(0) + , sndSmplRate_(8000) + , nbSamplesMic_(0) + , nbSamplesSpk_(0) + , nbSamplesMax_(3000) + , recordingEnabled_(false) + , mixBuffer_(new SFLDataFormat[nbSamplesMax_]) + , micBuffer_(new SFLDataFormat[nbSamplesMax_]) + , spkBuffer_(new SFLDataFormat[nbSamplesMax_]) + , savePath_() { - - mixBuffer_ = new SFLDataFormat[nbSamplesMax_]; - micBuffer_ = new SFLDataFormat[nbSamplesMax_]; - spkBuffer_ = new SFLDataFormat[nbSamplesMax_]; - createFilename(); } AudioRecord::~AudioRecord() { - if (mixBuffer_) { - delete [] mixBuffer_; - } - - if (micBuffer_) { - delete [] micBuffer_; - } - - if (spkBuffer_) { - delete [] spkBuffer_; - } + delete [] mixBuffer_; + delete [] micBuffer_; + delete [] spkBuffer_; } -void AudioRecord::setSndSamplingRate (int smplRate) +void AudioRecord::setSndSamplingRate(int smplRate) { sndSmplRate_ = smplRate; } int AudioRecord::getSndSamplingRate() const { - return sndSmplRate_; + return sndSmplRate_; } -void AudioRecord::setRecordingOption (FILE_TYPE type, SOUND_FORMAT format, int sndSmplRate, std::string path) +void AudioRecord::setRecordingOption(FILE_TYPE type, int sndSmplRate, const std::string &path) { - fileType_ = type; - sndFormat_ = format; channels_ = 1; sndSmplRate_ = sndSmplRate; - savePath_ = path + "/"; - } -void AudioRecord::initFileName (std::string peerNumber) +void AudioRecord::initFileName(std::string peerNumber) { - - std::string fName; - - fName = fileName_; - fName.append ("-"+peerNumber); + std::string fName = fileName_; + fName.append("-" + peerNumber); if (fileType_ == FILE_RAW) { - if (strstr (fileName_, ".raw") == NULL) { - _debug ("AudioRecord: concatenate .raw file extension: name : %s", fileName_); - fName.append (".raw"); + if (strstr(fileName_, ".raw") == NULL) { + DEBUG("AudioRecord: concatenate .raw file extension: name : %s", fileName_); + fName.append(".raw"); } } else if (fileType_ == FILE_WAV) { - if (strstr (fileName_, ".wav") == NULL) { - _debug ("AudioRecord: concatenate .wav file extension: name : %s", fileName_); - fName.append (".wav"); + if (strstr(fileName_, ".wav") == NULL) { + DEBUG("AudioRecord: concatenate .wav file extension: name : %s", fileName_); + fName.append(".wav"); } } - savePath_.append (fName); + savePath_.append(fName); } std::string AudioRecord::getFileName() @@ -140,28 +122,24 @@ std::string AudioRecord::getFileName() bool AudioRecord::openFile() { - bool result = false; - _debug ("AudioRecord: Open file()"); + DEBUG("AudioRecord: Open file()"); - if (isFileExist()) { - _debug ("AudioRecord: Filename does not exist, creating one"); + if (not fileExists()) { + DEBUG("AudioRecord: Filename does not exist, creating one"); byteCounter_ = 0; - if (fileType_ == FILE_RAW) { + if (fileType_ == FILE_RAW) result = setRawFile(); - } else if (fileType_ == FILE_WAV) { + else if (fileType_ == FILE_WAV) result = setWavFile(); - } } else { - _debug ("AudioRecord: Filename already exist opening it"); - - if (fileType_ == FILE_RAW) { + DEBUG("AudioRecord: Filename already exists, opening it"); + if (fileType_ == FILE_RAW) result = openExistingRawFile(); - } else if (fileType_ == FILE_WAV) { + else if (fileType_ == FILE_WAV) result = openExistingWavFile(); - } } return result; @@ -170,65 +148,45 @@ bool AudioRecord::openFile() void AudioRecord::closeFile() { - - if (fp == 0) return; + if (fileHandle_ == 0) return; if (fileType_ == FILE_RAW) - fclose (fp); + fclose(fileHandle_); else if (fileType_ == FILE_WAV) this->closeWavFile(); - - - } bool AudioRecord::isOpenFile() { - - if (fp) { - return true; - } else { - return false; - } + return fileHandle_ != 0; } -bool AudioRecord::isFileExist() +bool AudioRecord::fileExists() { - _info ("AudioRecord: Try to open name : %s ", fileName_); - - if (fopen (fileName_,"rb") ==0) { - return true; - } - - return false; + INFO("AudioRecord: Trying to open %s ", fileName_); + return fopen(fileName_,"rb") != 0; } -bool AudioRecord::isRecording() +bool AudioRecord::isRecording() const { - - if (recordingEnabled_) - return true; - else - return false; + return recordingEnabled_; } bool AudioRecord::setRecording() { - if (isOpenFile()) { if (!recordingEnabled_) { - _info ("AudioRecording: Start recording"); + INFO("AudioRecording: Start recording"); recordingEnabled_ = true; } else { + INFO("AudioRecording: Stop recording"); recordingEnabled_ = false; - _info ("AudioRecording: Stop recording"); } } else { openFile(); - recordingEnabled_ = true; // once opend file, start recording } @@ -239,22 +197,19 @@ bool AudioRecord::setRecording() void AudioRecord::stopRecording() { - _info ("AudioRecording: Stop recording"); - - if (recordingEnabled_) - recordingEnabled_ = false; + INFO("AudioRecording: Stop recording"); + recordingEnabled_ = false; } void AudioRecord::createFilename() { - time_t rawtime; struct tm * timeinfo; - rawtime = time (NULL); - timeinfo = localtime (&rawtime); + rawtime = time(NULL); + timeinfo = localtime(&rawtime); std::stringstream out; @@ -294,27 +249,21 @@ void AudioRecord::createFilename() out << timeinfo->tm_sec; // fileName_ = out.str(); - strncpy (fileName_, out.str().c_str(), 8192); + strncpy(fileName_, out.str().c_str(), 8192); - _info ("AudioRecord: create filename for this call %s ", fileName_); + INFO("AudioRecord: create filename for this call %s ", fileName_); } bool AudioRecord::setRawFile() { + fileHandle_ = fopen(savePath_.c_str(), "wb"); - fp = fopen (savePath_.c_str(), "wb"); - - if (!fp) { - _warn ("AudioRecord: Could not create RAW file!"); + if (!fileHandle_) { + WARN("AudioRecord: Could not create RAW file!"); return false; } - if (sndFormat_ != INT16) { // TODO need to change INT16 to SINT16 - sndFormat_ = INT16; - _debug ("AudioRecord::setRawFile() : using 16-bit signed integer data format for file."); - } - - _debug ("AudioRecord:setRawFile() : created RAW file."); + DEBUG("AudioRecord:setRawFile() : created RAW file."); return true; } @@ -322,12 +271,12 @@ bool AudioRecord::setRawFile() bool AudioRecord::setWavFile() { - _debug ("AudioRecord: Create new wave file %s, sampling rate: %d", savePath_.c_str(), sndSmplRate_); + DEBUG("AudioRecord: Create new wave file %s, sampling rate: %d", savePath_.c_str(), sndSmplRate_); - fp = fopen (savePath_.c_str(), "wb"); + fileHandle_ = fopen(savePath_.c_str(), "wb"); - if (!fp) { - _warn ("AudioRecord: Error: could not create WAV file."); + if (!fileHandle_) { + WARN("AudioRecord: Error: could not create WAV file."); return false; } @@ -336,27 +285,28 @@ bool AudioRecord::setWavFile() }; hdr.riff[3] = 'F'; + hdr.wave[3] = 'E'; + hdr.fmt[3] = ' '; + hdr.data[3] = 'a'; hdr.num_chans = channels_; - if (sndFormat_ == INT16) { // TODO need to write INT16 to SINT16 - hdr.bits_per_samp = 16; - } + hdr.bits_per_samp = 16; - hdr.bytes_per_samp = (SINT16) (channels_ * hdr.bits_per_samp / 8); + hdr.bytes_per_samp = (SINT16)(channels_ * hdr.bits_per_samp / 8); - hdr.bytes_per_sec = (SINT32) (hdr.sample_rate * hdr.bytes_per_samp); + hdr.bytes_per_sec = (SINT32)(hdr.sample_rate * hdr.bytes_per_samp); - if (fwrite (&hdr, 4, 11, fp) != 11) { - _warn ("AudioRecord: Error: could not write WAV header for file. "); + if (fwrite(&hdr, 4, 11, fileHandle_) != 11) { + WARN("AudioRecord: Error: could not write WAV header for file. "); return false; } - _debug ("AudioRecord: created WAV file successfully."); + DEBUG("AudioRecord: created WAV file successfully."); return true; } @@ -364,10 +314,10 @@ bool AudioRecord::setWavFile() bool AudioRecord::openExistingRawFile() { - fp = fopen (fileName_, "ab+"); + fileHandle_ = fopen(fileName_, "ab+"); - if (!fp) { - _warn ("AudioRecord: could not create RAW file!"); + if (!fileHandle_) { + WARN("AudioRecord: could not create RAW file!"); return false; } @@ -377,175 +327,139 @@ bool AudioRecord::openExistingRawFile() bool AudioRecord::openExistingWavFile() { - _info ("%s(%s)\n", __PRETTY_FUNCTION__, fileName_); + INFO("%s(%s)\n", __PRETTY_FUNCTION__, fileName_); - fp = fopen (fileName_, "rb+"); + fileHandle_ = fopen(fileName_, "rb+"); - if (!fp) { - _warn ("AudioRecord: Error: could not open WAV file!"); + if (!fileHandle_) { + WARN("AudioRecord: Error: could not open WAV file!"); return false; } - if (fseek (fp, 40, SEEK_SET) != 0) // jump to data length - _warn ("AudioRecord: Error: Couldn't seek offset 40 in the file "); - - if (fread (&byteCounter_, 4, 1, fp)) - _warn ("AudioRecord: Error: bytecounter Read successfully "); + if (fseek(fileHandle_, 40, SEEK_SET) != 0) // jump to data length + WARN("AudioRecord: Error: Couldn't seek offset 40 in the file "); - if (fseek (fp, 0 , SEEK_END) != 0) - _warn ("AudioRecord: Error: Couldn't seek at the en of the file "); + if (fread(&byteCounter_, 4, 1, fileHandle_)) + WARN("AudioRecord: Error: bytecounter Read successfully "); + if (fseek(fileHandle_, 0 , SEEK_END) != 0) + WARN("AudioRecord: Error: Couldn't seek at the en of the file "); - if (fclose (fp) != 0) - _warn ("AudioRecord: Error: Can't close file r+ "); + if (fclose(fileHandle_) != 0) + WARN("AudioRecord: Error: Can't close file r+ "); + fileHandle_ = fopen(fileName_, "ab+"); - fp = fopen (fileName_, "ab+"); - - if (!fp) { - _warn ("AudioRecord: Error: Could not createopen WAV file ab+!"); + if (!fileHandle_) { + WARN("AudioRecord: Error: Could not createopen WAV file ab+!"); return false; } - if (fseek (fp, 4 , SEEK_END) != 0) - _warn ("AudioRecord: Error: Couldn't seek at the en of the file "); + if (fseek(fileHandle_, 4 , SEEK_END) != 0) + WARN("AudioRecord: Error: Couldn't seek at the en of the file "); return true; } - void AudioRecord::closeWavFile() { - if (fp == 0) { - _debug ("AudioRecord: Can't closeWavFile, a file has not yet been opened!"); + if (fileHandle_ == 0) { + DEBUG("AudioRecord: Can't closeWavFile, a file has not yet been opened!"); return; } - _debug ("AudioRecord: Close wave file"); - + DEBUG("AudioRecord: Close wave file"); SINT32 bytes = byteCounter_ * channels_; - fseek (fp, 40, SEEK_SET); // jump to data length - - if (ferror (fp)) - _warn ("AudioRecord: Error: can't reach offset 40 while closing"); + fseek(fileHandle_, 40, SEEK_SET); // jump to data length - fwrite (&bytes, sizeof (SINT32), 1, fp); + if (ferror(fileHandle_)) + WARN("AudioRecord: Error: can't reach offset 40 while closing"); - if (ferror (fp)) - _warn ("AudioRecord: Error: can't write bytes for data length "); + fwrite(&bytes, sizeof(SINT32), 1, fileHandle_); + if (ferror(fileHandle_)) + WARN("AudioRecord: Error: can't write bytes for data length "); bytes = byteCounter_ * channels_ + 44; // + 44 for the wave header - fseek (fp, 4, SEEK_SET); // jump to file size - - if (ferror (fp)) - _warn ("AudioRecord: Error: can't reach offset 4"); - - fwrite (&bytes, 4, 1, fp); + fseek(fileHandle_, 4, SEEK_SET); // jump to file size - if (ferror (fp)) - _warn ("AudioRecord: Error: can't reach offset 4"); + if (ferror(fileHandle_)) + WARN("AudioRecord: Error: can't reach offset 4"); + fwrite(&bytes, 4, 1, fileHandle_); - if (fclose (fp) != 0) - _warn ("AudioRecord: Error: can't close file"); - + if (ferror(fileHandle_)) + WARN("AudioRecord: Error: can't reach offset 4"); + if (fclose(fileHandle_) != 0) + WARN("AudioRecord: Error: can't close file"); } -void AudioRecord::recSpkrData (SFLDataFormat* buffer, int nSamples) +void AudioRecord::recSpkrData(SFLDataFormat* buffer, int nSamples) { - if (recordingEnabled_) { - nbSamplesMic_ = nSamples; for (int i = 0; i < nbSamplesMic_; i++) micBuffer_[i] = buffer[i]; } - - return; } -void AudioRecord::recMicData (SFLDataFormat* buffer, int nSamples) +void AudioRecord::recMicData(SFLDataFormat* buffer, int nSamples) { - if (recordingEnabled_) { - nbSamplesSpk_ = nSamples; for (int i = 0; i < nbSamplesSpk_; i++) spkBuffer_[i] = buffer[i]; } - - return; } -void AudioRecord::recData (SFLDataFormat* buffer, int nSamples) +void AudioRecord::recData(SFLDataFormat* buffer, int nSamples) { - if (recordingEnabled_) { - - if (fp == 0) { - _debug ("AudioRecord: Can't record data, a file has not yet been opened!"); + if (fileHandle_ == 0) { + DEBUG("AudioRecord: Can't record data, a file has not yet been opened!"); return; } - - - if (sndFormat_ == INT16) { // TODO change INT16 to SINT16 - if (fwrite (buffer, sizeof (SFLDataFormat), nSamples, fp) != (unsigned int) nSamples) - _warn ("AudioRecord: Could not record data! "); - else { - fflush (fp); - byteCounter_ += (unsigned long) (nSamples*sizeof (SFLDataFormat)); - } + if (fwrite(buffer, sizeof(SFLDataFormat), nSamples, fileHandle_) != (unsigned int) nSamples) + WARN("AudioRecord: Could not record data! "); + else { + fflush(fileHandle_); + byteCounter_ += (unsigned long)(nSamples*sizeof(SFLDataFormat)); } } - - return; } -void AudioRecord::recData (SFLDataFormat* buffer_1, SFLDataFormat* buffer_2, int nSamples_1, int nSamples_2 UNUSED) +void AudioRecord::recData(SFLDataFormat* buffer_1, SFLDataFormat* buffer_2, + int nSamples_1, int /*nSamples_2*/) { - if (recordingEnabled_) { - - _debug ("Recording enabled"); - - if (fp == 0) { - _debug ("AudioRecord: Can't record data, a file has not yet been opened!"); + if (fileHandle_ == 0) { + DEBUG("AudioRecord: Can't record data, a file has not yet been opened!"); return; } + for (int k = 0; k < nSamples_1; k++) { + mixBuffer_[k] = (buffer_1[k]+buffer_2[k]); - if (sndFormat_ == INT16) { // TODO change INT16 to SINT16 - for (int k=0; k<nSamples_1; k++) { - - mixBuffer_[k] = (buffer_1[k]+buffer_2[k]); - - - if (fwrite (&mixBuffer_[k], 2, 1, fp) != 1) - _warn ("AudioRecord: Could not record data!"); - else { - fflush (fp); - } - } + if (fwrite(&mixBuffer_[k], 2, 1, fileHandle_) != 1) + WARN("AudioRecord: Could not record data!"); + else + fflush(fileHandle_); } - byteCounter_ += (unsigned long) (nSamples_1*sizeof (SFLDataFormat)); - + byteCounter_ += (unsigned long)(nSamples_1 * sizeof(SFLDataFormat)); } - - return; } diff --git a/daemon/src/audio/audiorecord.h b/daemon/src/audio/audiorecord.h index 752ce5e3972de40caee836cbeedbd7c4de6446cf..d865a5509e44a40190b832a58ef980886e85918d 100644 --- a/daemon/src/audio/audiorecord.h +++ b/daemon/src/audio/audiorecord.h @@ -35,40 +35,34 @@ #include <cstdlib> #include "global.h" +#include "noncopyable.h" -class AudioRecord -{ +class AudioRecord { public: + enum FILE_TYPE { FILE_RAW, FILE_WAV, FILE_INVALID }; AudioRecord(); ~AudioRecord(); - /** - * Set the sampling rate for this recorder - */ - void setSndSamplingRate (int smplRate); - - /** - * Get the recrding sampling rate - */ - int getSndSamplingRate(void) const; + void setSndSamplingRate(int smplRate); + /** + * Get the recrding sampling rate + */ + int getSndSamplingRate() const; - /** - * Set the recording option - */ - void setRecordingOption (FILE_TYPE type, SOUND_FORMAT format, int sndSmplRate, std::string path); + void setRecordingOption(FILE_TYPE type, int sndSmplRate, const std::string &path); - /** - * Init recording file path - */ - void initFileName (std::string peerNumber); + /** + * Init recording file path + */ + void initFileName(std::string peerNumber); /** - * Return the filepath of the recording - */ - std::string getFileName(void); + * Return the filepath of the recording + */ + std::string getFileName(); /** * Check if no otehr file is opened, then create a new one @@ -90,14 +84,14 @@ class AudioRecord bool isOpenFile(); /** - * Check if a file already exist + * Check if a file already exists */ - bool isFileExist(); + bool fileExists(); /** * Check recording state */ - bool isRecording(); + bool isRecording() const; /** * Set recording flag @@ -115,21 +109,21 @@ class AudioRecord * @param buffer The data chunk to be recorded * @param nSamples Number of samples (number of bytes) to be recorded */ - void recSpkrData (SFLDataFormat* buffer, int nSamples); + void recSpkrData(SFLDataFormat* buffer, int nSamples); /** * Record a chunk of data in an internal buffer * @param buffer The data chunk to be recorded * @param nSamples Number of samples (number of bytes) to be recorded */ - void recMicData (SFLDataFormat* buffer, int nSamples); + void recMicData(SFLDataFormat* buffer, int nSamples); /** * Record a chunk of data in an openend file * @param buffer The data chunk to be recorded * @param nSamples Number of samples (number of bytes) to be recorded */ - void recData (SFLDataFormat* buffer, int nSamples); + void recData(SFLDataFormat* buffer, int nSamples); /** * Record a chunk of data in an openend file, Mix two differnet buffer @@ -138,7 +132,7 @@ class AudioRecord * @param nSamples_1 Number of samples (number of bytes) of buffer_1 * @param nSamples_2 Number of samples (number of bytes) of buffer_2 */ - void recData (SFLDataFormat* buffer_1, SFLDataFormat* buffer_2, int nSamples_1, int nSamples_2); + void recData(SFLDataFormat* buffer_1, SFLDataFormat* buffer_2, int nSamples_1, int nSamples_2); protected: @@ -177,18 +171,13 @@ class AudioRecord /** * Pointer to the recorded file */ - FILE *fp; //file pointer + FILE *fileHandle_; /** * File format (RAW / WAVE) */ FILE_TYPE fileType_; - /** - * Sound format (SINT16/SINT32) - */ - SOUND_FORMAT sndFormat_; - /** * Number of channels */ @@ -249,6 +238,8 @@ class AudioRecord */ std::string savePath_; + private: + NON_COPYABLE(AudioRecord); }; #endif // _AUDIO_RECORD_H diff --git a/daemon/src/audio/audiorecorder.cpp b/daemon/src/audio/audiorecorder.cpp index 4b1ddfc7d9cd1ef1bf214db1c4aa644c29792561..462c32165b74342434d0ebff8e44d25e469476c7 100644 --- a/daemon/src/audio/audiorecorder.cpp +++ b/daemon/src/audio/audiorecorder.cpp @@ -30,56 +30,46 @@ #include "audiorecorder.h" #include "mainbuffer.h" -#include <assert.h> +#include <cassert> -int AudioRecorder::count = 0; +int AudioRecorder::count_ = 0; -AudioRecorder::AudioRecorder (AudioRecord *arec, MainBuffer *mb) : Thread() +AudioRecorder::AudioRecorder(AudioRecord *arec, MainBuffer *mb) : Thread(), + recorderId_(), mbuffer_(mb), arecord_(arec) { assert(mb); - setCancel (cancelDeferred); + setCancel(cancelDeferred); - ++count; + ++count_; - std::string id ("processid_"); + std::string id("processid_"); // convert count into string std::string s; std::stringstream out; - out << count; + out << count_; s = out.str(); - recorderId = id.append (s); - - arecord = arec; - mbuffer = mb; + recorderId_ = id.append(s); } - /** * Reimplementation of run() */ -void AudioRecorder::run (void) +void AudioRecorder::run() { - int bufferLength = 10000; SFLDataFormat buffer[bufferLength]; while (true) { - - int availBytes = mbuffer->availForGet (recorderId); - + int availBytes = mbuffer_->availForGet(recorderId_); int toGet = (availBytes < bufferLength) ? availBytes : bufferLength; - mbuffer->getData (buffer, toGet, recorderId); - - if (availBytes > 0) { + mbuffer_->getData(buffer, toGet, recorderId_); - arecord->recData (buffer, availBytes/sizeof (SFLDataFormat)); - } - - sleep (20); + if (availBytes > 0) + arecord_->recData(buffer, availBytes / sizeof(SFLDataFormat)); + sleep(20); } - } diff --git a/daemon/src/audio/audiorecorder.h b/daemon/src/audio/audiorecorder.h index 1a3e361bcb7197e2a3b9aeae7bfc99992b979d37..eb7ccf1fe146b4d763befce1afdabe8eff9e8856 100644 --- a/daemon/src/audio/audiorecorder.h +++ b/daemon/src/audio/audiorecorder.h @@ -31,39 +31,36 @@ #ifndef __AUDIORECORDER_H_ #define __AUDIORECORDER_H_ +#include <string> #include <cc++/thread.h> #include "audiorecord.h" -#include <string> +#include "noncopyable.h" class MainBuffer; -class AudioRecorder : public ost::Thread -{ +class AudioRecorder : public ost::Thread { public: - AudioRecorder (AudioRecord *arec, MainBuffer *mb); + AudioRecorder(AudioRecord *arec, MainBuffer *mb); - ~AudioRecorder (void) { + ~AudioRecorder() { terminate(); } - static int count; + static int count_; - std::string getRecorderID() { - return recorderId; + std::string getRecorderID() const { + return recorderId_; } virtual void run(); private: - AudioRecorder (const AudioRecorder& ar); - AudioRecorder& operator= (const AudioRecorder& ar); - - std::string recorderId; - - MainBuffer *mbuffer; + NON_COPYABLE(AudioRecorder); - AudioRecord *arecord; + std::string recorderId_; + MainBuffer *mbuffer_; + AudioRecord *arecord_; }; #endif diff --git a/daemon/src/audio/audiortp/AudioRtpFactory.cpp b/daemon/src/audio/audiortp/AudioRtpFactory.cpp deleted file mode 100644 index 82afe4a45733116eb2e286a31281a57b5a2dc154..0000000000000000000000000000000000000000 --- a/daemon/src/audio/audiortp/AudioRtpFactory.cpp +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. - * Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com> - * Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - - - -#include "AudioRtpFactory.h" -#include "AudioZrtpSession.h" -#include "AudioSrtpSession.h" -#include "AudioSymmetricRtpSession.h" -#include "manager.h" -#include "sip/sdp.h" -#include "sip/sipcall.h" -#include "sip/sipaccount.h" -#include "sip/SdesNegotiator.h" - -#include <cassert> - -namespace sfl -{ - -AudioRtpFactory::AudioRtpFactory(SIPCall *ca) : _rtpSession (NULL), remoteContext(NULL), localContext(NULL), ca_(ca) -{ - -} - -AudioRtpFactory::~AudioRtpFactory() -{ - delete _rtpSession; -} - -void AudioRtpFactory::initAudioRtpConfig () -{ - if (_rtpSession != NULL) - stop(); - - std::string accountId(Manager::instance().getAccountFromCall(ca_->getCallId())); - - SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount (accountId)); - if (account) { - _srtpEnabled = account->getSrtpEnabled(); - std::string key(account->getSrtpKeyExchange()); - - if (key == "sdes") - _keyExchangeProtocol = Sdes; - else if (key == "zrtp") - _keyExchangeProtocol = Zrtp; - else - _keyExchangeProtocol = Symmetric; - - _helloHashEnabled = account->getZrtpHelloHash(); - } else { - _srtpEnabled = false; - _keyExchangeProtocol = Symmetric; - _helloHashEnabled = false; - } -} - -void AudioRtpFactory::initAudioSymmetricRtpSession () -{ - ost::MutexLock m (_audioRtpThreadMutex); - - if (_srtpEnabled) { - std::string zidFilename (Manager::instance().voipPreferences.getZidFile()); - - switch (_keyExchangeProtocol) { - - case Zrtp: - _rtpSession = new AudioZrtpSession (ca_, zidFilename); - if (_helloHashEnabled) { - // TODO: be careful with that. The hello hash is computed asynchronously. Maybe it's - // not even available at that point. - ca_->getLocalSDP()->setZrtpHash (static_cast<AudioZrtpSession *> (_rtpSession)->getHelloHash()); - } - break; - - case Sdes: - _rtpSession = new AudioSrtpSession (ca_); - break; - - default: - throw UnsupportedRtpSessionType("Unsupported Rtp Session Exception Type!"); - } - } else { - _rtpSession = new AudioSymmetricRtpSession (ca_); - } -} - -void AudioRtpFactory::start (AudioCodec* audiocodec) -{ - if (_rtpSession == NULL) { - throw AudioRtpFactoryException ("AudioRtpFactory: Error: RTP session was null when trying to start audio thread"); - } - - if (_rtpSession->getAudioRtpType() == Sdes) { - if(localContext && remoteContext) { - static_cast<AudioSrtpSession *> (_rtpSession)->restoreCryptoContext(localContext, remoteContext); - } - } - if (_rtpSession->startRtpThread (audiocodec) != 0) { - throw AudioRtpFactoryException ("AudioRtpFactory: Error: Failed to start AudioZrtpSession thread"); - } - -} - -void AudioRtpFactory::stop (void) -{ - ost::MutexLock mutex (_audioRtpThreadMutex); - - if (_rtpSession == NULL) - return; - - if (_rtpSession->getAudioRtpType() == Sdes) { - localContext = static_cast<AudioSrtpSession *> (_rtpSession)->_localCryptoCtx; - remoteContext = static_cast<AudioSrtpSession *> (_rtpSession)->_remoteCryptoCtx; - } - - delete _rtpSession; - _rtpSession = NULL; -} - -int AudioRtpFactory::getSessionMedia() -{ - if (_rtpSession == NULL) { - throw AudioRtpFactoryException ("AudioRtpFactory: Error: RTP session was null when trying to get session media type"); - } - - return _rtpSession->getCodecPayloadType(); -} - -void AudioRtpFactory::updateSessionMedia (AudioCodec *audiocodec) -{ - if (_rtpSession == NULL) { - throw AudioRtpFactoryException ("AudioRtpFactory: Error: _rtpSession was null when trying to update IP address"); - } - _rtpSession->updateSessionMedia (audiocodec); -} - -void AudioRtpFactory::updateDestinationIpAddress (void) -{ - if (_rtpSession) - _rtpSession->updateDestinationIpAddress(); -} - -sfl::AudioZrtpSession * AudioRtpFactory::getAudioZrtpSession() -{ - if (_rtpSession->getAudioRtpType() == Zrtp) { - return static_cast<AudioZrtpSession *> (_rtpSession); - } else { - throw AudioRtpFactoryException ("RTP: Error: _rtpSession is NULL in getAudioZrtpSession"); - } -} - -void sfl::AudioRtpFactory::initLocalCryptoInfo () -{ - if (_rtpSession && _rtpSession->getAudioRtpType() == Sdes) { - static_cast<AudioSrtpSession *> (_rtpSession)->initLocalCryptoInfo (); - - ca_->getLocalSDP()->setLocalSdpCrypto (static_cast<AudioSrtpSession *> (_rtpSession)->getLocalCryptoInfo()); - } -} - -void AudioRtpFactory::setRemoteCryptoInfo (sfl::SdesNegotiator& nego) -{ - if (_rtpSession && _rtpSession->getAudioRtpType() == Sdes) { - static_cast<AudioSrtpSession *> (_rtpSession)->setRemoteCryptoInfo (nego); - } else { - throw AudioRtpFactoryException ("RTP: Error: _rtpSession is NULL in setRemoteCryptoInfo"); - } -} - -void AudioRtpFactory::setDtmfPayloadType(unsigned int payloadType) -{ - if (_rtpSession) - _rtpSession->setDtmfPayloadType(payloadType); -} - -void AudioRtpFactory::sendDtmfDigit (int digit) -{ - _rtpSession->putDtmfEvent(digit); -} - -} diff --git a/daemon/src/audio/audiortp/AudioRtpRecordHandler.cpp b/daemon/src/audio/audiortp/AudioRtpRecordHandler.cpp deleted file mode 100644 index 8e783314b77f5b8f87b7b5902d2d81a0c98bb989..0000000000000000000000000000000000000000 --- a/daemon/src/audio/audiortp/AudioRtpRecordHandler.cpp +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. - * Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - -#include "AudioRtpRecordHandler.h" -#include <fstream> - -#include "sip/sipcall.h" -#include "audio/audiolayer.h" -#include "manager.h" - -// #define DUMP_PROCESS_DATA_ENCODE - -namespace sfl -{ - -static const SFLDataFormat initFadeinFactor = 32000; - -AudioRtpRecord::AudioRtpRecord () : _audioCodec (NULL) - , _hasDynamicPayloadType (false) - , _converter (NULL) - , _codecSampleRate (0) - , _codecFrameSize (0) - , _micAmplFactor (initFadeinFactor) - , _noiseSuppress (NULL) - , _callId ("") - , _dtmfPayloadType(101) // same as Asterisk -{ - -} - - -AudioRtpRecord::~AudioRtpRecord() -{ - delete _converter; - delete _audioCodec; - delete _noiseSuppress; -} - - -AudioRtpRecordHandler::AudioRtpRecordHandler (SIPCall *ca) : _audioRtpRecord (), id_ (ca->getCallId()), echoCanceller(ca->getMemoryPool()), gainController(8000, -10.0) -{ - -} - - -AudioRtpRecordHandler::~AudioRtpRecordHandler() {} - -void AudioRtpRecordHandler::setRtpMedia (AudioCodec* audioCodec) -{ - _audioRtpRecord.audioCodecMutex.enter(); - - delete _audioRtpRecord._audioCodec; - // Set varios codec info to reduce indirection - _audioRtpRecord._audioCodec = audioCodec; - _audioRtpRecord._codecPayloadType = audioCodec->getPayloadType(); - _audioRtpRecord._codecSampleRate = audioCodec->getClockRate(); - _audioRtpRecord._codecFrameSize = audioCodec->getFrameSize(); - _audioRtpRecord._hasDynamicPayloadType = audioCodec->hasDynamicPayload(); - - _audioRtpRecord.audioCodecMutex.leave(); -} - -void AudioRtpRecordHandler::initBuffers() -{ - // Set sampling rate, main buffer choose the highest one - Manager::instance().audioSamplingRateChanged(_audioRtpRecord._codecSampleRate); - - // initialize SampleRate converter using AudioLayer's sampling rate - // (internal buffers initialized with maximal sampling rate and frame size) - delete _audioRtpRecord._converter; - _audioRtpRecord._converter = new SamplerateConverter (getCodecSampleRate()); -} - -void AudioRtpRecordHandler::initNoiseSuppress() -{ - _audioRtpRecord.audioProcessMutex.enter(); - - delete _audioRtpRecord._noiseSuppress; - - _audioRtpRecord._noiseSuppress = new NoiseSuppress(getCodecFrameSize(), getCodecSampleRate()); - - _audioRtpRecord.audioProcessMutex.leave(); -} - -void AudioRtpRecordHandler::putDtmfEvent (int digit) -{ - _audioRtpRecord._dtmfQueue.push_back(digit); -} - -#ifdef DUMP_PROCESS_DATA_ENCODE -std::ofstream teststream("test_process_data_encode.raw"); -#endif - -int AudioRtpRecordHandler::processDataEncode (void) -{ - SFLDataFormat *micData = _audioRtpRecord.decData; - unsigned char *micDataEncoded = _audioRtpRecord.encodedData; - SFLDataFormat *micDataConverted = _audioRtpRecord.resampledData; - - int codecSampleRate = getCodecSampleRate(); - int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); - - double resampleFactor = (double)mainBufferSampleRate / codecSampleRate; - - // compute nb of byte to get coresponding to 1 audio frame - int samplesToGet = resampleFactor * getCodecFrameSize(); - int bytesToGet = samplesToGet * sizeof (SFLDataFormat); - - if (Manager::instance().getMainBuffer()->availForGet (id_) < bytesToGet) { - return 0; - } - - int bytes = Manager::instance().getMainBuffer()->getData (micData, bytesToGet, id_); - if (bytes != bytesToGet) { - _error("%s : asked %d bytes from mainbuffer, got %d", __PRETTY_FUNCTION__, bytesToGet, bytes); - return 0; - } - - int samples = bytesToGet / sizeof(SFLDataFormat); - - fadeIn (micData, samples, &_audioRtpRecord._micAmplFactor); - - if(Manager::instance().getEchoCancelState()) - echoCanceller.getData(micData); - -#ifdef DUMP_PROCESS_DATA_ENCODE - teststream.write(reinterpret_cast<char *>(micData), bytesToGet); -#endif - - SFLDataFormat *out = micData; - if (codecSampleRate != mainBufferSampleRate) { - out = micDataConverted; - _audioRtpRecord._converter->resample (micData, micDataConverted, codecSampleRate, mainBufferSampleRate, samplesToGet); - } - - if (Manager::instance().audioPreference.getNoiseReduce()) { - _audioRtpRecord.audioProcessMutex.enter(); - _audioRtpRecord._noiseSuppress->process(micData, getCodecFrameSize()); - _audioRtpRecord.audioProcessMutex.leave(); - } - - _audioRtpRecord.audioCodecMutex.enter(); - int compSize = _audioRtpRecord._audioCodec->encode (micDataEncoded, out, getCodecFrameSize()); - _audioRtpRecord.audioCodecMutex.leave(); - - return compSize; -} - -void AudioRtpRecordHandler::processDataDecode (unsigned char *spkrData, unsigned int size, int payloadType) -{ - if (getCodecPayloadType() != payloadType) - return; - - int codecSampleRate = getCodecSampleRate(); - - SFLDataFormat *spkrDataDecoded = _audioRtpRecord.decData; - SFLDataFormat *spkrDataConverted = _audioRtpRecord.resampledData; - - int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); - - _audioRtpRecord.audioCodecMutex.enter(); - - // Return the size of data in samples - int inSamples = _audioRtpRecord._audioCodec->decode (spkrDataDecoded , spkrData , size); - - _audioRtpRecord.audioCodecMutex.leave(); - - fadeIn (spkrDataDecoded, inSamples, &_audioRtpRecord._micAmplFactor); - - // Normalize incomming signal - gainController.process(spkrDataDecoded, inSamples); - - SFLDataFormat *out = spkrDataDecoded; - int outSamples = inSamples; - // test if resampling is required - if (codecSampleRate != mainBufferSampleRate) { - // Do sample rate conversion - outSamples = ((float) inSamples * ( (float) mainBufferSampleRate / (float) codecSampleRate)); - _audioRtpRecord._converter->resample (spkrDataDecoded, spkrDataConverted, codecSampleRate, mainBufferSampleRate, inSamples); - out = spkrDataConverted; - } - - if(Manager::instance().getEchoCancelState()) - echoCanceller.putData(out, outSamples); - Manager::instance().getMainBuffer()->putData (out, outSamples * sizeof (SFLDataFormat), id_); -} - -void AudioRtpRecordHandler::fadeIn (SFLDataFormat *audio, int size, SFLDataFormat *factor) -{ - // if factor reach 0, this function should have no effect - if (*factor <= 0) - return; - - while (size) - audio[--size] /= *factor; - - *factor /= FADEIN_STEP_SIZE; -} - -} diff --git a/daemon/src/audio/audiortp/AudioRtpSession.cpp b/daemon/src/audio/audiortp/AudioRtpSession.cpp deleted file mode 100644 index 04f75d4f13651d568274b4e529dc48731cca83dd..0000000000000000000000000000000000000000 --- a/daemon/src/audio/audiortp/AudioRtpSession.cpp +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. - * Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com> - * Author: Alexandre Bourget <alexandre.bourget@savoirfairelinux.com> - * Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com> - * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> - * Author: Yan Morin <yan.morin@savoirfairelinux.com> - * Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - -#include "AudioRtpSession.h" -#include "AudioSymmetricRtpSession.h" - -#include "sip/sdp.h" -#include "audio/audiolayer.h" -#include <ccrtp/rtp.h> -#include <ccrtp/oqueue.h> -#include "manager.h" - -namespace sfl -{ -AudioRtpSession::AudioRtpSession (SIPCall * sipcall, RtpMethod type, ost::RTPDataQueue *queue, ost::Thread *thread) : - AudioRtpRecordHandler (sipcall) - , _ca (sipcall) - , _type(type) - , _timestamp (0) - , _timestampIncrement (0) - , _timestampCount (0) - , _isStarted (false) - , _queue(queue) - , _thread(thread) -{ - assert (_ca); - _queue->setTypeOfService (ost::RTPDataQueue::tosEnhanced); -} - -AudioRtpSession::~AudioRtpSession() -{ - _queue->disableStack(); -} - -void AudioRtpSession::updateSessionMedia (AudioCodec *audioCodec) -{ - int lastSamplingRate = _audioRtpRecord._codecSampleRate; - - setSessionMedia(audioCodec); - - Manager::instance().audioSamplingRateChanged(_audioRtpRecord._codecSampleRate); - - if (lastSamplingRate != _audioRtpRecord._codecSampleRate) { - _debug ("AudioRtpSession: Update noise suppressor with sampling rate %d and frame size %d", getCodecSampleRate(), getCodecFrameSize()); - initNoiseSuppress(); - } - -} - -void AudioRtpSession::setSessionMedia (AudioCodec *audioCodec) -{ - setRtpMedia (audioCodec); - - // store codec info locally - int payloadType = getCodecPayloadType(); - int frameSize = getCodecFrameSize(); - int smplRate = getCodecSampleRate(); - bool dynamic = getHasDynamicPayload(); - - // G722 requires timestamp to be incremented at 8kHz - if (payloadType == g722PayloadType) - _timestampIncrement = g722RtpTimeincrement; - else - _timestampIncrement = frameSize; - - _debug ("AudioRptSession: Codec payload: %d", payloadType); - _debug ("AudioSymmetricRtpSession: Codec sampling rate: %d", smplRate); - _debug ("AudioSymmetricRtpSession: Codec frame size: %d", frameSize); - _debug ("AudioSymmetricRtpSession: RTP timestamp increment: %d", _timestampIncrement); - - if (payloadType == g722PayloadType) { - _debug ("AudioSymmetricRtpSession: Setting G722 payload format"); - _queue->setPayloadFormat (ost::DynamicPayloadFormat ( (ost::PayloadType) payloadType, g722RtpClockRate)); - } else { - if (dynamic) { - _debug ("AudioSymmetricRtpSession: Setting dynamic payload format"); - _queue->setPayloadFormat (ost::DynamicPayloadFormat ( (ost::PayloadType) payloadType, smplRate)); - } else { - _debug ("AudioSymmetricRtpSession: Setting static payload format"); - _queue->setPayloadFormat (ost::StaticPayloadFormat ( (ost::StaticPayloadType) payloadType)); - } - } - - if (_type != Zrtp) - _ca->setRecordingSmplRate (getCodecSampleRate()); -} - -void AudioRtpSession::sendDtmfEvent () -{ - ost::RTPPacket::RFC2833Payload payload; - - payload.event = _audioRtpRecord._dtmfQueue.front(); - payload.ebit = false; // end of event bit - payload.rbit = false; // reserved bit - payload.duration = 1; // duration for this event - - _audioRtpRecord._dtmfQueue.pop_front(); - - _debug ("AudioRtpSession: Send RTP Dtmf (%d)", payload.event); - - _timestamp += (_type == Zrtp) ? 160 : _timestampIncrement; - - // discard equivalent size of audio - processDataEncode(); - - // change Payload type for DTMF payload - _queue->setPayloadFormat (ost::DynamicPayloadFormat ( (ost::PayloadType) getDtmfPayloadType(), 8000)); - - _queue->setMark (true); - _queue->sendImmediate (_timestamp, (const unsigned char *) (&payload), sizeof (payload)); - _queue->setMark (false); - - // get back the payload to audio - _queue->setPayloadFormat (ost::StaticPayloadFormat ( (ost::StaticPayloadType) getCodecPayloadType())); -} - - -void AudioRtpSession::receiveSpeakerData () -{ - const ost::AppDataUnit* adu = _queue->getData (_queue->getFirstTimestamp()); - if (!adu) - return; - - unsigned char* spkrDataIn = (unsigned char*) adu->getData(); // data in char - unsigned int size = adu->getSize(); // size in char - - // DTMF over RTP, size must be over 4 in order to process it as voice data - if (size > 4) - processDataDecode (spkrDataIn, size, adu->getType()); - - delete adu; -} - - - -void AudioRtpSession::sendMicData() -{ - int compSize = processDataEncode(); - - // if no data return - if (!compSize) - return; - - // Increment timestamp for outgoing packet - _timestamp += _timestampIncrement; - - if (_type == Zrtp) - _queue->putData (_timestamp, getMicDataEncoded(), compSize); - // putData put the data on RTP queue, sendImmediate bypass this queue - _queue->sendImmediate (_timestamp, getMicDataEncoded(), compSize); -} - - -void AudioRtpSession::setSessionTimeouts (void) -{ - _debug ("AudioRtpSession: Set session scheduling timeout (%d) and expireTimeout (%d)", sfl::schedulingTimeout, sfl::expireTimeout); - - _queue->setSchedulingTimeout (sfl::schedulingTimeout); - _queue->setExpireTimeout (sfl::expireTimeout); -} - -void AudioRtpSession::setDestinationIpAddress (void) -{ - _info ("AudioRtpSession: Setting IP address for the RTP session"); - - // Store remote ip in case we would need to forget current destination - _remote_ip = ost::InetHostAddress (_ca->getLocalSDP()->getRemoteIP().c_str()); - - if (!_remote_ip) { - _warn ("AudioRtpSession: Target IP address (%s) is not correct!", - _ca->getLocalSDP()->getRemoteIP().data()); - return; - } - - // Store remote port in case we would need to forget current destination - _remote_port = (unsigned short) _ca->getLocalSDP()->getRemoteAudioPort(); - - _info ("AudioRtpSession: New remote address for session: %s:%d", - _ca->getLocalSDP()->getRemoteIP().data(), _remote_port); - - if (!_queue->addDestination (_remote_ip, _remote_port)) { - _warn ("AudioRtpSession: Can't add new destination to session!"); - return; - } -} - -void AudioRtpSession::updateDestinationIpAddress (void) -{ - _debug ("AudioRtpSession: Update destination ip address"); - - // Destination address are stored in a list in ccrtp - // This method remove the current destination entry - - if (!_queue->forgetDestination (_remote_ip, _remote_port, _remote_port+1)) - _warn ("AudioRtpSession: Could not remove previous destination"); - - // new destination is stored in call - // we just need to recall this method - setDestinationIpAddress(); -} - - -int AudioRtpSession::startRtpThread (AudioCodec* audiocodec) -{ - if (_isStarted) - return 0; - - _debug ("AudioSymmetricRtpSession: Starting main thread"); - - _isStarted = true; - setSessionTimeouts(); - setSessionMedia (audiocodec); - initBuffers(); - initNoiseSuppress(); - - _queue->enableStack(); - int ret = _thread->start(); - if (_type == Zrtp) - return ret; - - AudioSymmetricRtpSession *self = dynamic_cast<AudioSymmetricRtpSession*>(this); - assert(self); - return self->startSymmetricRtpThread(); -} - - -bool AudioRtpSession::onRTPPacketRecv (ost::IncomingRTPPkt&) -{ - receiveSpeakerData(); - return true; -} - -} diff --git a/daemon/src/audio/audiortp/Makefile.am b/daemon/src/audio/audiortp/Makefile.am index a727a9e6f6a2e9be6e71c60765858afb90f7ad76..5d5daf3755ebbbd9eb0f8884dc6cefd643fd597e 100644 --- a/daemon/src/audio/audiortp/Makefile.am +++ b/daemon/src/audio/audiortp/Makefile.am @@ -3,20 +3,18 @@ include $(top_srcdir)/globals.mak noinst_LTLIBRARIES = libaudiortp.la libaudiortp_la_SOURCES = \ - AudioRtpSession.cpp \ - AudioSymmetricRtpSession.cpp \ - AudioRtpRecordHandler.cpp \ - AudioRtpFactory.cpp \ - AudioZrtpSession.cpp \ - ZrtpSessionCallback.cpp \ - AudioSrtpSession.cpp - -noinst_HEADERS = \ - AudioRtpSession.h \ - AudioRtpRecordHandler.h \ - AudioRtpFactory.h \ - AudioSymmetricRtpSession.h \ - AudioZrtpSession.h \ - ZrtpSessionCallback.h \ - AudioSrtpSession.h + audio_rtp_session.cpp \ + audio_symmetric_rtp_session.cpp \ + audio_rtp_record_handler.cpp \ + audio_rtp_factory.cpp \ + audio_zrtp_session.cpp \ + zrtp_session_callback.cpp \ + audio_srtp_session.cpp \ + audio_rtp_session.h \ + audio_rtp_record_handler.h \ + audio_rtp_factory.h \ + audio_symmetric_rtp_session.h \ + audio_zrtp_session.h \ + zrtp_session_callback.h \ + audio_srtp_session.h diff --git a/daemon/src/audio/audiortp/ZrtpSessionCallback.cpp b/daemon/src/audio/audiortp/ZrtpSessionCallback.cpp deleted file mode 100644 index f7ab8cc49edbc729afe6f046a5b85eb7903a8a80..0000000000000000000000000000000000000000 --- a/daemon/src/audio/audiortp/ZrtpSessionCallback.cpp +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. - * Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ -#include "ZrtpSessionCallback.h" - -#include "global.h" -#include "sip/sipcall.h" -#include "dbus/dbusmanager.h" -#include "dbus/callmanager.h" -#include "manager.h" - -#include <cstdlib> -#include <string> -#include <map> -#include <utility> // for std::pair - -using namespace GnuZrtpCodes; - -using namespace ost; - -namespace sfl -{ - -ZrtpSessionCallback::ZrtpSessionCallback (SIPCall *sipcall) : - _sipcall (sipcall) -{ - using std::pair; - using std::string; - - if (_mapInitialized) { - return; - } - - _info ("Zrtp: Initialize callbacks"); - - /** - * Information Map - */ - - _infoMap.insert (pair<int32, string*> (InfoHelloReceived, new string ("Hello received, preparing a Commit"))); - _infoMap.insert (pair<int32, string*> (InfoCommitDHGenerated, new string ("Commit: Generated a public DH key"))); - _infoMap.insert (pair<int32, string*> (InfoRespCommitReceived, new string ("Responder: Commit received, preparing DHPart1"))); - _infoMap.insert (pair<int32, string*> (InfoDH1DHGenerated, new string ("DH1Part: Generated a public DH key"))); - _infoMap.insert (pair<int32, string*> (InfoInitDH1Received, new string ("Initiator: DHPart1 received, preparing DHPart2"))); - _infoMap.insert (pair<int32, string*> (InfoRespDH2Received, new string ("Responder: DHPart2 received, preparing Confirm1"))); - _infoMap.insert (pair<int32, string*> (InfoInitConf1Received, new string ("Initiator: Confirm1 received, preparing Confirm2"))); - _infoMap.insert (pair<int32, string*> (InfoRespConf2Received, new string ("Responder: Confirm2 received, preparing Conf2Ack"))); - _infoMap.insert (pair<int32, string*> (InfoRSMatchFound, new string ("At least one retained secrets matches - security OK"))); - _infoMap.insert (pair<int32, string*> (InfoSecureStateOn, new string ("Entered secure state"))); - _infoMap.insert (pair<int32, string*> (InfoSecureStateOff, new string ("No more security for this session"))); - - /** - * Warning Map - */ - - _warningMap.insert (pair<int32, string*> (WarningDHAESmismatch, - new string ("Commit contains an AES256 cipher but does not offer a Diffie-Helman 4096"))); - _warningMap.insert (pair<int32, string*> (WarningGoClearReceived, new string ("Received a GoClear message"))); - _warningMap.insert (pair<int32, string*> (WarningDHShort, - new string ("Hello offers an AES256 cipher but does not offer a Diffie-Helman 4096"))); - _warningMap.insert (pair<int32, string*> (WarningNoRSMatch, new string ("No retained secret matches - verify SAS"))); - _warningMap.insert (pair<int32, string*> (WarningCRCmismatch, new string ("Internal ZRTP packet checksum mismatch - packet dropped"))); - _warningMap.insert (pair<int32, string*> (WarningSRTPauthError, new string ("Dropping packet because SRTP authentication failed!"))); - _warningMap.insert (pair<int32, string*> (WarningSRTPreplayError, new string ("Dropping packet because SRTP replay check failed!"))); - - _severeMap.insert (pair<int32, string*> (SevereHelloHMACFailed, new string ("Hash HMAC check of Hello failed!"))); - _severeMap.insert (pair<int32, string*> (SevereCommitHMACFailed, new string ("Hash HMAC check of Commit failed!"))); - _severeMap.insert (pair<int32, string*> (SevereDH1HMACFailed, new string ("Hash HMAC check of DHPart1 failed!"))); - _severeMap.insert (pair<int32, string*> (SevereDH2HMACFailed, new string ("Hash HMAC check of DHPart2 failed!"))); - _severeMap.insert (pair<int32, string*> (SevereCannotSend, new string ("Cannot send data - connection or peer down?"))); - _severeMap.insert (pair<int32, string*> (SevereProtocolError, new string ("Internal protocol error occured!"))); - _severeMap.insert (pair<int32, string*> (SevereNoTimer, new string ("Cannot start a timer - internal resources exhausted?"))); - _severeMap.insert (pair<int32, string*> (SevereTooMuchRetries, - new string ("Too much retries during ZRTP negotiation - connection or peer down?"))); - - /** - * Zrtp protocol related messages map - */ - - _zrtpMap.insert (pair<int32, string*> (MalformedPacket, new string ("Malformed packet (CRC OK, but wrong structure)"))); - _zrtpMap.insert (pair<int32, string*> (CriticalSWError, new string ("Critical software error"))); - _zrtpMap.insert (pair<int32, string*> (UnsuppZRTPVersion, new string ("Unsupported ZRTP version"))); - _zrtpMap.insert (pair<int32, string*> (HelloCompMismatch, new string ("Hello components mismatch"))); - _zrtpMap.insert (pair<int32, string*> (UnsuppHashType, new string ("Hash type not supported"))); - _zrtpMap.insert (pair<int32, string*> (UnsuppCiphertype, new string ("Cipher type not supported"))); - _zrtpMap.insert (pair<int32, string*> (UnsuppPKExchange, new string ("Public key exchange not supported"))); - _zrtpMap.insert (pair<int32, string*> (UnsuppSRTPAuthTag, new string ("SRTP auth. tag not supported"))); - _zrtpMap.insert (pair<int32, string*> (UnsuppSASScheme, new string ("SAS scheme not supported"))); - _zrtpMap.insert (pair<int32, string*> (NoSharedSecret, new string ("No shared secret available, DH mode required"))); - _zrtpMap.insert (pair<int32, string*> (DHErrorWrongPV, new string ("DH Error: bad pvi or pvr ( == 1, 0, or p-1)"))); - _zrtpMap.insert (pair<int32, string*> (DHErrorWrongHVI, new string ("DH Error: hvi != hashed data"))); - _zrtpMap.insert (pair<int32, string*> (SASuntrustedMiTM, new string ("Received relayed SAS from untrusted MiTM"))); - _zrtpMap.insert (pair<int32, string*> (ConfirmHMACWrong, new string ("Auth. Error: Bad Confirm pkt HMAC"))); - _zrtpMap.insert (pair<int32, string*> (NonceReused, new string ("Nonce reuse"))); - _zrtpMap.insert (pair<int32, string*> (EqualZIDHello, new string ("Equal ZIDs in Hello"))); - _zrtpMap.insert (pair<int32, string*> (GoCleatNotAllowed, new string ("GoClear packet received, but not allowed"))); - - _mapInitialized = true; -} - -void -ZrtpSessionCallback::secureOn (std::string cipher) -{ - _debug ("Zrtp: Secure mode is on with cipher %s", cipher.c_str()); - Manager::instance().getDbusManager()->getCallManager()->secureZrtpOn (_sipcall->getCallId(), cipher); -} - -void -ZrtpSessionCallback::secureOff (void) -{ - _debug ("Zrtp: Secure mode is off"); - Manager::instance().getDbusManager()->getCallManager()->secureZrtpOff (_sipcall->getCallId()); -} - -void -ZrtpSessionCallback::showSAS (std::string sas, bool verified) -{ - _debug ("Zrtp: SAS is: %s", sas.c_str()); - Manager::instance().getDbusManager()->getCallManager()->showSAS (_sipcall->getCallId(), sas, verified); -} - - -void -ZrtpSessionCallback::zrtpNotSuppOther() -{ - _debug ("Zrtp: Callee does not support ZRTP"); - Manager::instance().getDbusManager()->getCallManager()->zrtpNotSuppOther (_sipcall->getCallId()); -} - - -void -ZrtpSessionCallback::showMessage (GnuZrtpCodes::MessageSeverity sev, int32_t subCode) -{ - std::string* msg; - - if (sev == Info) { - msg = _infoMap[subCode]; - - if (msg != NULL) { - } - } - - if (sev == Warning) { - msg = _warningMap[subCode]; - - if (msg != NULL) { - } - } - - if (sev == Severe) { - msg = _severeMap[subCode]; - - if (msg != NULL) { - } - } - - - - if (sev == ZrtpError) { - if (subCode < 0) { // received an error packet from peer - subCode *= -1; - _debug ("Received an error packet from peer:"); - } else { - _debug ("Sent error packet to peer:"); - } - - msg = _zrtpMap[subCode]; - - if (msg != NULL) { - - } - } -} - -void -ZrtpSessionCallback::zrtpNegotiationFailed (MessageSeverity severity, int subCode) -{ - std::string* msg; - - if (severity == ZrtpError) { - if (subCode < 0) { // received an error packet from peer - subCode *= -1; - _debug ("Zrtp: Received error packet: "); - } else { - _debug ("Zrtp: Sent error packet: "); - } - - msg = _zrtpMap[subCode]; - - if (msg != NULL) { - _debug ("%s", msg->c_str()); - Manager::instance().getDbusManager()->getCallManager()->zrtpNegotiationFailed (_sipcall->getCallId(), *msg, "ZRTP"); - } - } else { - msg = _severeMap[subCode]; - _debug ("%s", msg->c_str()); - Manager::instance().getDbusManager()->getCallManager()->zrtpNegotiationFailed (_sipcall->getCallId(), *msg, "severe"); - } -} - -void -ZrtpSessionCallback::confirmGoClear() -{ - _debug ("Zrtp: Received go clear message. Until confirmation, ZRTP won't send any data"); - Manager::instance().getDbusManager()->getCallManager()->zrtpNotSuppOther (_sipcall->getCallId()); -} - -std::map<int32, std::string*>ZrtpSessionCallback::_infoMap; -std::map<int32, std::string*>ZrtpSessionCallback::_warningMap; -std::map<int32, std::string*>ZrtpSessionCallback::_severeMap; -std::map<int32, std::string*>ZrtpSessionCallback::_zrtpMap; - -bool ZrtpSessionCallback::_mapInitialized = false; -} - diff --git a/daemon/src/audio/audiortp/audio_rtp_factory.cpp b/daemon/src/audio/audiortp/audio_rtp_factory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ce37ce1f53c08fc342d4b60daff3beefc3173dd --- /dev/null +++ b/daemon/src/audio/audiortp/audio_rtp_factory.cpp @@ -0,0 +1,198 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. + * Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com> + * Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com> + * + * 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Additional permission under GNU GPL version 3 section 7: + * + * If you modify this program, or any covered work, by linking or + * combining it with the OpenSSL project's OpenSSL library (or a + * modified version of that library), containing parts covered by the + * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. + * grants you additional permission to convey the resulting work. + * Corresponding Source for a non-source form of such a combination + * shall include the source code for the parts of OpenSSL used as well + * as that of the covered work. + */ + + + +#include "audio_rtp_factory.h" +#include "audio_zrtp_session.h" +#include "audio_srtp_session.h" +#include "audio_symmetric_rtp_session.h" +#include "manager.h" +#include "sip/sdp.h" +#include "sip/sipcall.h" +#include "sip/sipaccount.h" +#include "sip/sdes_negotiator.h" + +namespace sfl { + +AudioRtpFactory::AudioRtpFactory(SIPCall *ca) : rtpSession_(NULL), + audioRtpThreadMutex_(), srtpEnabled_(false), + keyExchangeProtocol_(Symmetric), helloHashEnabled_(false), + remoteContext_(NULL), localContext_(NULL), ca_(ca) +{} + +AudioRtpFactory::~AudioRtpFactory() +{ + delete rtpSession_; +} + +void AudioRtpFactory::initAudioRtpConfig() +{ + if (rtpSession_ != NULL) + stop(); + + std::string accountId(Manager::instance().getAccountFromCall(ca_->getCallId())); + + SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(accountId)); + + if (account) { + srtpEnabled_ = account->getSrtpEnabled(); + std::string key(account->getSrtpKeyExchange()); + + if (key == "sdes") + keyExchangeProtocol_ = Sdes; + else if (key == "zrtp") + keyExchangeProtocol_ = Zrtp; + else + keyExchangeProtocol_ = Symmetric; + + helloHashEnabled_ = account->getZrtpHelloHash(); + } else { + srtpEnabled_ = false; + keyExchangeProtocol_ = Symmetric; + helloHashEnabled_ = false; + } +} + +void AudioRtpFactory::initAudioSymmetricRtpSession() +{ + ost::MutexLock m(audioRtpThreadMutex_); + + if (srtpEnabled_) { + std::string zidFilename(Manager::instance().voipPreferences.getZidFile()); + + switch (keyExchangeProtocol_) { + + case Zrtp: + rtpSession_ = new AudioZrtpSession(ca_, zidFilename); + // TODO: be careful with that. The hello hash is computed asynchronously. Maybe it's + // not even available at that point. + if (helloHashEnabled_) + ca_->getLocalSDP()->setZrtpHash(static_cast<AudioZrtpSession *>(rtpSession_)->getHelloHash()); + break; + + case Sdes: + rtpSession_ = new AudioSrtpSession(ca_); + break; + + default: + throw UnsupportedRtpSessionType("Unsupported Rtp Session Exception Type!"); + } + } else + rtpSession_ = new AudioSymmetricRtpSession(ca_); +} + +void AudioRtpFactory::start(AudioCodec* audiocodec) +{ + if (rtpSession_ == NULL) + throw AudioRtpFactoryException("AudioRtpFactory: Error: RTP session was null when trying to start audio thread"); + + if (rtpSession_->getAudioRtpType() == Sdes) + if (localContext_ and remoteContext_) + static_cast<AudioSrtpSession *>(rtpSession_)->restoreCryptoContext(localContext_, remoteContext_); + + if (rtpSession_->startRtpThread(audiocodec) != 0) + throw AudioRtpFactoryException("AudioRtpFactory: Error: Failed to start AudioZrtpSession thread"); +} + +void AudioRtpFactory::stop() +{ + ost::MutexLock mutex(audioRtpThreadMutex_); + + if (rtpSession_ == NULL) + return; + + if (rtpSession_->getAudioRtpType() == Sdes) { + localContext_ = static_cast<AudioSrtpSession*>(rtpSession_)->localCryptoCtx_; + remoteContext_ = static_cast<AudioSrtpSession*>(rtpSession_)->remoteCryptoCtx_; + } + + delete rtpSession_; + rtpSession_ = NULL; +} + +int AudioRtpFactory::getSessionMedia() +{ + if (rtpSession_ == NULL) + throw AudioRtpFactoryException("AudioRtpFactory: Error: RTP session was null when trying to get session media type"); + + return rtpSession_->getCodecPayloadType(); +} + +void AudioRtpFactory::updateSessionMedia(AudioCodec *audiocodec) +{ + if (rtpSession_ == NULL) + throw AudioRtpFactoryException("AudioRtpFactory: Error: rtpSession_ was null when trying to update IP address"); + + rtpSession_->updateSessionMedia(audiocodec); +} + +void AudioRtpFactory::updateDestinationIpAddress() +{ + if (rtpSession_) + rtpSession_->updateDestinationIpAddress(); +} + +sfl::AudioZrtpSession * AudioRtpFactory::getAudioZrtpSession() +{ + if (rtpSession_->getAudioRtpType() == Zrtp) + return static_cast<AudioZrtpSession *>(rtpSession_); + else + throw AudioRtpFactoryException("RTP: Error: rtpSession_ is NULL in getAudioZrtpSession"); +} + +void sfl::AudioRtpFactory::initLocalCryptoInfo() +{ + if (rtpSession_ && rtpSession_->getAudioRtpType() == Sdes) { + static_cast<AudioSrtpSession *>(rtpSession_)->initLocalCryptoInfo(); + ca_->getLocalSDP()->setLocalSdpCrypto(static_cast<AudioSrtpSession *>(rtpSession_)->getLocalCryptoInfo()); + } +} + +void AudioRtpFactory::setRemoteCryptoInfo(sfl::SdesNegotiator& nego) +{ + if (rtpSession_ && rtpSession_->getAudioRtpType() == Sdes) + static_cast<AudioSrtpSession *>(rtpSession_)->setRemoteCryptoInfo(nego); + else + throw AudioRtpFactoryException("RTP: Error: rtpSession_ is NULL in setRemoteCryptoInfo"); +} + +void AudioRtpFactory::setDtmfPayloadType(unsigned int payloadType) +{ + if (rtpSession_) + rtpSession_->setDtmfPayloadType(payloadType); +} + +void AudioRtpFactory::sendDtmfDigit(int digit) +{ + rtpSession_->putDtmfEvent(digit); +} + +} diff --git a/daemon/src/audio/audiortp/AudioRtpFactory.h b/daemon/src/audio/audiortp/audio_rtp_factory.h similarity index 76% rename from daemon/src/audio/audiortp/AudioRtpFactory.h rename to daemon/src/audio/audiortp/audio_rtp_factory.h index 35144c67da75d951b8358b90661793ad44117db2..9e8ca514ceb67216b48bb6408de2f1eb88d0f89d 100644 --- a/daemon/src/audio/audiortp/AudioRtpFactory.h +++ b/daemon/src/audio/audiortp/audio_rtp_factory.h @@ -28,47 +28,41 @@ * as that of the covered work. */ -#ifndef __SFL_AUDIO_RTP_FACTORY_H__ -#define __SFL_AUDIO_RTP_FACTORY_H__ +#ifndef __AUDIO_RTP_FACTORY_H__ +#define __AUDIO_RTP_FACTORY_H__ #include <stdexcept> #include <cc++/thread.h> -#include "account.h" // for typedef of std::string (std::string) #include <ccrtp/CryptoContext.h> -#include "AudioRtpSession.h" +#include "audio_rtp_session.h" +#include "noncopyable.h" -#include "sip/SdesNegotiator.h" +#include "sip/sdes_negotiator.h" class SdesNegotiator; class SIPCall; -class Account; -class SIPAccount; -namespace sfl -{ +namespace sfl { class AudioZrtpSession; class AudioCodec; -class UnsupportedRtpSessionType : public std::logic_error -{ +class UnsupportedRtpSessionType : public std::logic_error { public: - UnsupportedRtpSessionType (const std::string& msg = "") : std::logic_error (msg) {} + UnsupportedRtpSessionType(const std::string& msg = "") : std::logic_error(msg) {} }; -class AudioRtpFactoryException : public std::logic_error -{ +class AudioRtpFactoryException : public std::logic_error { public: - AudioRtpFactoryException (const std::string& msg = "") : std::logic_error (msg) {} + AudioRtpFactoryException(const std::string& msg = "") : std::logic_error(msg) {} }; -class AudioRtpFactory -{ +class AudioRtpFactory { public: AudioRtpFactory(SIPCall *ca); ~AudioRtpFactory(); - void initAudioRtpConfig (); + void initAudioRtpConfig(); /** * Lazy instantiation method. Create a new RTP session of a given @@ -76,14 +70,14 @@ class AudioRtpFactory * @param ca A pointer on a SIP call * @return A new AudioSymmetricRtpSession object */ - void initAudioSymmetricRtpSession (); + void initAudioSymmetricRtpSession(); /** * Start the audio rtp thread of the type specified in the configuration * file. initAudioSymmetricRtpSession must have been called prior to that. * @param None */ - void start (AudioCodec*); + void start(AudioCodec*); /** * Stop the audio rtp thread of the type specified in the configuration @@ -100,23 +94,23 @@ class AudioRtpFactory /** * Dynamically update session media */ - void updateSessionMedia (AudioCodec *); + void updateSessionMedia(AudioCodec *); /** * Update current RTP destination address with one stored in call * @param None */ - void updateDestinationIpAddress (void); + void updateDestinationIpAddress(); - bool isSdesEnabled (void) const { - return _srtpEnabled && _keyExchangeProtocol == sfl::Sdes; + bool isSdesEnabled() const { + return srtpEnabled_ and keyExchangeProtocol_ == sfl::Sdes; } /** * Manually set the srtpEnable option (usefull for RTP fallback) */ - void setSrtpEnabled (bool enable) { - _srtpEnabled = enable; + void setSrtpEnabled(bool enable) { + srtpEnabled_ = enable; } /** @@ -126,13 +120,13 @@ class AudioRtpFactory */ sfl::AudioZrtpSession * getAudioZrtpSession(); - void initLocalCryptoInfo (); + void initLocalCryptoInfo(); /** * Set remote cryptographic info. Should be called after negotiation in SDP * offer/answer session. */ - void setRemoteCryptoInfo (sfl::SdesNegotiator& nego); + void setRemoteCryptoInfo(sfl::SdesNegotiator& nego); void setDtmfPayloadType(unsigned int); @@ -142,29 +136,30 @@ class AudioRtpFactory * send the appropriate DTMF digit using this payload, discard coresponding data from mainbuffer and get * back the codec payload for further audio processing. */ - void sendDtmfDigit (int digit); + void sendDtmfDigit(int digit); private: - AudioRtpSession *_rtpSession; - ost::Mutex _audioRtpThreadMutex; + NON_COPYABLE(AudioRtpFactory); + AudioRtpSession *rtpSession_; + ost::Mutex audioRtpThreadMutex_; // Field used when initializinga udio rtp session // May be set manually or from config using initAudioRtpConfig - bool _srtpEnabled; + bool srtpEnabled_; // Field used when initializinga udio rtp session // May be set manually or from config using initAudioRtpConfig - RtpMethod _keyExchangeProtocol; + RtpMethod keyExchangeProtocol_; // Field used when initializinga udio rtp session // May be set manually or from config using initAudioRtpConfig - bool _helloHashEnabled; + bool helloHashEnabled_; /** Remote srtp crypto context to be set into incoming data queue. */ - ost::CryptoContext *remoteContext; + ost::CryptoContext *remoteContext_; /** Local srtp crypto context to be set into outgoing data queue. */ - ost::CryptoContext *localContext; + ost::CryptoContext *localContext_; SIPCall *ca_; }; diff --git a/daemon/src/audio/audiortp/audio_rtp_record_handler.cpp b/daemon/src/audio/audiortp/audio_rtp_record_handler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ce03be48914e6902196162e5b23d51cba85c0d1 --- /dev/null +++ b/daemon/src/audio/audiortp/audio_rtp_record_handler.cpp @@ -0,0 +1,225 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. + * Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com> + * + * 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Additional permission under GNU GPL version 3 section 7: + * + * If you modify this program, or any covered work, by linking or + * combining it with the OpenSSL project's OpenSSL library (or a + * modified version of that library), containing parts covered by the + * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. + * grants you additional permission to convey the resulting work. + * Corresponding Source for a non-source form of such a combination + * shall include the source code for the parts of OpenSSL used as well + * as that of the covered work. + */ + +#include "audio_rtp_record_handler.h" +#include <fstream> + +#include "sip/sipcall.h" +#include "audio/audiolayer.h" +#include "manager.h" + +namespace sfl { + +static const SFLDataFormat initFadeinFactor = 32000; + +AudioRtpRecord::AudioRtpRecord() : + audioCodec_(0) + , audioCodecMutex_() + , codecPayloadType_(0) + , hasDynamicPayloadType_(false) + , converter_(0) + , codecSampleRate_(0) + , codecFrameSize_(0) + , converterSamplingRate_(0) + , dtmfQueue_() + , micAmplFactor_(initFadeinFactor) + , noiseSuppress_(0) + , audioProcessMutex_() + , callId_("") + , dtmfPayloadType_(101) // same as Asterisk +{ + memset(decData_, 0x0, sizeof decData_); + memset(resampledData_, 0x0, sizeof resampledData_); + memset(encodedData_, 0x0, sizeof encodedData_); +} + +AudioRtpRecord::~AudioRtpRecord() +{ + delete converter_; + delete audioCodec_; + delete noiseSuppress_; +} + + +AudioRtpRecordHandler::AudioRtpRecordHandler(SIPCall *ca) : audioRtpRecord_(), id_(ca->getCallId()), echoCanceller(ca->getMemoryPool()), gainController(8000, -10.0) +{} + + +AudioRtpRecordHandler::~AudioRtpRecordHandler() {} + +void AudioRtpRecordHandler::setRtpMedia(AudioCodec* audioCodec) +{ + ost::MutexLock lock(audioRtpRecord_.audioCodecMutex_); + + delete audioRtpRecord_.audioCodec_; + // Set varios codec info to reduce indirection + audioRtpRecord_.audioCodec_ = audioCodec; + audioRtpRecord_.codecPayloadType_ = audioCodec->getPayloadType(); + audioRtpRecord_.codecSampleRate_ = audioCodec->getClockRate(); + audioRtpRecord_.codecFrameSize_ = audioCodec->getFrameSize(); + audioRtpRecord_.hasDynamicPayloadType_ = audioCodec->hasDynamicPayload(); +} + +void AudioRtpRecordHandler::initBuffers() +{ + // Set sampling rate, main buffer choose the highest one + Manager::instance().audioSamplingRateChanged(audioRtpRecord_.codecSampleRate_); + + // initialize SampleRate converter using AudioLayer's sampling rate + // (internal buffers initialized with maximal sampling rate and frame size) + delete audioRtpRecord_.converter_; + audioRtpRecord_.converter_ = new SamplerateConverter(getCodecSampleRate()); +} + +void AudioRtpRecordHandler::initNoiseSuppress() +{ + ost::MutexLock lock(audioRtpRecord_.audioProcessMutex_); + delete audioRtpRecord_.noiseSuppress_; + audioRtpRecord_.noiseSuppress_ = new NoiseSuppress(getCodecFrameSize(), getCodecSampleRate()); +} + +void AudioRtpRecordHandler::putDtmfEvent(int digit) +{ + audioRtpRecord_.dtmfQueue_.push_back(digit); +} + +#ifdef DUMP_PROCESS_DATA_ENCODE +std::ofstream teststream("test_process_data_encode.raw"); +#endif + +int AudioRtpRecordHandler::processDataEncode() +{ + SFLDataFormat *micData = audioRtpRecord_.decData_; + unsigned char *micDataEncoded = audioRtpRecord_.encodedData_; + SFLDataFormat *micDataConverted = audioRtpRecord_.resampledData_; + + int codecSampleRate = getCodecSampleRate(); + int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); + + double resampleFactor = (double)mainBufferSampleRate / codecSampleRate; + + // compute nb of byte to get coresponding to 1 audio frame + int samplesToGet = resampleFactor * getCodecFrameSize(); + int bytesToGet = samplesToGet * sizeof(SFLDataFormat); + + if (Manager::instance().getMainBuffer()->availForGet(id_) < bytesToGet) + return 0; + + int bytes = Manager::instance().getMainBuffer()->getData(micData, bytesToGet, id_); + + if (bytes != bytesToGet) { + ERROR("%s : asked %d bytes from mainbuffer, got %d", __PRETTY_FUNCTION__, bytesToGet, bytes); + return 0; + } + + int samples = bytesToGet / sizeof(SFLDataFormat); + + fadeIn(micData, samples, &audioRtpRecord_.micAmplFactor_); + + if (Manager::instance().getEchoCancelState()) + echoCanceller.getData(micData); + +#ifdef DUMP_PROCESS_DATA_ENCODE + teststream.write(reinterpret_cast<char *>(micData), bytesToGet); +#endif + + SFLDataFormat *out = micData; + + if (codecSampleRate != mainBufferSampleRate) { + out = micDataConverted; + audioRtpRecord_.converter_->resample(micData, micDataConverted, codecSampleRate, mainBufferSampleRate, samplesToGet); + } + + if (Manager::instance().audioPreference.getNoiseReduce()) { + ost::MutexLock lock(audioRtpRecord_.audioProcessMutex_); + audioRtpRecord_.noiseSuppress_->process(micData, getCodecFrameSize()); + } + + int compSize; + { + ost::MutexLock lock(audioRtpRecord_.audioCodecMutex_); + compSize = audioRtpRecord_.audioCodec_->encode(micDataEncoded, out, getCodecFrameSize()); + } + + return compSize; +} + +void AudioRtpRecordHandler::processDataDecode(unsigned char *spkrData, unsigned int size, int payloadType) +{ + if (getCodecPayloadType() != payloadType) + return; + + int codecSampleRate = getCodecSampleRate(); + + SFLDataFormat *spkrDataDecoded = audioRtpRecord_.decData_; + SFLDataFormat *spkrDataConverted = audioRtpRecord_.resampledData_; + + int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); + + int inSamples; + { + ost::MutexLock lock(audioRtpRecord_.audioCodecMutex_); + // Return the size of data in samples + inSamples = audioRtpRecord_.audioCodec_->decode(spkrDataDecoded , spkrData , size); + } + + fadeIn(spkrDataDecoded, inSamples, &audioRtpRecord_.micAmplFactor_); + + // Normalize incomming signal + gainController.process(spkrDataDecoded, inSamples); + + SFLDataFormat *out = spkrDataDecoded; + int outSamples = inSamples; + + // test if resampling is required + if (codecSampleRate != mainBufferSampleRate) { + // Do sample rate conversion + outSamples = ((float) inSamples * ((float) mainBufferSampleRate / (float) codecSampleRate)); + audioRtpRecord_.converter_->resample(spkrDataDecoded, spkrDataConverted, codecSampleRate, mainBufferSampleRate, inSamples); + out = spkrDataConverted; + } + + if (Manager::instance().getEchoCancelState()) + echoCanceller.putData(out, outSamples); + + Manager::instance().getMainBuffer()->putData(out, outSamples * sizeof(SFLDataFormat), id_); +} + +void AudioRtpRecordHandler::fadeIn(SFLDataFormat *audio, int size, SFLDataFormat *factor) +{ + // if factor reach 0, this function should have no effect + if (*factor <= 0) + return; + + while (size) + audio[--size] /= *factor; + + *factor /= FADEIN_STEP_SIZE; +} +} diff --git a/daemon/src/audio/audiortp/AudioRtpRecordHandler.h b/daemon/src/audio/audiortp/audio_rtp_record_handler.h similarity index 60% rename from daemon/src/audio/audiortp/AudioRtpRecordHandler.h rename to daemon/src/audio/audiortp/audio_rtp_record_handler.h index b9897c05c898ee5fe816ebb8a46fe5fcfc8df4d7..9012049a133d1b279448835ba31e3c5d7bcb4a75 100644 --- a/daemon/src/audio/audiortp/AudioRtpRecordHandler.h +++ b/daemon/src/audio/audiortp/audio_rtp_record_handler.h @@ -27,8 +27,8 @@ * as that of the covered work. */ -#ifndef AUDIORTPRECORDHANDLER_H_ -#define AUDIORTPRECORDHANDLER_H_ +#ifndef AUDIO_RTP_RECORD_HANDLER_H__ +#define AUDIO_RTP_RECORD_HANDLER_H__ #include <cstddef> using std::ptrdiff_t; @@ -37,16 +37,15 @@ using std::ptrdiff_t; #include <list> class SIPCall; +#include "noncopyable.h" #include "audio/codecs/audiocodec.h" #include "audio/samplerateconverter.h" #include "audio/noisesuppress.h" #include "audio/speexechocancel.h" #include "audio/echosuppress.h" #include "audio/gaincontrol.h" -#include "managerimpl.h" -namespace sfl -{ +namespace sfl { // Frequency (in packet number) #define RTP_TIMESTAMP_RESET_FREQ 100 @@ -65,9 +64,9 @@ static const int g722RtpClockRate = 8000; static const int g722RtpTimeincrement = 160; inline uint32 -timeval2microtimeout (const timeval& t) +timeval2microtimeout(const timeval& t) { - return ( (t.tv_sec * 1000000ul) + t.tv_usec); + return ((t.tv_sec * 1000000ul) + t.tv_usec); } /** @@ -75,35 +74,34 @@ timeval2microtimeout (const timeval& t) * resample, process, and packetize audio streams. This class should not be * handled directly. Use AudioRtpRecorrdHandeler */ -class AudioRtpRecord -{ +class AudioRtpRecord { public: - AudioRtpRecord (); + AudioRtpRecord(); ~AudioRtpRecord(); - AudioCodec *_audioCodec; - ost::Mutex audioCodecMutex; - int _codecPayloadType; - bool _hasDynamicPayloadType; - SFLDataFormat decData[DEC_BUFFER_SIZE]; - SFLDataFormat resampledData[DEC_BUFFER_SIZE]; - unsigned char encodedData[DEC_BUFFER_SIZE]; - SamplerateConverter *_converter; - int _codecSampleRate; - int _codecFrameSize; - int _converterSamplingRate; - std::list<int> _dtmfQueue; - SFLDataFormat _micAmplFactor; - NoiseSuppress *_noiseSuppress; - ost::Mutex audioProcessMutex; - std::string _callId; - unsigned int _dtmfPayloadType; - + AudioCodec *audioCodec_; + ost::Mutex audioCodecMutex_; + int codecPayloadType_; + bool hasDynamicPayloadType_; + SFLDataFormat decData_[DEC_BUFFER_SIZE]; + SFLDataFormat resampledData_[DEC_BUFFER_SIZE]; + unsigned char encodedData_[DEC_BUFFER_SIZE]; + SamplerateConverter *converter_; + int codecSampleRate_; + int codecFrameSize_; + int converterSamplingRate_; + std::list<int> dtmfQueue_; + SFLDataFormat micAmplFactor_; + NoiseSuppress *noiseSuppress_; + ost::Mutex audioProcessMutex_; + std::string callId_; + unsigned int dtmfPayloadType_; + private: + NON_COPYABLE(AudioRtpRecord); }; -class AudioRtpRecordHandler -{ +class AudioRtpRecordHandler { public: AudioRtpRecordHandler(SIPCall *); virtual ~AudioRtpRecordHandler(); @@ -111,79 +109,74 @@ class AudioRtpRecordHandler /** * Set rtp media for this session */ + void setRtpMedia(AudioCodec* audioCodec); - void setRtpMedia (AudioCodec* audioCodec); - - AudioCodec *getAudioCodec (void) const { - return _audioRtpRecord._audioCodec; + AudioCodec *getAudioCodec() const { + return audioRtpRecord_.audioCodec_; } - int getCodecPayloadType (void) const { - return _audioRtpRecord._codecPayloadType; + int getCodecPayloadType() const { + return audioRtpRecord_.codecPayloadType_; } - int getCodecSampleRate (void) const { - return _audioRtpRecord._codecSampleRate; + int getCodecSampleRate() const { + return audioRtpRecord_.codecSampleRate_; } - int getCodecFrameSize (void) const { - return _audioRtpRecord._codecFrameSize; + int getCodecFrameSize() const { + return audioRtpRecord_.codecFrameSize_; } - bool getHasDynamicPayload (void) const { - return _audioRtpRecord._hasDynamicPayloadType; + bool getHasDynamicPayload() const { + return audioRtpRecord_.hasDynamicPayloadType_; } - int DtmfPending (void) const { - return _audioRtpRecord._dtmfQueue.size() > 0; + int DtmfPending() const { + return audioRtpRecord_.dtmfQueue_.size() > 0; } - const unsigned char *getMicDataEncoded (void) const { - return _audioRtpRecord.encodedData; + const unsigned char *getMicDataEncoded() const { + return audioRtpRecord_.encodedData_; } - void initBuffers (void); + void initBuffers(); - void initNoiseSuppress (void); + void initNoiseSuppress(); /** * Encode audio data from mainbuffer */ - int processDataEncode (void); + int processDataEncode(); /** * Decode audio data received from peer */ - void processDataDecode (unsigned char * spkrData, unsigned int size, int payloadType); + void processDataDecode(unsigned char * spkrData, unsigned int size, int payloadType); /** * Ramp In audio data to avoid audio click from peer */ - void fadeIn (SFLDataFormat *audio, int size, SFLDataFormat *factor); + void fadeIn(SFLDataFormat *audio, int size, SFLDataFormat *factor); void setDtmfPayloadType(unsigned int payloadType) { - _audioRtpRecord._dtmfPayloadType = payloadType; + audioRtpRecord_.dtmfPayloadType_ = payloadType; } - unsigned int getDtmfPayloadType(void) const { - return _audioRtpRecord._dtmfPayloadType; + unsigned int getDtmfPayloadType() const { + return audioRtpRecord_.dtmfPayloadType_; } - void putDtmfEvent (int digit); + void putDtmfEvent(int digit); protected: - - AudioRtpRecord _audioRtpRecord; + AudioRtpRecord audioRtpRecord_; private: const std::string id_; - EchoSuppress echoCanceller; - GainControl gainController; }; - } -#endif /* AUDIORTPRECORD_H_ */ +#endif // AUDIO_RTP_RECORD_HANDLER_H__ diff --git a/daemon/src/audio/audiortp/audio_rtp_session.cpp b/daemon/src/audio/audiortp/audio_rtp_session.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c898441773cb0dff2e2a65434ad742c7f43b7d1 --- /dev/null +++ b/daemon/src/audio/audiortp/audio_rtp_session.cpp @@ -0,0 +1,269 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. + * Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com> + * Author: Alexandre Bourget <alexandre.bourget@savoirfairelinux.com> + * Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com> + * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> + * Author: Yan Morin <yan.morin@savoirfairelinux.com> + * Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com> + * + * 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Additional permission under GNU GPL version 3 section 7: + * + * If you modify this program, or any covered work, by linking or + * combining it with the OpenSSL project's OpenSSL library (or a + * modified version of that library), containing parts covered by the + * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. + * grants you additional permission to convey the resulting work. + * Corresponding Source for a non-source form of such a combination + * shall include the source code for the parts of OpenSSL used as well + * as that of the covered work. + */ + +#include "audio_rtp_session.h" +#include "audio_symmetric_rtp_session.h" + +#include "sip/sdp.h" +#include "sip/sipcall.h" +#include "audio/audiolayer.h" +#include <ccrtp/rtp.h> +#include <ccrtp/oqueue.h> +#include "manager.h" + +namespace sfl { +AudioRtpSession::AudioRtpSession(SIPCall * sipcall, RtpMethod type, ost::RTPDataQueue *queue, ost::Thread *thread) : + AudioRtpRecordHandler(sipcall) + , ca_(sipcall) + , type_(type) + , remote_ip_() + , remote_port_(0) + , timestamp_(0) + , timestampIncrement_(0) + , timestampCount_(0) + , isStarted_(false) + , queue_(queue) + , thread_(thread) +{ + assert(ca_); + queue_->setTypeOfService(ost::RTPDataQueue::tosEnhanced); +} + +AudioRtpSession::~AudioRtpSession() +{ + queue_->disableStack(); +} + +void AudioRtpSession::updateSessionMedia(AudioCodec *audioCodec) +{ + int lastSamplingRate = audioRtpRecord_.codecSampleRate_; + + setSessionMedia(audioCodec); + + Manager::instance().audioSamplingRateChanged(audioRtpRecord_.codecSampleRate_); + + if (lastSamplingRate != audioRtpRecord_.codecSampleRate_) { + DEBUG("AudioRtpSession: Update noise suppressor with sampling rate %d and frame size %d", getCodecSampleRate(), getCodecFrameSize()); + initNoiseSuppress(); + } + +} + +void AudioRtpSession::setSessionMedia(AudioCodec *audioCodec) +{ + setRtpMedia(audioCodec); + + // store codec info locally + int payloadType = getCodecPayloadType(); + int frameSize = getCodecFrameSize(); + int smplRate = getCodecSampleRate(); + bool dynamic = getHasDynamicPayload(); + + // G722 requires timestamp to be incremented at 8kHz + if (payloadType == g722PayloadType) + timestampIncrement_ = g722RtpTimeincrement; + else + timestampIncrement_ = frameSize; + + DEBUG("AudioRptSession: Codec payload: %d", payloadType); + DEBUG("AudioSymmetricRtpSession: Codec sampling rate: %d", smplRate); + DEBUG("AudioSymmetricRtpSession: Codec frame size: %d", frameSize); + DEBUG("AudioSymmetricRtpSession: RTP timestamp increment: %d", timestampIncrement_); + + if (payloadType == g722PayloadType) { + DEBUG("AudioSymmetricRtpSession: Setting G722 payload format"); + queue_->setPayloadFormat(ost::DynamicPayloadFormat((ost::PayloadType) payloadType, g722RtpClockRate)); + } else { + if (dynamic) { + DEBUG("AudioSymmetricRtpSession: Setting dynamic payload format"); + queue_->setPayloadFormat(ost::DynamicPayloadFormat((ost::PayloadType) payloadType, smplRate)); + } else { + DEBUG("AudioSymmetricRtpSession: Setting static payload format"); + queue_->setPayloadFormat(ost::StaticPayloadFormat((ost::StaticPayloadType) payloadType)); + } + } + + if (type_ != Zrtp) + ca_->setRecordingSmplRate(getCodecSampleRate()); +} + +void AudioRtpSession::sendDtmfEvent() +{ + ost::RTPPacket::RFC2833Payload payload; + + payload.event = audioRtpRecord_.dtmfQueue_.front(); + payload.ebit = false; // end of event bit + payload.rbit = false; // reserved bit + payload.duration = 1; // duration for this event + + audioRtpRecord_.dtmfQueue_.pop_front(); + + DEBUG("AudioRtpSession: Send RTP Dtmf (%d)", payload.event); + + timestamp_ += (type_ == Zrtp) ? 160 : timestampIncrement_; + + // discard equivalent size of audio + processDataEncode(); + + // change Payload type for DTMF payload + queue_->setPayloadFormat(ost::DynamicPayloadFormat((ost::PayloadType) getDtmfPayloadType(), 8000)); + + queue_->setMark(true); + queue_->sendImmediate(timestamp_, (const unsigned char *)(&payload), sizeof(payload)); + queue_->setMark(false); + + // get back the payload to audio + queue_->setPayloadFormat(ost::StaticPayloadFormat((ost::StaticPayloadType) getCodecPayloadType())); +} + + +void AudioRtpSession::receiveSpeakerData() +{ + const ost::AppDataUnit* adu = queue_->getData(queue_->getFirstTimestamp()); + + if (!adu) + return; + + unsigned char* spkrDataIn = (unsigned char*) adu->getData(); // data in char + unsigned int size = adu->getSize(); // size in char + + // DTMF over RTP, size must be over 4 in order to process it as voice data + if (size > 4) + processDataDecode(spkrDataIn, size, adu->getType()); + + delete adu; +} + + + +void AudioRtpSession::sendMicData() +{ + int compSize = processDataEncode(); + + // if no data return + if (!compSize) + return; + + // Increment timestamp for outgoing packet + timestamp_ += timestampIncrement_; + + if (type_ == Zrtp) + queue_->putData(timestamp_, getMicDataEncoded(), compSize); + + // putData put the data on RTP queue, sendImmediate bypass this queue + queue_->sendImmediate(timestamp_, getMicDataEncoded(), compSize); +} + + +void AudioRtpSession::setSessionTimeouts() +{ + DEBUG("AudioRtpSession: Set session scheduling timeout (%d) and expireTimeout (%d)", sfl::schedulingTimeout, sfl::expireTimeout); + + queue_->setSchedulingTimeout(sfl::schedulingTimeout); + queue_->setExpireTimeout(sfl::expireTimeout); +} + +void AudioRtpSession::setDestinationIpAddress() +{ + INFO("AudioRtpSession: Setting IP address for the RTP session"); + + // Store remote ip in case we would need to forget current destination + remote_ip_ = ost::InetHostAddress(ca_->getLocalSDP()->getRemoteIP().c_str()); + + if (!remote_ip_) { + WARN("AudioRtpSession: Target IP address (%s) is not correct!", + ca_->getLocalSDP()->getRemoteIP().data()); + return; + } + + // Store remote port in case we would need to forget current destination + remote_port_ = (unsigned short) ca_->getLocalSDP()->getRemoteAudioPort(); + + INFO("AudioRtpSession: New remote address for session: %s:%d", + ca_->getLocalSDP()->getRemoteIP().data(), remote_port_); + + if (!queue_->addDestination(remote_ip_, remote_port_)) { + WARN("AudioRtpSession: Can't add new destination to session!"); + return; + } +} + +void AudioRtpSession::updateDestinationIpAddress() +{ + DEBUG("AudioRtpSession: Update destination ip address"); + + // Destination address are stored in a list in ccrtp + // This method remove the current destination entry + + if (!queue_->forgetDestination(remote_ip_, remote_port_, remote_port_ + 1)) + DEBUG("AudioRtpSession: Did not remove previous destination"); + + // new destination is stored in call + // we just need to recall this method + setDestinationIpAddress(); +} + + +int AudioRtpSession::startRtpThread(AudioCodec* audiocodec) +{ + if (isStarted_) + return 0; + + DEBUG("AudioSymmetricRtpSession: Starting main thread"); + + isStarted_ = true; + setSessionTimeouts(); + setSessionMedia(audiocodec); + initBuffers(); + initNoiseSuppress(); + + queue_->enableStack(); + int ret = thread_->start(); + + if (type_ == Zrtp) + return ret; + + AudioSymmetricRtpSession *self = dynamic_cast<AudioSymmetricRtpSession*>(this); + assert(self); + return self->startSymmetricRtpThread(); +} + + +bool AudioRtpSession::onRTPPacketRecv(ost::IncomingRTPPkt&) +{ + receiveSpeakerData(); + return true; +} + +} diff --git a/daemon/src/audio/audiortp/AudioRtpSession.h b/daemon/src/audio/audiortp/audio_rtp_session.h similarity index 78% rename from daemon/src/audio/audiortp/AudioRtpSession.h rename to daemon/src/audio/audiortp/audio_rtp_session.h index 0a609646fc52e42ba2c0e398542c4caf1fff5ed0..58031f9aba6f1a2b8e715c904594ed66ccf30d99 100644 --- a/daemon/src/audio/audiortp/AudioRtpSession.h +++ b/daemon/src/audio/audiortp/audio_rtp_session.h @@ -34,15 +34,15 @@ #ifndef __SFL_AUDIO_RTP_SESSION_H__ #define __SFL_AUDIO_RTP_SESSION_H__ -#include "AudioRtpRecordHandler.h" +#include "audio_rtp_record_handler.h" #include <audio/codecs/audiocodec.h> #include <ccrtp/rtp.h> #include <ccrtp/formats.h> +#include "noncopyable.h" class SIPCall; -namespace sfl -{ +namespace sfl { class AudioCodec; @@ -54,29 +54,30 @@ typedef enum RtpMethod { } RtpMethod; -class AudioRtpSession : public AudioRtpRecordHandler -{ +class AudioRtpSession : public AudioRtpRecordHandler { public: /** * Constructor * @param sipcall The pointer on the SIP call */ - AudioRtpSession (SIPCall* sipcall, RtpMethod type, ost::RTPDataQueue *queue, ost::Thread *thread); + AudioRtpSession(SIPCall* sipcall, RtpMethod type, ost::RTPDataQueue *queue, ost::Thread *thread); virtual ~AudioRtpSession(); - RtpMethod getAudioRtpType() { return _type; } - void updateSessionMedia (AudioCodec *audioCodec); + RtpMethod getAudioRtpType() { + return type_; + } + void updateSessionMedia(AudioCodec *audioCodec); - int startRtpThread (AudioCodec*); + int startRtpThread(AudioCodec*); /** * Used mostly when receiving a reinvite */ - void updateDestinationIpAddress (void); + void updateDestinationIpAddress(); protected: - bool onRTPPacketRecv (ost::IncomingRTPPkt&); + bool onRTPPacketRecv(ost::IncomingRTPPkt&); /** * Send DTMF over RTP (RFC2833). The timestamp and sequence number must be @@ -84,72 +85,71 @@ class AudioRtpSession : public AudioRtpRecordHandler * send the appropriate DTMF digit using this payload, discard coresponding data from mainbuffer and get * back the codec payload for further audio processing. */ - void sendDtmfEvent (); + void sendDtmfEvent(); /** * Send encoded data to peer */ void sendMicData(); - SIPCall *_ca; + SIPCall *ca_; - RtpMethod _type; + RtpMethod type_; private: + NON_COPYABLE(AudioRtpSession); /** * Set the audio codec for this RTP session */ - void setSessionMedia (AudioCodec*); + void setSessionMedia(AudioCodec*); /** * Set RTP Sockets send/receive timeouts */ - void setSessionTimeouts (void); + void setSessionTimeouts(); /** * Retreive destination address for this session. Stored in CALL */ - void setDestinationIpAddress (void); - + void setDestinationIpAddress(); /** * Receive data from peer */ - void receiveSpeakerData (); + void receiveSpeakerData(); // Main destination address for this rtp session. // Stored in case or reINVITE, which may require to forget // this destination and update a new one. - ost::InetHostAddress _remote_ip; + ost::InetHostAddress remote_ip_; // Main destination port for this rtp session. // Stored in case reINVITE, which may require to forget // this destination and update a new one - unsigned short _remote_port; + unsigned short remote_port_; /** * Timestamp for this session */ - int _timestamp; + int timestamp_; /** * Timestamp incrementation value based on codec period length (framesize) * except for G722 which require a 8 kHz incrementation. */ - int _timestampIncrement; + int timestampIncrement_; /** * Timestamp reset frequency specified in number of packet sent */ - short _timestampCount; - + short timestampCount_; - bool _isStarted; + bool isStarted_; - ost::RTPDataQueue *_queue; + ost::RTPDataQueue *queue_; - ost::Thread *_thread; + ost::Thread *thread_; }; } diff --git a/daemon/src/audio/audiortp/AudioSrtpSession.cpp b/daemon/src/audio/audiortp/audio_srtp_session.cpp similarity index 50% rename from daemon/src/audio/audiortp/AudioSrtpSession.cpp rename to daemon/src/audio/audiortp/audio_srtp_session.cpp index d26b7304e887e26086e3f33873af7a0e1cd6e31e..0f3bf23c0983d40b6461602b4997a2a5feef7490 100644 --- a/daemon/src/audio/audiortp/AudioSrtpSession.cpp +++ b/daemon/src/audio/audiortp/audio_srtp_session.cpp @@ -27,7 +27,7 @@ * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ -#include "AudioSrtpSession.h" +#include "audio_srtp_session.h" #include "sip/sipcall.h" @@ -42,32 +42,31 @@ #include <cstring> #include <cerrno> -namespace sfl +namespace sfl { + +AudioSrtpSession::AudioSrtpSession(SIPCall * sipcall) : + AudioSymmetricRtpSession(sipcall), + remoteCryptoCtx_(NULL), + localCryptoCtx_(NULL), + localCryptoSuite_(0), + remoteCryptoSuite_(0), + localMasterKeyLength_(0), + localMasterSaltLength_(0), + remoteMasterKeyLength_(0), + remoteMasterSaltLength_(0), + remoteOfferIsSet_(false) { - -AudioSrtpSession::AudioSrtpSession (SIPCall * sipcall) : - AudioSymmetricRtpSession (sipcall), - _remoteCryptoCtx (NULL), - _localCryptoCtx (NULL), - _localCryptoSuite (0), - _remoteCryptoSuite (0), - _localMasterKeyLength (0), - _localMasterSaltLength (0), - _remoteMasterKeyLength (0), - _remoteMasterSaltLength (0), - _remoteOfferIsSet (false) -{ - this->_type = Sdes; + type_ = Sdes; } AudioSrtpSession::~AudioSrtpSession() { - _debug("AudioSrtp: Destroy audio srtp session"); + DEBUG("AudioSrtp: Destroy audio srtp session"); } void AudioSrtpSession::initLocalCryptoInfo() { - _debug ("AudioSrtp: Set cryptographic info for this rtp session"); + DEBUG("AudioSrtp: Set cryptographic info for this rtp session"); // Initialize local Crypto context initializeLocalMasterKey(); @@ -75,16 +74,15 @@ void AudioSrtpSession::initLocalCryptoInfo() initializeLocalCryptoContext(); // Set local crypto context in ccrtp - _localCryptoCtx->deriveSrtpKeys (0); - - setOutQueueCryptoContext (_localCryptoCtx); + localCryptoCtx_->deriveSrtpKeys(0); + setOutQueueCryptoContext(localCryptoCtx_); } std::vector<std::string> AudioSrtpSession::getLocalCryptoInfo() { - _debug ("AudioSrtp: Get Cryptographic info from this rtp session"); + DEBUG("AudioSrtp: Get Cryptographic info from this rtp session"); std::vector<std::string> crypto_vector; @@ -92,7 +90,7 @@ std::vector<std::string> AudioSrtpSession::getLocalCryptoInfo() // cryptographic context tagged 1, 2, 3... std::string tag = "1"; - std::string crypto_suite = sfl::CryptoSuites[_localCryptoSuite].name; + std::string crypto_suite = sfl::CryptoSuites[localCryptoSuite_].name; // srtp keys formated as the following as the following // inline:keyParameters|keylifetime|MasterKeyIdentifier @@ -102,150 +100,138 @@ std::vector<std::string> AudioSrtpSession::getLocalCryptoInfo() // srtp_keys.append("|2^20|1:32"); // generate crypto attribute - std::string crypto_attr = tag.append (" "); - crypto_attr += crypto_suite.append (" "); + std::string crypto_attr = tag.append(" "); + crypto_attr += crypto_suite.append(" "); crypto_attr += srtp_keys; - _debug ("%s", crypto_attr.c_str()); + DEBUG("%s", crypto_attr.c_str()); - crypto_vector.push_back (crypto_attr); + crypto_vector.push_back(crypto_attr); return crypto_vector; } - -void AudioSrtpSession::setRemoteCryptoInfo (sfl::SdesNegotiator& nego) +void AudioSrtpSession::setRemoteCryptoInfo(sfl::SdesNegotiator& nego) { - if (!_remoteOfferIsSet) { - - _debug ("%s", nego.getKeyInfo().c_str()); + if (not remoteOfferIsSet_) { + DEBUG("%s", nego.getKeyInfo().c_str()); // Use second crypto suite if key length is 32 bit, default is 80; if (nego.getAuthTagLength() == "32") { - _localCryptoSuite = 1; - _remoteCryptoSuite = 1; + localCryptoSuite_ = 1; + remoteCryptoSuite_ = 1; } // decode keys - unBase64ConcatenatedKeys (nego.getKeyInfo()); + unBase64ConcatenatedKeys(nego.getKeyInfo()); // init crypto content in Srtp session initializeRemoteCryptoContext(); - setInQueueCryptoContext (_remoteCryptoCtx); + setInQueueCryptoContext(remoteCryptoCtx_); // initLocalCryptoInfo(); - _remoteOfferIsSet = true; + remoteOfferIsSet_ = true; } - } - -void AudioSrtpSession::initializeLocalMasterKey (void) +void AudioSrtpSession::initializeLocalMasterKey() { - _debug ("AudioSrtp: Init local master key"); + DEBUG("AudioSrtp: Init local master key"); // @TODO key may have different length depending on cipher suite - _localMasterKeyLength = sfl::CryptoSuites[_localCryptoSuite].masterKeyLength / 8; + localMasterKeyLength_ = sfl::CryptoSuites[localCryptoSuite_].masterKeyLength / 8; - _debug ("AudioSrtp: Local master key length %d", _localMasterKeyLength); + DEBUG("AudioSrtp: Local master key length %d", localMasterKeyLength_); // Allocate memory for key - unsigned char *random_key = new unsigned char[_localMasterKeyLength]; + unsigned char *random_key = new unsigned char[localMasterKeyLength_]; // Generate ryptographically strong pseudo-random bytes int err; - if ( (err = RAND_bytes (random_key, _localMasterKeyLength)) != 1) - _debug ("Error occured while generating cryptographically strong pseudo-random key"); - - memcpy (_localMasterKey, random_key, _localMasterKeyLength); + if ((err = RAND_bytes(random_key, localMasterKeyLength_)) != 1) + DEBUG("Error occured while generating cryptographically strong pseudo-random key"); + memcpy(localMasterKey_, random_key, localMasterKeyLength_); } - -void AudioSrtpSession::initializeLocalMasterSalt (void) +void AudioSrtpSession::initializeLocalMasterSalt() { - // @TODO key may have different length depending on cipher suite - _localMasterSaltLength = sfl::CryptoSuites[_localCryptoSuite].masterSaltLength / 8; + localMasterSaltLength_ = sfl::CryptoSuites[localCryptoSuite_].masterSaltLength / 8; // Allocate memory for key - unsigned char *random_key = new unsigned char[_localMasterSaltLength]; + unsigned char *random_key = new unsigned char[localMasterSaltLength_]; - _debug ("AudioSrtp: Local master salt length %d", _localMasterSaltLength); + DEBUG("AudioSrtp: Local master salt length %d", localMasterSaltLength_); // Generate ryptographically strong pseudo-random bytes int err; - if ( (err = RAND_bytes (random_key, _localMasterSaltLength)) != 1) - _debug ("Error occured while generating cryptographically strong pseudo-random key"); - - memcpy (_localMasterSalt, random_key, _localMasterSaltLength); - + if ((err = RAND_bytes(random_key, localMasterSaltLength_)) != 1) + DEBUG("Error occured while generating cryptographically strong pseudo-random key"); + memcpy(localMasterSalt_, random_key, localMasterSaltLength_); } - std::string AudioSrtpSession::getBase64ConcatenatedKeys() { - _debug ("AudioSrtp: Get base64 concatenated keys"); + DEBUG("AudioSrtp: Get base64 concatenated keys"); // compute concatenated master and salt length - int concatLength = _localMasterKeyLength + _localMasterSaltLength; + int concatLength = localMasterKeyLength_ + localMasterSaltLength_; uint8 concatKeys[concatLength]; - _debug ("AudioSrtp: Concatenated length %d", concatLength); + DEBUG("AudioSrtp: Concatenated length %d", concatLength); // concatenate keys - memcpy ( (void*) concatKeys, (void*) _localMasterKey, _localMasterKeyLength); - memcpy ( (void*) (concatKeys + _localMasterKeyLength), (void*) _localMasterSalt, _localMasterSaltLength); + memcpy((void*) concatKeys, (void*) localMasterKey_, localMasterKeyLength_); + memcpy((void*)(concatKeys + localMasterKeyLength_), (void*) localMasterSalt_, localMasterSaltLength_); // encode concatenated keys in base64 - return encodeBase64 ( (unsigned char*) concatKeys, concatLength); + return encodeBase64((unsigned char*) concatKeys, concatLength); } - -void AudioSrtpSession::unBase64ConcatenatedKeys (std::string base64keys) +void AudioSrtpSession::unBase64ConcatenatedKeys(std::string base64keys) { - _remoteMasterKeyLength = sfl::CryptoSuites[_remoteCryptoSuite].masterKeyLength / 8; - _remoteMasterSaltLength = sfl::CryptoSuites[_remoteCryptoSuite].masterSaltLength / 8; + remoteMasterKeyLength_ = sfl::CryptoSuites[remoteCryptoSuite_].masterKeyLength / 8; + remoteMasterSaltLength_ = sfl::CryptoSuites[remoteCryptoSuite_].masterSaltLength / 8; // pointer to binary data char *dataptr = (char*) base64keys.data(); // decode concatenated binary keys - char *output = decodeBase64 ( (unsigned char*) dataptr, strlen (dataptr)); + char *output = decodeBase64((unsigned char*) dataptr, strlen(dataptr)); // copy master and slt respectively - memcpy ( (void*) _remoteMasterKey, (void*) output, _remoteMasterKeyLength); - memcpy ( (void*) _remoteMasterSalt, (void*) (output + _remoteMasterKeyLength), _remoteMasterSaltLength); + memcpy((void*) remoteMasterKey_, (void*) output, remoteMasterKeyLength_); + memcpy((void*) remoteMasterSalt_, (void*)(output + remoteMasterKeyLength_), remoteMasterSaltLength_); delete[] output; } - -void AudioSrtpSession::initializeRemoteCryptoContext (void) +void AudioSrtpSession::initializeRemoteCryptoContext() { - _debug ("AudioSrtp: Initialize remote crypto context"); + DEBUG("AudioSrtp: Initialize remote crypto context"); - CryptoSuiteDefinition crypto = sfl::CryptoSuites[_remoteCryptoSuite]; + CryptoSuiteDefinition crypto = sfl::CryptoSuites[remoteCryptoSuite_]; - if (_remoteCryptoCtx) { - delete _remoteCryptoCtx; - _remoteCryptoCtx = NULL; + if (remoteCryptoCtx_) { + delete remoteCryptoCtx_; + remoteCryptoCtx_ = NULL; } - _remoteCryptoCtx = new ost::CryptoContext (0x0, + remoteCryptoCtx_ = new ost::CryptoContext(0x0, 0, // roc, 0L, // keydr, SrtpEncryptionAESCM, // encryption algo SrtpAuthenticationSha1Hmac, // authtication algo - _remoteMasterKey, - _remoteMasterKeyLength, - _remoteMasterSalt, - _remoteMasterSaltLength, + remoteMasterKey_, + remoteMasterKeyLength_, + remoteMasterSalt_, + remoteMasterSaltLength_, crypto.encryptionKeyLength / 8, crypto.srtpAuthKeyLength / 8, crypto.masterSaltLength / 8, // session salt len @@ -253,88 +239,87 @@ void AudioSrtpSession::initializeRemoteCryptoContext (void) } -void AudioSrtpSession::initializeLocalCryptoContext (void) +void AudioSrtpSession::initializeLocalCryptoContext() { - _debug ("AudioSrtp: Initialize local crypto context"); + DEBUG("AudioSrtp: Initialize local crypto context"); - CryptoSuiteDefinition crypto = sfl::CryptoSuites[_localCryptoSuite]; + CryptoSuiteDefinition crypto = sfl::CryptoSuites[localCryptoSuite_]; - if (_localCryptoCtx) { - delete _localCryptoCtx; - _localCryptoCtx = NULL; + if (localCryptoCtx_) { + delete localCryptoCtx_; + localCryptoCtx_ = NULL; } - _localCryptoCtx = new ost::CryptoContext (OutgoingDataQueue::getLocalSSRC(), + localCryptoCtx_ = new ost::CryptoContext(OutgoingDataQueue::getLocalSSRC(), 0, // roc, 0L, // keydr, SrtpEncryptionAESCM, // encryption algo SrtpAuthenticationSha1Hmac, // authtication algo - _localMasterKey, - _localMasterKeyLength, - _localMasterSalt, - _localMasterSaltLength, + localMasterKey_, + localMasterKeyLength_, + localMasterSalt_, + localMasterSaltLength_, crypto.encryptionKeyLength / 8, crypto.srtpAuthKeyLength / 8, crypto.masterSaltLength / 8, // session salt len crypto.srtpAuthTagLength / 8); - } -void AudioSrtpSession::restoreCryptoContext(ost::CryptoContext *localContext, ost::CryptoContext *remoteContext) { - setInQueueCryptoContext (remoteContext); - setOutQueueCryptoContext (localContext); +void AudioSrtpSession::restoreCryptoContext(ost::CryptoContext *localContext, ost::CryptoContext *remoteContext) +{ + setInQueueCryptoContext(remoteContext); + setOutQueueCryptoContext(localContext); } -std::string AudioSrtpSession::encodeBase64 (unsigned char *input, int length) +std::string AudioSrtpSession::encodeBase64(unsigned char *input, int length) { BIO *b64, *bmem; BUF_MEM *bptr ; // init decoder - b64 = BIO_new (BIO_f_base64()); - BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL); + b64 = BIO_new(BIO_f_base64()); + BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); // init internal buffer - bmem = BIO_new (BIO_s_mem()); + bmem = BIO_new(BIO_s_mem()); // create decoder chain - b64 = BIO_push (b64, bmem); + b64 = BIO_push(b64, bmem); - BIO_write (b64, input, length); + BIO_write(b64, input, length); // BIO_flush (b64); // get pointer to data - BIO_get_mem_ptr (b64, &bptr); + BIO_get_mem_ptr(b64, &bptr); std::string output(bptr->data, bptr->length); - BIO_free_all (bmem); + BIO_free_all(bmem); return output; } -char* AudioSrtpSession::decodeBase64 (unsigned char *input, int length) +char* AudioSrtpSession::decodeBase64(unsigned char *input, int length) { BIO *b64, *bmem; // init decoder and read-only BIO buffer - b64 = BIO_new (BIO_f_base64()); - BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL); + b64 = BIO_new(BIO_f_base64()); + BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); // init internal buffer - bmem = BIO_new_mem_buf (input, length); + bmem = BIO_new_mem_buf(input, length); // create encoder chain - bmem = BIO_push (b64, bmem); + bmem = BIO_push(b64, bmem); char *buffer = new char[length]; - memset (buffer, 0, length); + memset(buffer, 0, length); - BIO_read (bmem, buffer, length); + BIO_read(bmem, buffer, length); - BIO_free_all (bmem); + BIO_free_all(bmem); return buffer; } - } diff --git a/daemon/src/audio/audiortp/AudioSrtpSession.h b/daemon/src/audio/audiortp/audio_srtp_session.h similarity index 79% rename from daemon/src/audio/audiortp/AudioSrtpSession.h rename to daemon/src/audio/audiortp/audio_srtp_session.h index 754e0bea5ae4794d720c9c5ce5a9bfb318ef224d..f641e8eaa55b21065e7efcee35eb87f3543f93eb 100644 --- a/daemon/src/audio/audiortp/AudioSrtpSession.h +++ b/daemon/src/audio/audiortp/audio_srtp_session.h @@ -27,12 +27,13 @@ * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ -#ifndef __SFL_AUDIO_SRTP_SESSION_H__ -#define __SFL_AUDIO_SRTP_SESSION_H__ +#ifndef __AUDIO_SRTP_SESSION_H__ +#define __AUDIO_SRTP_SESSION_H__ -#include "AudioRtpSession.h" -#include "AudioSymmetricRtpSession.h" -#include "sip/SdesNegotiator.h" +#include "audio_rtp_session.h" +#include "audio_symmetric_rtp_session.h" +#include "sip/sdes_negotiator.h" +#include "noncopyable.h" #include <ccrtp/CryptoContext.h> #include <vector> @@ -64,17 +65,15 @@ class SIPCall; */ -namespace sfl -{ +namespace sfl { -class AudioSrtpSession : public AudioSymmetricRtpSession -{ +class AudioSrtpSession : public AudioSymmetricRtpSession { public: /** * Constructor for this rtp session */ - AudioSrtpSession (SIPCall * sipcall); + AudioSrtpSession(SIPCall * sipcall); ~AudioSrtpSession(); @@ -83,19 +82,19 @@ class AudioSrtpSession : public AudioSymmetricRtpSession * method must be called befor setRemoteCryptoInfo in case of an * outgoing call or after in case of an outgoing call. */ - std::vector<std::string> getLocalCryptoInfo (void); + std::vector<std::string> getLocalCryptoInfo(); /** * Set remote crypto header from incoming sdp offer */ - void setRemoteCryptoInfo (sfl::SdesNegotiator& nego); + void setRemoteCryptoInfo(sfl::SdesNegotiator& nego); /** * Init local crypto context for outgoing data * this method must be called before sending first Invite request * with SDP offer. */ - void initLocalCryptoInfo (void); + void initLocalCryptoInfo(); /** * Restore the cryptographic context. most likely useful to restore @@ -105,36 +104,37 @@ class AudioSrtpSession : public AudioSymmetricRtpSession /** Remote srtp crypto context to be set into incoming data queue. */ - ost::CryptoContext* _remoteCryptoCtx; + ost::CryptoContext* remoteCryptoCtx_; /** Local srtp crypto context to be set into outgoing data queue. */ - ost::CryptoContext* _localCryptoCtx; + ost::CryptoContext* localCryptoCtx_; private: + NON_COPYABLE(AudioSrtpSession); /** * Init local master key according to current crypto context * as defined in SdesNegotiator.h */ - void initializeLocalMasterKey (void); + void initializeLocalMasterKey(); /** * Init local master salt according to current crypto context * as defined in SdesNegotiator.h */ - void initializeLocalMasterSalt (void); + void initializeLocalMasterSalt(); /** * Init remote crypto context in audio srtp session. This method * must be called after unBase64ConcatenatedKeys. */ - void initializeRemoteCryptoContext (void); + void initializeRemoteCryptoContext(); /** * Init local crypto context in audio srtp session. Make sure remote * crypto context is set before calling this method for incoming calls. */ - void initializeLocalCryptoContext (void); + void initializeLocalCryptoContext(); /** * Used to generate local keys to be included in SDP offer/answer. @@ -144,48 +144,47 @@ class AudioSrtpSession : public AudioSymmetricRtpSession /** * Used to retreive keys from base64 serialization */ - void unBase64ConcatenatedKeys (std::string base64keys); + void unBase64ConcatenatedKeys(std::string base64keys); /** * Encode input data as base64 */ - std::string encodeBase64 (unsigned char *input, int length); + std::string encodeBase64(unsigned char *input, int length); /** * Decode base64 data */ - char* decodeBase64 (unsigned char *input, int length); + char* decodeBase64(unsigned char *input, int length); /** Default local crypto suite is AES_CM_128_HMAC_SHA1_80*/ - int _localCryptoSuite; + int localCryptoSuite_; /** Remote crypto suite is initialized at AES_CM_128_HMAC_SHA1_80*/ - int _remoteCryptoSuite; + int remoteCryptoSuite_; - uint8 _localMasterKey[16]; + uint8 localMasterKey_[16]; /** local master key length in byte */ - int _localMasterKeyLength; + int localMasterKeyLength_; - uint8 _localMasterSalt[14]; + uint8 localMasterSalt_[14]; /** local master salt length in byte */ - int _localMasterSaltLength; + int localMasterSaltLength_; - uint8 _remoteMasterKey[16]; + uint8 remoteMasterKey_[16]; /** remote master key length in byte */ - int _remoteMasterKeyLength; + int remoteMasterKeyLength_; - uint8 _remoteMasterSalt[14]; + uint8 remoteMasterSalt_[14]; /** remote master salt length in byte */ - int _remoteMasterSaltLength; + int remoteMasterSaltLength_; /** Used to make sure remote crypto context not initialized wice. */ - bool _remoteOfferIsSet; + bool remoteOfferIsSet_; }; - } #endif // __AUDIO_SRTP_SESSION_H__ diff --git a/daemon/src/audio/audiortp/AudioSymmetricRtpSession.cpp b/daemon/src/audio/audiortp/audio_symmetric_rtp_session.cpp similarity index 61% rename from daemon/src/audio/audiortp/AudioSymmetricRtpSession.cpp rename to daemon/src/audio/audiortp/audio_symmetric_rtp_session.cpp index f872ddc983897517ede56e6e3a9785fb29b412be..4107133d34d7530b12c57e63aaceebd28f4b7498 100644 --- a/daemon/src/audio/audiortp/AudioSymmetricRtpSession.cpp +++ b/daemon/src/audio/audiortp/audio_symmetric_rtp_session.cpp @@ -32,66 +32,56 @@ * as that of the covered work. */ -#include "AudioRtpSession.h" -#include "AudioSymmetricRtpSession.h" -#include "AudioRtpRecordHandler.h" - - +#include "audio_rtp_session.h" +#include "audio_symmetric_rtp_session.h" +#include "audio_rtp_record_handler.h" #include "sip/sdp.h" +#include "sip/sipcall.h" #include "audio/audiolayer.h" -namespace sfl -{ -AudioSymmetricRtpSession::AudioSymmetricRtpSession (SIPCall * sipcall) : - ost::SymmetricRTPSession (ost::InetHostAddress (sipcall->getLocalIp().c_str()), sipcall->getLocalAudioPort()) - , AudioRtpSession(sipcall, Symmetric, this, this) - , _rtpThread (new AudioRtpThread (this)) -{ - _info ("AudioSymmetricRtpSession: Setting new RTP session with destination %s:%d", _ca->getLocalIp().c_str(), _ca->getLocalAudioPort()); - - _audioRtpRecord._callId = _ca->getCallId(); -} +namespace sfl { -AudioSymmetricRtpSession::~AudioSymmetricRtpSession() +AudioSymmetricRtpSession::AudioSymmetricRtpSession(SIPCall * sipcall) : + ost::TimerPort() + , ost::SymmetricRTPSession(ost::InetHostAddress(sipcall->getLocalIp().c_str()), sipcall->getLocalAudioPort()) + , AudioRtpSession(sipcall, Symmetric, this, this) + , echoCanceller() + , rtpThread_(new AudioRtpThread(this)) { - _info ("AudioSymmetricRtpSession: Delete AudioSymmetricRtpSession instance"); - - _rtpThread->running = false; - delete _rtpThread; + INFO("AudioSymmetricRtpSession: Setting new RTP session with destination %s:%d", ca_->getLocalIp().c_str(), ca_->getLocalAudioPort()); + audioRtpRecord_.callId_ = ca_->getCallId(); } -AudioSymmetricRtpSession::AudioRtpThread::AudioRtpThread (AudioSymmetricRtpSession *session) : running (true), rtpSession (session) +AudioSymmetricRtpSession::~AudioSymmetricRtpSession() { - _debug ("AudioSymmetricRtpSession: Create new rtp thread"); + rtpThread_->running = false; + delete rtpThread_; } -AudioSymmetricRtpSession::AudioRtpThread::~AudioRtpThread() -{ - _debug ("AudioSymmetricRtpSession: Delete rtp thread"); -} +AudioSymmetricRtpSession::AudioRtpThread::AudioRtpThread(AudioSymmetricRtpSession *session) : running(true), rtpSession(session) +{} void AudioSymmetricRtpSession::AudioRtpThread::run() { int threadSleep = 20; - TimerPort::setTimer (threadSleep); + TimerPort::setTimer(threadSleep); - _debug ("AudioRtpThread: Entering Audio rtp thread main loop"); + DEBUG("AudioRtpThread: Entering Audio rtp thread main loop"); while (running) { - // Send session if (rtpSession->DtmfPending()) - rtpSession->sendDtmfEvent (); + rtpSession->sendDtmfEvent(); else - rtpSession->sendMicData (); + rtpSession->sendMicData(); - Thread::sleep (TimerPort::getTimer()); + Thread::sleep(TimerPort::getTimer()); - TimerPort::incTimer (threadSleep); + TimerPort::incTimer(threadSleep); } - _debug ("AudioRtpThread: Leaving audio rtp thread loop"); + DEBUG("AudioRtpThread: Leaving audio rtp thread loop"); } } diff --git a/daemon/src/audio/audiortp/AudioSymmetricRtpSession.h b/daemon/src/audio/audiortp/audio_symmetric_rtp_session.h similarity index 74% rename from daemon/src/audio/audiortp/AudioSymmetricRtpSession.h rename to daemon/src/audio/audiortp/audio_symmetric_rtp_session.h index 5fd4ac9330697afc6ee41e9c81bb72462420d77c..162bcadbed5f43d1a611a829b44a72e2e8aa5258 100644 --- a/daemon/src/audio/audiortp/AudioSymmetricRtpSession.h +++ b/daemon/src/audio/audiortp/audio_symmetric_rtp_session.h @@ -31,72 +31,65 @@ * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ -#ifndef __SFL_AUDIO_SYMMETRIC_RTP_SESSION_H__ -#define __SFL_AUDIO_SYMMETRIC_RTP_SESSION_H__ +#ifndef __AUDIO_SYMMETRIC_RTP_SESSION_H__ +#define __AUDIO_SYMMETRIC_RTP_SESSION_H__ -#include <iostream> #include <exception> -#include <list> +#include <cassert> #include <cstddef> -#include "global.h" - -#include "AudioRtpSession.h" -#include "AudioRtpRecordHandler.h" -#include "sip/sipcall.h" -#include "audio/codecs/audiocodec.h" +#include "audio_rtp_session.h" +#include "noncopyable.h" using std::ptrdiff_t; + #include <ccrtp/rtp.h> #include <ccrtp/iqueue.h> #include <cc++/numbers.h> // ost::Time -#include <fstream> -namespace sfl -{ +class SIPCall; + +namespace sfl { -class AudioSymmetricRtpSession : public ost::TimerPort, public ost::SymmetricRTPSession, public AudioRtpSession -{ +class AudioSymmetricRtpSession : public ost::TimerPort, public ost::SymmetricRTPSession, public AudioRtpSession { public: /** * Constructor * @param sipcall The pointer on the SIP call */ - AudioSymmetricRtpSession (SIPCall* sipcall); + AudioSymmetricRtpSession(SIPCall* sipcall); ~AudioSymmetricRtpSession(); - virtual bool onRTPPacketRecv (ost::IncomingRTPPkt& pkt) { return AudioRtpSession::onRTPPacketRecv(pkt); } + virtual bool onRTPPacketRecv(ost::IncomingRTPPkt& pkt) { + return AudioRtpSession::onRTPPacketRecv(pkt); + } - int startSymmetricRtpThread (void) { - assert(_rtpThread); - return _rtpThread->start(); + int startSymmetricRtpThread() { + assert(rtpThread_); + return rtpThread_->start(); } private: + NON_COPYABLE(AudioSymmetricRtpSession); - class AudioRtpThread : public ost::Thread, public ost::TimerPort - { + class AudioRtpThread : public ost::Thread, public ost::TimerPort { public: - AudioRtpThread (AudioSymmetricRtpSession *session); - ~AudioRtpThread(); + AudioRtpThread(AudioSymmetricRtpSession *session); + ~AudioRtpThread(){} virtual void run(); bool running; private: + NON_COPYABLE(AudioRtpThread); AudioSymmetricRtpSession *rtpSession; }; SpeexEchoCancel echoCanceller; - protected: - - AudioRtpThread *_rtpThread; - - public: - - friend class AudioRtpThread; + private: + AudioRtpThread *rtpThread_; }; } diff --git a/daemon/src/audio/audiortp/AudioZrtpSession.cpp b/daemon/src/audio/audiortp/audio_zrtp_session.cpp similarity index 51% rename from daemon/src/audio/audiortp/AudioZrtpSession.cpp rename to daemon/src/audio/audiortp/audio_zrtp_session.cpp index 0a7ef0fd6bf2982e0d44c3c71be273b9e923d326..81af2f5e1026d40928fba5273f4967fcb0def7ab 100644 --- a/daemon/src/audio/audiortp/AudioZrtpSession.cpp +++ b/daemon/src/audio/audiortp/audio_zrtp_session.cpp @@ -27,8 +27,10 @@ * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ -#include "AudioZrtpSession.h" -#include "ZrtpSessionCallback.h" + +#include "config.h" +#include "audio_zrtp_session.h" +#include "zrtp_session_callback.h" #include "sip/sipcall.h" #include "sip/sdp.h" @@ -45,145 +47,122 @@ #include <ccrtp/rtp.h> -namespace sfl -{ +namespace sfl { -AudioZrtpSession::AudioZrtpSession (SIPCall * sipcall, const std::string& zidFilename) : - // ost::SymmetricZRTPSession (ost::InetHostAddress (sipcall->getLocalIp().c_str()), sipcall->getLocalAudioPort()), - AudioRtpSession(sipcall, Zrtp, static_cast<ost::RTPDataQueue *>(this), static_cast<ost::Thread *>(this)) - ,ost::TRTPSessionBase<ost::SymmetricRTPChannel, ost::SymmetricRTPChannel, ost::ZrtpQueue> (ost::InetHostAddress (sipcall->getLocalIp().c_str()), +AudioZrtpSession::AudioZrtpSession(SIPCall * sipcall, const std::string& zidFilename) : + AudioRtpSession(sipcall, Zrtp, this, this), + ost::TRTPSessionBase<ost::SymmetricRTPChannel, ost::SymmetricRTPChannel, ost::ZrtpQueue>(ost::InetHostAddress(sipcall->getLocalIp().c_str()), sipcall->getLocalAudioPort(), 0, ost::MembershipBookkeeping::defaultMembersHashSize, - ost::defaultApplication()) - , _zidFilename (zidFilename) + ost::defaultApplication()), + zidFilename_(zidFilename) { - _debug ("AudioZrtpSession initialized"); + DEBUG("AudioZrtpSession initialized"); initializeZid(); - setCancel (cancelDefault); + setCancel(cancelDefault); - _info ("AudioZrtpSession: Setting new RTP session with destination %s:%d", _ca->getLocalIp().c_str(), _ca->getLocalAudioPort()); + INFO("AudioZrtpSession: Setting new RTP session with destination %s:%d", ca_->getLocalIp().c_str(), ca_->getLocalAudioPort()); } AudioZrtpSession::~AudioZrtpSession() { - _debug ("AudioZrtpSession: Delete AudioSymmetricRtpSession instance"); - - try { - terminate(); - } catch (...) { - _debug ("AudioZrtpSession: Thread destructor didn't terminate correctly"); - throw; - } - - Manager::instance().getMainBuffer()->unBindAll (_ca->getCallId()); + ost::Thread::terminate(); + Manager::instance().getMainBuffer()->unBindAll(ca_->getCallId()); } void AudioZrtpSession::final() { - delete this; +// tmatth:Oct 25 2011:FIXME: +// This was crashing...seems like it's not necessary. Double check +// with valgrind/helgrind +// delete this; } -void AudioZrtpSession::initializeZid (void) +void AudioZrtpSession::initializeZid() { - - if (_zidFilename.empty()) { + if (zidFilename_.empty()) throw ZrtpZidException("zid filename empty"); - } std::string zidCompleteFilename; - // xdg_config = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".cache/sflphone"; + std::string xdg_config = std::string(HOMEDIR) + DIR_SEPARATOR_STR + ".cache" + DIR_SEPARATOR_STR + PACKAGE + "/" + zidFilename_; - std::string xdg_config = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".cache" + DIR_SEPARATOR_STR + PROGDIR + "/" + _zidFilename; - - _debug (" xdg_config %s", xdg_config.c_str()); + DEBUG(" xdg_config %s", xdg_config.c_str()); if (XDG_CACHE_HOME != NULL) { - std::string xdg_env = std::string (XDG_CACHE_HOME) + _zidFilename; - _debug (" xdg_env %s", xdg_env.c_str()); + std::string xdg_env = std::string(XDG_CACHE_HOME) + zidFilename_; + DEBUG(" xdg_env %s", xdg_env.c_str()); (xdg_env.length() > 0) ? zidCompleteFilename = xdg_env : zidCompleteFilename = xdg_config; } else zidCompleteFilename = xdg_config; - if (initialize (zidCompleteFilename.c_str()) >= 0) { - _debug ("Register callbacks"); - setEnableZrtp (true); - setUserCallback (new ZrtpSessionCallback (_ca)); + if (initialize(zidCompleteFilename.c_str()) >= 0) { + DEBUG("Register callbacks"); + setEnableZrtp(true); + setUserCallback(new ZrtpSessionCallback(ca_)); return; } - _debug ("Initialization from ZID file failed. Trying to remove..."); + DEBUG("Initialization from ZID file failed. Trying to remove..."); - if (remove (zidCompleteFilename.c_str()) !=0) { - _debug ("Failed to remove zid file: %m"); + if (remove(zidCompleteFilename.c_str()) != 0) throw ZrtpZidException("zid file deletion failed"); - } - if (initialize (zidCompleteFilename.c_str()) < 0) { - _debug ("ZRTP initialization failed"); + if (initialize(zidCompleteFilename.c_str()) < 0) throw ZrtpZidException("zid initialization failed"); - } return; } -void AudioZrtpSession::run () +void AudioZrtpSession::run() { - // Set recording sampling rate - _ca->setRecordingSmplRate (getCodecSampleRate()); - - _debug ("AudioZrtpSession: Entering mainloop for call %s",_ca->getCallId().c_str()); + ca_->setRecordingSmplRate(getCodecSampleRate()); + DEBUG("AudioZrtpSession: Entering mainloop for call %s", ca_->getCallId().c_str()); uint32 timeout = 0; while (isActive()) { - - if (timeout < 1000) { // !(timeout/1000) + if (timeout < 1000) timeout = getSchedulingTimeout(); - } // Send session if (DtmfPending()) - sendDtmfEvent (); + sendDtmfEvent(); else - sendMicData (); + sendMicData(); - setCancel (cancelDeferred); + setCancel(cancelDeferred); controlReceptionService(); controlTransmissionService(); - setCancel (cancelImmediate); - uint32 maxWait = timeval2microtimeout (getRTCPCheckInterval()); + setCancel(cancelImmediate); + uint32 maxWait = timeval2microtimeout(getRTCPCheckInterval()); // make sure the scheduling timeout is // <= the check interval for RTCP // packets timeout = (timeout > maxWait) ? maxWait : timeout; if (timeout < 1000) { // !(timeout/1000) - setCancel (cancelDeferred); + setCancel(cancelDeferred); // dispatchDataPacket(); - setCancel (cancelImmediate); + setCancel(cancelImmediate); timerTick(); } else { - if (isPendingData (timeout/1000)) { - setCancel (cancelDeferred); + if (isPendingData(timeout/1000)) { + setCancel(cancelDeferred); - if (isActive()) { // take in only if active + if (isActive()) takeInDataPacket(); - } - setCancel (cancelImmediate); + setCancel(cancelImmediate); } - timeout = 0; } - } - _debug ("AudioZrtpSession: Left main loop for call %s", _ca->getCallId().c_str()); + DEBUG("AudioZrtpSession: Left main loop for call %s", ca_->getCallId().c_str()); } - } diff --git a/daemon/src/audio/audiortp/AudioZrtpSession.h b/daemon/src/audio/audiortp/audio_zrtp_session.h similarity index 80% rename from daemon/src/audio/audiortp/AudioZrtpSession.h rename to daemon/src/audio/audiortp/audio_zrtp_session.h index a0ffafcf363ec359f290d0103fa5262d089b9a56..3a19a5e3fd148e2e9090965a0b058bb56296407f 100644 --- a/daemon/src/audio/audiortp/AudioZrtpSession.h +++ b/daemon/src/audio/audiortp/audio_zrtp_session.h @@ -27,8 +27,8 @@ * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ -#ifndef __SFL_AUDIO_ZRTP_SESSION_H__ -#define __SFL_AUDIO_ZRTP_SESSION_H__ +#ifndef __AUDIO_ZRTP_SESSION_H__ +#define __AUDIO_ZRTP_SESSION_H__ #include <cstddef> #include <stdexcept> @@ -39,41 +39,37 @@ using std::ptrdiff_t; #include <libzrtpcpp/ZrtpQueue.h> #include <libzrtpcpp/ZrtpUserCallback.h> -#include "AudioRtpSession.h" +#include "audio_rtp_session.h" #include <cc++/numbers.h> // OST::Time class SIPCall; -namespace sfl -{ +namespace sfl { -class ZrtpZidException: public std::runtime_error -{ +class ZrtpZidException: public std::runtime_error { public: - ZrtpZidException (const std::string& str="") : + ZrtpZidException(const std::string& str = "") : std::runtime_error("ZRTP ZID initialization failed." + str) {} }; // class AudioZrtpSession : public ost::TimerPort, public ost::SymmetricZRTPSession, public AudioRtpRecordHandler -class AudioZrtpSession : public AudioRtpSession, protected ost::Thread, public ost::TRTPSessionBase<ost::SymmetricRTPChannel, ost::SymmetricRTPChannel, ost::ZrtpQueue> -{ +class AudioZrtpSession : public AudioRtpSession, protected ost::Thread, public ost::TRTPSessionBase<ost::SymmetricRTPChannel, ost::SymmetricRTPChannel, ost::ZrtpQueue> { public: - AudioZrtpSession (SIPCall * sipcall, const std::string& zidFilename); - + AudioZrtpSession(SIPCall * sipcall, const std::string& zidFilename); ~AudioZrtpSession(); virtual void final(); // Thread associated method - virtual void run (); + virtual void run(); - virtual bool onRTPPacketRecv (ost::IncomingRTPPkt& pkt) { return AudioRtpSession::onRTPPacketRecv(pkt); } + virtual bool onRTPPacketRecv(ost::IncomingRTPPkt& pkt) { + return AudioRtpSession::onRTPPacketRecv(pkt); + } private: - - void initializeZid (void); - - std::string _zidFilename; + void initializeZid(); + std::string zidFilename_; }; } diff --git a/daemon/src/audio/audiortp/zrtp_session_callback.cpp b/daemon/src/audio/audiortp/zrtp_session_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..24e6a9bbf8e6953a98d55be2edeaa9950ebbc3f1 --- /dev/null +++ b/daemon/src/audio/audiortp/zrtp_session_callback.cpp @@ -0,0 +1,189 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. + * Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com> + * + * 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Additional permission under GNU GPL version 3 section 7: + * + * If you modify this program, or any covered work, by linking or + * combining it with the OpenSSL project's OpenSSL library (or a + * modified version of that library), containing parts covered by the + * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. + * grants you additional permission to convey the resulting work. + * Corresponding Source for a non-source form of such a combination + * shall include the source code for the parts of OpenSSL used as well + * as that of the covered work. + */ +#include "zrtp_session_callback.h" +#include "global.h" +#include "sip/sipcall.h" +#include "dbus/dbusmanager.h" +#include "dbus/callmanager.h" +#include "manager.h" + +#include <cstdlib> +#include <string> +#include <map> +#include <utility> // for std::pair + +using namespace GnuZrtpCodes; + +using namespace ost; + +namespace sfl { + +ZrtpSessionCallback::ZrtpSessionCallback(SIPCall *sipcall) : + sipcall_(sipcall) +{ + using std::pair; + using std::string; + + // we've already initialized the maps, we only need to check one + if (not infoMap_.empty()) + return; + + INFO("Zrtp: Initialize callbacks"); + + // Information Map + infoMap_[InfoHelloReceived] = "Hello received, preparing a Commit"; + infoMap_[InfoCommitDHGenerated] = "Commit: Generated a public DH key"; + infoMap_[InfoRespCommitReceived] = "Responder: Commit received, preparing DHPart1"; + infoMap_[InfoDH1DHGenerated] = "DH1Part: Generated a public DH key"; + infoMap_[InfoInitDH1Received] = "Initiator: DHPart1 received, preparing DHPart2"; + infoMap_[InfoRespDH2Received] = "Responder: DHPart2 received, preparing Confirm1"; + infoMap_[InfoInitConf1Received] = "Initiator: Confirm1 received, preparing Confirm2"; + infoMap_[InfoRespConf2Received] = "Responder: Confirm2 received, preparing Conf2Ack"; + infoMap_[InfoRSMatchFound] = "At least one retained secrets matches - security OK"; + infoMap_[InfoSecureStateOn] = "Entered secure state"; + infoMap_[InfoSecureStateOff] = "No more security for this session"; + + // Warning Map + warningMap_[WarningDHAESmismatch] = "Commit contains an AES256 cipher but does not offer a Diffie-Helman 4096"; + warningMap_[WarningGoClearReceived] = "Received a GoClear message"; + warningMap_[WarningDHShort] = "Hello offers an AES256 cipher but does not offer a Diffie-Helman 4096"; + warningMap_[WarningNoRSMatch] = "No retained secret matches - verify SAS"; + warningMap_[WarningCRCmismatch] = "Internal ZRTP packet checksum mismatch - packet dropped"; + warningMap_[WarningSRTPauthError] = "Dropping packet because SRTP authentication failed!"; + warningMap_[WarningSRTPreplayError] = "Dropping packet because SRTP replay check failed!"; + + severeMap_[SevereHelloHMACFailed] = "Hash HMAC check of Hello failed!"; + severeMap_[SevereCommitHMACFailed] = "Hash HMAC check of Commit failed!"; + severeMap_[SevereDH1HMACFailed] = "Hash HMAC check of DHPart1 failed!"; + severeMap_[SevereDH2HMACFailed] = "Hash HMAC check of DHPart2 failed!"; + severeMap_[SevereCannotSend] = "Cannot send data - connection or peer down?"; + severeMap_[SevereProtocolError] = "Internal protocol error occured!"; + severeMap_[SevereNoTimer] = "Cannot start a timer - internal resources exhausted?"; + severeMap_[SevereTooMuchRetries] = "Too much retries during ZRTP negotiation - connection or peer down?"; + + // Zrtp protocol related messages map + zrtpMap_[MalformedPacket] = "Malformed packet (CRC OK, but wrong structure)"; + zrtpMap_[CriticalSWError] = "Critical software error"; + zrtpMap_[UnsuppZRTPVersion] = "Unsupported ZRTP version"; + zrtpMap_[HelloCompMismatch] = "Hello components mismatch"; + zrtpMap_[UnsuppHashType] = "Hash type not supported"; + zrtpMap_[UnsuppCiphertype] = "Cipher type not supported"; + zrtpMap_[UnsuppPKExchange] = "Public key exchange not supported"; + zrtpMap_[UnsuppSRTPAuthTag] = "SRTP auth. tag not supported"; + zrtpMap_[UnsuppSASScheme] = "SAS scheme not supported"; + zrtpMap_[NoSharedSecret] = "No shared secret available, DH mode required"; + zrtpMap_[DHErrorWrongPV] = "DH Error: bad pvi or pvr ( == 1, 0, or p-1)"; + zrtpMap_[DHErrorWrongHVI] = "DH Error: hvi != hashed data"; + zrtpMap_[SASuntrustedMiTM] = "Received relayed SAS from untrusted MiTM"; + zrtpMap_[ConfirmHMACWrong] = "Auth. Error: Bad Confirm pkt HMAC"; + zrtpMap_[NonceReused] = "Nonce reuse"; + zrtpMap_[EqualZIDHello] = "Equal ZIDs in Hello"; + zrtpMap_[GoCleatNotAllowed] = "GoClear packet received, but not allowed"; +} + +void +ZrtpSessionCallback::secureOn(std::string cipher) +{ + DEBUG("Zrtp: Secure mode is on with cipher %s", cipher.c_str()); + Manager::instance().getDbusManager()->getCallManager()->secureZrtpOn(sipcall_->getCallId(), cipher); +} + +void +ZrtpSessionCallback::secureOff() +{ + DEBUG("Zrtp: Secure mode is off"); + Manager::instance().getDbusManager()->getCallManager()->secureZrtpOff(sipcall_->getCallId()); +} + +void +ZrtpSessionCallback::showSAS(std::string sas, bool verified) +{ + DEBUG("Zrtp: SAS is: %s", sas.c_str()); + Manager::instance().getDbusManager()->getCallManager()->showSAS(sipcall_->getCallId(), sas, verified); +} + + +void +ZrtpSessionCallback::zrtpNotSuppOther() +{ + DEBUG("Zrtp: Callee does not support ZRTP"); + Manager::instance().getDbusManager()->getCallManager()->zrtpNotSuppOther(sipcall_->getCallId()); +} + + +void +ZrtpSessionCallback::showMessage(GnuZrtpCodes::MessageSeverity sev, int32_t subCode) +{ + if (sev == ZrtpError) { + if (subCode < 0) { // received an error packet from peer + subCode *= -1; + DEBUG("Received an error packet from peer:"); + } else + DEBUG("Sent error packet to peer:"); + } +} + +void +ZrtpSessionCallback::zrtpNegotiationFailed(MessageSeverity severity, int subCode) +{ + if (severity == ZrtpError) { + if (subCode < 0) { // received an error packet from peer + subCode *= -1; + DEBUG("Zrtp: Received error packet: "); + } else + DEBUG("Zrtp: Sent error packet: "); + + std::map<int32, std::string>::const_iterator iter = zrtpMap_.find(subCode); + if (iter != zrtpMap_.end()) { + DEBUG("%s", iter->second.c_str()); + Manager::instance().getDbusManager()->getCallManager()->zrtpNegotiationFailed(sipcall_->getCallId(), iter->second, "ZRTP"); + } + } else { + std::map<int32, std::string>::const_iterator iter = severeMap_.find(subCode); + if (iter != severeMap_.end()) { + DEBUG("%s", iter->second.c_str()); + Manager::instance().getDbusManager()->getCallManager()->zrtpNegotiationFailed(sipcall_->getCallId(), iter->second, "severe"); + } + } +} + +void +ZrtpSessionCallback::confirmGoClear() +{ + DEBUG("Zrtp: Received go clear message. Until confirmation, ZRTP won't send any data"); + Manager::instance().getDbusManager()->getCallManager()->zrtpNotSuppOther(sipcall_->getCallId()); +} + +std::map<int32, std::string> ZrtpSessionCallback::infoMap_; +std::map<int32, std::string> ZrtpSessionCallback::warningMap_; +std::map<int32, std::string> ZrtpSessionCallback::severeMap_; +std::map<int32, std::string> ZrtpSessionCallback::zrtpMap_; +} + diff --git a/daemon/src/audio/audiortp/ZrtpSessionCallback.h b/daemon/src/audio/audiortp/zrtp_session_callback.h similarity index 66% rename from daemon/src/audio/audiortp/ZrtpSessionCallback.h rename to daemon/src/audio/audiortp/zrtp_session_callback.h index 85e2a6172683e453fe9a949a2ed2ec59349c2a10..08bb9cf4fb4c9bffd2f9fbc49d50520dda88a6c3 100644 --- a/daemon/src/audio/audiortp/ZrtpSessionCallback.h +++ b/daemon/src/audio/audiortp/zrtp_session_callback.h @@ -28,8 +28,8 @@ * as that of the covered work. */ -#ifndef __SFL_ZRTP_CALLBACK_H__ -#define __SFL_ZRTP_CALLBACK_H__ +#ifndef __ZRTP_SESSION_CALLBACK_H__ +#define __ZRTP_SESSION_CALLBACK_H__ #include <cstddef> using std::ptrdiff_t; @@ -39,33 +39,31 @@ using std::ptrdiff_t; #include <libzrtpcpp/ZrtpUserCallback.h> #include <exception> #include <map> +#include "noncopyable.h" class SIPCall; -namespace sfl -{ +namespace sfl { -class ZrtpSessionCallback: public ZrtpUserCallback -{ +class ZrtpSessionCallback: public ZrtpUserCallback { public: - ZrtpSessionCallback (SIPCall *sipcall); + ZrtpSessionCallback(SIPCall *sipcall); - void secureOn (std::string cipher); - void secureOff (void); - void showSAS (std::string sas, bool verified); - void zrtpNotSuppOther (void); - void showMessage (GnuZrtpCodes::MessageSeverity sev, int32_t subCode); - void zrtpNegotiationFailed (GnuZrtpCodes::MessageSeverity severity, int subCode); + void secureOn(std::string cipher); + void secureOff(); + void showSAS(std::string sas, bool verified); + void zrtpNotSuppOther(); + void showMessage(GnuZrtpCodes::MessageSeverity sev, int32_t subCode); + void zrtpNegotiationFailed(GnuZrtpCodes::MessageSeverity severity, int subCode); void confirmGoClear(); private: - SIPCall* _sipcall; - /* FIXME: why are these strings dynamically allocated? */ - static std::map<int32, std::string*> _infoMap; - static std::map<int32, std::string*> _warningMap; - static std::map<int32, std::string*> _severeMap; - static std::map<int32, std::string*> _zrtpMap; - static bool _mapInitialized; + NON_COPYABLE(ZrtpSessionCallback); + SIPCall* sipcall_; + static std::map<int32, std::string> infoMap_; + static std::map<int32, std::string> warningMap_; + static std::map<int32, std::string> severeMap_; + static std::map<int32, std::string> zrtpMap_; }; } -#endif +#endif // __ZRTP_SESSION_CALLBACK_H__ diff --git a/daemon/src/audio/codecs/alaw.cpp b/daemon/src/audio/codecs/alaw.cpp index db03155fd9bd4688533816ec7f8f86819edc045f..77df91008b0b4aad6830191c43372d49d9a45cfb 100644 --- a/daemon/src/audio/codecs/alaw.cpp +++ b/daemon/src/audio/codecs/alaw.cpp @@ -34,45 +34,44 @@ #include "audiocodec.h" #include <cassert> -class Alaw : public sfl::AudioCodec -{ +class Alaw : public sfl::AudioCodec { public: // 8 PCMA A 8000 1 [RFC3551] - Alaw (int payload=8) - : sfl::AudioCodec (payload, "PCMA") { - _clockRate = 8000; - _frameSize = 160; // samples, 20 ms at 8kHz - _channel = 1; - _bitrate = 64; - _hasDynamicPayload = false; + Alaw(int payload=8) + : sfl::AudioCodec(payload, "PCMA") { + clockRate_ = 8000; + frameSize_ = 160; // samples, 20 ms at 8kHz + channel_ = 1; + bitrate_ = 64; + hasDynamicPayload_ = false; } virtual ~Alaw() {} - virtual int decode (short *dst, unsigned char *src, size_t buf_size) { - assert(buf_size == _frameSize / 2 /* compression factor = 2:1 */ * sizeof(SFLDataFormat)); - unsigned char* end = src+buf_size; + virtual int decode(short *dst, unsigned char *src, size_t buf_size) { + assert(buf_size == frameSize_ / 2 /* compression factor = 2:1 */ * sizeof(SFLDataFormat)); + unsigned char* end = src + buf_size; - while (src<end) - *dst++ = ALawDecode (*src++); + while (src < end) + *dst++ = ALawDecode(*src++); - return _frameSize; + return frameSize_; } - virtual int encode (unsigned char *dst, short *src, size_t buf_size) { - assert(buf_size >= _frameSize / 2 /* compression factor = 2:1 */ * sizeof(SFLDataFormat)); - uint8* end = dst+_frameSize; + virtual int encode(unsigned char *dst, short *src, size_t buf_size) { + assert(buf_size >= frameSize_ / 2 /* compression factor = 2:1 */ * sizeof(SFLDataFormat)); + uint8* end = dst + frameSize_; - while (dst<end) - *dst++ = ALawEncode (*src++); + while (dst < end) + *dst++ = ALawEncode(*src++); - return _frameSize / 2 /* compression factor = 2:1 */ * sizeof(SFLDataFormat); + return frameSize_ / 2 /* compression factor = 2:1 */ * sizeof(SFLDataFormat); } - int ALawDecode (uint8 alaw) { + int ALawDecode(uint8 alaw) { alaw ^= 0x55; // A-law has alternate bits inverted for transmission uint sign = alaw&0x80; int linear = alaw&0x1f; @@ -81,9 +80,9 @@ class Alaw : public sfl::AudioCodec alaw &= 0x7f; - if (alaw>=0x20) { + if (alaw >= 0x20) { linear |= 0x100; // Put in MSB - uint shift = (alaw>>4)-1; + uint shift = (alaw >> 4) - 1; linear <<= shift; } @@ -94,11 +93,11 @@ class Alaw : public sfl::AudioCodec } - uint8 ALawEncode (int16 pcm16) { + uint8 ALawEncode(int16 pcm16) { int p = pcm16; uint a; // u-law value we are forming - if (p<0) { + if (p < 0) { p = ~p; a = 0x00; // sign = 0 } else { @@ -136,10 +135,10 @@ class Alaw : public sfl::AudioCodec // the class factories extern "C" sfl::Codec* create() { - return new Alaw (8); + return new Alaw(8); } -extern "C" void destroy (sfl::Codec* a) +extern "C" void destroy(sfl::Codec* a) { delete a; } diff --git a/daemon/src/audio/codecs/audiocodec.cpp b/daemon/src/audio/codecs/audiocodec.cpp index ed5c5cc95fdb32d52d4c8c84c15788b6d9294217..e9701c6b306ee196d00ef458c20ac70889f824e0 100644 --- a/daemon/src/audio/codecs/audiocodec.cpp +++ b/daemon/src/audio/codecs/audiocodec.cpp @@ -36,33 +36,30 @@ using std::ptrdiff_t; namespace sfl { -AudioCodec::AudioCodec (uint8 payload, const std::string &codecName) : - _codecName (codecName), _clockRate (8000), _channel (1), _bitrate (0.0), - _hasDynamicPayload (false), _payload(payload) +AudioCodec::AudioCodec(uint8 payload, const std::string &codecName) : + codecName_(codecName), clockRate_(8000), channel_(1), frameSize_(0), + bitrate_(0.0), bandwidth_(0.0), hasDynamicPayload_(false), + payload_(payload), payloadFormat_(0) { - init (payload, _clockRate); + init(payload, clockRate_); } -AudioCodec::AudioCodec (const AudioCodec& codec) : - _codecName (codec._codecName), _clockRate (codec._clockRate), _channel ( - codec._channel), _bitrate (codec._bitrate), - _hasDynamicPayload (false), _payload(codec._payload) +AudioCodec::AudioCodec(const AudioCodec& c) : + codecName_(c.codecName_), clockRate_(c.clockRate_), channel_(c.channel_), + frameSize_(c.frameSize_), bitrate_(c.bitrate_), bandwidth_(c.bandwidth_), + hasDynamicPayload_(c.hasDynamicPayload_), payload_(c.payload_), + payloadFormat_(c.payloadFormat_) { - init (codec._payload, codec._clockRate); + init(c.payload_, c.clockRate_); } -void AudioCodec::init (uint8 payloadType, uint32 clockRate) +void AudioCodec::init(uint8 payloadType, uint32 clockRate) { - _payloadFormat = new ost::DynamicPayloadFormat (payloadType, clockRate); - - _hasDynamicPayload = (_payload >= 96 && _payload <= 127) ? true : false; + payloadFormat_ = new ost::DynamicPayloadFormat(payloadType, clockRate); // If g722 (payload 9), we need to init libccrtp symetric sessions with using // dynamic payload format. This way we get control on rtp clockrate. - - if (_payload == 9) { - _hasDynamicPayload = true; - } + hasDynamicPayload_ = ((payload_ >= 96 and payload_ <= 127) or payload_ == 9); } std::string AudioCodec::getMimeType() const @@ -72,47 +69,47 @@ std::string AudioCodec::getMimeType() const std::string AudioCodec::getMimeSubtype() const { - return _codecName; + return codecName_; } const ost::PayloadFormat& AudioCodec::getPayloadFormat() { - return (*_payloadFormat); + return *payloadFormat_; } -uint8 AudioCodec::getPayloadType (void) const +uint8 AudioCodec::getPayloadType() const { - return _payload; + return payload_; } -bool AudioCodec::hasDynamicPayload (void) const +bool AudioCodec::hasDynamicPayload() const { - return _hasDynamicPayload; + return hasDynamicPayload_; } -uint32 AudioCodec::getClockRate (void) const +uint32 AudioCodec::getClockRate() const { - return _clockRate; + return clockRate_; } -unsigned AudioCodec::getFrameSize (void) const +unsigned AudioCodec::getFrameSize() const { - return _frameSize; + return frameSize_; } -uint8 AudioCodec::getChannel (void) const +uint8 AudioCodec::getChannel() const { - return _channel; + return channel_; } -double AudioCodec::getBitRate (void) const +double AudioCodec::getBitRate() const { - return _bitrate; + return bitrate_; } AudioCodec::~AudioCodec() { - delete _payloadFormat; + delete payloadFormat_; } } // end namespace sfl diff --git a/daemon/src/audio/codecs/audiocodec.h b/daemon/src/audio/codecs/audiocodec.h index b2d23fe0026bb111af67d18ef076de60cf57e159..f1b42ffe86d7f4c1afef1927947f9de13ffb14e9 100644 --- a/daemon/src/audio/codecs/audiocodec.h +++ b/daemon/src/audio/codecs/audiocodec.h @@ -33,10 +33,9 @@ #define __AUDIO_CODEC_H__ #include <string> -#include <iostream> #include <dlfcn.h> -#include "Codec.h" +#include "codec.h" // We assume all decoders will be fed 20ms of audio or less // And we'll resample them to 44.1kHz or less @@ -44,21 +43,20 @@ #define DEC_BUFFER_SIZE ((44100 * 20) / 1000) namespace ost { - class PayloadFormat; - class DynamicPayloadFormat; +class PayloadFormat; +class DynamicPayloadFormat; } namespace sfl { -class AudioCodec : public Codec -{ +class AudioCodec : public Codec { public: - AudioCodec (uint8 payload, const std::string &codecName); + AudioCodec(uint8 payload, const std::string &codecName); /** * Copy constructor. */ - AudioCodec (const AudioCodec& codec); + AudioCodec(const AudioCodec& codec); virtual ~AudioCodec(); @@ -80,12 +78,12 @@ class AudioCodec : public Codec /** * @Override */ - void setParameter (const std::string& /*name*/, const std::string& /*value*/) {}; + void setParameter(const std::string& /*name*/, const std::string& /*value*/) {}; /** * @Override */ - std::string getParameter (const std::string& /*name*/) const { + std::string getParameter(const std::string& /*name*/) const { return ""; }; @@ -94,14 +92,14 @@ class AudioCodec : public Codec * @param buffer_size : the size of the input buffer * @return the number of samples decoded */ - virtual int decode (short *dst, unsigned char *buf, size_t buffer_size) = 0; + virtual int decode(short *dst, unsigned char *buf, size_t buffer_size) = 0; /** * Encode an input buffer and fill the output buffer with the encoded data * @param buffer_size : the maximum size of encoded data buffer (dst) * @return the number of bytes encoded */ - virtual int encode (unsigned char *dst, short *src, size_t buffer_size) = 0; + virtual int encode(unsigned char *dst, short *src, size_t buffer_size) = 0; /** * @Override @@ -112,7 +110,7 @@ class AudioCodec : public Codec * @Override */ void setPayloadType(uint8 pt) { - _payload = pt; + payload_ = pt; } /** @@ -142,31 +140,32 @@ class AudioCodec : public Codec protected: /** Holds SDP-compliant codec name */ - std::string _codecName; // what we put inside sdp + std::string codecName_; // what we put inside sdp /** Clock rate or sample rate of the codec, in Hz */ - uint32 _clockRate; + uint32 clockRate_; /** Number of channel 1 = mono, 2 = stereo */ - uint8 _channel; + uint8 channel_; /** codec frame size in samples*/ - unsigned _frameSize; + unsigned frameSize_; /** Bitrate */ - double _bitrate; + double bitrate_; /** Bandwidth */ - double _bandwidth; + double bandwidth_; - bool _hasDynamicPayload; + bool hasDynamicPayload_; private: - uint8 _payload; + AudioCodec& operator=(const AudioCodec&); + uint8 payload_; - ost::DynamicPayloadFormat* _payloadFormat; + ost::DynamicPayloadFormat* payloadFormat_; - void init (uint8 payloadType, uint32 clockRate); + void init(uint8 payloadType, uint32 clockRate); }; } // end namespace sfl diff --git a/daemon/src/audio/codecs/audiocodecfactory.cpp b/daemon/src/audio/codecs/audiocodecfactory.cpp index 60191b19cce367776b41cade72f016bb9e857c7a..0dc73e5832f3a36ee0b45f5b75d2471e10c84bb0 100644 --- a/daemon/src/audio/codecs/audiocodecfactory.cpp +++ b/daemon/src/audio/codecs/audiocodecfactory.cpp @@ -31,22 +31,25 @@ * as that of the covered work. */ +#include "config.h" #include "audiocodecfactory.h" #include <cstdlib> #include <algorithm> // for std::find #include "fileutils.h" -AudioCodecFactory::AudioCodecFactory() : codecsMap_() +AudioCodecFactory::AudioCodecFactory() : + codecsMap_(), defaultCodecOrder_(), libCache_(), codecInMemory_() { typedef std::vector<sfl::Codec*> CodecVector; CodecVector codecDynamicList(scanCodecDirectory()); + if (codecDynamicList.empty()) - _error ("Error - No codecs available"); + ERROR("Error - No codecs available"); else { for (CodecVector::const_iterator iter = codecDynamicList.begin(); iter != codecDynamicList.end() ; ++iter) { - codecsMap_[ (int) (*iter)->getPayloadType() ] = *iter; - _debug ("Loaded codec %s" , (*iter)->getMimeSubtype().c_str()); + codecsMap_[(int)(*iter)->getPayloadType()] = *iter; + DEBUG("Loaded codec %s" , (*iter)->getMimeSubtype().c_str()); } } } @@ -55,14 +58,15 @@ void AudioCodecFactory::setDefaultOrder() { defaultCodecOrder_.clear(); CodecsMap::const_iterator iter; + for (iter = codecsMap_.begin(); iter != codecsMap_.end(); ++iter) - defaultCodecOrder_.push_back (iter->first); + defaultCodecOrder_.push_back(iter->first); } std::string -AudioCodecFactory::getCodecName (int payload) const +AudioCodecFactory::getCodecName(int payload) const { - CodecsMap::const_iterator iter = codecsMap_.find (payload); + CodecsMap::const_iterator iter = codecsMap_.find(payload); if (iter != codecsMap_.end()) return iter->second->getMimeSubtype(); @@ -73,31 +77,31 @@ AudioCodecFactory::getCodecName (int payload) const std::vector<int32_t > AudioCodecFactory::getAudioCodecList() const { - std::vector<int32_t> list; + std::vector<int32_t> list; - for (CodecsMap::const_iterator iter = codecsMap_.begin(); iter != codecsMap_.end(); ++iter) - if (iter->second) - list.push_back((int32_t)iter->first); + for (CodecsMap::const_iterator iter = codecsMap_.begin(); iter != codecsMap_.end(); ++iter) + if (iter->second) + list.push_back((int32_t)iter->first); - return list; + return list; } sfl::Codec* -AudioCodecFactory::getCodec (int payload) const +AudioCodecFactory::getCodec(int payload) const { - CodecsMap::const_iterator iter = codecsMap_.find (payload); + CodecsMap::const_iterator iter = codecsMap_.find(payload); if (iter != codecsMap_.end()) return iter->second; else { - _error ("CodecDescriptor: cannot find codec %i", payload); + ERROR("CodecDescriptor: cannot find codec %i", payload); return NULL; } } -double AudioCodecFactory::getBitRate (int payload) const +double AudioCodecFactory::getBitRate(int payload) const { - CodecsMap::const_iterator iter = codecsMap_.find (payload); + CodecsMap::const_iterator iter = codecsMap_.find(payload); if (iter != codecsMap_.end()) return iter->second->getBitRate(); @@ -106,9 +110,9 @@ double AudioCodecFactory::getBitRate (int payload) const } -int AudioCodecFactory::getSampleRate (int payload) const +int AudioCodecFactory::getSampleRate(int payload) const { - CodecsMap::const_iterator iter = codecsMap_.find (payload); + CodecsMap::const_iterator iter = codecsMap_.find(payload); if (iter != codecsMap_.end()) return iter->second->getClockRate(); @@ -116,7 +120,7 @@ int AudioCodecFactory::getSampleRate (int payload) const return 0; } -void AudioCodecFactory::saveActiveCodecs (const std::vector<std::string>& list) +void AudioCodecFactory::saveActiveCodecs(const std::vector<std::string>& list) { defaultCodecOrder_.clear(); // list contains the ordered payload of active codecs picked by the user @@ -124,8 +128,9 @@ void AudioCodecFactory::saveActiveCodecs (const std::vector<std::string>& list) for (std::vector<std::string>::const_iterator iter = list.begin(); iter != list.end(); ++iter) { int payload = std::atoi(iter->c_str()); - if (isCodecLoaded (payload)) - defaultCodecOrder_.push_back ( (int) payload); + + if (isCodecLoaded(payload)) + defaultCodecOrder_.push_back((int) payload); } } @@ -133,8 +138,8 @@ void AudioCodecFactory::saveActiveCodecs (const std::vector<std::string>& list) AudioCodecFactory::~AudioCodecFactory() { for (std::vector<CodecHandlePointer>::const_iterator iter = - codecInMemory_.begin(); iter != codecInMemory_.end(); ++iter) - unloadCodec (*iter); + codecInMemory_.begin(); iter != codecInMemory_.end(); ++iter) + unloadCodec(*iter); } std::vector<sfl::Codec*> AudioCodecFactory::scanCodecDirectory() @@ -142,95 +147,106 @@ std::vector<sfl::Codec*> AudioCodecFactory::scanCodecDirectory() std::vector<sfl::Codec*> codecs; std::vector<std::string> dirToScan; - dirToScan.push_back(std::string(HOMEDIR) + DIR_SEPARATOR_STR "." PROGDIR "/"); + dirToScan.push_back(std::string(HOMEDIR) + DIR_SEPARATOR_STR "." PACKAGE "/"); dirToScan.push_back(CODECS_DIR "/"); const char *envDir = getenv("CODECS_PATH"); + if (envDir) dirToScan.push_back(std::string(envDir) + DIR_SEPARATOR_STR); + const char *progDir = get_program_dir(); + if (progDir) dirToScan.push_back(std::string(progDir) + DIR_SEPARATOR_STR + "audio/codecs/"); for (size_t i = 0 ; i < dirToScan.size() ; i++) { std::string dirStr = dirToScan[i]; - _debug ("CodecDescriptor: Scanning %s to find audio codecs....", dirStr.c_str()); + DEBUG("CodecDescriptor: Scanning %s to find audio codecs....", dirStr.c_str()); + + DIR *dir = opendir(dirStr.c_str()); - DIR *dir = opendir (dirStr.c_str()); if (!dir) continue; dirent *dirStruct; - while ( (dirStruct = readdir (dir))) { + + while ((dirStruct = readdir(dir))) { std::string file = dirStruct->d_name ; - if (file == CURRENT_DIR or file == PARENT_DIR) + + if (file == "." or file == "..") continue; - if (seemsValid (file) && !alreadyInCache (file)) { - sfl::Codec* audioCodec = loadCodec (dirStr+file); + if (seemsValid(file) && !alreadyInCache(file)) { + sfl::Codec* audioCodec = loadCodec(dirStr+file); + if (audioCodec) { - codecs.push_back (audioCodec); - libCache_.push_back (file); + codecs.push_back(audioCodec); + libCache_.push_back(file); } } } - closedir (dir); + closedir(dir); } return codecs; } -sfl::Codec* AudioCodecFactory::loadCodec (const std::string &path) +sfl::Codec* AudioCodecFactory::loadCodec(const std::string &path) { - void * codecHandle = dlopen (path.c_str() , RTLD_LAZY); + void * codecHandle = dlopen(path.c_str() , RTLD_LAZY); + if (!codecHandle) { - _error("%s\n", dlerror()); + ERROR("%s\n", dlerror()); return NULL; } dlerror(); - create_t* createCodec = (create_t*) dlsym (codecHandle , "create"); + create_t* createCodec = (create_t*) dlsym(codecHandle , "create"); char *error = dlerror(); + if (error) { - _error("%s\n", error); + ERROR("%s\n", error); return NULL; } sfl::Codec* a = createCodec(); - codecInMemory_.push_back (CodecHandlePointer (a, codecHandle)); + codecInMemory_.push_back(CodecHandlePointer(a, codecHandle)); return a; } -void AudioCodecFactory::unloadCodec (CodecHandlePointer p) +void AudioCodecFactory::unloadCodec(CodecHandlePointer p) { - destroy_t* destroyCodec = (destroy_t*) dlsym (p.second , "destroy"); + destroy_t* destroyCodec = (destroy_t*) dlsym(p.second , "destroy"); char *error = dlerror(); + if (error) { - _error("%s\n", error); + ERROR("%s\n", error); return; } - destroyCodec (p.first); + destroyCodec(p.first); - dlclose (p.second); + dlclose(p.second); } -sfl::Codec* AudioCodecFactory::instantiateCodec (int payload) const +sfl::Codec* AudioCodecFactory::instantiateCodec(int payload) const { std::vector< CodecHandlePointer >::const_iterator iter; for (iter = codecInMemory_.begin(); iter != codecInMemory_.end(); ++iter) { if (iter->first->getPayloadType() == payload) { - create_t* createCodec = (create_t*) dlsym (iter->second , "create"); + create_t* createCodec = (create_t*) dlsym(iter->second , "create"); char *error = dlerror(); + if (error) - _error("%s\n", error); + ERROR("%s\n", error); else return createCodec(); } @@ -239,54 +255,63 @@ sfl::Codec* AudioCodecFactory::instantiateCodec (int payload) const return NULL; } -bool AudioCodecFactory::seemsValid (const std::string &lib) +bool AudioCodecFactory::seemsValid(const std::string &lib) { // The name of the shared library seems valid <==> it looks like libcodec_xxx.so // We check this - std::string prefix = SFL_CODEC_VALID_PREFIX; - std::string suffix = SFL_CODEC_VALID_EXTEN; + + static const std::string prefix("libcodec_"); + static const std::string suffix(".so"); ssize_t len = lib.length() - prefix.length() - suffix.length(); + if (len < 0) return false; // Second: check the extension of the file name. // If it is different than SFL_CODEC_VALID_EXTEN , not a SFL shared library - if (lib.substr (lib.length() - suffix.length() , lib.length()) != suffix) + if (lib.substr(lib.length() - suffix.length() , lib.length()) != suffix) return false; #ifndef HAVE_SPEEX_CODEC - if (lib.substr (prefix.length() , len) == SPEEX_STRING_DESCRIPTION) + + if (lib.substr(prefix.length() , len) == "speex") return false; + #endif #ifndef HAVE_GSM_CODEC - if (lib.substr (prefix.length() , len) == GSM_STRING_DESCRIPTION) + + if (lib.substr(prefix.length() , len) == "gsm") return false; + #endif #ifndef BUILD_ILBC - if (lib.substr (prefix.length() , len) == ILBC_STRING_DESCRIPTION) + + if (lib.substr(prefix.length() , len) == "ilbc") return false; + #endif - if (lib.substr (0, prefix.length()) == prefix) - if (lib.substr (lib.length() - suffix.length() , suffix.length()) == suffix) + if (lib.substr(0, prefix.length()) == prefix) + if (lib.substr(lib.length() - suffix.length() , suffix.length()) == suffix) return true; return false; } bool -AudioCodecFactory::alreadyInCache (const std::string &lib) +AudioCodecFactory::alreadyInCache(const std::string &lib) { return std::find(libCache_.begin(), libCache_.end(), lib) != libCache_.end(); } -bool AudioCodecFactory::isCodecLoaded (int payload) const +bool AudioCodecFactory::isCodecLoaded(int payload) const { CodecsMap::const_iterator iter; + for (iter = codecsMap_.begin(); iter != codecsMap_.end(); ++iter) if (iter->first == payload) return true; @@ -294,7 +319,7 @@ bool AudioCodecFactory::isCodecLoaded (int payload) const return false; } -std::vector <std::string> AudioCodecFactory::getCodecSpecifications (const int32_t& payload) const +std::vector <std::string> AudioCodecFactory::getCodecSpecifications(const int32_t& payload) const { std::vector<std::string> v; std::stringstream ss; @@ -303,7 +328,7 @@ std::vector <std::string> AudioCodecFactory::getCodecSpecifications (const int32 v.push_back(getCodecName(static_cast<int>(payload))); // Add the sample rate - ss << getSampleRate (static_cast<int>(payload)); + ss << getSampleRate(static_cast<int>(payload)); v.push_back(ss.str()); ss.str(""); diff --git a/daemon/src/audio/codecs/audiocodecfactory.h b/daemon/src/audio/codecs/audiocodecfactory.h index 17f04cfab416e599e042651fa30144fec1b471f0..1b4e7a4396183903a77521b6106d5070a9e81af7 100644 --- a/daemon/src/audio/codecs/audiocodecfactory.h +++ b/daemon/src/audio/codecs/audiocodecfactory.h @@ -48,12 +48,11 @@ /** Maps a pointer on an audiocodec object to a payload */ typedef std::map<int, sfl::Codec*> CodecsMap; -class AudioCodecFactory -{ +class AudioCodecFactory { public: - AudioCodecFactory(); + AudioCodecFactory(); - ~AudioCodecFactory(); + ~AudioCodecFactory(); /** * Get codec name by its payload @@ -61,7 +60,7 @@ class AudioCodecFactory * same as getPayload() * @return std::string The name of the codec */ - std::string getCodecName (int payload) const; + std::string getCodecName(int payload) const; std::vector<int32_t > getAudioCodecList() const; /** @@ -69,7 +68,7 @@ class AudioCodecFactory * @param payload The payload looked for * @return AudioCodec* A pointer on a AudioCodec object */ - sfl::Codec* getCodec (int payload) const; + sfl::Codec* getCodec(int payload) const; /** * Set the default codecs order. @@ -82,26 +81,26 @@ class AudioCodecFactory * @param payload The payload of the codec * @return double The bit rate */ - double getBitRate (int payload) const; + double getBitRate(int payload) const; /** * Get the clock rate of the specified codec * @param payload The payload of the codec * @return int The clock rate of the specified codec */ - int getSampleRate (int payload) const; + int getSampleRate(int payload) const; /** * Set the order of codecs by their payload * @param list The ordered list sent by DBus */ - void saveActiveCodecs (const std::vector<std::string>& list); + void saveActiveCodecs(const std::vector<std::string>& list); /** * Instantiate a codec, used in AudioRTP to get an instance of Codec per call * @param CodecHandlePointer The map containing the pointer on the object and the pointer on the handle function */ - sfl::Codec* instantiateCodec (int payload) const; + sfl::Codec* instantiateCodec(int payload) const; /** * For a given codec, return its specification @@ -109,7 +108,7 @@ class AudioCodecFactory * @param payload The RTP payload of the codec * @return std::vector <std::string> A vector containing codec's name, sample rate, bandwidth and bit rate */ - std::vector <std::string> getCodecSpecifications (const int32_t& payload) const; + std::vector <std::string> getCodecSpecifications(const int32_t& payload) const; /** * Check if the audiocodec object has been successfully created @@ -117,7 +116,7 @@ class AudioCodecFactory * @return bool True if the audiocodec has been created * false otherwise */ - bool isCodecLoaded (int payload) const; + bool isCodecLoaded(int payload) const; private: /** Enable us to keep the handle pointer on the codec dynamicaly loaded so that we could destroy when we dont need it anymore */ @@ -129,20 +128,20 @@ class AudioCodecFactory * And load the dynamic library * @return std::vector<AudioCodec*> The list of the codec object successfully loaded in memory */ - std::vector<sfl::Codec *> scanCodecDirectory (); + std::vector<sfl::Codec *> scanCodecDirectory(); /** * Load a codec * @param std::string The path of the shared ( dynamic ) library. * @return AudioCodec* the pointer of the object loaded. */ - sfl::Codec* loadCodec (const std::string &path); + sfl::Codec* loadCodec(const std::string &path); /** * Unload a codec * @param CodecHandlePointer The map containing the pointer on the object and the pointer on the handle function */ - void unloadCodec (CodecHandlePointer); + void unloadCodec(CodecHandlePointer); /** * Check if the files found in searched directories seems valid @@ -150,7 +149,7 @@ class AudioCodecFactory * @return bool True if the file name begins with libcodec_ and ends with .so * false otherwise */ - static bool seemsValid (const std::string &lib); + static bool seemsValid(const std::string &lib); /** * Check if the codecs shared library has already been scanned during the session @@ -159,7 +158,7 @@ class AudioCodecFactory * @return bool True if the codecs has been scanned * false otherwise */ - bool alreadyInCache (const std::string &lib); + bool alreadyInCache(const std::string &lib); /** * Map the payload of a codec and the object associated ( AudioCodec * ) diff --git a/daemon/src/audio/codecs/celtcodec.cpp b/daemon/src/audio/codecs/celtcodec.cpp index 276728821bffa211bddfffd5b1d8a17dae720acc..ccc59910e16944ee6782903a18bb8e22e6597ede 100644 --- a/daemon/src/audio/codecs/celtcodec.cpp +++ b/daemon/src/audio/codecs/celtcodec.cpp @@ -32,23 +32,20 @@ #include <cstdio> #include <celt/celt.h> #include <stdexcept> +#include "noncopyable.h" - -class Celt : public sfl::AudioCodec -{ +class Celt : public sfl::AudioCodec { public: - Celt (int payload=115) : sfl::AudioCodec (payload, "celt") { - - _clockRate = 32000; - _frameSize = 320; // fixed frameSize, TODO: support variable size from 64 to 512 - _channel = 1; - _bitrate = 0; - _hasDynamicPayload = true; - + Celt(int payload = 115) : sfl::AudioCodec(payload, "celt"), mode_(0), enc_(0), dec_(0) { + clockRate_ = 32000; + frameSize_ = 320; // fixed frameSize, TODO: support variable size from 64 to 512 + channel_ = 1; + bitrate_ = 0; + hasDynamicPayload_ = true; int error = 0; - _mode = celt_mode_create (_clockRate, _frameSize, &error); + mode_ = celt_mode_create(clockRate_, frameSize_, &error); if (error != CELT_OK) { switch (error) { @@ -79,81 +76,62 @@ class Celt : public sfl::AudioCodec } - if (_mode == NULL) + if (mode_ == NULL) throw std::runtime_error("Celt: Failed to create Celt mode"); - // bytes_per_packet = 1024; - // if (bytes_per_packet < 0 || bytes_per_packet > MAX_PACKET) - // { - // throw std::runtime_error("bytes per packet must be between 0 and %d"); - // } - - // celt_mode_info(mode, CELT_GET_FRAME_SIZE, &frame_size); - // celt_mode_info(mode, CELT_GET_NB_CHANNELS, &_channel); - - _enc = celt_encoder_create (_mode, _channel, &error); + enc_ = celt_encoder_create(mode_, channel_, &error); + dec_ = celt_decoder_create(mode_, channel_, &error); - _dec = celt_decoder_create (_mode, _channel, &error); - - celt_encoder_ctl (_enc, CELT_SET_COMPLEXITY (2)); - celt_decoder_ctl (_dec, CELT_SET_COMPLEXITY (2)); - - celt_encoder_ctl (_enc, CELT_SET_PREDICTION (2)); - celt_decoder_ctl (_dec, CELT_SET_PREDICTION (2)); + celt_encoder_ctl(enc_, CELT_SET_COMPLEXITY(2)); + celt_decoder_ctl(dec_, CELT_SET_COMPLEXITY(2)); + celt_encoder_ctl(enc_, CELT_SET_PREDICTION(2)); + celt_decoder_ctl(dec_, CELT_SET_PREDICTION(2)); } - Celt (const Celt&); - Celt& operator= (const Celt&); + NON_COPYABLE(Celt); ~Celt() { - celt_encoder_destroy (_enc); - celt_decoder_destroy (_dec); - celt_mode_destroy (_mode); + celt_encoder_destroy(enc_); + celt_decoder_destroy(dec_); + celt_mode_destroy(mode_); } - virtual int decode (short *dst, unsigned char *src, size_t buf_size) { + virtual int decode(short *dst, unsigned char *src, size_t buf_size) { #ifdef BUILD_CELT_91 // == 91 - //int err = 0; - /*err =*/ celt_decode (_dec, src, buf_size, (celt_int16*) dst, _frameSize); + celt_decode(dec_, src, buf_size, (celt_int16*) dst, frameSize_); #endif #ifdef BUILD_CELT_71 - //int err = 0; // FIXME: check error code - /*err =*/ celt_decode (_dec, src, buf_size, (celt_int16*) dst); + celt_decode(dec_, src, buf_size, (celt_int16*) dst); #endif - return _frameSize; + return frameSize_; } - virtual int encode (unsigned char *dst, short *src, size_t buf_size) { + virtual int encode(unsigned char *dst, short *src, size_t buf_size) { int len = 0; #ifdef BUILD_CELT_91// == 91 - len = celt_encode (_enc, (celt_int16*) src, _frameSize, dst, buf_size); + len = celt_encode(enc_, (celt_int16*) src, frameSize_, dst, buf_size); #endif #ifdef BUILD_CELT_71 - len = celt_encode (_enc, (celt_int16*) src, (celt_int16 *) src, dst, buf_size); + len = celt_encode(enc_, (celt_int16*) src, (celt_int16 *) src, dst, buf_size); #endif return len; } private: + CELTMode *mode_; - CELTMode *_mode; - - CELTEncoder *_enc; - CELTDecoder *_dec; - - celt_int32 _celt_frame_size; - celt_int32 skip; - + CELTEncoder *enc_; + CELTDecoder *dec_; }; // the class factories extern "C" sfl::Codec* create() { - return new Celt (115); + return new Celt(115); } -extern "C" void destroy (sfl::Codec* a) +extern "C" void destroy(sfl::Codec* a) { delete a; } diff --git a/daemon/src/audio/codecs/g722.cpp b/daemon/src/audio/codecs/g722.cpp index 26edcb1dfd884d497f5edee9df5777bd8be70993..7a7931ce7a5e3df6b21bef52201e28d74061c07a 100644 --- a/daemon/src/audio/codecs/g722.cpp +++ b/daemon/src/audio/codecs/g722.cpp @@ -36,67 +36,56 @@ #include "../common.h" #include "audiocodec.h" #include "g722.h" +#include "noncopyable.h" #include <stdlib.h> #include <string.h> #include <cassert> -#define TRUE 1 -#define FALSE 0 - - -class G722 : public sfl::AudioCodec -{ +class G722 : public sfl::AudioCodec { public: - - G722 (int payload=9) - : sfl::AudioCodec (payload, "G722") { - _clockRate = 16000; - _frameSize = 320; // samples, 20 ms at 16kHz - _channel = 1; - _bitrate = 64; - _hasDynamicPayload = false; - - - decode_s = new g722_decode_state_t; - encode_s = new g722_encode_state_t; - - g722_decode_init (); - g722_encode_init (); - + G722(int payload=9) : sfl::AudioCodec(payload, "G722"), + decode_s(new g722_decode_state_t), + encode_s(new g722_encode_state_t) { + clockRate_ = 16000; + frameSize_ = 320; // samples, 20 ms at 16kHz + channel_ = 1; + bitrate_ = 64; + hasDynamicPayload_ = false; + + g722_decode_init(); + g722_encode_init(); } ~G722() { - g722_decode_release(); - g722_encode_release(); + g722_decode_release(); + g722_encode_release(); } - virtual int decode (short *dst, unsigned char *src, size_t buf_size) { - assert(buf_size == _frameSize / sizeof(SFLDataFormat) * encode_s->bits_per_sample / 8); - return g722_decode ( (int16_t*) dst, (const uint8_t*) src, buf_size); + virtual int decode(short *dst, unsigned char *src, size_t buf_size) { + assert(buf_size == frameSize_ / sizeof(SFLDataFormat) * encode_s->bits_per_sample / 8); + return g722_decode((int16_t*) dst, (const uint8_t*) src, buf_size); } - virtual int encode (unsigned char *dst, short *src, size_t buf_size) { - int out = g722_encode ( (uint8_t*) dst, (const int16_t*) src, _frameSize); + virtual int encode(unsigned char *dst, short *src, size_t buf_size) { + int out = g722_encode((uint8_t*) dst, (const int16_t*) src, frameSize_); assert((size_t)out <= buf_size); return out; } - void g722_encode_init (void) { - - encode_s->itu_test_mode = FALSE; + void g722_encode_init() { + encode_s->itu_test_mode = false; // 8 => 64 kbps; 7 => 56 kbps; 6 => 48 kbps encode_s->bits_per_sample = 8; // Enable 8khz mode, encode using lower subband only - encode_s->eight_k = FALSE; + encode_s->eight_k = false; - - // Never set packed TRUE when using 64 kbps - encode_s->packed = FALSE; + // Never set packed true when using 64 kbps + encode_s->packed = false; memset(encode_s->band, 0, sizeof(decode_s->band)); encode_s->band[0].det = 32; @@ -110,18 +99,18 @@ class G722 : public sfl::AudioCodec decode_s->out_bits = 0; } - void g722_decode_init (void) { + void g722_decode_init() { - decode_s->itu_test_mode = FALSE; + decode_s->itu_test_mode = false; // 8 => 64 kbps; 7 => 56 kbps; 6 => 48 kbps decode_s->bits_per_sample = 8; // Enable 8khz mode, encode using lower subband only - decode_s->eight_k = FALSE; + decode_s->eight_k = false; - // Never set packed TRUE when using 64 kbps - decode_s->packed = FALSE; + // Never set packed true when using 64 kbps + decode_s->packed = false; memset(decode_s->band, 0, sizeof(decode_s->band)); decode_s->band[0].det = 32; @@ -137,7 +126,7 @@ class G722 : public sfl::AudioCodec decode_s->out_bits = 0; } - int16_t saturate (int32_t amp) { + int16_t saturate(int32_t amp) { int16_t amp16 = 0; /* Hopefully this is optimised for the common case - not clipping */ @@ -153,7 +142,7 @@ class G722 : public sfl::AudioCodec } - void block4_encode (int band, int d) { + void block4_encode(int band, int d) { int wd1 = 0; int wd2 = 0; int wd3 = 0; @@ -161,24 +150,24 @@ class G722 : public sfl::AudioCodec /* Block 4, RECONS */ encode_s->band[band].d[0] = d; - encode_s->band[band].r[0] = saturate (encode_s->band[band].s + d); + encode_s->band[band].r[0] = saturate(encode_s->band[band].s + d); /* Block 4, PARREC */ - encode_s->band[band].p[0] = saturate (encode_s->band[band].sz + d); + encode_s->band[band].p[0] = saturate(encode_s->band[band].sz + d); /* Block 4, UPPOL2 */ for (i = 0; i < 3; i++) encode_s->band[band].sg[i] = encode_s->band[band].p[i] >> 15; - wd1 = saturate (encode_s->band[band].a[1] << 2); + wd1 = saturate(encode_s->band[band].a[1] << 2); wd2 = (encode_s->band[band].sg[0] == encode_s->band[band].sg[1]) ? -wd1 : wd1; if (wd2 > 32767) wd2 = 32767; - wd3 = (wd2 >> 7) + ( (encode_s->band[band].sg[0] == encode_s->band[band].sg[2]) ? 128 : -128); + wd3 = (wd2 >> 7) + ((encode_s->band[band].sg[0] == encode_s->band[band].sg[2]) ? 128 : -128); wd3 += (encode_s->band[band].a[2]*32512) >> 15; @@ -198,9 +187,9 @@ class G722 : public sfl::AudioCodec wd2 = (encode_s->band[band].a[1]*32640) >> 15; - encode_s->band[band].ap[1] = saturate (wd1 + wd2); + encode_s->band[band].ap[1] = saturate(wd1 + wd2); - wd3 = saturate (15360 - encode_s->band[band].ap[2]); + wd3 = saturate(15360 - encode_s->band[band].ap[2]); if (encode_s->band[band].ap[1] > wd3) encode_s->band[band].ap[1] = wd3; @@ -216,7 +205,7 @@ class G722 : public sfl::AudioCodec encode_s->band[band].sg[i] = encode_s->band[band].d[i] >> 15; wd2 = (encode_s->band[band].sg[i] == encode_s->band[band].sg[0]) ? wd1 : -wd1; wd3 = (encode_s->band[band].b[i]*32640) >> 15; - encode_s->band[band].bp[i] = saturate (wd2 + wd3); + encode_s->band[band].bp[i] = saturate(wd2 + wd3); } /* Block 4, DELAYA */ @@ -232,32 +221,32 @@ class G722 : public sfl::AudioCodec } /* Block 4, FILTEP */ - wd1 = saturate (encode_s->band[band].r[1] + encode_s->band[band].r[1]); + wd1 = saturate(encode_s->band[band].r[1] + encode_s->band[band].r[1]); wd1 = (encode_s->band[band].a[1]*wd1) >> 15; - wd2 = saturate (encode_s->band[band].r[2] + encode_s->band[band].r[2]); + wd2 = saturate(encode_s->band[band].r[2] + encode_s->band[band].r[2]); wd2 = (encode_s->band[band].a[2]*wd2) >> 15; - encode_s->band[band].sp = saturate (wd1 + wd2); + encode_s->band[band].sp = saturate(wd1 + wd2); /* Block 4, FILTEZ */ encode_s->band[band].sz = 0; for (i = 6; i > 0; i--) { - wd1 = saturate (encode_s->band[band].d[i] + encode_s->band[band].d[i]); + wd1 = saturate(encode_s->band[band].d[i] + encode_s->band[band].d[i]); encode_s->band[band].sz += (encode_s->band[band].b[i]*wd1) >> 15; } - encode_s->band[band].sz = saturate (encode_s->band[band].sz); + encode_s->band[band].sz = saturate(encode_s->band[band].sz); /* Block 4, PREDIC */ - encode_s->band[band].s = saturate (encode_s->band[band].sp + encode_s->band[band].sz); + encode_s->band[band].s = saturate(encode_s->band[band].sp + encode_s->band[band].sz); } - void block4_decode (int band, int d) { + void block4_decode(int band, int d) { int wd1 = 0; int wd2 = 0; int wd3 = 0; @@ -265,17 +254,17 @@ class G722 : public sfl::AudioCodec /* Block 4, RECONS */ decode_s->band[band].d[0] = d; - decode_s->band[band].r[0] = saturate (decode_s->band[band].s + d); + decode_s->band[band].r[0] = saturate(decode_s->band[band].s + d); /* Block 4, PARREC */ - decode_s->band[band].p[0] = saturate (decode_s->band[band].sz + d); + decode_s->band[band].p[0] = saturate(decode_s->band[band].sz + d); /* Block 4, UPPOL2 */ for (i = 0; i < 3; i++) decode_s->band[band].sg[i] = decode_s->band[band].p[i] >> 15; - wd1 = saturate (decode_s->band[band].a[1] << 2); + wd1 = saturate(decode_s->band[band].a[1] << 2); wd2 = (decode_s->band[band].sg[0] == decode_s->band[band].sg[1]) ? -wd1 : wd1; @@ -304,9 +293,9 @@ class G722 : public sfl::AudioCodec wd2 = (decode_s->band[band].a[1]*32640) >> 15; - decode_s->band[band].ap[1] = saturate (wd1 + wd2); + decode_s->band[band].ap[1] = saturate(wd1 + wd2); - wd3 = saturate (15360 - decode_s->band[band].ap[2]); + wd3 = saturate(15360 - decode_s->band[band].ap[2]); if (decode_s->band[band].ap[1] > wd3) decode_s->band[band].ap[1] = wd3; @@ -322,7 +311,7 @@ class G722 : public sfl::AudioCodec decode_s->band[band].sg[i] = decode_s->band[band].d[i] >> 15; wd2 = (decode_s->band[band].sg[i] == decode_s->band[band].sg[0]) ? wd1 : -wd1; wd3 = (decode_s->band[band].b[i]*32640) >> 15; - decode_s->band[band].bp[i] = saturate (wd2 + wd3); + decode_s->band[band].bp[i] = saturate(wd2 + wd3); } /* Block 4, DELAYA */ @@ -338,28 +327,28 @@ class G722 : public sfl::AudioCodec } /* Block 4, FILTEP */ - wd1 = saturate (decode_s->band[band].r[1] + decode_s->band[band].r[1]); + wd1 = saturate(decode_s->band[band].r[1] + decode_s->band[band].r[1]); wd1 = (decode_s->band[band].a[1]*wd1) >> 15; - wd2 = saturate (decode_s->band[band].r[2] + decode_s->band[band].r[2]); + wd2 = saturate(decode_s->band[band].r[2] + decode_s->band[band].r[2]); wd2 = (decode_s->band[band].a[2]*wd2) >> 15; - decode_s->band[band].sp = saturate (wd1 + wd2); + decode_s->band[band].sp = saturate(wd1 + wd2); /* Block 4, FILTEZ */ decode_s->band[band].sz = 0; for (i = 6; i > 0; i--) { - wd1 = saturate (decode_s->band[band].d[i] + decode_s->band[band].d[i]); + wd1 = saturate(decode_s->band[band].d[i] + decode_s->band[band].d[i]); decode_s->band[band].sz += (decode_s->band[band].b[i]*wd1) >> 15; } - decode_s->band[band].sz = saturate (decode_s->band[band].sz); + decode_s->band[band].sz = saturate(decode_s->band[band].sz); /* Block 4, PREDIC */ - decode_s->band[band].s = saturate (decode_s->band[band].sp + decode_s->band[band].sz); + decode_s->band[band].s = saturate(decode_s->band[band].sp + decode_s->band[band].sz); } int g722_encode_release() { @@ -375,7 +364,7 @@ class G722 : public sfl::AudioCodec return 0; } - int g722_decode (int16_t amp[], const uint8_t g722_data[], int len) { + int g722_decode(int16_t amp[], const uint8_t g722_data[], int len) { static const int wl[8] = {-60, -30, 58, 172, 334, 538, 1198, 3042 }; static const int rl42[16] = {0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0 }; static const int ilb[32] = { @@ -454,7 +443,7 @@ class G722 : public sfl::AudioCodec decode_s->in_bits += 8; } - code = decode_s->in_buffer & ( (1 << decode_s->bits_per_sample) - 1); + code = decode_s->in_buffer & ((1 << decode_s->bits_per_sample) - 1); decode_s->in_buffer >>= decode_s->bits_per_sample; decode_s->in_bits -= decode_s->bits_per_sample; @@ -527,7 +516,7 @@ class G722 : public sfl::AudioCodec decode_s->band[0].det = wd3 << 2; - block4_decode (0, dlowt); + block4_decode(0, dlowt); if (!decode_s->eight_k) { /* Block 2H, INVQAH */ @@ -565,12 +554,12 @@ class G722 : public sfl::AudioCodec decode_s->band[1].det = wd3 << 2; - block4_decode (1, dhigh); + block4_decode(1, dhigh); } if (decode_s->itu_test_mode) { - amp[outlen++] = (int16_t) (rlow << 1); - amp[outlen++] = (int16_t) (rhigh << 1); + amp[outlen++] = (int16_t)(rlow << 1); + amp[outlen++] = (int16_t)(rhigh << 1); } else { if (decode_s->eight_k) { amp[outlen++] = (int16_t) rlow; @@ -592,9 +581,9 @@ class G722 : public sfl::AudioCodec xout1 += decode_s->x[2*i + 1]*qmf_coeffs[11 - i]; } - amp[outlen++] = (int16_t) (xout1 >> 12); + amp[outlen++] = (int16_t)(xout1 >> 12); - amp[outlen++] = (int16_t) (xout2 >> 12); + amp[outlen++] = (int16_t)(xout2 >> 12); } } } @@ -602,7 +591,7 @@ class G722 : public sfl::AudioCodec return outlen; } - int g722_encode (uint8_t g722_data[], const int16_t amp[], int len) { + int g722_encode(uint8_t g722_data[], const int16_t amp[], int len) { static const int q6[32] = { 0, 35, 72, 110, 150, 190, 233, 276, 323, 370, 422, 473, 530, 587, 650, 714, @@ -713,7 +702,7 @@ class G722 : public sfl::AudioCodec } /* Block 1L, SUBTRA */ - el = saturate (xlow - encode_s->band[0].s); + el = saturate(xlow - encode_s->band[0].s); /* Block 1L, QUANTL */ wd = (el >= 0) ? el : - (el + 1); @@ -751,14 +740,14 @@ class G722 : public sfl::AudioCodec encode_s->band[0].det = wd3 << 2; - block4_encode (0, dlow); + block4_encode(0, dlow); if (encode_s->eight_k) { /* Just leave the high bits as zero */ code = (0xC0 | ilow) >> (8 - encode_s->bits_per_sample); } else { /* Block 1H, SUBTRA */ - eh = saturate (xhigh - encode_s->band[1].s); + eh = saturate(xhigh - encode_s->band[1].s); /* Block 1H, QUANTH */ wd = (eh >= 0) ? eh : - (eh + 1); @@ -789,9 +778,9 @@ class G722 : public sfl::AudioCodec encode_s->band[1].det = wd3 << 2; - block4_encode (1, dhigh); + block4_encode(1, dhigh); - code = ( (ihigh << 6) | ilow) >> (8 - encode_s->bits_per_sample); + code = ((ihigh << 6) | ilow) >> (8 - encode_s->bits_per_sample); } if (encode_s->packed) { @@ -800,7 +789,7 @@ class G722 : public sfl::AudioCodec encode_s->out_bits += encode_s->bits_per_sample; if (encode_s->out_bits >= 8) { - g722_data[g722_bytes++] = (uint8_t) (encode_s->out_buffer & 0xFF); + g722_data[g722_bytes++] = (uint8_t)(encode_s->out_buffer & 0xFF); encode_s->out_bits -= 8; encode_s->out_buffer >>= 8; } @@ -813,6 +802,7 @@ class G722 : public sfl::AudioCodec } private: + NON_COPYABLE(G722); g722_decode_state_t *decode_s; g722_encode_state_t *encode_s; @@ -822,12 +812,11 @@ class G722 : public sfl::AudioCodec // the class factories extern "C" sfl::Codec* create() { - return new G722 (9); + return new G722(9); } -extern "C" void destroy (sfl::Codec* a) +extern "C" void destroy(sfl::Codec* a) { delete a; } - diff --git a/daemon/src/audio/codecs/g722.h b/daemon/src/audio/codecs/g722.h index cc1cbcd3dc4f49db16e94cbe58e970425aedf93e..cb589e54c801af74b04f7ed4c236ede61839ee0c 100644 --- a/daemon/src/audio/codecs/g722.h +++ b/daemon/src/audio/codecs/g722.h @@ -136,13 +136,13 @@ typedef struct { extern "C" { #endif - void g722_encode_init (void); + void g722_encode_init(); int g722_encode_release(); - int g722_encode (uint8_t g722_data[], const int16_t amp[], int len); + int g722_encode(uint8_t g722_data[], const int16_t amp[], int len); - void g722_decode_init (void); + void g722_decode_init(); int g722_decode_release(); - int g722_decode (int16_t amp[], const uint8_t g722_data[], int len); + int g722_decode(int16_t amp[], const uint8_t g722_data[], int len); #ifdef __cplusplus } diff --git a/daemon/src/audio/codecs/gsmcodec.cpp b/daemon/src/audio/codecs/gsmcodec.cpp index 30c66cc6d873ab5cd4f31853f80911e05a88f66b..8160253587a3dc2df02f4ce596530d0fa1d6ac80 100644 --- a/daemon/src/audio/codecs/gsmcodec.cpp +++ b/daemon/src/audio/codecs/gsmcodec.cpp @@ -31,6 +31,7 @@ #include "audiocodec.h" +#include "noncopyable.h" #include <cassert> #include <stdexcept> @@ -42,62 +43,56 @@ extern "C" { * GSM audio codec C++ class (over gsm/gsm.h) */ -class Gsm : public sfl::AudioCodec -{ +class Gsm : public sfl::AudioCodec { public: // _payload should be 3 - Gsm (int payload=3) : sfl::AudioCodec (payload, "GSM"), _decode_gsmhandle (NULL), _encode_gsmhandle (NULL) { - _clockRate = 8000; - _frameSize = 160; // samples, 20 ms at 8kHz - _channel = 1; - _bitrate = 13.3; - _hasDynamicPayload = false; - - if (! (_decode_gsmhandle = gsm_create())) + Gsm(int payload=3) : sfl::AudioCodec(payload, "GSM"), decode_gsmhandle_(NULL), encode_gsmhandle_(NULL) { + clockRate_ = 8000; + frameSize_ = 160; // samples, 20 ms at 8kHz + channel_ = 1; + bitrate_ = 13.3; + hasDynamicPayload_ = false; + + if (!(decode_gsmhandle_ = gsm_create())) throw std::runtime_error("ERROR: decode_gsm_create\n"); - if (! (_encode_gsmhandle = gsm_create())) + if (!(encode_gsmhandle_ = gsm_create())) throw std::runtime_error("ERROR: encode_gsm_create\n"); } - Gsm (const Gsm&); - - Gsm& operator= (const Gsm&); - - virtual ~Gsm (void) { - gsm_destroy (_decode_gsmhandle); - gsm_destroy (_encode_gsmhandle); + virtual ~Gsm() { + gsm_destroy(decode_gsmhandle_); + gsm_destroy(encode_gsmhandle_); } - virtual int decode (short * dst, unsigned char * src, size_t buf_size) { - assert(buf_size == 33); - (void) buf_size; + virtual int decode(short * dst, unsigned char * src, size_t buf_size) { + assert(buf_size == 33); - if (gsm_decode (_decode_gsmhandle, (gsm_byte*) src, (gsm_signal*) dst) < 0) + if (gsm_decode(decode_gsmhandle_, (gsm_byte*) src, (gsm_signal*) dst) < 0) throw std::runtime_error("ERROR: gsm_decode\n"); - return _frameSize; + return frameSize_; } - virtual int encode (unsigned char * dst, short * src, size_t buf_size) { - (void) buf_size; + virtual int encode(unsigned char * dst, short * src, size_t buf_size) { assert(buf_size >= 33); - gsm_encode (_encode_gsmhandle, (gsm_signal*) src, (gsm_byte*) dst); + gsm_encode(encode_gsmhandle_, (gsm_signal*) src, (gsm_byte*) dst); return 33; } private: - gsm _decode_gsmhandle; - gsm _encode_gsmhandle; + NON_COPYABLE(Gsm); + gsm decode_gsmhandle_; + gsm encode_gsmhandle_; }; extern "C" sfl::Codec* create() { - return new Gsm (3); + return new Gsm(3); } -extern "C" void destroy (sfl::Codec* a) +extern "C" void destroy(sfl::Codec* a) { delete a; } diff --git a/daemon/src/audio/codecs/speexcodec.h b/daemon/src/audio/codecs/speexcodec.h index 2c93a2e238e13880b974271a5d26039692d92aac..7b53fcdce261ed1b24bb644341080f3faee599b9 100644 --- a/daemon/src/audio/codecs/speexcodec.h +++ b/daemon/src/audio/codecs/speexcodec.h @@ -31,6 +31,7 @@ #include "global.h" #include "audiocodec.h" +#include "noncopyable.h" #include <cstdio> #include <speex/speex.h> #include <cassert> @@ -62,66 +63,66 @@ const SpeexMode* speexMode[3] = { &speex_uwb_mode, // wb }; -class Speex : public sfl::AudioCodec -{ +class Speex : public sfl::AudioCodec { public: - Speex (int payload) : sfl::AudioCodec (payload, "speex") - { - assert(payload >= 110 && payload <= 112); - assert(110 == PAYLOAD_CODEC_SPEEX_8000 && - 111 == PAYLOAD_CODEC_SPEEX_16000 && - 112 == PAYLOAD_CODEC_SPEEX_32000); - int type = payload - 110; + Speex(int payload) : + sfl::AudioCodec(payload, "speex"), speex_dec_bits_(), + speex_enc_bits_(), speex_dec_state_(0), speex_enc_state_(0), + speex_frame_size_(0) { + assert(payload >= 110 && payload <= 112); + assert(110 == PAYLOAD_CODEC_SPEEX_8000 && + 111 == PAYLOAD_CODEC_SPEEX_16000 && + 112 == PAYLOAD_CODEC_SPEEX_32000); + int type = payload - 110; - _clockRate = clockRate[type]; - _frameSize = frameSize[type]; - _channel = 1; - _bitrate = bitRate[type]; - _hasDynamicPayload = dynamicPayload[type]; + clockRate_ = clockRate[type]; + frameSize_ = frameSize[type]; + channel_ = 1; + bitrate_ = bitRate[type]; + hasDynamicPayload_ = dynamicPayload[type]; - // Init the decoder struct - speex_bits_init (&_speex_dec_bits); - _speex_dec_state = speex_decoder_init (speexMode[type]); + // Init the decoder struct + speex_bits_init(&speex_dec_bits_); + speex_dec_state_ = speex_decoder_init(speexMode[type]); - // Init the encoder struct - speex_bits_init (&_speex_enc_bits); - _speex_enc_state = speex_encoder_init (speexMode[type]); + // Init the encoder struct + speex_bits_init(&speex_enc_bits_); + speex_enc_state_ = speex_encoder_init(speexMode[type]); - speex_encoder_ctl (_speex_enc_state,SPEEX_SET_SAMPLING_RATE,&_clockRate); - speex_decoder_ctl (_speex_dec_state, SPEEX_GET_FRAME_SIZE, &_speex_frame_size); + speex_encoder_ctl(speex_enc_state_, SPEEX_SET_SAMPLING_RATE, &clockRate_); + speex_decoder_ctl(speex_dec_state_, SPEEX_GET_FRAME_SIZE, &speex_frame_size_); } - Speex (const Speex&); - Speex& operator= (const Speex&); + NON_COPYABLE(Speex); ~Speex() { // Destroy the decoder struct - speex_bits_destroy (&_speex_dec_bits); - speex_decoder_destroy (_speex_dec_state); - _speex_dec_state = 0; + speex_bits_destroy(&speex_dec_bits_); + speex_decoder_destroy(speex_dec_state_); + speex_dec_state_ = 0; // Destroy the encoder struct - speex_bits_destroy (&_speex_enc_bits); - speex_encoder_destroy (_speex_enc_state); - _speex_enc_state = 0; + speex_bits_destroy(&speex_enc_bits_); + speex_encoder_destroy(speex_enc_state_); + speex_enc_state_ = 0; } - virtual int decode (short *dst, unsigned char *src, size_t buf_size) { - speex_bits_read_from (&_speex_dec_bits, (char*) src, buf_size); - speex_decode_int (_speex_dec_state, &_speex_dec_bits, dst); - return _frameSize; + virtual int decode(short *dst, unsigned char *src, size_t buf_size) { + speex_bits_read_from(&speex_dec_bits_, (char*) src, buf_size); + speex_decode_int(speex_dec_state_, &speex_dec_bits_, dst); + return frameSize_; } - virtual int encode (unsigned char *dst, short *src, size_t buf_size) { - speex_bits_reset (&_speex_enc_bits); - speex_encode_int (_speex_enc_state, src, &_speex_enc_bits); - return speex_bits_write (&_speex_enc_bits, (char*) dst, buf_size); + virtual int encode(unsigned char *dst, short *src, size_t buf_size) { + speex_bits_reset(&speex_enc_bits_); + speex_encode_int(speex_enc_state_, src, &speex_enc_bits_); + return speex_bits_write(&speex_enc_bits_, (char*) dst, buf_size); } private: - SpeexBits _speex_dec_bits; - SpeexBits _speex_enc_bits; - void *_speex_dec_state; - void *_speex_enc_state; - int _speex_frame_size; + SpeexBits speex_dec_bits_; + SpeexBits speex_enc_bits_; + void *speex_dec_state_; + void *speex_enc_state_; + int speex_frame_size_; }; diff --git a/daemon/src/audio/codecs/speexcodec_nb.cpp b/daemon/src/audio/codecs/speexcodec_nb.cpp index 6757f9ecbb38adfa04f4bca36adb69a712a88983..d9e5d0f9c649e96ce90080c7a010346017bdea71 100644 --- a/daemon/src/audio/codecs/speexcodec_nb.cpp +++ b/daemon/src/audio/codecs/speexcodec_nb.cpp @@ -34,10 +34,10 @@ extern "C" sfl::Codec* create() { - return new Speex (110); + return new Speex(110); } -extern "C" void destroy (sfl::Codec* a) +extern "C" void destroy(sfl::Codec* a) { delete a; } diff --git a/daemon/src/audio/codecs/speexcodec_ub.cpp b/daemon/src/audio/codecs/speexcodec_ub.cpp index 3ed6e695018c8f43453ba2f37c91bb1215e779d6..ffd7027676f2312700ff4dc0926acdca5a7e265d 100644 --- a/daemon/src/audio/codecs/speexcodec_ub.cpp +++ b/daemon/src/audio/codecs/speexcodec_ub.cpp @@ -34,10 +34,10 @@ extern "C" sfl::Codec* create() { - return new Speex (112); + return new Speex(112); } -extern "C" void destroy (sfl::Codec* a) +extern "C" void destroy(sfl::Codec* a) { delete a; } diff --git a/daemon/src/audio/codecs/speexcodec_wb.cpp b/daemon/src/audio/codecs/speexcodec_wb.cpp index e7acebbf5c5b394f75a6fb5d6a88800e233a6971..1fd1fb8a5f6e74639b9f715d152634b7f3570f16 100644 --- a/daemon/src/audio/codecs/speexcodec_wb.cpp +++ b/daemon/src/audio/codecs/speexcodec_wb.cpp @@ -34,10 +34,10 @@ extern "C" sfl::Codec* create() { - return new Speex (111); + return new Speex(111); } -extern "C" void destroy (sfl::Codec* a) +extern "C" void destroy(sfl::Codec* a) { delete a; } diff --git a/daemon/src/audio/codecs/ulaw.cpp b/daemon/src/audio/codecs/ulaw.cpp index 4faf466a16a804b56bdad3a255d44e1491c06865..5b6e7400c900e28d8ba4d095ded161a96e5ff0c1 100644 --- a/daemon/src/audio/codecs/ulaw.cpp +++ b/daemon/src/audio/codecs/ulaw.cpp @@ -35,40 +35,39 @@ #include "audiocodec.h" #include <cassert> -class Ulaw : public sfl::AudioCodec -{ +class Ulaw : public sfl::AudioCodec { public: // 0 PCMU A 8000 1 [RFC3551] - Ulaw (int payload=0) - : sfl::AudioCodec (payload, "PCMU") { - _clockRate = 8000; - _frameSize = 160; // samples, 20 ms at 8kHz - _channel = 1; - _bitrate = 64; - _hasDynamicPayload = false; + Ulaw(int payload=0) + : sfl::AudioCodec(payload, "PCMU") { + clockRate_ = 8000; + frameSize_ = 160; // samples, 20 ms at 8kHz + channel_ = 1; + bitrate_ = 64; + hasDynamicPayload_ = false; } - virtual int decode (short *dst, unsigned char *src, size_t buf_size) { - assert(buf_size == _frameSize / 2 /* compression factor = 2:1 */ * sizeof(SFLDataFormat)); + virtual int decode(short *dst, unsigned char *src, size_t buf_size) { + assert(buf_size == frameSize_ / 2 /* compression factor = 2:1 */ * sizeof(SFLDataFormat)); unsigned char* end = src+buf_size; while (src<end) - *dst++ = ULawDecode (*src++); + *dst++ = ULawDecode(*src++); - return _frameSize; + return frameSize_; } - virtual int encode (unsigned char *dst, short *src, size_t buf_size) { - assert(buf_size >= _frameSize / 2 /* compression factor = 2:1 */ * sizeof(SFLDataFormat)); - uint8* end = dst+_frameSize; + virtual int encode(unsigned char *dst, short *src, size_t buf_size) { + assert(buf_size >= frameSize_ / 2 /* compression factor = 2:1 */ * sizeof(SFLDataFormat)); + uint8* end = dst + frameSize_; while (dst<end) - *dst++ = ULawEncode (*src++); + *dst++ = ULawEncode(*src++); - return _frameSize / 2 /* compression factor = 2:1 */ * sizeof(SFLDataFormat);; + return frameSize_ / 2 /* compression factor = 2:1 */ * sizeof(SFLDataFormat);; } - int ULawDecode (uint8 ulaw) { + int ULawDecode(uint8 ulaw) { ulaw ^= 0xff; // u-law has all bits inverted for transmission int linear = ulaw&0x0f; linear <<= 3; @@ -85,7 +84,7 @@ class Ulaw : public sfl::AudioCodec return linear; } - uint8 ULawEncode (int16 pcm16) { + uint8 ULawEncode(int16 pcm16) { int p = pcm16; uint u; // u-law value we are forming @@ -128,10 +127,10 @@ class Ulaw : public sfl::AudioCodec // the class factories extern "C" sfl::Codec* create() { - return new Ulaw (0); + return new Ulaw(0); } -extern "C" void destroy (sfl::Codec* a) +extern "C" void destroy(sfl::Codec* a) { delete a; } diff --git a/daemon/src/audio/dcblocker.cpp b/daemon/src/audio/dcblocker.cpp index f413f2e619d6b9867d5b21409feb23e3194a1473..3aa1169a36fa0ffbf0fe7f48df336a8ee6408643 100644 --- a/daemon/src/audio/dcblocker.cpp +++ b/daemon/src/audio/dcblocker.cpp @@ -30,27 +30,24 @@ #include "dcblocker.h" -DcBlocker::DcBlocker() : _y (0), _x (0), _xm1 (0), _ym1 (0) {} - -DcBlocker::~DcBlocker() {} - void DcBlocker::reset() { - _y = 0; - _x = 0; - _xm1 = 0; - _ym1 = 0; + y_ = 0; + x_ = 0; + xm1_ = 0; + ym1_ = 0; } -void DcBlocker::process (SFLDataFormat *out, SFLDataFormat *in, int samples) +void DcBlocker::process(SFLDataFormat *out, SFLDataFormat *in, int samples) { - for (int i = 0; i < samples; i++) { - _x = in[i]; + for (int i = 0; i < samples; ++i) { + x_ = in[i]; - _y = (SFLDataFormat) ( (float) _x - (float) _xm1 + 0.9999 * (float) _y); - _xm1 = _x; - _ym1 = _y; + y_ = (SFLDataFormat) ((float) x_ - (float) xm1_ + 0.9999 * (float) y_); + xm1_ = x_; + ym1_ = y_; - out[i] = _y; + out[i] = y_; } } + diff --git a/daemon/src/audio/dcblocker.h b/daemon/src/audio/dcblocker.h index c5db0e4d265c87d384b6456842b5833357a2fdbe..6dbb073ea50330eef90b3308d20a99b1e2c4f524 100644 --- a/daemon/src/audio/dcblocker.h +++ b/daemon/src/audio/dcblocker.h @@ -33,22 +33,14 @@ #include "global.h" -class DcBlocker -{ - +class DcBlocker { public: - - DcBlocker(); - - ~DcBlocker(); - - void reset (void); - - void process (SFLDataFormat *out, SFLDataFormat *in, int samples); + void reset(); + void process(SFLDataFormat *out, SFLDataFormat *in, int samples); private: - SFLDataFormat _y, _x, _xm1, _ym1; + SFLDataFormat y_, x_, xm1_, ym1_; }; #endif diff --git a/daemon/src/audio/delaydetection.cpp b/daemon/src/audio/delaydetection.cpp index 86d0cb8716666c9ae3b9c935799076cc5c497b01..3f56f0c7823c947c92e01d08c1db1a2615ccc268 100644 --- a/daemon/src/audio/delaydetection.cpp +++ b/daemon/src/audio/delaydetection.cpp @@ -35,8 +35,9 @@ #include <string.h> #include <samplerate.h> +namespace { // decimation filter coefficient -float decimationCoefs[] = {-0.09870257, 0.07473655, 0.05616626, 0.04448337, 0.03630817, 0.02944626, +const float decimationCoefs[] = {-0.09870257, 0.07473655, 0.05616626, 0.04448337, 0.03630817, 0.02944626, 0.02244098, 0.01463477, 0.00610982, -0.00266367, -0.01120109, -0.01873722, -0.02373243, -0.02602213, -0.02437806, -0.01869834, -0.00875287, 0.00500204, 0.02183252, 0.04065763, 0.06015944, 0.0788299, 0.09518543, 0.10799179, @@ -46,153 +47,143 @@ float decimationCoefs[] = {-0.09870257, 0.07473655, 0.05616626, 0.04448337, 0.03 0.00610982, 0.01463477, 0.02244098, 0.02944626, 0.03630817, 0.04448337, 0.05616626, 0.07473655, -0.09870257 }; -std::vector<double> ird (decimationCoefs, decimationCoefs + sizeof (decimationCoefs) /sizeof (float)); +std::vector<double> ird(decimationCoefs, decimationCoefs + sizeof(decimationCoefs) /sizeof(float)); // decimation filter coefficient -float bandpassCoefs[] = {0.06278034, -0.0758545, -0.02274943, -0.0084497, 0.0702427, 0.05986113, +const float bandpassCoefs[] = {0.06278034, -0.0758545, -0.02274943, -0.0084497, 0.0702427, 0.05986113, 0.06436469, -0.02412049, -0.03433526, -0.07568665, -0.03214543, -0.07236507, -0.06979052, -0.12446371, -0.05530828, 0.00947243, 0.15294699, 0.17735563, 0.15294699, 0.00947243, -0.05530828, -0.12446371, -0.06979052, -0.07236507, -0.03214543, -0.07568665, -0.03433526, -0.02412049, 0.06436469, 0.05986113, 0.0702427, -0.0084497, -0.02274943, -0.0758545, 0.06278034 }; -std::vector<double> irb (bandpassCoefs, bandpassCoefs + sizeof (bandpassCoefs) /sizeof (float)); +std::vector<double> irb(bandpassCoefs, bandpassCoefs + sizeof(bandpassCoefs) / sizeof(float)); +} // end anonymous namespace -FirFilter::FirFilter (std::vector<double> ir) : _length (ir.size()), - _impulseResponse (ir), - _count (0) +FirFilter::FirFilter(const std::vector<double> &ir) : length_(ir.size()), + impulseResponse_(ir), + counter_(0) { - memset (_taps, 0, sizeof (double) *MAXFILTERSIZE); + memset(taps_, 0, sizeof(double) * MAXFILTERSIZE); } -FirFilter::~FirFilter() {} - -float FirFilter::getOutputSample (float inputSample) +float FirFilter::getOutputSample(float inputSample) { - _taps[_count] = inputSample; + taps_[counter_] = inputSample; double result = 0.0; - int index = _count; + int index = counter_; - for (int i = 0; i < _length; i++) { - result = result + _impulseResponse[i] * _taps[index--]; + for (int i = 0; i < length_; ++i) { + result = result + impulseResponse_[i] * taps_[index--]; if (index < 0) - index = _length-1; + index = length_ - 1; } - _count++; + counter_++; - if (_count >= _length) - _count = 0; + if (counter_ >= length_) + counter_ = 0; return result; } -void FirFilter::reset (void) +void FirFilter::reset() { - for (int i = 0; i < _length; i++) { - _impulseResponse[i] = 0.0; - } + for (int i = 0; i < length_; ++i) + impulseResponse_[i] = 0.0; } -DelayDetection::DelayDetection() : _internalState (WaitForSpeaker), _decimationFilter (ird), _bandpassFilter (irb), _segmentSize (DELAY_BUFF_SIZE), _downsamplingFactor (8) +DelayDetection::DelayDetection() : + internalState_(WaitForSpeaker), decimationFilter_(ird), + bandpassFilter_(irb), segmentSize_(DELAY_BUFF_SIZE), + downsamplingFactor_(8), + spkrDownSize_(DELAY_BUFF_SIZE / downsamplingFactor_), + micDownSize_(WINDOW_SIZE / downsamplingFactor_), + nbMicSampleStored_(0), + nbSpkrSampleStored_(0) { - _micDownSize = WINDOW_SIZE / _downsamplingFactor; - _spkrDownSize = DELAY_BUFF_SIZE / _downsamplingFactor; - - memset (_spkrReference, 0, sizeof (float) *WINDOW_SIZE*2); - memset (_capturedData, 0, sizeof (float) *DELAY_BUFF_SIZE*2); - memset (_spkrReferenceDown, 0, sizeof (float) *WINDOW_SIZE*2); - memset (_captureDataDown, 0, sizeof (float) *DELAY_BUFF_SIZE*2); - memset (_spkrReferenceFilter, 0, sizeof (float) *WINDOW_SIZE*2); - memset (_captureDataFilter, 0, sizeof (float) *DELAY_BUFF_SIZE*2); - memset (_correlationResult, 0, sizeof (float) *DELAY_BUFF_SIZE*2); + memset(spkrReference_, 0, sizeof(float) *WINDOW_SIZE*2); + memset(capturedData_, 0, sizeof(float) *DELAY_BUFF_SIZE*2); + memset(spkrReferenceDown_, 0, sizeof(float) *WINDOW_SIZE*2); + memset(captureDataDown_, 0, sizeof(float) *DELAY_BUFF_SIZE*2); + memset(spkrReferenceFilter_, 0, sizeof(float) *WINDOW_SIZE*2); + memset(captureDataFilter_, 0, sizeof(float) *DELAY_BUFF_SIZE*2); + memset(correlationResult_, 0, sizeof(float) *DELAY_BUFF_SIZE*2); } -void DelayDetection::putData (SFLDataFormat *inputData, int nbSamples) +void DelayDetection::putData(SFLDataFormat *inputData, int nbSamples) { // Machine may already got a spkr and is waiting for mic or computing correlation - if (_nbSpkrSampleStored == WINDOW_SIZE) + if (nbSpkrSampleStored_ == WINDOW_SIZE) return; - if ( (_nbSpkrSampleStored + nbSamples) > WINDOW_SIZE) - nbSamples = WINDOW_SIZE - _nbSpkrSampleStored; - + if ((nbSpkrSampleStored_ + nbSamples) > WINDOW_SIZE) + nbSamples = WINDOW_SIZE - nbSpkrSampleStored_; if (nbSamples) { float tmp[nbSamples]; float down[nbSamples]; - convertInt16ToFloat32 (inputData, tmp, nbSamples); - memcpy (_spkrReference+_nbSpkrSampleStored, tmp, nbSamples*sizeof (float)); + convertInt16ToFloat32(inputData, tmp, nbSamples); + memcpy(spkrReference_ + nbSpkrSampleStored_, tmp, nbSamples * sizeof(float)); - downsampleData (tmp, down, nbSamples, _downsamplingFactor); - bandpassFilter (down, nbSamples/_downsamplingFactor); - memcpy (_spkrReferenceDown+ (_nbSpkrSampleStored/_downsamplingFactor), down, (nbSamples/_downsamplingFactor) *sizeof (float)); - - _nbSpkrSampleStored += nbSamples; + downsampleData(tmp, down, nbSamples, downsamplingFactor_); + bandpassFilter(down, nbSamples / downsamplingFactor_); + memcpy(spkrReferenceDown_+ (nbSpkrSampleStored_ / downsamplingFactor_), down, (nbSamples / downsamplingFactor_) * sizeof(float)); + nbSpkrSampleStored_ += nbSamples; } // Update the state - _internalState = WaitForMic; - + internalState_ = WaitForMic; } -void DelayDetection::process (SFLDataFormat *inputData, int nbSamples) +void DelayDetection::process(SFLDataFormat *inputData, int nbSamples) { - if (_internalState != WaitForMic) + if (internalState_ != WaitForMic) return; - if ( (_nbMicSampleStored + nbSamples) > DELAY_BUFF_SIZE) - nbSamples = DELAY_BUFF_SIZE - _nbMicSampleStored; + if ((nbMicSampleStored_ + nbSamples) > DELAY_BUFF_SIZE) + nbSamples = DELAY_BUFF_SIZE - nbMicSampleStored_; if (nbSamples) { float tmp[nbSamples]; float down[nbSamples]; - convertInt16ToFloat32 (inputData, tmp, nbSamples); - memcpy (_capturedData+_nbMicSampleStored, tmp, nbSamples); + convertInt16ToFloat32(inputData, tmp, nbSamples); + memcpy(capturedData_ + nbMicSampleStored_, tmp, nbSamples); - downsampleData (tmp, down, nbSamples, _downsamplingFactor); + downsampleData(tmp, down, nbSamples, downsamplingFactor_); - memcpy (_captureDataDown+ (_nbMicSampleStored/_downsamplingFactor), down, (nbSamples/_downsamplingFactor) *sizeof (float)); - - _nbMicSampleStored += nbSamples; + memcpy(captureDataDown_ + (nbMicSampleStored_ / downsamplingFactor_), down, (nbSamples / downsamplingFactor_) * sizeof(float)); + nbMicSampleStored_ += nbSamples; } - if (_nbMicSampleStored == DELAY_BUFF_SIZE) - _internalState = ComputeCorrelation; + if (nbMicSampleStored_ == DELAY_BUFF_SIZE) + internalState_ = ComputeCorrelation; else return; - _debug ("_spkrDownSize: %d, _micDownSize: %d", _spkrDownSize, _micDownSize); - crossCorrelate (_spkrReferenceDown, _captureDataDown, _correlationResult, _micDownSize, _spkrDownSize); - - int maxIndex = getMaxIndex (_correlationResult, _spkrDownSize); - - _debug ("MaxIndex: %d", maxIndex); + crossCorrelate(spkrReferenceDown_, captureDataDown_, correlationResult_, micDownSize_, spkrDownSize_); } -void DelayDetection::crossCorrelate (float *ref, float *seg, float *res, int refSize, int segSize) +void DelayDetection::crossCorrelate(float *ref, float *seg, float *res, int refSize, int segSize) { - - _debug ("CrossCorrelate"); - // Output has same size as the int rsize = refSize; int ssize = segSize; - int tmpsize = segSize-refSize+1; + int tmpsize = segSize - refSize + 1; // perform autocorrelation on reference signal - float acref = correlate (ref, ref, rsize); + float acref = correlate(ref, ref, rsize); // perform crossrelation on signal float acseg = 0.0; @@ -200,9 +191,9 @@ void DelayDetection::crossCorrelate (float *ref, float *seg, float *res, int ref while (--tmpsize) { --ssize; - acseg = correlate (seg+tmpsize, seg+tmpsize, rsize); - res[ssize] = correlate (ref, seg+tmpsize, rsize); - r = sqrt (acref*acseg); + acseg = correlate(seg+tmpsize, seg+tmpsize, rsize); + res[ssize] = correlate(ref, seg+tmpsize, rsize); + r = sqrt(acref*acseg); if (r < 0.0000001) res[ssize] = 0.0; @@ -214,14 +205,14 @@ void DelayDetection::crossCorrelate (float *ref, float *seg, float *res, int ref int i = 0; while (rsize) { - acseg = correlate (seg, seg, rsize); - res[ssize-1] = correlate (ref+i, seg, rsize); - r = sqrt (acref*acseg); + acseg = correlate(seg, seg, rsize); + res[ssize - 1] = correlate(ref + i, seg, rsize); + r = sqrt(acref * acseg); if (r < 0.0001) - res[ssize-1] = 0.0; + res[ssize - 1] = 0.0; else - res[ssize-1] = res[ssize-1] / r; + res[ssize - 1] = res[ssize-1] / r; --rsize; --ssize; @@ -229,24 +220,22 @@ void DelayDetection::crossCorrelate (float *ref, float *seg, float *res, int ref } } -double DelayDetection::correlate (float *sig1, float *sig2, short size) +double DelayDetection::correlate(float *sig1, float *sig2, short size) { - short s = size; double ac = 0.0; while (s--) - ac += sig1[s]*sig2[s]; + ac += sig1[s] * sig2[s]; return ac; } -void DelayDetection::convertInt16ToFloat32 (SFLDataFormat *input, float *output, int nbSamples) +void DelayDetection::convertInt16ToFloat32(SFLDataFormat *input, float *output, int nbSamples) { - -#define S2F_FACTOR .000030517578125f; + static const float S2F_FACTOR = .000030517578125f; int len = nbSamples; while (len) { @@ -256,12 +245,10 @@ void DelayDetection::convertInt16ToFloat32 (SFLDataFormat *input, float *output, } -void DelayDetection::downsampleData (float *input, float *output, int nbSamples, int factor) +void DelayDetection::downsampleData(float *input, float *output, int nbSamples, int factor) { - - int _src_err; - - SRC_STATE *_src_state = src_new (SRC_LINEAR, 1, &_src_err); + int src_err; + SRC_STATE *src_state = src_new(SRC_LINEAR, 1, &src_err); double downfactor = 1.0 / (double) factor; @@ -274,21 +261,20 @@ void DelayDetection::downsampleData (float *input, float *output, int nbSamples, src_data.src_ratio = downfactor; src_data.end_of_input = 0; // More data will come - src_process (_src_state, &src_data); + src_process(src_state, &src_data); } } -void DelayDetection::bandpassFilter (float *input, int nbSamples) +void DelayDetection::bandpassFilter(float *input, int nbSamples) { - for (int i = 0; i < nbSamples; i++) - input[i] = _bandpassFilter.getOutputSample (input[i]); + for (int i = 0; i < nbSamples; ++i) + input[i] = bandpassFilter_.getOutputSample(input[i]); } -int DelayDetection::getMaxIndex (float *data, int size) +int DelayDetection::getMaxIndex(float *data, int size) { - float max = 0.0; int k = 0; diff --git a/daemon/src/audio/delaydetection.h b/daemon/src/audio/delaydetection.h index b8a1825c65c6dc16a06defb1cd3668e256ee395a..286baab13c628402b9ebfb615b5bd2fbb80ff99c 100644 --- a/daemon/src/audio/delaydetection.h +++ b/daemon/src/audio/delaydetection.h @@ -42,72 +42,51 @@ #define MAX_DELAY 150 // Size of internal buffers in samples -#define DELAY_BUFF_SIZE MAX_DELAY*8000/1000 +#define DELAY_BUFF_SIZE MAX_DELAY * 8000 / 1000 #define MAXFILTERSIZE 100 - - -class FirFilter -{ +class FirFilter { public: - - /** - * Constructor for this class - */ - FirFilter (std::vector<double> ir); - - /** - * SDestructor for this class - */ - ~FirFilter(); - + FirFilter(const std::vector<double> &ir); /** * Perform filtering on one sample */ - float getOutputSample (float inputSample); - - void reset (void); + float getOutputSample(float inputSample); + void reset(); private: /** * Length of the filter */ - int _length; + int length_; /** * Coefficient of the filter */ - std::vector<double> _impulseResponse; + std::vector<double> impulseResponse_; /** * Circular buffer */ - double _taps[MAXFILTERSIZE]; - - /** - * Counter - */ - int _count; - + double taps_[MAXFILTERSIZE]; + int counter_; }; -class DelayDetection -{ - +class DelayDetection { public: DelayDetection(); ~DelayDetection(); - void putData (SFLDataFormat *inputData, int samples); + void putData(SFLDataFormat *inputData, int samples); - void process (SFLDataFormat *inputData, int samples); + void process(SFLDataFormat *inputData, int samples); private: @@ -121,62 +100,55 @@ class DelayDetection /** * Perform a normalized crosscorrelation between template and segment */ - void crossCorrelate (float *ref, float *seg, float *res, int refSize, int segSize); + void crossCorrelate(float *ref, float *seg, float *res, int refSize, int segSize); /** * Perform a correlation on specified signals (mac) */ - double correlate (float *sig1, float *sig2, short size); + double correlate(float *sig1, float *sig2, short size); - void convertInt16ToFloat32 (SFLDataFormat *input, float *ouput, int nbSamples); + void convertInt16ToFloat32(SFLDataFormat *input, float *ouput, int nbSamples); - void downsampleData (float *input, float *output, int nbSamples, int factor); + void downsampleData(float *input, float *output, int nbSamples, int factor); - void bandpassFilter (float *input, int nbSamples); + void bandpassFilter(float *input, int nbSamples); - int getMaxIndex (float *data, int size); + static int getMaxIndex(float *data, int size); - State _internalState; + State internalState_; - FirFilter _decimationFilter; + FirFilter decimationFilter_; - FirFilter _bandpassFilter; + FirFilter bandpassFilter_; /** * Segment size in samples for correlation */ - short _segmentSize; - - int _downsamplingFactor; - - /** - * Resulting correlation size (s + w -1) - */ - short _correlationSize; + short segmentSize_; - float _spkrReference[WINDOW_SIZE*2]; + int downsamplingFactor_; - float _capturedData[DELAY_BUFF_SIZE*2]; + float spkrReference_[WINDOW_SIZE*2]; - float _spkrReferenceDown[WINDOW_SIZE*2]; + float capturedData_[DELAY_BUFF_SIZE*2]; - float _captureDataDown[DELAY_BUFF_SIZE*2]; + float spkrReferenceDown_[WINDOW_SIZE*2]; - float _spkrReferenceFilter[WINDOW_SIZE*2]; + float captureDataDown_[DELAY_BUFF_SIZE*2]; - float _captureDataFilter[DELAY_BUFF_SIZE*2]; + float spkrReferenceFilter_[WINDOW_SIZE*2]; - float _correlationResult[DELAY_BUFF_SIZE*2]; + float captureDataFilter_[DELAY_BUFF_SIZE*2]; - int _remainingIndex; + float correlationResult_[DELAY_BUFF_SIZE*2]; - int _spkrDownSize; + int spkrDownSize_; - int _micDownSize; + int micDownSize_; - int _nbMicSampleStored; + int nbMicSampleStored_; - int _nbSpkrSampleStored; + int nbSpkrSampleStored_; public: diff --git a/daemon/src/audio/echosuppress.cpp b/daemon/src/audio/echosuppress.cpp index e1c08a2f0f6b4c7c487f7f5a208c464b58a89451..4f384c0bf8a747ab752d52cf6ee6ccff86f17be8 100644 --- a/daemon/src/audio/echosuppress.cpp +++ b/daemon/src/audio/echosuppress.cpp @@ -14,28 +14,30 @@ #define SAMPLES_PER_FRAME 160 -EchoSuppress::EchoSuppress(pj_pool_t *pool) +EchoSuppress::EchoSuppress(pj_pool_t *pool) : echoState_(0) { - if (pjmedia_echo_create(pool, 8000, SAMPLES_PER_FRAME, 250, 0, PJMEDIA_ECHO_SIMPLE | PJMEDIA_ECHO_NO_LOCK, &echoState) != PJ_SUCCESS) - throw std::runtime_error("EchoCancel: Could not create echo canceller"); + if (pjmedia_echo_create(pool, 8000, SAMPLES_PER_FRAME, 250, 0, PJMEDIA_ECHO_SIMPLE | PJMEDIA_ECHO_NO_LOCK, &echoState_) != PJ_SUCCESS) + throw std::runtime_error("EchoCancel: Could not create echo canceller"); } EchoSuppress::~EchoSuppress() { - pjmedia_echo_destroy(echoState); + pjmedia_echo_destroy(echoState_); } -void EchoSuppress::putData (SFLDataFormat *inputData, int samples) +void EchoSuppress::putData(SFLDataFormat *inputData, int samples) { - assert(samples == SAMPLES_PER_FRAME); - assert(sizeof(SFLDataFormat) == sizeof(pj_int16_t)); - if (pjmedia_echo_playback(echoState, reinterpret_cast<pj_int16_t *>(inputData)) != PJ_SUCCESS) - _warn("EchoCancel: Problem while putting input data"); + assert(samples == SAMPLES_PER_FRAME); + assert(sizeof(SFLDataFormat) == sizeof(pj_int16_t)); + + if (pjmedia_echo_playback(echoState_, reinterpret_cast<pj_int16_t *>(inputData)) != PJ_SUCCESS) + WARN("EchoCancel: Problem while putting input data"); } void EchoSuppress::getData(SFLDataFormat *outputData) { - assert(sizeof(SFLDataFormat) == sizeof(pj_int16_t)); - if (pjmedia_echo_capture(echoState, reinterpret_cast<pj_int16_t *>(outputData), 0) != PJ_SUCCESS) - _warn("EchoCancel: Problem while getting output data"); + assert(sizeof(SFLDataFormat) == sizeof(pj_int16_t)); + + if (pjmedia_echo_capture(echoState_, reinterpret_cast<pj_int16_t *>(outputData), 0) != PJ_SUCCESS) + WARN("EchoCancel: Problem while getting output data"); } diff --git a/daemon/src/audio/echosuppress.h b/daemon/src/audio/echosuppress.h index 1232b14ee422b56a3a860de9d4af54b9833a46de..15b7eed93231622d00ed5d6c56ebcc014fd61e68 100644 --- a/daemon/src/audio/echosuppress.h +++ b/daemon/src/audio/echosuppress.h @@ -10,6 +10,7 @@ #include "pjmedia/echo.h" #include "global.h" +#include "noncopyable.h" class EchoSuppress { public: @@ -21,16 +22,17 @@ class EchoSuppress { * Add speaker data into internal buffer * \param inputData containing far-end voice data to be sent to speakers */ - void putData (SFLDataFormat *, int); + void putData(SFLDataFormat *, int); void getData(SFLDataFormat *); private: + NON_COPYABLE(EchoSuppress); /** * The internal state of the echo canceller */ - pjmedia_echo_state *echoState; + pjmedia_echo_state *echoState_; }; #endif /* ECHOSUPPRESS_H_ */ diff --git a/daemon/src/audio/gaincontrol.cpp b/daemon/src/audio/gaincontrol.cpp index 3dd42aa65a3ee2fc379b5abe97a08c6e76246917..336d99870cd5ebb93b69b451ac7c85c380da0982 100644 --- a/daemon/src/audio/gaincontrol.cpp +++ b/daemon/src/audio/gaincontrol.cpp @@ -1,7 +1,6 @@ -#include <math.h> -#include <limits.h> +#include <cmath> +#include <climits> #include <fstream> -#include <iostream> #include "global.h" #include "gaincontrol.h" @@ -14,122 +13,78 @@ #define SFL_GAIN_LOGe10 2.30258509299404568402 -// #define DUMP_GAIN_CONTROL_SIGNAL - -GainControl::GainControl(double sr, double target) : averager(sr, SFL_GAIN_ATTACK_TIME, SFL_GAIN_RELEASE_TIME) - , limiter(SFL_GAIN_LIMITER_RATIO, SFL_GAIN_LIMITER_THRESHOLD) - , targetLeveldB(target) - , targetLevelLinear(0.0) - , currentGain(1.0) - , previousGain(0.0) - , maxIncreaseStep(0.0) - , maxDecreaseStep(0.0) +GainControl::GainControl(double sr, double target) : averager_(sr, SFL_GAIN_ATTACK_TIME, SFL_GAIN_RELEASE_TIME) + , limiter_(SFL_GAIN_LIMITER_RATIO, SFL_GAIN_LIMITER_THRESHOLD) + , targetLeveldB_(target) + , targetLevelLinear_(exp(targetLeveldB_ * 0.05 * SFL_GAIN_LOGe10)) + , currentGain_(1.0) + , previousGain_(0.0) + , maxIncreaseStep_(exp(0.11513 * 12. * 160 / 8000)) // Computed on 12 frames (240 ms) + , maxDecreaseStep_(exp(-0.11513 * 40. * 160 / 8000))// Computed on 40 frames (800 ms) { - targetLevelLinear = exp(targetLeveldB * 0.05 * SFL_GAIN_LOGe10); - - maxIncreaseStep = exp(0.11513 * 12. * 160 / 8000); // Computed on 12 frames (240 ms) - maxDecreaseStep = exp(-0.11513 * 40. * 160 / 8000); // Computed on 40 frames (800 ms) - - _debug("GainControl: Target gain %f dB (%f linear)", targetLeveldB, targetLevelLinear); - + DEBUG("GainControl: Target gain %f dB (%f linear)", targetLeveldB_, targetLevelLinear_); } -GainControl::~GainControl() {} - -#ifdef DUMP_GAIN_CONTROL_SIGNAL -std::fstream tmpRms("gaintestrms.raw", std::fstream::out); -std::fstream tmpIn("gaintestin.raw", std::fstream::out); -std::fstream tmpOut("gaintestout.raw", std::fstream::out); -#endif - void GainControl::process(SFLDataFormat *buf, int samples) { double rms, rmsAvgLevel, in, out, diffRms, maxRms; maxRms = 0.0; - for(int i = 0; i < samples; i++) { - // linear conversion - in = (double)buf[i] / (double)SHRT_MAX; - - out = currentGain * in; - rms = detector.getRms(out); - rmsAvgLevel = sqrt(averager.getAverage(rms)); + for (int i = 0; i < samples; i++) { + // linear conversion + in = (double)buf[i] / (double)SHRT_MAX; -#ifdef DUMP_GAIN_CONTROL_SIGNAL - tmpRms.write(reinterpret_cast<char *>(&rmsAvgLevel), sizeof(double)); - tmpIn.write(reinterpret_cast<char *>(&in), sizeof(double)); -#endif + out = currentGain_ * in; - if(rmsAvgLevel > maxRms) { - maxRms = rmsAvgLevel; - } + rms = out * out; + rmsAvgLevel = sqrt(averager_.getAverage(rms)); - out = limiter.limit(out); + if (rmsAvgLevel > maxRms) + maxRms = rmsAvgLevel; -#ifdef DUMP_GAIN_CONTROL_SIGNAL - tmpOut.write(reinterpret_cast<char *>(&out), sizeof(double)); -#endif + out = limiter_.limit(out); buf[i] = (short)(out * (double)SHRT_MAX); } - diffRms = maxRms - targetLevelLinear; - - if((diffRms > 0.0) && (maxRms > 0.1)) { - currentGain *= maxDecreaseStep; - } - else if((diffRms <= 0.0) && (maxRms > 0.1)) { - currentGain *= maxIncreaseStep; - } - else if(maxRms <= 0.1) { - currentGain = 1.0; - } + diffRms = maxRms - targetLevelLinear_; - currentGain = 0.5 * (currentGain + previousGain); + if ((diffRms > 0.0) && (maxRms > 0.1)) + currentGain_ *= maxDecreaseStep_; + else if ((diffRms <= 0.0) && (maxRms > 0.1)) + currentGain_ *= maxIncreaseStep_; + else if (maxRms <= 0.1) + currentGain_ = 1.0; - previousGain = currentGain; + currentGain_ = 0.5 * (currentGain_ + previousGain_); - // _debug("GainControl: current gain: %f, target gain: %f, rmsAvgLevel %f, target level %f", - // currentGain, gainTargetLevel, rmsAvgLevel, targetLevelLinear); + previousGain_ = currentGain_; } -GainControl::RmsDetection::RmsDetection() {} - -double GainControl::RmsDetection::getRms(double in) +GainControl::DetectionAverage::DetectionAverage(double sr, double ta, double tr) : + g_a_(0.0), teta_a_(ta), g_r_(0.0), teta_r_(tr), samplingRate_(sr), previous_y_(0.0) { - return in * in; -} - -GainControl::DetectionAverage::DetectionAverage(double sr, double ta, double tr) : - g_a(0.0), teta_a(ta), g_r(0.0), teta_r(tr), samplingRate(sr), previous_y(0.0) -{ - g_a = exp(-1.0 / (samplingRate * (teta_a / 1000.0))); - g_r = exp(-1.0 / (samplingRate * (teta_r / 1000.0))); + g_a_ = exp(-1.0 / (samplingRate_ * (teta_a_ / 1000.0))); + g_r_ = exp(-1.0 / (samplingRate_ * (teta_r_ / 1000.0))); } double GainControl::DetectionAverage::getAverage(double in) { - if(in > previous_y) { - previous_y = ((1.0 - g_a) * in) + (g_a * previous_y); - } - else { - previous_y = ((1.0 - g_r) * in) + (g_r * previous_y); - } - - return previous_y; + if (in > previous_y_) + previous_y_ = ((1.0 - g_a_) * in) + (g_a_ * previous_y_); + else + previous_y_ = ((1.0 - g_r_) * in) + (g_r_ * previous_y_); + return previous_y_; } -GainControl::Limiter::Limiter(double r, double thresh) : ratio(r), threshold(thresh) -{ -} +GainControl::Limiter::Limiter(double r, double thresh) : ratio_(r), threshold_(thresh) +{} double GainControl::Limiter::limit(double in) { - double out; - - out = (in > threshold ? (ratio * (in - threshold)) + threshold : - in < -threshold ? (ratio * (in + threshold)) - threshold : in); + double out = (in > threshold_ ? (ratio_ * (in - threshold_)) + threshold_ : + in < -threshold_ ? (ratio_ * (in + threshold_)) - threshold_ : in); return out; } diff --git a/daemon/src/audio/gaincontrol.h b/daemon/src/audio/gaincontrol.h index 531c205fa6f9201860d6d43b2ddc9cf020812098..e8f0ecd685103c14d4232805d7f17b2cf79ebec7 100644 --- a/daemon/src/audio/gaincontrol.h +++ b/daemon/src/audio/gaincontrol.h @@ -3,160 +3,129 @@ #include "global.h" -#define SFL_GAIN_BUFFER_LENGTH 160 - class GainControl { -public: - /** - * Constructor for the gain controller - * /param Sampling rate - * /param Target gain in dB - */ - GainControl(double, double); - - /** - * Destructor for this class - */ - ~GainControl(void); - - /** - * Apply addaptive gain factor on input signal - * /param Input audio buffer - * /param Input samples - */ - void process(SFLDataFormat *, int samples); - -private: - - /** - * Rms detector - */ - class RmsDetection { public: - /** - * Constructor for this class - */ - RmsDetection(void); - /** - * Get rms value - * /param Audio sample - */ - double getRms(double); - - }; - - class DetectionAverage { - public: - /** - * Constructor for this class + * Constructor for the gain controller * /param Sampling rate - * /param Attack ramping time - * /param Release ramping time + * /param Target gain in dB */ - DetectionAverage(double, double, double); - + GainControl(double, double); + /** - * Process average - */ - double getAverage(double); + * Apply addaptive gain factor on input signal + * /param Input audio buffer + * /param Input samples + */ + void process(SFLDataFormat *, int samples); private: + class DetectionAverage { + public: + /** + * Constructor for this class + * /param Sampling rate + * /param Attack ramping time + * /param Release ramping time + */ + DetectionAverage(double, double, double); + + /** + * Process average + */ + double getAverage(double); + + private: + /** + * Average factor for attack + */ + double g_a_; + + /** + * Attack ramp time (in ms) + */ + double teta_a_; + + /** + * Average factor for release + */ + double g_r_; + + /** + * Release ramp time (in ms) + */ + double teta_r_; + + /** + * Samplig rate + */ + double samplingRate_; + + /** + * Previous gain (first order memory) + */ + double previous_y_; + }; + + class Limiter { + public: + /** + * Limiter + * /param Threshold + * /param Ratio + */ + Limiter(double, double); + + /** + * Perform compression on input signal + */ + double limit(double); + + private: + double ratio_; + double threshold_; + }; + /** - * Average factor for attack + * First order mean filter */ - double g_a; + DetectionAverage averager_; /** - * Attack ramp time (in ms) + * Post processing compression */ - double teta_a; + Limiter limiter_; /** - * Average factor for release - */ - double g_r; + * Target audio level in dB + */ + double targetLeveldB_; /** - * Release ramp time (in ms) + * Target audio level in linear scale */ - double teta_r; + double targetLevelLinear_; /** - * Samplig rate - */ - double samplingRate; + * Current gain + */ + double currentGain_; /** - * Previous gain (first order memory) + * Previou gain for smoothing */ - double previous_y; - }; + double previousGain_; - class Limiter { - public: /** - * Limiter - * /param Threshold - * /param Ratio + * Maximum incrementation stop of current gain */ - Limiter(double, double); + double maxIncreaseStep_; /** - * Perform compression on input signal + * Maximum decrease step */ - double limit(double); - - private: - double ratio; - double threshold; - }; - - /** - * Current audio level detection - */ - RmsDetection detector; - - /** - * First order mean filter - */ - DetectionAverage averager; - - /** - * Post processing compression - */ - Limiter limiter; - - /** - * Target audio level in dB - */ - double targetLeveldB; - - /** - * Target audio level in linear scale - */ - double targetLevelLinear; - - /** - * Current gain - */ - double currentGain; - - /** - * Previou gain for smoothing - */ - double previousGain; - - /** - * Maximum incrementation stop of current gain - */ - double maxIncreaseStep; - - /** - * Maximum decrease step - */ - double maxDecreaseStep; + double maxDecreaseStep_; }; diff --git a/daemon/src/audio/mainbuffer.cpp b/daemon/src/audio/mainbuffer.cpp index 8e8072d87cdd36976e47d7b10dda3f981e443410..997db982023a46f5386d097fc95a4675e2c42618 100644 --- a/daemon/src/audio/mainbuffer.cpp +++ b/daemon/src/audio/mainbuffer.cpp @@ -33,222 +33,200 @@ #include <utility> // for std::pair #include "manager.h" -MainBuffer::MainBuffer() : _internalSamplingRate (8000) -{ -} - +MainBuffer::MainBuffer() : ringBufferMap_(), callIDMap_(), mutex_(), internalSamplingRate_(8000) +{} MainBuffer::~MainBuffer() { // delete any ring buffers that didn't get removed - for (RingBufferMap::iterator iter = _ringBufferMap.begin(); iter != _ringBufferMap.end(); ++iter) + for (RingBufferMap::iterator iter = ringBufferMap_.begin(); iter != ringBufferMap_.end(); ++iter) delete iter->second; } - -void MainBuffer::setInternalSamplingRate (int sr) +void MainBuffer::setInternalSamplingRate(int sr) { - if (sr > _internalSamplingRate) { + if (sr > internalSamplingRate_) { flushAllBuffers(); - _internalSamplingRate = sr; + internalSamplingRate_ = sr; } } -CallIDSet* MainBuffer::getCallIDSet (const std::string & call_id) +CallIDSet* MainBuffer::getCallIDSet(const std::string & call_id) { - CallIDMap::iterator iter = _callIDMap.find (call_id); - return (iter != _callIDMap.end()) ? iter->second : NULL; + CallIDMap::iterator iter = callIDMap_.find(call_id); + return (iter != callIDMap_.end()) ? iter->second : NULL; } -void MainBuffer::createCallIDSet (const std::string & set_id) +void MainBuffer::createCallIDSet(const std::string & set_id) { - _callIDMap.insert (std::pair<std::string, CallIDSet*> (set_id, new CallIDSet)); + callIDMap_.insert(std::pair<std::string, CallIDSet*> (set_id, new CallIDSet)); } -bool MainBuffer::removeCallIDSet (const std::string & set_id) +bool MainBuffer::removeCallIDSet(const std::string & set_id) { - CallIDSet* callid_set = getCallIDSet (set_id); + CallIDSet* callid_set = getCallIDSet(set_id); if (!callid_set) { - _debug ("removeCallIDSet error callid set %s does not exist!", set_id.c_str()); + DEBUG("removeCallIDSet error callid set %s does not exist!", set_id.c_str()); return false; } - if (_callIDMap.erase (set_id) == 0) { - _debug ("removeCallIDSet error while removing callid set %s!", set_id.c_str()); - return false; + if (callIDMap_.erase(set_id) == 0) { + DEBUG("removeCallIDSet error while removing callid set %s!", set_id.c_str()); + return false; } - delete callid_set; - callid_set = NULL; - return true; + + delete callid_set; + callid_set = NULL; + return true; } -void MainBuffer::addCallIDtoSet (const std::string & set_id, const std::string & call_id) +void MainBuffer::addCallIDtoSet(const std::string & set_id, const std::string & call_id) { - CallIDSet* callid_set = getCallIDSet (set_id); - callid_set->insert (call_id); + CallIDSet* callid_set = getCallIDSet(set_id); + callid_set->insert(call_id); } -void MainBuffer::removeCallIDfromSet (const std::string & set_id, const std::string & call_id) +void MainBuffer::removeCallIDfromSet(const std::string & set_id, const std::string & call_id) { - CallIDSet* callid_set = getCallIDSet (set_id); + CallIDSet* callid_set = getCallIDSet(set_id); if (callid_set == NULL) - _error("removeCallIDfromSet error callid set %s does not exist!", set_id.c_str()); - else if (callid_set->erase (call_id) == 0) - _error("removeCallIDfromSet error while removing callid %s from set %s!", call_id.c_str(), set_id.c_str()); + ERROR("removeCallIDfromSet error callid set %s does not exist!", set_id.c_str()); + else if (callid_set->erase(call_id) == 0) + ERROR("removeCallIDfromSet error while removing callid %s from set %s!", call_id.c_str(), set_id.c_str()); } - -RingBuffer* MainBuffer::getRingBuffer (const std::string & call_id) +RingBuffer* MainBuffer::getRingBuffer(const std::string & call_id) { - RingBufferMap::iterator iter = _ringBufferMap.find (call_id); - - return (iter != _ringBufferMap.end()) ? iter->second : NULL; + RingBufferMap::iterator iter = ringBufferMap_.find(call_id); + return (iter != ringBufferMap_.end()) ? iter->second : NULL; } - -RingBuffer* MainBuffer::createRingBuffer (const std::string & call_id) +RingBuffer* MainBuffer::createRingBuffer(const std::string & call_id) { - RingBuffer* newRingBuffer = new RingBuffer (SIZEBUF, call_id); - _ringBufferMap.insert (std::pair<std::string, RingBuffer*> (call_id, newRingBuffer)); + RingBuffer* newRingBuffer = new RingBuffer(SIZEBUF, call_id); + ringBufferMap_.insert(std::pair<std::string, RingBuffer*> (call_id, newRingBuffer)); return newRingBuffer; } - -bool MainBuffer::removeRingBuffer (const std::string & call_id) +bool MainBuffer::removeRingBuffer(const std::string & call_id) { - RingBuffer* ring_buffer = getRingBuffer (call_id); + RingBuffer* ring_buffer = getRingBuffer(call_id); if (ring_buffer != NULL) { - if (_ringBufferMap.erase (call_id) != 0) { + if (ringBufferMap_.erase(call_id) != 0) { delete ring_buffer; return true; } else { - _error ("BufferManager: Error: Fail to delete ringbuffer %s!", call_id.c_str()); + ERROR("BufferManager: Error: Fail to delete ringbuffer %s!", call_id.c_str()); return false; } } else { - _debug ("BufferManager: Error: Ringbuffer %s does not exist!", call_id.c_str()); + DEBUG("BufferManager: Error: Ringbuffer %s does not exist!", call_id.c_str()); return true; } } - -void MainBuffer::bindCallID (const std::string & call_id1, const std::string & call_id2) +void MainBuffer::bindCallID(const std::string & call_id1, const std::string & call_id2) { - ost::MutexLock guard (_mutex); + ost::MutexLock guard(mutex_); RingBuffer* ring_buffer; CallIDSet* callid_set; - if ( (ring_buffer = getRingBuffer (call_id1)) == NULL) - createRingBuffer (call_id1); - - if ( (callid_set = getCallIDSet (call_id1)) == NULL) - createCallIDSet (call_id1); - - if ( (ring_buffer = getRingBuffer (call_id2)) == NULL) - createRingBuffer (call_id2); + if ((ring_buffer = getRingBuffer(call_id1)) == NULL) + createRingBuffer(call_id1); - if ( (callid_set = getCallIDSet (call_id2)) == NULL) - createCallIDSet (call_id2); + if ((callid_set = getCallIDSet(call_id1)) == NULL) + createCallIDSet(call_id1); - getRingBuffer (call_id1)->createReadPointer (call_id2); + if ((ring_buffer = getRingBuffer(call_id2)) == NULL) + createRingBuffer(call_id2); - getRingBuffer (call_id2)->createReadPointer (call_id1); - - addCallIDtoSet (call_id1, call_id2); - - addCallIDtoSet (call_id2, call_id1); + if ((callid_set = getCallIDSet(call_id2)) == NULL) + createCallIDSet(call_id2); + getRingBuffer(call_id1)->createReadPointer(call_id2); + getRingBuffer(call_id2)->createReadPointer(call_id1); + addCallIDtoSet(call_id1, call_id2); + addCallIDtoSet(call_id2, call_id1); } -void MainBuffer::bindHalfDuplexOut (const std::string & process_id, const std::string & call_id) +void MainBuffer::bindHalfDuplexOut(const std::string & process_id, const std::string & call_id) { - ost::MutexLock guard (_mutex); + ost::MutexLock guard(mutex_); // This method is used only for active calls, if this call does not exist, do nothing - if (!getRingBuffer (call_id)) + if (!getRingBuffer(call_id)) return; - if (!getCallIDSet (process_id)) - createCallIDSet (process_id); - - getRingBuffer (call_id)->createReadPointer (process_id); - - addCallIDtoSet (process_id, call_id); + if (!getCallIDSet(process_id)) + createCallIDSet(process_id); + getRingBuffer(call_id)->createReadPointer(process_id); + addCallIDtoSet(process_id, call_id); } - -void MainBuffer::unBindCallID (const std::string & call_id1, const std::string & call_id2) +void MainBuffer::unBindCallID(const std::string & call_id1, const std::string & call_id2) { - ost::MutexLock guard (_mutex); + ost::MutexLock guard(mutex_); - removeCallIDfromSet (call_id1, call_id2); - removeCallIDfromSet (call_id2, call_id1); + removeCallIDfromSet(call_id1, call_id2); + removeCallIDfromSet(call_id2, call_id1); - RingBuffer* ringbuffer = getRingBuffer (call_id2); + RingBuffer* ringbuffer = getRingBuffer(call_id2); if (ringbuffer) { - - ringbuffer->removeReadPointer (call_id1); + ringbuffer->removeReadPointer(call_id1); if (ringbuffer->getNbReadPointer() == 0) { - removeCallIDSet (call_id2); - removeRingBuffer (call_id2); + removeCallIDSet(call_id2); + removeRingBuffer(call_id2); } - } - ringbuffer = getRingBuffer (call_id1); + ringbuffer = getRingBuffer(call_id1); if (ringbuffer) { - - ringbuffer->removeReadPointer (call_id2); + ringbuffer->removeReadPointer(call_id2); if (ringbuffer->getNbReadPointer() == 0) { - removeCallIDSet (call_id1); - removeRingBuffer (call_id1); + removeCallIDSet(call_id1); + removeRingBuffer(call_id1); } } } -void MainBuffer::unBindHalfDuplexOut (const std::string & process_id, const std::string & call_id) +void MainBuffer::unBindHalfDuplexOut(const std::string & process_id, const std::string & call_id) { - ost::MutexLock guard (_mutex); + ost::MutexLock guard(mutex_); - removeCallIDfromSet (process_id, call_id); + removeCallIDfromSet(process_id, call_id); - RingBuffer* ringbuffer = getRingBuffer (call_id); + RingBuffer* ringbuffer = getRingBuffer(call_id); if (ringbuffer) { - ringbuffer->removeReadPointer (process_id); + ringbuffer->removeReadPointer(process_id); if (ringbuffer->getNbReadPointer() == 0) { - removeCallIDSet (call_id); - removeRingBuffer (call_id); + removeCallIDSet(call_id); + removeRingBuffer(call_id); } } else { - _debug ("Error: did not found ringbuffer %s", process_id.c_str()); - removeCallIDSet (process_id); + DEBUG("Error: did not found ringbuffer %s", process_id.c_str()); + removeCallIDSet(process_id); } + CallIDSet* callid_set = getCallIDSet(process_id); - CallIDSet* callid_set = getCallIDSet (process_id); - - if (callid_set) { - if (callid_set->empty()) - removeCallIDSet (process_id); - } - + if (callid_set and callid_set->empty()) + removeCallIDSet(process_id); } - -void MainBuffer::unBindAll (const std::string & call_id) +void MainBuffer::unBindAll(const std::string & call_id) { - CallIDSet* callid_set = getCallIDSet (call_id); + CallIDSet* callid_set = getCallIDSet(call_id); if (callid_set == NULL) return; @@ -262,58 +240,55 @@ void MainBuffer::unBindAll (const std::string & call_id) while (iter_set != temp_set.end()) { std::string call_id_in_set = *iter_set; - unBindCallID (call_id, call_id_in_set); + unBindCallID(call_id, call_id_in_set); iter_set++; } - } - -void MainBuffer::putData (void *buffer, int toCopy, const std::string & call_id) +void MainBuffer::putData(void *buffer, int toCopy, const std::string & call_id) { - ost::MutexLock guard (_mutex); + ost::MutexLock guard(mutex_); + + RingBuffer* ring_buffer = getRingBuffer(call_id); - RingBuffer* ring_buffer = getRingBuffer (call_id); if (ring_buffer) - ring_buffer->Put (buffer, toCopy); + ring_buffer->Put(buffer, toCopy); } -int MainBuffer::getData (void *buffer, int toCopy, const std::string & call_id) +int MainBuffer::getData(void *buffer, int toCopy, const std::string & call_id) { - ost::MutexLock guard (_mutex); + ost::MutexLock guard(mutex_); - CallIDSet* callid_set = getCallIDSet (call_id); + CallIDSet* callid_set = getCallIDSet(call_id); - if (!callid_set || callid_set->empty()) { + if (not callid_set or callid_set->empty()) return 0; - } if (callid_set->size() == 1) { CallIDSet::iterator iter_id = callid_set->begin(); - if (iter_id != callid_set->end()) { - return getDataByID (buffer, toCopy, *iter_id, call_id); - } else + if (iter_id != callid_set->end()) + return getDataByID(buffer, toCopy, *iter_id, call_id); + else return 0; } else { - memset (buffer, 0, toCopy); + memset(buffer, 0, toCopy); int size = 0; CallIDSet::iterator iter_id = callid_set->begin(); while (iter_id != callid_set->end()) { - int nbSmplToCopy = toCopy / sizeof (SFLDataFormat); + int nbSmplToCopy = toCopy / sizeof(SFLDataFormat); SFLDataFormat mixBuffer[nbSmplToCopy]; - memset (mixBuffer, 0, toCopy); - size = getDataByID (mixBuffer, toCopy, *iter_id, call_id); + memset(mixBuffer, 0, toCopy); + size = getDataByID(mixBuffer, toCopy, *iter_id, call_id); if (size > 0) { - for (int k = 0; k < nbSmplToCopy; k++) { - ( (SFLDataFormat*) (buffer)) [k] += mixBuffer[k]; - } + for (int k = 0; k < nbSmplToCopy; k++) + ((SFLDataFormat*)(buffer))[k] += mixBuffer[k]; } iter_id++; @@ -323,36 +298,31 @@ int MainBuffer::getData (void *buffer, int toCopy, const std::string & call_id) } } - -int MainBuffer::getDataByID (void *buffer, int toCopy, const std::string & call_id, const std::string & reader_id) +int MainBuffer::getDataByID(void *buffer, int toCopy, const std::string & call_id, const std::string & reader_id) { - RingBuffer* ring_buffer = getRingBuffer (call_id); - + RingBuffer* ring_buffer = getRingBuffer(call_id); return ring_buffer ? ring_buffer->Get(buffer, toCopy, reader_id) : 0; } - -int MainBuffer::availForGet (const std::string & call_id) +int MainBuffer::availForGet(const std::string & call_id) { - ost::MutexLock guard (_mutex); + ost::MutexLock guard(mutex_); - CallIDSet* callid_set = getCallIDSet (call_id); + CallIDSet* callid_set = getCallIDSet(call_id); if (callid_set == NULL) return 0; - if (callid_set->empty()) { + if (callid_set->empty()) return 0; - } if (callid_set->size() == 1) { CallIDSet::iterator iter_id = callid_set->begin(); - if ( (call_id != Call::DEFAULT_ID) && (*iter_id == call_id)) { - _debug ("This problem should not occur since we have %i element", (int) callid_set->size()); - } + if ((call_id != Call::DEFAULT_ID) && (*iter_id == call_id)) + DEBUG("This problem should not occur since we have %i element", (int) callid_set->size()); - return availForGetByID (*iter_id, call_id); + return availForGetByID(*iter_id, call_id); } else { @@ -360,94 +330,89 @@ int MainBuffer::availForGet (const std::string & call_id) int nb_bytes; CallIDSet::iterator iter_id = callid_set->begin(); - syncBuffers (call_id); + syncBuffers(call_id); for (iter_id = callid_set->begin(); iter_id != callid_set->end(); iter_id++) { - nb_bytes = availForGetByID (*iter_id, call_id); + nb_bytes = availForGetByID(*iter_id, call_id); - if ( (nb_bytes != 0) && (nb_bytes < avail_bytes)) + if ((nb_bytes != 0) && (nb_bytes < avail_bytes)) avail_bytes = nb_bytes; } return avail_bytes != 99999 ? avail_bytes : 0; } - } - -int MainBuffer::availForGetByID (const std::string & call_id, const std::string & reader_id) +int MainBuffer::availForGetByID(const std::string & call_id, const std::string & reader_id) { - if ( (call_id != Call::DEFAULT_ID) && (reader_id == call_id)) { - _error ("MainBuffer: Error: RingBuffer has a readpointer on tiself"); - } + if ((call_id != Call::DEFAULT_ID) and (reader_id == call_id)) + ERROR("MainBuffer: Error: RingBuffer has a readpointer on tiself"); - RingBuffer* ringbuffer = getRingBuffer (call_id); + RingBuffer* ringbuffer = getRingBuffer(call_id); if (ringbuffer == NULL) { - _error ("MainBuffer: Error: RingBuffer does not exist"); + ERROR("MainBuffer: Error: RingBuffer does not exist"); return 0; } else - return ringbuffer->AvailForGet (reader_id); + return ringbuffer->AvailForGet(reader_id); } - -int MainBuffer::discard (int toDiscard, const std::string & call_id) +int MainBuffer::discard(int toDiscard, const std::string & call_id) { - ost::MutexLock guard (_mutex); + ost::MutexLock guard(mutex_); - CallIDSet* callid_set = getCallIDSet (call_id); + CallIDSet* callid_set = getCallIDSet(call_id); - if (!callid_set || callid_set->empty()) + if (!callid_set or callid_set->empty()) return 0; - for (CallIDSet::iterator iter = callid_set->begin(); iter != callid_set->end(); iter++) - discardByID (toDiscard, *iter, call_id); + for (CallIDSet::iterator iter = callid_set->begin(); iter != callid_set->end(); iter++) + discardByID(toDiscard, *iter, call_id); - return toDiscard; + return toDiscard; } - -void MainBuffer::discardByID (int toDiscard, const std::string & call_id, const std::string & reader_id) +void MainBuffer::discardByID(int toDiscard, const std::string & call_id, const std::string & reader_id) { - RingBuffer* ringbuffer = getRingBuffer (call_id); + RingBuffer* ringbuffer = getRingBuffer(call_id); + if (ringbuffer) - ringbuffer->Discard (toDiscard, reader_id); + ringbuffer->Discard(toDiscard, reader_id); } - - -void MainBuffer::flush (const std::string & call_id) +void MainBuffer::flush(const std::string & call_id) { - ost::MutexLock guard (_mutex); + ost::MutexLock guard(mutex_); + + CallIDSet* callid_set = getCallIDSet(call_id); - CallIDSet* callid_set = getCallIDSet (call_id); if (callid_set == NULL) return; - for (CallIDSet::iterator iter = callid_set->begin(); iter != callid_set->end(); iter++) - flushByID (*iter, call_id); + for (CallIDSet::iterator iter = callid_set->begin(); iter != callid_set->end(); iter++) + flushByID(*iter, call_id); } -void MainBuffer::flushByID (const std::string & call_id, const std::string & reader_id) +void MainBuffer::flushByID(const std::string & call_id, const std::string & reader_id) { - RingBuffer* ringbuffer = getRingBuffer (call_id); + RingBuffer* ringbuffer = getRingBuffer(call_id); if (ringbuffer != NULL) - ringbuffer->flush (reader_id); + ringbuffer->flush(reader_id); } void MainBuffer::flushAllBuffers() { - for (RingBufferMap::iterator iter = _ringBufferMap.begin(); iter != _ringBufferMap.end(); ++iter) + for (RingBufferMap::iterator iter = ringBufferMap_.begin(); iter != ringBufferMap_.end(); ++iter) iter->second->flushAll(); } -void MainBuffer::syncBuffers (const std::string & call_id) +void MainBuffer::syncBuffers(const std::string & call_id) { - CallIDSet* callid_set = getCallIDSet (call_id); + CallIDSet* callid_set = getCallIDSet(call_id); if (callid_set || callid_set->empty()) return; @@ -458,56 +423,56 @@ void MainBuffer::syncBuffers (const std::string & call_id) float mean_nbBytes = 0.0; CallIDSet::iterator iter; + // compute mean nb byte in buffers for (iter = callid_set->begin(); iter != callid_set->end(); iter++) - mean_nbBytes += availForGetByID (*iter, call_id); + mean_nbBytes += availForGetByID(*iter, call_id); mean_nbBytes /= (float) callid_set->size(); // resync buffers in this conference according to the computed mean for (iter = callid_set->begin(); iter != callid_set->end(); iter++) - if (availForGetByID (*iter, call_id) > (mean_nbBytes + 640)) - discardByID (640, *iter, call_id); + if (availForGetByID(*iter, call_id) > (mean_nbBytes + 640)) + discardByID(640, *iter, call_id); } - void MainBuffer::stateInfo() { // print each call and bound call ids - for (CallIDMap::iterator iter_call = _callIDMap.begin(); iter_call != _callIDMap.end(); ++iter_call) { - - std::string dbg_str (" Call: \t"); - dbg_str.append (iter_call->first); - dbg_str.append (" is bound to: \t"); + for (CallIDMap::iterator iter_call = callIDMap_.begin(); iter_call != callIDMap_.end(); ++iter_call) { + std::string dbg_str(" Call: \t"); + dbg_str.append(iter_call->first); + dbg_str.append(" is bound to: \t"); CallIDSet *call_id_set = iter_call->second; + for (CallIDSet::iterator iter = call_id_set->begin(); iter != call_id_set->end(); ++iter) { - dbg_str.append (*iter); - dbg_str.append (", "); + dbg_str.append(*iter); + dbg_str.append(", "); } - _debug("%s", dbg_str.c_str()); + + DEBUG("%s", dbg_str.c_str()); } // Print ringbuffers ids and readpointers - for (RingBufferMap::iterator iter_buffer = _ringBufferMap.begin(); iter_buffer != _ringBufferMap.end(); ++iter_buffer) { + for (RingBufferMap::iterator iter_buffer = ringBufferMap_.begin(); iter_buffer != ringBufferMap_.end(); ++iter_buffer) { RingBuffer* rbuffer = iter_buffer->second; ReadPointer* rpointer = NULL; - std::string dbg_str (" Buffer: \t"); + std::string dbg_str(" Buffer: \t"); - dbg_str.append (iter_buffer->first); - dbg_str.append (" as read pointer: \t"); + dbg_str.append(iter_buffer->first); + dbg_str.append(" as read pointer: \t"); if (rbuffer) rpointer = rbuffer->getReadPointerList(); if (rpointer) { for (ReadPointer::iterator iter = rpointer->begin(); iter != rpointer->end(); ++iter) { - dbg_str.append (iter->first); - dbg_str.append (", "); + dbg_str.append(iter->first); + dbg_str.append(", "); } } - _debug("%s", dbg_str.c_str()); + DEBUG("%s", dbg_str.c_str()); } - } diff --git a/daemon/src/audio/mainbuffer.h b/daemon/src/audio/mainbuffer.h index 006326ee249f42ad5b27d0465c6d385924c4c8c7..b2fddc4c0a03fb73dcdd316ae156345ef7faf3be 100644 --- a/daemon/src/audio/mainbuffer.h +++ b/daemon/src/audio/mainbuffer.h @@ -47,8 +47,7 @@ typedef std::set<std::string> CallIDSet; typedef std::map<std::string, CallIDSet*> CallIDMap; -class MainBuffer -{ +class MainBuffer { public: @@ -56,92 +55,92 @@ class MainBuffer ~MainBuffer(); - void setInternalSamplingRate (int sr); + void setInternalSamplingRate(int sr); int getInternalSamplingRate() { - return _internalSamplingRate; + return internalSamplingRate_; } /** * Bind together two audio streams so taht a client will be able * to put and get data specifying its callid only. */ - void bindCallID (const std::string & call_id1, const std::string & call_id2 = Call::DEFAULT_ID); + void bindCallID(const std::string & call_id1, const std::string & call_id2 = Call::DEFAULT_ID); /** * Add a new call_id to unidirectional outgoing stream * \param call_id New call id to be added for this stream * \param process_id Process that require this stream */ - void bindHalfDuplexOut (const std::string & process_id, const std::string & call_id = Call::DEFAULT_ID); + void bindHalfDuplexOut(const std::string & process_id, const std::string & call_id = Call::DEFAULT_ID); /** * Unbind two calls */ - void unBindCallID (const std::string & call_id1, const std::string & call_id2 = Call::DEFAULT_ID); + void unBindCallID(const std::string & call_id1, const std::string & call_id2 = Call::DEFAULT_ID); /** * Unbind a unidirectional stream */ - void unBindHalfDuplexOut (const std::string & process_id, const std::string & call_id = Call::DEFAULT_ID); + void unBindHalfDuplexOut(const std::string & process_id, const std::string & call_id = Call::DEFAULT_ID); - void unBindAll (const std::string & call_id); + void unBindAll(const std::string & call_id); - void putData (void *buffer, int toCopy, const std::string & call_id = Call::DEFAULT_ID); + void putData(void *buffer, int toCopy, const std::string & call_id = Call::DEFAULT_ID); - int getData (void *buffer, int toCopy, const std::string & call_id = Call::DEFAULT_ID); + int getData(void *buffer, int toCopy, const std::string & call_id = Call::DEFAULT_ID); - int availForGet (const std::string & call_id = Call::DEFAULT_ID); + int availForGet(const std::string & call_id = Call::DEFAULT_ID); - int discard (int toDiscard, const std::string & call_id = Call::DEFAULT_ID); + int discard(int toDiscard, const std::string & call_id = Call::DEFAULT_ID); - void flush (const std::string & call_id = Call::DEFAULT_ID); + void flush(const std::string & call_id = Call::DEFAULT_ID); void flushAllBuffers(); - void syncBuffers (const std::string & call_id); + void syncBuffers(const std::string & call_id); void stateInfo(); private: - CallIDSet* getCallIDSet (const std::string & call_id); + CallIDSet* getCallIDSet(const std::string & call_id); - void createCallIDSet (const std::string & set_id); + void createCallIDSet(const std::string & set_id); - bool removeCallIDSet (const std::string & set_id); + bool removeCallIDSet(const std::string & set_id); /** * Add a new call id to this set */ - void addCallIDtoSet (const std::string & set_id, const std::string & call_id); + void addCallIDtoSet(const std::string & set_id, const std::string & call_id); - void removeCallIDfromSet (const std::string & set_id, const std::string & call_id); + void removeCallIDfromSet(const std::string & set_id, const std::string & call_id); /** * Create a new ringbuffer with default readpointer */ - RingBuffer* createRingBuffer (const std::string & call_id); + RingBuffer* createRingBuffer(const std::string & call_id); - bool removeRingBuffer (const std::string & call_id); + bool removeRingBuffer(const std::string & call_id); - RingBuffer* getRingBuffer (const std::string & call_id); + RingBuffer* getRingBuffer(const std::string & call_id); - int getDataByID (void *buffer, int toCopy, const std::string & call_id, const std::string & reader_id); + int getDataByID(void *buffer, int toCopy, const std::string & call_id, const std::string & reader_id); - int availForGetByID (const std::string & call_id, const std::string & reader_id); + int availForGetByID(const std::string & call_id, const std::string & reader_id); - void discardByID (int toDiscard, const std::string & call_id, const std::string & reader_id); + void discardByID(int toDiscard, const std::string & call_id, const std::string & reader_id); - void flushByID (const std::string & call_id, const std::string & reader_id); + void flushByID(const std::string & call_id, const std::string & reader_id); - RingBufferMap _ringBufferMap; + RingBufferMap ringBufferMap_; - CallIDMap _callIDMap; + CallIDMap callIDMap_; - ost::Mutex _mutex; + ost::Mutex mutex_; - int _internalSamplingRate; + int internalSamplingRate_; public: diff --git a/daemon/src/audio/noisesuppress.cpp b/daemon/src/audio/noisesuppress.cpp index 41c95b9b448736c6fb995e706d691b06088dfbf7..24d6d7302b6982a78212a23f2e9cdb889ca52c7b 100644 --- a/daemon/src/audio/noisesuppress.cpp +++ b/daemon/src/audio/noisesuppress.cpp @@ -31,38 +31,38 @@ #include <cassert> #include "noisesuppress.h" -NoiseSuppress::NoiseSuppress (int smplPerFrame, int samplingRate) - : _smplPerFrame (smplPerFrame) +NoiseSuppress::NoiseSuppress(int smplPerFrame, int samplingRate) : + smplPerFrame_(smplPerFrame), + noiseState_(speex_preprocess_state_init(smplPerFrame_, samplingRate)) { - _noiseState = speex_preprocess_state_init (_smplPerFrame, samplingRate); - int i=1; - speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DENOISE, &i); - i=-20; - speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &i); - i=0; - speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC, &i); - i=8000; - speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC_TARGET, &i); - i=16000; - speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_AGC_LEVEL, &i); - i=0; - speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB, &i); - float f=0.0; - speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &f); - f=0.0; - speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &f); + int i = 1; + speex_preprocess_ctl(noiseState_, SPEEX_PREPROCESS_SET_DENOISE, &i); + i = -20; + speex_preprocess_ctl(noiseState_, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &i); i = 0; - speex_preprocess_ctl (_noiseState, SPEEX_PREPROCESS_SET_VAD, &i); + speex_preprocess_ctl(noiseState_, SPEEX_PREPROCESS_SET_AGC, &i); + i = 8000; + speex_preprocess_ctl(noiseState_, SPEEX_PREPROCESS_SET_AGC_TARGET, &i); + i = 16000; + speex_preprocess_ctl(noiseState_, SPEEX_PREPROCESS_SET_AGC_LEVEL, &i); + i = 0; + speex_preprocess_ctl(noiseState_, SPEEX_PREPROCESS_SET_DEREVERB, &i); + float f = 0.0; + speex_preprocess_ctl(noiseState_, SPEEX_PREPROCESS_SET_DEREVERB_DECAY, &f); + f = 0.0; + speex_preprocess_ctl(noiseState_, SPEEX_PREPROCESS_SET_DEREVERB_LEVEL, &f); + i = 0; + speex_preprocess_ctl(noiseState_, SPEEX_PREPROCESS_SET_VAD, &i); } NoiseSuppress::~NoiseSuppress() { - speex_preprocess_state_destroy (_noiseState); + speex_preprocess_state_destroy(noiseState_); } -void NoiseSuppress::process (SFLDataFormat *data, int samples) +void NoiseSuppress::process(SFLDataFormat *data, int samples) { - assert(_smplPerFrame == samples); - speex_preprocess_run (_noiseState, data); + assert(smplPerFrame_ == samples); + speex_preprocess_run(noiseState_, data); } diff --git a/daemon/src/audio/noisesuppress.h b/daemon/src/audio/noisesuppress.h index 121b629518e9755fb4428a03809868155f64e87c..0e58f20ac7ffaee5ec641305c71648d4c495e5ac 100644 --- a/daemon/src/audio/noisesuppress.h +++ b/daemon/src/audio/noisesuppress.h @@ -32,23 +32,20 @@ #define NOISESUPPRESS_H #include <speex/speex_preprocess.h> -#include "global.h" +#include "global.h" // for SFLDataFormat +#include "noncopyable.h" -class NoiseSuppress -{ +class NoiseSuppress { public: - - NoiseSuppress (int smplPerFrame, int samplingRate); - - ~NoiseSuppress (void); - - void process (SFLDataFormat *data, int samples); + NoiseSuppress(int smplPerFrame, int samplingRate); + ~NoiseSuppress(); + void process(SFLDataFormat *data, int samples); private: + NON_COPYABLE(NoiseSuppress); - SpeexPreprocessState *_noiseState; - - int _smplPerFrame; + int smplPerFrame_; + SpeexPreprocessState *noiseState_; }; #endif diff --git a/daemon/src/audio/pulseaudio/audiostream.cpp b/daemon/src/audio/pulseaudio/audiostream.cpp index b36b849bd3efabd5172e85e4915069cb7d9156fc..c0ffe920db965b05725231dd6689e8a256767e50 100644 --- a/daemon/src/audio/pulseaudio/audiostream.cpp +++ b/daemon/src/audio/pulseaudio/audiostream.cpp @@ -31,106 +31,107 @@ #include <audiostream.h> #include "pulselayer.h" -AudioStream::AudioStream (pa_context *c, pa_threaded_mainloop *m, const char *desc, int type, int smplrate, std::string *deviceName) - : _mainloop (m) +AudioStream::AudioStream(pa_context *c, pa_threaded_mainloop *m, const char *desc, int type, int smplrate, std::string *deviceName) + : audiostream_(0), mainloop_(m) { static const pa_channel_map channel_map = { - 1, - { PA_CHANNEL_POSITION_MONO }, + 1, + { PA_CHANNEL_POSITION_MONO }, }; - pa_sample_spec sample_spec = { - PA_SAMPLE_S16LE, // PA_SAMPLE_FLOAT32LE, - smplrate, - 1 - }; + pa_sample_spec sample_spec = { + PA_SAMPLE_S16LE, // PA_SAMPLE_FLOAT32LE, + smplrate, + 1 + }; + + assert(pa_sample_spec_valid(&sample_spec)); + assert(pa_channel_map_valid(&channel_map)); - assert (pa_sample_spec_valid (&sample_spec)); - assert (pa_channel_map_valid (&channel_map)); + audiostream_ = pa_stream_new(c, desc, &sample_spec, &channel_map); - _audiostream = pa_stream_new (c, desc, &sample_spec, &channel_map); - if (!_audiostream) { - _error("Pulse: %s: pa_stream_new() failed : %s" , desc, pa_strerror (pa_context_errno (c))); - throw std::runtime_error("Pulse : could not create stream\n"); + if (!audiostream_) { + ERROR("Pulse: %s: pa_stream_new() failed : %s" , desc, pa_strerror(pa_context_errno(c))); + throw std::runtime_error("Pulse : could not create stream\n"); } pa_buffer_attr attributes; - attributes.maxlength = pa_usec_to_bytes (160 * PA_USEC_PER_MSEC, &sample_spec); - attributes.tlength = pa_usec_to_bytes (80 * PA_USEC_PER_MSEC, &sample_spec); + attributes.maxlength = pa_usec_to_bytes(160 * PA_USEC_PER_MSEC, &sample_spec); + attributes.tlength = pa_usec_to_bytes(80 * PA_USEC_PER_MSEC, &sample_spec); attributes.prebuf = 0; - attributes.fragsize = pa_usec_to_bytes (80 * PA_USEC_PER_MSEC, &sample_spec); + attributes.fragsize = pa_usec_to_bytes(80 * PA_USEC_PER_MSEC, &sample_spec); attributes.minreq = (uint32_t) -1; const char *name = deviceName ? deviceName->c_str() : NULL; - pa_threaded_mainloop_lock (_mainloop); + pa_threaded_mainloop_lock(mainloop_); if (type == PLAYBACK_STREAM || type == RINGTONE_STREAM) - pa_stream_connect_playback (_audiostream , name, &attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); + pa_stream_connect_playback(audiostream_, name, &attributes, (pa_stream_flags_t)(PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE), NULL, NULL); else if (type == CAPTURE_STREAM) - pa_stream_connect_record (_audiostream, name, &attributes, (pa_stream_flags_t) (PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE)); + pa_stream_connect_record(audiostream_, name, &attributes, (pa_stream_flags_t)(PA_STREAM_ADJUST_LATENCY|PA_STREAM_AUTO_TIMING_UPDATE)); - pa_threaded_mainloop_unlock (_mainloop); + pa_threaded_mainloop_unlock(mainloop_); - pa_stream_set_state_callback (_audiostream , stream_state_callback, NULL); + pa_stream_set_state_callback(audiostream_, stream_state_callback, NULL); } AudioStream::~AudioStream() { - pa_threaded_mainloop_lock (_mainloop); + pa_threaded_mainloop_lock(mainloop_); - pa_stream_disconnect (_audiostream); + pa_stream_disconnect(audiostream_); - // make sure we don't get any further callback - pa_stream_set_state_callback (_audiostream, NULL, NULL); - pa_stream_set_write_callback (_audiostream, NULL, NULL); - pa_stream_set_underflow_callback (_audiostream, NULL, NULL); - pa_stream_set_overflow_callback (_audiostream, NULL, NULL); + // make sure we don't get any further callback + pa_stream_set_state_callback(audiostream_, NULL, NULL); + pa_stream_set_write_callback(audiostream_, NULL, NULL); + pa_stream_set_underflow_callback(audiostream_, NULL, NULL); + pa_stream_set_overflow_callback(audiostream_, NULL, NULL); - pa_stream_unref (_audiostream); + pa_stream_unref(audiostream_); - pa_threaded_mainloop_unlock (_mainloop); + pa_threaded_mainloop_unlock(mainloop_); } void -AudioStream::stream_state_callback (pa_stream* s, void* user_data UNUSED) +AudioStream::stream_state_callback(pa_stream* s, void* user_data UNUSED) { char str[PA_SAMPLE_SPEC_SNPRINT_MAX]; - switch (pa_stream_get_state (s)) { - + switch (pa_stream_get_state(s)) { case PA_STREAM_CREATING: - _info ("Pulse: Stream is creating..."); + INFO("Pulse: Stream is creating..."); break; case PA_STREAM_TERMINATED: - _info ("Pulse: Stream is terminating..."); + INFO("Pulse: Stream is terminating..."); break; case PA_STREAM_READY: - _info ("Pulse: Stream successfully created, connected to %s", pa_stream_get_device_name (s)); - _debug ("Pulse: maxlength %u", pa_stream_get_buffer_attr (s)->maxlength); - _debug ("Pulse: tlength %u", pa_stream_get_buffer_attr (s)->tlength); - _debug ("Pulse: prebuf %u", pa_stream_get_buffer_attr (s)->prebuf); - _debug ("Pulse: minreq %u", pa_stream_get_buffer_attr (s)->minreq); - _debug ("Pulse: fragsize %u", pa_stream_get_buffer_attr (s)->fragsize); - _debug ("Pulse: samplespec %s", pa_sample_spec_snprint (str, sizeof (str), pa_stream_get_sample_spec (s))); + INFO("Pulse: Stream successfully created, connected to %s", pa_stream_get_device_name(s)); + DEBUG("Pulse: maxlength %u", pa_stream_get_buffer_attr(s)->maxlength); + DEBUG("Pulse: tlength %u", pa_stream_get_buffer_attr(s)->tlength); + DEBUG("Pulse: prebuf %u", pa_stream_get_buffer_attr(s)->prebuf); + DEBUG("Pulse: minreq %u", pa_stream_get_buffer_attr(s)->minreq); + DEBUG("Pulse: fragsize %u", pa_stream_get_buffer_attr(s)->fragsize); + DEBUG("Pulse: samplespec %s", pa_sample_spec_snprint(str, sizeof(str), pa_stream_get_sample_spec(s))); break; case PA_STREAM_UNCONNECTED: - _info ("Pulse: Stream unconnected"); + INFO("Pulse: Stream unconnected"); break; case PA_STREAM_FAILED: default: - _error("Pulse: Sink/Source doesn't exists: %s" , pa_strerror (pa_context_errno (pa_stream_get_context (s)))); + ERROR("Pulse: Sink/Source doesn't exists: %s" , pa_strerror(pa_context_errno(pa_stream_get_context(s)))); break; } } -bool AudioStream::isReady (void) +bool AudioStream::isReady() { - if (!_audiostream) - return false; - return pa_stream_get_state (_audiostream) == PA_STREAM_READY; + if (!audiostream_) + return false; + + return pa_stream_get_state(audiostream_) == PA_STREAM_READY; } diff --git a/daemon/src/audio/pulseaudio/audiostream.h b/daemon/src/audio/pulseaudio/audiostream.h index 00eb7a2e12fdb9907c7cdadc97a891d5aa2a9215..8d484407b91962c00603f49dc824b2ca49aff8cc 100644 --- a/daemon/src/audio/pulseaudio/audiostream.h +++ b/daemon/src/audio/pulseaudio/audiostream.h @@ -33,63 +33,59 @@ #include <pulse/pulseaudio.h> #include <string> +#include "noncopyable.h" /** * This data structure contains the different king of audio streams available */ enum STREAM_TYPE { - PLAYBACK_STREAM, CAPTURE_STREAM, RINGTONE_STREAM + PLAYBACK_STREAM, CAPTURE_STREAM, RINGTONE_STREAM }; class AudioStream { -public: + public: - /** - * Constructor - * - * @param context pulseaudio's application context. - * @param mainloop pulseaudio's main loop - * @param description - * @param types - * @param audio sampling rate - * @param device name - */ - AudioStream(pa_context *, pa_threaded_mainloop *, const char *, int, int, std::string *); + /** + * Constructor + * + * @param context pulseaudio's application context. + * @param mainloop pulseaudio's main loop + * @param description + * @param types + * @param audio sampling rate + * @param device name + */ + AudioStream(pa_context *, pa_threaded_mainloop *, const char *, int, int, std::string *); - ~AudioStream(); + ~AudioStream(); - /** - * Accessor: Get the pulseaudio stream object - * @return pa_stream* The stream - */ - pa_stream* pulseStream() { - return _audiostream; - } + /** + * Accessor: Get the pulseaudio stream object + * @return pa_stream* The stream + */ + pa_stream* pulseStream() { + return audiostream_; + } - bool isReady(void); + bool isReady(); -private: + private: + NON_COPYABLE(AudioStream); - // Copy Constructor - AudioStream(const AudioStream& rh); + /** + * Mandatory asynchronous callback on the audio stream state + */ + static void stream_state_callback(pa_stream* s, void* user_data); - // Assignment Operator - AudioStream& operator=(const AudioStream& rh); + /** + * The pulse audio object + */ + pa_stream* audiostream_; - /** - * Mandatory asynchronous callback on the audio stream state - */ - static void stream_state_callback(pa_stream* s, void* user_data); - - /** - * The pulse audio object - */ - pa_stream* _audiostream; - - /** - * A pointer to the opaque threaded main loop object - */ - pa_threaded_mainloop * _mainloop; + /** + * A pointer to the opaque threaded main loop object + */ + pa_threaded_mainloop * mainloop_; }; #endif // _AUDIO_STREAM_H diff --git a/daemon/src/audio/pulseaudio/pulselayer.cpp b/daemon/src/audio/pulseaudio/pulselayer.cpp index c6b1148dc2be6cb2053e077d1b3435a4b1d38470..2568b3a08d9a62186291637ae719a7642a54b90e 100644 --- a/daemon/src/audio/pulseaudio/pulselayer.cpp +++ b/daemon/src/audio/pulseaudio/pulselayer.cpp @@ -36,237 +36,117 @@ #include "audio/dcblocker.h" #include "managerimpl.h" -namespace +namespace { +void playback_callback(pa_stream* s, size_t bytes, void* userdata) { -void playback_callback (pa_stream* s, size_t bytes, void* userdata) -{ - assert (s && bytes); - assert (bytes > 0); - static_cast<PulseLayer*> (userdata)->writeToSpeaker(); + assert(s && bytes); + assert(bytes > 0); + static_cast<PulseLayer*>(userdata)->writeToSpeaker(); } -void capture_callback (pa_stream* s, size_t bytes, void* userdata) +void capture_callback(pa_stream* s, size_t bytes, void* userdata) { - assert (s && bytes); - assert (bytes > 0); - static_cast<PulseLayer*> (userdata)->readFromMic(); + assert(s && bytes); + assert(bytes > 0); + static_cast<PulseLayer*>(userdata)->readFromMic(); } -void ringtone_callback (pa_stream* s, size_t bytes, void* userdata) +void ringtone_callback(pa_stream* s, size_t bytes, void* userdata) { - assert (s && bytes); - assert (bytes > 0); - static_cast<PulseLayer*> (userdata)->ringtoneToSpeaker(); -} - -void stream_moved_callback (pa_stream *s, void *userdata UNUSED) -{ - _debug ("stream_moved_callback: stream %d to %d", pa_stream_get_index (s), pa_stream_get_device_index (s)); -} - -void sink_input_info_callback (pa_context *c UNUSED, const pa_sink_info *i, int eol, void *userdata) -{ - char s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX]; - - if (eol) - return; - - _debug ("Sink %u\n" - " Name: %s\n" - " Driver: %s\n" - " Description: %s\n" - " Sample Specification: %s\n" - " Channel Map: %s\n" - " Owner Module: %u\n" - " Volume: %s\n" - " Monitor Source: %u\n" - " Latency: %0.0f usec\n" - " Flags: %s%s%s\n", - i->index, - i->name, - i->driver, - i->description, - pa_sample_spec_snprint (s, sizeof (s), &i->sample_spec), - pa_channel_map_snprint (cm, sizeof (cm), &i->channel_map), - i->owner_module, - i->mute ? "muted" : pa_cvolume_snprint (cv, sizeof (cv), &i->volume), - i->monitor_source, - (double) i->latency, - i->flags & PA_SINK_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "", - i->flags & PA_SINK_LATENCY ? "LATENCY " : "", - i->flags & PA_SINK_HARDWARE ? "HARDWARE" : ""); - - ((PulseLayer *)userdata)->getSinkList()->push_back (i->name); + assert(s && bytes); + assert(bytes > 0); + static_cast<PulseLayer*>(userdata)->ringtoneToSpeaker(); } -void source_input_info_callback (pa_context *c UNUSED, const pa_source_info *i, int eol, void *userdata) +void stream_moved_callback(pa_stream *s, void *userdata UNUSED) { - char s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX]; - - if (!eol) - return; - _debug ("Sink %u\n" - " Name: %s\n" - " Driver: %s\n" - " Description: %s\n" - " Sample Specification: %s\n" - " Channel Map: %s\n" - " Owner Module: %u\n" - " Volume: %s\n" - " Monitor if Sink: %u\n" - " Latency: %0.0f usec\n" - " Flags: %s%s%s\n", - i->index, - i->name, - i->driver, - i->description, - pa_sample_spec_snprint (s, sizeof (s), &i->sample_spec), - pa_channel_map_snprint (cm, sizeof (cm), &i->channel_map), - i->owner_module, - i->mute ? "muted" : pa_cvolume_snprint (cv, sizeof (cv), &i->volume), - i->monitor_of_sink, - (double) i->latency, - i->flags & PA_SOURCE_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "", - i->flags & PA_SOURCE_LATENCY ? "LATENCY " : "", - i->flags & PA_SOURCE_HARDWARE ? "HARDWARE" : ""); - - ((PulseLayer *)userdata)->getSourceList()->push_back (i->name); + DEBUG("stream_moved_callback: stream %d to %d", pa_stream_get_index(s), pa_stream_get_device_index(s)); } -void context_changed_callback (pa_context* c, pa_subscription_event_type_t t, uint32_t idx UNUSED, void* userdata) -{ - - switch (t) { - case PA_SUBSCRIPTION_EVENT_SINK: - _debug ("Audio: PA_SUBSCRIPTION_EVENT_SINK"); - ( (PulseLayer *) userdata)->getSinkList()->clear(); - pa_context_get_sink_info_list (c, sink_input_info_callback, userdata); - break; - case PA_SUBSCRIPTION_EVENT_SOURCE: - _debug ("Audio: PA_SUBSCRIPTION_EVENT_SOURCE"); - ( (PulseLayer *) userdata)->getSourceList()->clear(); - pa_context_get_source_info_list (c, source_input_info_callback, userdata); - break; - case PA_SUBSCRIPTION_EVENT_SINK_INPUT: - _debug ("Audio: PA_SUBSCRIPTION_EVENT_SINK_INPUT"); - break; - case PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT: - _debug ("Audio: PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT"); - break; - case PA_SUBSCRIPTION_EVENT_MODULE: - _debug ("Audio: PA_SUBSCRIPTION_EVENT_MODULE"); - break; - case PA_SUBSCRIPTION_EVENT_CLIENT: - _debug ("Audio: PA_SUBSCRIPTION_EVENT_CLIENT"); - break; - case PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE: - _debug ("Audio: PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE"); - break; - case PA_SUBSCRIPTION_EVENT_SERVER: - _debug ("Audio: PA_SUBSCRIPTION_EVENT_SERVER"); - break; - case PA_SUBSCRIPTION_EVENT_CARD: - _debug ("Audio: PA_SUBSCRIPTION_EVENT_CARD"); - break; - case PA_SUBSCRIPTION_EVENT_FACILITY_MASK: - _debug ("Audio: PA_SUBSCRIPTION_EVENT_FACILITY_MASK"); - break; - case PA_SUBSCRIPTION_EVENT_CHANGE: - _debug ("Audio: PA_SUBSCRIPTION_EVENT_CHANGE"); - break; - case PA_SUBSCRIPTION_EVENT_REMOVE: - _debug ("Audio: PA_SUBSCRIPTION_EVENT_REMOVE"); - ( (PulseLayer *) userdata)->getSinkList()->clear(); - ( (PulseLayer *) userdata)->getSourceList()->clear(); - pa_context_get_sink_info_list (c, sink_input_info_callback, userdata); - pa_context_get_source_info_list (c, source_input_info_callback, userdata); - break; - case PA_SUBSCRIPTION_EVENT_TYPE_MASK: - _debug ("Audio: PA_SUBSCRIPTION_EVENT_TYPE_MASK"); - break; - default: - _debug ("Audio: Unknown event type %d", t); - - } -} } // end anonymous namespace -PulseLayer::PulseLayer () +PulseLayer::PulseLayer() : playback_(0) , record_(0) , ringtone_(0) - , mic_buffer_(NULL) - , mic_buf_size_(0) + , sinkList_() + , sourceList_() + , mic_buffer_(0) + , mic_buf_size_(0) + , context_(0) + , mainloop_(pa_threaded_mainloop_new()) { - setenv ("PULSE_PROP_media.role", "phone", 1); + setenv("PULSE_PROP_media.role", "phone", 1); + + + if (!mainloop_) + throw std::runtime_error("Couldn't create pulseaudio mainloop"); - mainloop_ = pa_threaded_mainloop_new(); - if (!mainloop_) - throw std::runtime_error("Couldn't create pulseaudio mainloop"); + context_ = pa_context_new(pa_threaded_mainloop_get_api(mainloop_) , "SFLphone"); - context_ = pa_context_new (pa_threaded_mainloop_get_api (mainloop_) , "SFLphone"); - if (!context_) - throw std::runtime_error("Couldn't create pulseaudio context"); + if (!context_) + throw std::runtime_error("Couldn't create pulseaudio context"); - pa_context_set_state_callback (context_, context_state_callback, this); + pa_context_set_state_callback(context_, context_state_callback, this); - if (pa_context_connect (context_, NULL , PA_CONTEXT_NOAUTOSPAWN , NULL) < 0) - throw std::runtime_error("Could not connect pulseaudio context to the server"); + if (pa_context_connect(context_, NULL , PA_CONTEXT_NOAUTOSPAWN , NULL) < 0) + throw std::runtime_error("Could not connect pulseaudio context to the server"); - pa_threaded_mainloop_lock (mainloop_); + pa_threaded_mainloop_lock(mainloop_); - if (pa_threaded_mainloop_start (mainloop_) < 0) - throw std::runtime_error("Failed to start pulseaudio mainloop"); - pa_threaded_mainloop_wait (mainloop_); + if (pa_threaded_mainloop_start(mainloop_) < 0) + throw std::runtime_error("Failed to start pulseaudio mainloop"); - if (pa_context_get_state (context_) != PA_CONTEXT_READY) - throw std::runtime_error("Couldn't connect to pulse audio server"); + pa_threaded_mainloop_wait(mainloop_); - pa_threaded_mainloop_unlock (mainloop_); + if (pa_context_get_state(context_) != PA_CONTEXT_READY) + throw std::runtime_error("Couldn't connect to pulse audio server"); - isStarted_ = true; + pa_threaded_mainloop_unlock(mainloop_); + + isStarted_ = true; } -PulseLayer::~PulseLayer (void) +PulseLayer::~PulseLayer() { disconnectAudioStream(); if (mainloop_) - pa_threaded_mainloop_stop (mainloop_); + pa_threaded_mainloop_stop(mainloop_); if (context_) { - pa_context_disconnect (context_); - pa_context_unref (context_); + pa_context_disconnect(context_); + pa_context_unref(context_); } if (mainloop_) - pa_threaded_mainloop_free (mainloop_); + pa_threaded_mainloop_free(mainloop_); delete[] mic_buffer_; } -void PulseLayer::context_state_callback (pa_context* c, void* user_data) +void PulseLayer::context_state_callback(pa_context* c, void* user_data) { PulseLayer* pulse = (PulseLayer*) user_data; - assert (c && pulse->mainloop_); + assert(c && pulse->mainloop_); - switch (pa_context_get_state (c)) { + switch (pa_context_get_state(c)) { case PA_CONTEXT_CONNECTING: case PA_CONTEXT_AUTHORIZING: case PA_CONTEXT_SETTING_NAME: - _debug ("Audio: Waiting...."); + DEBUG("Audio: Waiting...."); break; case PA_CONTEXT_READY: - _debug ("Audio: Connection to PulseAudio server established"); - pa_threaded_mainloop_signal (pulse->mainloop_, 0); - pa_context_subscribe (c, (pa_subscription_mask_t) (PA_SUBSCRIPTION_MASK_SINK| - PA_SUBSCRIPTION_MASK_SOURCE), NULL, pulse); - pa_context_set_subscribe_callback (c, context_changed_callback, pulse); + DEBUG("Audio: Connection to PulseAudio server established"); + pa_threaded_mainloop_signal(pulse->mainloop_, 0); + pa_context_subscribe(c, (pa_subscription_mask_t)(PA_SUBSCRIPTION_MASK_SINK| + PA_SUBSCRIPTION_MASK_SOURCE), NULL, pulse); + pa_context_set_subscribe_callback(c, context_changed_callback, pulse); pulse->updateSinkList(); break; @@ -276,80 +156,80 @@ void PulseLayer::context_state_callback (pa_context* c, void* user_data) case PA_CONTEXT_FAILED: default: - _error("Pulse: %s" , pa_strerror (pa_context_errno (c))); - pa_threaded_mainloop_signal (pulse->mainloop_, 0); + ERROR("Pulse: %s" , pa_strerror(pa_context_errno(c))); + pa_threaded_mainloop_signal(pulse->mainloop_, 0); pulse->disconnectAudioStream(); break; } } -void PulseLayer::updateSinkList (void) +void PulseLayer::updateSinkList() { - getSinkList()->clear(); - pa_context_get_sink_info_list (context_, sink_input_info_callback, this); + sinkList_.clear(); + pa_context_get_sink_info_list(context_, sink_input_info_callback, this); } -void PulseLayer::updateSourceList (void) +void PulseLayer::updateSourceList() { - getSourceList()->clear(); - pa_context_get_source_info_list (context_, source_input_info_callback, this); + sourceList_.clear(); + pa_context_get_source_info_list(context_, source_input_info_callback, this); } -bool PulseLayer::inSinkList (const std::string &deviceName) const +bool PulseLayer::inSinkList(const std::string &deviceName) const { return std::find(sinkList_.begin(), sinkList_.end(), deviceName) != sinkList_.end(); } -bool PulseLayer::inSourceList (const std::string &deviceName) const +bool PulseLayer::inSourceList(const std::string &deviceName) const { return std::find(sourceList_.begin(), sourceList_.end(), deviceName) != sourceList_.end(); } -void PulseLayer::createStreams (pa_context* c) +void PulseLayer::createStreams(pa_context* c) { std::string playbackDevice(audioPref.getDevicePlayback()); std::string recordDevice(audioPref.getDeviceRecord()); std::string ringtoneDevice(audioPref.getDeviceRingtone()); - _debug ("PulseAudio: Devices: playback %s , record %s , ringtone %s", - playbackDevice.c_str(), recordDevice.c_str(), ringtoneDevice.c_str()); + DEBUG("PulseAudio: Devices: playback %s , record %s , ringtone %s", + playbackDevice.c_str(), recordDevice.c_str(), ringtoneDevice.c_str()); - playback_ = new AudioStream (c, mainloop_, "SFLphone playback", PLAYBACK_STREAM, audioSampleRate_, - inSinkList(playbackDevice) ? &playbackDevice : NULL); + playback_ = new AudioStream(c, mainloop_, "SFLphone playback", PLAYBACK_STREAM, audioSampleRate_, + inSinkList(playbackDevice) ? &playbackDevice : NULL); - pa_stream_set_write_callback (playback_->pulseStream(), playback_callback, this); - pa_stream_set_moved_callback (playback_->pulseStream(), stream_moved_callback, this); + pa_stream_set_write_callback(playback_->pulseStream(), playback_callback, this); + pa_stream_set_moved_callback(playback_->pulseStream(), stream_moved_callback, this); - record_ = new AudioStream (c, mainloop_, "SFLphone capture", CAPTURE_STREAM, audioSampleRate_, - inSourceList(recordDevice) ? &recordDevice : NULL); + record_ = new AudioStream(c, mainloop_, "SFLphone capture", CAPTURE_STREAM, audioSampleRate_, + inSourceList(recordDevice) ? &recordDevice : NULL); - pa_stream_set_read_callback (record_->pulseStream() , capture_callback, this); - pa_stream_set_moved_callback (record_->pulseStream(), stream_moved_callback, this); + pa_stream_set_read_callback(record_->pulseStream() , capture_callback, this); + pa_stream_set_moved_callback(record_->pulseStream(), stream_moved_callback, this); - ringtone_ = new AudioStream (c, mainloop_, "SFLphone ringtone", RINGTONE_STREAM, audioSampleRate_, - inSourceList(ringtoneDevice) ? &ringtoneDevice : NULL); + ringtone_ = new AudioStream(c, mainloop_, "SFLphone ringtone", RINGTONE_STREAM, audioSampleRate_, + inSourceList(ringtoneDevice) ? &ringtoneDevice : NULL); - pa_stream_set_write_callback (ringtone_->pulseStream(), ringtone_callback, this); - pa_stream_set_moved_callback (ringtone_->pulseStream(), stream_moved_callback, this); + pa_stream_set_write_callback(ringtone_->pulseStream(), ringtone_callback, this); + pa_stream_set_moved_callback(ringtone_->pulseStream(), stream_moved_callback, this); - pa_threaded_mainloop_signal (mainloop_, 0); + pa_threaded_mainloop_signal(mainloop_, 0); flushMain(); flushUrgent(); } -void PulseLayer::disconnectAudioStream (void) +void PulseLayer::disconnectAudioStream() { if (playback_) { if (playback_->pulseStream()) { - const char *name = pa_stream_get_device_name (playback_->pulseStream()); + const char *name = pa_stream_get_device_name(playback_->pulseStream()); if (name && *name) - audioPref.setDevicePlayback (name); + audioPref.setDevicePlayback(name); } delete playback_; @@ -357,33 +237,35 @@ void PulseLayer::disconnectAudioStream (void) } if (ringtone_) { - if (ringtone_->pulseStream()) { - const char *name = pa_stream_get_device_name (ringtone_->pulseStream()); - if (name && *name) - audioPref.setDeviceRingtone (name); - } - - delete ringtone_; - ringtone_ = NULL; + if (ringtone_->pulseStream()) { + const char *name = pa_stream_get_device_name(ringtone_->pulseStream()); + + if (name && *name) + audioPref.setDeviceRingtone(name); + } + + delete ringtone_; + ringtone_ = NULL; } if (record_) { - if (record_->pulseStream()) { - const char *name = pa_stream_get_device_name (record_->pulseStream()); - if (name && *name) - audioPref.setDeviceRecord (name); - } - - delete record_; - record_ = NULL; + if (record_->pulseStream()) { + const char *name = pa_stream_get_device_name(record_->pulseStream()); + + if (name && *name) + audioPref.setDeviceRecord(name); + } + + delete record_; + record_ = NULL; } } -void PulseLayer::startStream (void) +void PulseLayer::startStream() { // Create Streams if (!playback_ or !record_) - createStreams (context_); + createStreams(context_); // Flush outside the if statement: every time start stream is // called is to notify a new event @@ -393,158 +275,174 @@ void PulseLayer::startStream (void) void -PulseLayer::stopStream (void) +PulseLayer::stopStream() { - pa_threaded_mainloop_lock (mainloop_); + pa_threaded_mainloop_lock(mainloop_); if (playback_) - pa_stream_flush (playback_->pulseStream(), NULL, NULL); + pa_stream_flush(playback_->pulseStream(), NULL, NULL); if (record_) - pa_stream_flush (record_->pulseStream(), NULL, NULL); + pa_stream_flush(record_->pulseStream(), NULL, NULL); - pa_threaded_mainloop_unlock (mainloop_); + pa_threaded_mainloop_unlock(mainloop_); disconnectAudioStream(); } -void PulseLayer::writeToSpeaker (void) +void PulseLayer::writeToSpeaker() { if (!playback_ or !playback_->isReady()) - return; + return; pa_stream *s = playback_->pulseStream(); // available bytes to be written in pulseaudio internal buffer int writable = pa_stream_writable_size(s); + if (writable < 0) - _error("Pulse: playback error : %s", pa_strerror(writable)); + ERROR("Pulse: playback error : %s", pa_strerror(writable)); + if (writable <= 0) return; + size_t bytes = writable; - void *data; + void *data; notifyincomingCall(); size_t urgentBytes = urgentRingBuffer_.AvailForGet(); + if (urgentBytes > bytes) - urgentBytes = bytes; + urgentBytes = bytes; + if (urgentBytes) { - pa_stream_begin_write(s, &data, &urgentBytes); - urgentRingBuffer_.Get (data, urgentBytes); - pa_stream_write (s, data, urgentBytes, NULL, 0, PA_SEEK_RELATIVE); + pa_stream_begin_write(s, &data, &urgentBytes); + urgentRingBuffer_.Get(data, urgentBytes); + pa_stream_write(s, data, urgentBytes, NULL, 0, PA_SEEK_RELATIVE); // Consume the regular one as well (same amount of bytes) - Manager::instance().getMainBuffer()->discard (urgentBytes); + Manager::instance().getMainBuffer()->discard(urgentBytes); return; } AudioLoop *toneToPlay = Manager::instance().getTelephoneTone(); + if (toneToPlay) { - if (playback_->isReady()) { - pa_stream_begin_write(s, &data, &bytes); - toneToPlay->getNext ((SFLDataFormat*)data, bytes / sizeof (SFLDataFormat), 100); - pa_stream_write (s, data, bytes, NULL, 0, PA_SEEK_RELATIVE); - } - return; + if (playback_->isReady()) { + pa_stream_begin_write(s, &data, &bytes); + toneToPlay->getNext((SFLDataFormat*)data, bytes / sizeof(SFLDataFormat), 100); + pa_stream_write(s, data, bytes, NULL, 0, PA_SEEK_RELATIVE); + } + + return; + } + + flushUrgent(); // flush remaining samples in _urgentRingBuffer + + size_t availSamples = Manager::instance().getMainBuffer()->availForGet() / sizeof(SFLDataFormat); + + if (availSamples == 0) { + pa_stream_begin_write(s, &data, &bytes); + memset(data, 0, bytes); + pa_stream_write(s, data, bytes, NULL, 0, PA_SEEK_RELATIVE); + return; } - flushUrgent(); // flush remaining samples in _urgentRingBuffer - - size_t availSamples = Manager::instance().getMainBuffer()->availForGet() / sizeof(SFLDataFormat); - if (availSamples == 0) { - pa_stream_begin_write(s, &data, &bytes); - memset(data, 0, bytes); - pa_stream_write (s, data, bytes, NULL, 0, PA_SEEK_RELATIVE); - return; - } - - unsigned int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); - bool resample = audioSampleRate_ != mainBufferSampleRate; - - // how much samples we can write in the output - size_t outSamples = bytes / sizeof(SFLDataFormat); - - // how much samples we want to read from the buffer - size_t inSamples = outSamples; - - double resampleFactor = 1.; - if (resample) { - resampleFactor = (double) audioSampleRate_ / mainBufferSampleRate; - inSamples = (double) inSamples / resampleFactor; - } - - if (inSamples > availSamples) - inSamples = availSamples; - size_t outBytes = (double)inSamples * resampleFactor * sizeof(SFLDataFormat); - - size_t inBytes = inSamples * sizeof (SFLDataFormat); - pa_stream_begin_write(s, &data, &inBytes); - Manager::instance().getMainBuffer()->getData (data, inBytes); - - if (resample) { - SFLDataFormat* rsmpl_out = (SFLDataFormat*) pa_xmalloc (outBytes); - converter_->resample((SFLDataFormat*)data, rsmpl_out, mainBufferSampleRate, audioSampleRate_, inSamples); - pa_stream_write (s, rsmpl_out, outBytes, NULL, 0, PA_SEEK_RELATIVE); - pa_xfree (rsmpl_out); - } else - pa_stream_write (s, data, inBytes, NULL, 0, PA_SEEK_RELATIVE); + unsigned int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); + bool resample = audioSampleRate_ != mainBufferSampleRate; + + // how much samples we can write in the output + size_t outSamples = bytes / sizeof(SFLDataFormat); + + // how much samples we want to read from the buffer + size_t inSamples = outSamples; + + double resampleFactor = 1.; + + if (resample) { + resampleFactor = (double) audioSampleRate_ / mainBufferSampleRate; + inSamples = (double) inSamples / resampleFactor; + } + + if (inSamples > availSamples) + inSamples = availSamples; + + size_t outBytes = (double)inSamples * resampleFactor * sizeof(SFLDataFormat); + + size_t inBytes = inSamples * sizeof(SFLDataFormat); + pa_stream_begin_write(s, &data, &inBytes); + Manager::instance().getMainBuffer()->getData(data, inBytes); + + if (resample) { + SFLDataFormat* rsmpl_out = (SFLDataFormat*) pa_xmalloc(outBytes); + converter_->resample((SFLDataFormat*)data, rsmpl_out, mainBufferSampleRate, audioSampleRate_, inSamples); + pa_stream_write(s, rsmpl_out, outBytes, NULL, 0, PA_SEEK_RELATIVE); + pa_xfree(rsmpl_out); + } else + pa_stream_write(s, data, inBytes, NULL, 0, PA_SEEK_RELATIVE); } -void PulseLayer::readFromMic (void) +void PulseLayer::readFromMic() { if (!record_ or !record_->isReady()) - return; + return; - const char *data = NULL; + const char *data = NULL; size_t bytes; - if (pa_stream_peek (record_->pulseStream() , (const void**) &data , &bytes) < 0 or !data) { - _error("Audio: Error capture stream peek failed: %s" , pa_strerror (pa_context_errno (context_))); + + if (pa_stream_peek(record_->pulseStream() , (const void**) &data , &bytes) < 0 or !data) { + ERROR("Audio: Error capture stream peek failed: %s" , pa_strerror(pa_context_errno(context_))); return; } - unsigned int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); - bool resample = audioSampleRate_ != mainBufferSampleRate; - if (resample) { - double resampleFactor = (double) audioSampleRate_ / mainBufferSampleRate; - bytes = (double) bytes * resampleFactor; - } + unsigned int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); + bool resample = audioSampleRate_ != mainBufferSampleRate; - size_t samples = bytes / sizeof(SFLDataFormat); - if (bytes > mic_buf_size_) { - mic_buf_size_ = bytes; - delete[] mic_buffer_; - mic_buffer_ = new SFLDataFormat[samples]; - } + if (resample) { + double resampleFactor = (double) audioSampleRate_ / mainBufferSampleRate; + bytes = (double) bytes * resampleFactor; + } - if (resample) - converter_->resample((SFLDataFormat*)data, mic_buffer_, mainBufferSampleRate, audioSampleRate_, samples); + size_t samples = bytes / sizeof(SFLDataFormat); - dcblocker_.process(mic_buffer_, resample ? mic_buffer_ : (SFLDataFormat*)data, samples); - Manager::instance().getMainBuffer()->putData(mic_buffer_, bytes); + if (bytes > mic_buf_size_) { + mic_buf_size_ = bytes; + delete[] mic_buffer_; + mic_buffer_ = new SFLDataFormat[samples]; + } - if (pa_stream_drop (record_->pulseStream()) < 0) - _error ("Audio: Error: capture stream drop failed: %s" , pa_strerror (pa_context_errno (context_))); + if (resample) + converter_->resample((SFLDataFormat*)data, mic_buffer_, mainBufferSampleRate, audioSampleRate_, samples); + + dcblocker_.process(mic_buffer_, resample ? mic_buffer_ : (SFLDataFormat*)data, samples); + Manager::instance().getMainBuffer()->putData(mic_buffer_, bytes); + + if (pa_stream_drop(record_->pulseStream()) < 0) + ERROR("Audio: Error: capture stream drop failed: %s" , pa_strerror(pa_context_errno(context_))); } -void PulseLayer::ringtoneToSpeaker (void) +void PulseLayer::ringtoneToSpeaker() { if (!ringtone_ or !ringtone_->isReady()) - return; + return; pa_stream *s = ringtone_->pulseStream(); - int writable = pa_stream_writable_size (s); + int writable = pa_stream_writable_size(s); + if (writable < 0) - _error("Pulse: ringtone error : %s", pa_strerror (writable)); + ERROR("Pulse: ringtone error : %s", pa_strerror(writable)); + if (writable <= 0) return; size_t bytes = writable; - void *data; + void *data; - pa_stream_begin_write(s, &data, &bytes); + pa_stream_begin_write(s, &data, &bytes); AudioLoop *fileToPlay = Manager::instance().getTelephoneFile(); + if (fileToPlay) fileToPlay->getNext((SFLDataFormat*)data, bytes / sizeof(SFLDataFormat), 100); else @@ -552,3 +450,131 @@ void PulseLayer::ringtoneToSpeaker (void) pa_stream_write(s, data, bytes, NULL, 0, PA_SEEK_RELATIVE); } + +void PulseLayer::context_changed_callback(pa_context* c, pa_subscription_event_type_t t, uint32_t idx UNUSED, void* userdata) +{ + + switch (t) { + case PA_SUBSCRIPTION_EVENT_SINK: + DEBUG("Audio: PA_SUBSCRIPTION_EVENT_SINK"); + ((PulseLayer *) userdata)->sinkList_.clear(); + pa_context_get_sink_info_list(c, sink_input_info_callback, userdata); + break; + case PA_SUBSCRIPTION_EVENT_SOURCE: + DEBUG("Audio: PA_SUBSCRIPTION_EVENT_SOURCE"); + ((PulseLayer *) userdata)->sourceList_.clear(); + pa_context_get_source_info_list(c, source_input_info_callback, userdata); + break; + case PA_SUBSCRIPTION_EVENT_SINK_INPUT: + DEBUG("Audio: PA_SUBSCRIPTION_EVENT_SINK_INPUT"); + break; + case PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT: + DEBUG("Audio: PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT"); + break; + case PA_SUBSCRIPTION_EVENT_MODULE: + DEBUG("Audio: PA_SUBSCRIPTION_EVENT_MODULE"); + break; + case PA_SUBSCRIPTION_EVENT_CLIENT: + DEBUG("Audio: PA_SUBSCRIPTION_EVENT_CLIENT"); + break; + case PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE: + DEBUG("Audio: PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE"); + break; + case PA_SUBSCRIPTION_EVENT_SERVER: + DEBUG("Audio: PA_SUBSCRIPTION_EVENT_SERVER"); + break; + case PA_SUBSCRIPTION_EVENT_CARD: + DEBUG("Audio: PA_SUBSCRIPTION_EVENT_CARD"); + break; + case PA_SUBSCRIPTION_EVENT_FACILITY_MASK: + DEBUG("Audio: PA_SUBSCRIPTION_EVENT_FACILITY_MASK"); + break; + case PA_SUBSCRIPTION_EVENT_CHANGE: + DEBUG("Audio: PA_SUBSCRIPTION_EVENT_CHANGE"); + break; + case PA_SUBSCRIPTION_EVENT_REMOVE: + DEBUG("Audio: PA_SUBSCRIPTION_EVENT_REMOVE"); + ((PulseLayer *) userdata)->sinkList_.clear(); + ((PulseLayer *) userdata)->sourceList_.clear(); + pa_context_get_sink_info_list(c, sink_input_info_callback, userdata); + pa_context_get_source_info_list(c, source_input_info_callback, userdata); + break; + case PA_SUBSCRIPTION_EVENT_TYPE_MASK: + DEBUG("Audio: PA_SUBSCRIPTION_EVENT_TYPE_MASK"); + break; + default: + DEBUG("Audio: Unknown event type %d", t); + + } +} + +void PulseLayer::source_input_info_callback(pa_context *c UNUSED, const pa_source_info *i, int eol, void *userdata) +{ + char s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX]; + + if (!eol) + return; + + DEBUG("Sink %u\n" + " Name: %s\n" + " Driver: %s\n" + " Description: %s\n" + " Sample Specification: %s\n" + " Channel Map: %s\n" + " Owner Module: %u\n" + " Volume: %s\n" + " Monitor if Sink: %u\n" + " Latency: %0.0f usec\n" + " Flags: %s%s%s\n", + i->index, + i->name, + i->driver, + i->description, + pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec), + pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map), + i->owner_module, + i->mute ? "muted" : pa_cvolume_snprint(cv, sizeof(cv), &i->volume), + i->monitor_of_sink, + (double) i->latency, + i->flags & PA_SOURCE_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "", + i->flags & PA_SOURCE_LATENCY ? "LATENCY " : "", + i->flags & PA_SOURCE_HARDWARE ? "HARDWARE" : ""); + + ((PulseLayer *)userdata)->sourceList_.push_back(i->name); +} + +void PulseLayer::sink_input_info_callback(pa_context *c UNUSED, const pa_sink_info *i, int eol, void *userdata) +{ + char s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX]; + + if (eol) + return; + + DEBUG("Sink %u\n" + " Name: %s\n" + " Driver: %s\n" + " Description: %s\n" + " Sample Specification: %s\n" + " Channel Map: %s\n" + " Owner Module: %u\n" + " Volume: %s\n" + " Monitor Source: %u\n" + " Latency: %0.0f usec\n" + " Flags: %s%s%s\n", + i->index, + i->name, + i->driver, + i->description, + pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec), + pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map), + i->owner_module, + i->mute ? "muted" : pa_cvolume_snprint(cv, sizeof(cv), &i->volume), + i->monitor_source, + (double) i->latency, + i->flags & PA_SINK_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "", + i->flags & PA_SINK_LATENCY ? "LATENCY " : "", + i->flags & PA_SINK_HARDWARE ? "HARDWARE" : ""); + + ((PulseLayer *)userdata)->sinkList_.push_back(i->name); +} + diff --git a/daemon/src/audio/pulseaudio/pulselayer.h b/daemon/src/audio/pulseaudio/pulselayer.h index 2da6ada062b25ecb8fe83bd337df7744e48d4fc1..ae4092b1324b33ec21331ef386b6c11d929215e8 100644 --- a/daemon/src/audio/pulseaudio/pulselayer.h +++ b/daemon/src/audio/pulseaudio/pulselayer.h @@ -29,75 +29,67 @@ * as that of the covered work. */ -#ifndef _PULSE_LAYER_H -#define _PULSE_LAYER_H - -#include "audio/audiolayer.h" -#include <pulse/pulseaudio.h> -#include <pulse/stream.h> +#ifndef PULSE_LAYER_H_ +#define PULSE_LAYER_H_ #include <list> #include <string> +#include <pulse/pulseaudio.h> +#include <pulse/stream.h> +#include "audio/audiolayer.h" +#include "noncopyable.h" class AudioStream; -class PulseLayer : public AudioLayer -{ +class PulseLayer : public AudioLayer { public: - PulseLayer (); - ~PulseLayer (void); - - std::list<std::string>* getSinkList (void) { - return &sinkList_; - } - - std::list<std::string>* getSourceList (void) { - return &sourceList_; - } + PulseLayer(); + ~PulseLayer(); /** * Write data from the ring buffer to the harware and read data from the hardware */ - void readFromMic (void); - void writeToSpeaker (void); - void ringtoneToSpeaker (void); - + void readFromMic(); + void writeToSpeaker(); + void ringtoneToSpeaker(); - void updateSinkList (void); - void updateSourceList (void); + void updateSinkList(); - bool inSinkList (const std::string &deviceName) const; + void updateSourceList(); - bool inSourceList (const std::string &deviceName) const; + bool inSinkList(const std::string &deviceName) const; - void startStream (void); + bool inSourceList(const std::string &deviceName) const; - void stopStream (void); + void startStream(); - static void context_state_callback (pa_context* c, void* user_data); + void stopStream(); private: - // Copy Constructor - PulseLayer (const PulseLayer& rh); - - // Assignment Operator - PulseLayer& operator= (const PulseLayer& rh); + static void context_state_callback(pa_context* c, void* user_data); + static void context_changed_callback(pa_context* c, + pa_subscription_event_type_t t, + uint32_t idx , void* userdata); + static void source_input_info_callback(pa_context *c, + const pa_source_info *i, + int eol, void *userdata); + static void sink_input_info_callback(pa_context *c, + const pa_sink_info *i, + int eol, void *userdata); + + NON_COPYABLE(PulseLayer); /** * Create the audio streams into the given context * @param c The pulseaudio context */ - void createStreams (pa_context* c); + void createStreams(pa_context* c); /** * Close the connection with the local pulseaudio server */ - void disconnectAudioStream (void); - - /** PulseAudio context and asynchronous loop */ - pa_context* context_; - pa_threaded_mainloop* mainloop_; + void disconnectAudioStream(); /** * A stream object to handle the pulseaudio playback stream @@ -123,9 +115,12 @@ class PulseLayer : public AudioLayer SFLDataFormat *mic_buffer_; size_t mic_buf_size_; - public: + /** PulseAudio context and asynchronous loop */ + pa_context* context_; + pa_threaded_mainloop* mainloop_; + friend class AudioLayerTest; }; -#endif // _PULSE_LAYER_H_ +#endif // PULSE_LAYER_H_ diff --git a/daemon/src/audio/recordable.cpp b/daemon/src/audio/recordable.cpp index e98a39ba32511be7a98a6b7494d73caf99415bc8..b55b4ed7cbece13b86170dab909459d3c14bdb50 100644 --- a/daemon/src/audio/recordable.cpp +++ b/daemon/src/audio/recordable.cpp @@ -30,46 +30,33 @@ #include "recordable.h" #include "manager.h" -Recordable::Recordable() : recorder (&recAudio, Manager::instance().getMainBuffer()) +Recordable::Recordable() : recAudio(), recorder(&recAudio, Manager::instance().getMainBuffer()) { - - _debug("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Recordable Constructor -=-=-=-=-=-=-=-=-=--=-=-=-"); - - FILE_TYPE fileType = FILE_WAV; - SOUND_FORMAT soundFormat = INT16; - - recAudio.setRecordingOption (fileType, soundFormat, 8000, Manager::instance().audioPreference.getRecordpath()); + recAudio.setRecordingOption(AudioRecord::FILE_WAV, 8000, Manager::instance().audioPreference.getRecordpath()); } - Recordable::~Recordable() { - _debug("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Recordable Destructor -=-=-=-=-=-=-=-=-=-=-=-=-=-"); - - if (recAudio.isOpenFile()) { + if (recAudio.isOpenFile()) recAudio.closeFile(); - } } - -void Recordable::initRecFileName (std::string filename) +void Recordable::initRecFileName(std::string filename) { - recAudio.initFileName (filename); + recAudio.initFileName(filename); } std::string Recordable::getFileName() { - return recAudio.getFileName(); + return recAudio.getFileName(); } -void Recordable::setRecordingSmplRate (int smplRate) +void Recordable::setRecordingSmplRate(int smplRate) { - recAudio.setSndSamplingRate (smplRate); + recAudio.setSndSamplingRate(smplRate); } int Recordable::getRecordingSmplRate() const { - return recAudio.getSndSamplingRate(); + return recAudio.getSndSamplingRate(); } - - diff --git a/daemon/src/audio/recordable.h b/daemon/src/audio/recordable.h index 7e76705e9846e46667660be8690e87347200bf21..13effb2ef53da4eee22c724a3ddbc3dbc08dc6c2 100644 --- a/daemon/src/audio/recordable.h +++ b/daemon/src/audio/recordable.h @@ -33,13 +33,11 @@ #include "audiorecord.h" #include "audiorecorder.h" -class Recordable -{ +class Recordable { public: Recordable(); - virtual ~Recordable(); /** @@ -58,34 +56,34 @@ class Recordable /** * Stop recording */ - void stopRecording(void) { + void stopRecording() { recAudio.stopRecording(); } /** * Init the recording file name according to path specified in configuration */ - void initRecFileName (std::string filename); + void initRecFileName(std::string filename); - /** - * Return the file path for this recording - */ - std::string getFileName(void); - /** - * Set recording sampling rate. + * Return the file path for this recording */ - void setRecordingSmplRate (int smplRate); + std::string getFileName(); - /** - * Return the recording sampling rate + /** + * Set recording sampling rate. */ - int getRecordingSmplRate(void) const; + void setRecordingSmplRate(int smplRate); - /** - * Virtual method to be implemented in order to the main - * buffer to retreive the recorded id. - */ + /** + * Return the recording sampling rate + */ + int getRecordingSmplRate() const; + + /** + * Virtual method to be implemented in order to the main + * buffer to retreive the recorded id. + */ virtual std::string getRecFileId() const = 0; /** @@ -94,7 +92,6 @@ class Recordable AudioRecord recAudio; AudioRecorder recorder; - }; #endif diff --git a/daemon/src/audio/ringbuffer.cpp b/daemon/src/audio/ringbuffer.cpp index 7681d24107447558e7ea9b14b7187578b60c9fec..9119838ffea0acfdebc05288b9204bfb8963c269 100644 --- a/daemon/src/audio/ringbuffer.cpp +++ b/daemon/src/audio/ringbuffer.cpp @@ -45,62 +45,66 @@ int RingBuffer::count_rb = 0; // Create a ring buffer with 'size' bytes -RingBuffer::RingBuffer (int size, const std::string &call_id) : mEnd (0) - , mBufferSize (size > MIN_BUFFER_SIZE ? size : MIN_BUFFER_SIZE) - , mBuffer (NULL) - , buffer_id (call_id) +RingBuffer::RingBuffer(int size, const std::string &call_id) : endPos_(0) + , bufferSize_(size > MIN_BUFFER_SIZE ? size : MIN_BUFFER_SIZE) + , buffer_(NULL) + , readpointer_() + , buffer_id_(call_id) + , buffer_input_rec(0) + , buffer_output_rec(0) { - mBuffer = new unsigned char[mBufferSize]; + buffer_ = new unsigned char[bufferSize_]; count_rb++; } RingBuffer::~RingBuffer() { - delete[] mBuffer; + delete[] buffer_; } void -RingBuffer::flush (const std::string &call_id) +RingBuffer::flush(const std::string &call_id) { - storeReadPointer (mEnd, call_id); + storeReadPointer(endPos_, call_id); } void -RingBuffer::flushAll () +RingBuffer::flushAll() { ReadPointer::iterator iter; - for (iter = _readpointer.begin(); iter != _readpointer.end(); ++iter) - iter->second = mEnd; + + for (iter = readpointer_.begin(); iter != readpointer_.end(); ++iter) + iter->second = endPos_; } int RingBuffer::putLen() { - int mStart = (_readpointer.size() >= 1) ? getSmallestReadPointer() : 0; - return (mEnd + mBufferSize - mStart) % mBufferSize; + int startPos = (readpointer_.size() >= 1) ? getSmallestReadPointer() : 0; + return (endPos_ + bufferSize_ - startPos) % bufferSize_; } int -RingBuffer::getLen (const std::string &call_id) +RingBuffer::getLen(const std::string &call_id) { - return (mEnd + mBufferSize - getReadPointer (call_id)) % mBufferSize; + return (endPos_ + bufferSize_ - getReadPointer(call_id)) % bufferSize_; } void RingBuffer::debug() { - _debug ("Start=%d; End=%d; BufferSize=%d", getSmallestReadPointer(), mEnd, mBufferSize); + DEBUG("Start=%d; End=%d; BufferSize=%d", getSmallestReadPointer(), endPos_, bufferSize_); } int -RingBuffer::getReadPointer (const std::string &call_id) +RingBuffer::getReadPointer(const std::string &call_id) { if (getNbReadPointer() == 0) return 0; - ReadPointer::iterator iter = _readpointer.find (call_id); - return (iter != _readpointer.end()) ? iter->second : 0; + ReadPointer::iterator iter = readpointer_.find(call_id); + return (iter != readpointer_.end()) ? iter->second : 0; } int @@ -109,10 +113,11 @@ RingBuffer::getSmallestReadPointer() if (getNbReadPointer() == 0) return 0; - int smallest = mBufferSize; + int smallest = bufferSize_; ReadPointer::iterator iter; - for (iter = _readpointer.begin(); iter != _readpointer.end(); ++iter) + + for (iter = readpointer_.begin(); iter != readpointer_.end(); ++iter) if (iter->second < smallest) smallest = iter->second; @@ -120,46 +125,46 @@ RingBuffer::getSmallestReadPointer() } void -RingBuffer::storeReadPointer (int pointer_value, const std::string &call_id) +RingBuffer::storeReadPointer(int pointer_value, const std::string &call_id) { - ReadPointer::iterator iter = _readpointer.find (call_id); + ReadPointer::iterator iter = readpointer_.find(call_id); - if (iter != _readpointer.end()) { + if (iter != readpointer_.end()) iter->second = pointer_value; - } else { - _debug ("storeReadPointer: Cannot find \"%s\" readPointer in \"%s\" ringbuffer", call_id.c_str(), buffer_id.c_str()); - } + else + DEBUG("storeReadPointer: Cannot find \"%s\" readPointer in \"%s\" ringbuffer", call_id.c_str(), buffer_id_.c_str()); } void -RingBuffer::createReadPointer (const std::string &call_id) +RingBuffer::createReadPointer(const std::string &call_id) { - if (!hasThisReadPointer (call_id)) - _readpointer.insert (std::pair<std::string, int> (call_id, mEnd)); + if (!hasThisReadPointer(call_id)) + readpointer_.insert(std::pair<std::string, int> (call_id, endPos_)); } void -RingBuffer::removeReadPointer (const std::string &call_id) +RingBuffer::removeReadPointer(const std::string &call_id) { - ReadPointer::iterator iter = _readpointer.find (call_id); - if (iter != _readpointer.end()) - _readpointer.erase (iter); + ReadPointer::iterator iter = readpointer_.find(call_id); + + if (iter != readpointer_.end()) + readpointer_.erase(iter); } bool -RingBuffer::hasThisReadPointer (const std::string &call_id) +RingBuffer::hasThisReadPointer(const std::string &call_id) { - return _readpointer.find (call_id) != _readpointer.end(); + return readpointer_.find(call_id) != readpointer_.end(); } int RingBuffer::getNbReadPointer() { - return _readpointer.size(); + return readpointer_.size(); } // @@ -168,28 +173,29 @@ RingBuffer::getNbReadPointer() // This one puts some data inside the ring buffer. void -RingBuffer::Put (void* buffer, int toCopy) +RingBuffer::Put(void* buffer, int toCopy) { int len = putLen(); - if (toCopy > mBufferSize - len) - toCopy = mBufferSize - len; + + if (toCopy > bufferSize_ - len) + toCopy = bufferSize_ - len; unsigned char *src = (unsigned char *) buffer; - int pos = mEnd; + int pos = endPos_; while (toCopy) { int block = toCopy; - if (block > mBufferSize - pos) // Wrap block around ring ? - block = mBufferSize - pos; // Fill in to the end of the buffer - memcpy (mBuffer + pos, src, block); + if (block > bufferSize_ - pos) // Wrap block around ring ? + block = bufferSize_ - pos; // Fill in to the end of the buffer + + memcpy(buffer_ + pos, src, block); src += block; - pos = (pos + block) % mBufferSize; + pos = (pos + block) % bufferSize_; toCopy -= block; } - - mEnd = pos; + endPos_ = pos; } // @@ -197,57 +203,60 @@ RingBuffer::Put (void* buffer, int toCopy) // int -RingBuffer::AvailForGet (const std::string &call_id) +RingBuffer::AvailForGet(const std::string &call_id) { // Used space - return getLen (call_id); + return getLen(call_id); } // Get will move 'toCopy' bytes from the internal FIFO to 'buffer' int -RingBuffer::Get (void *buffer, int toCopy, const std::string &call_id) +RingBuffer::Get(void *buffer, int toCopy, const std::string &call_id) { if (getNbReadPointer() == 0) return 0; - if (!hasThisReadPointer (call_id)) + if (!hasThisReadPointer(call_id)) return 0; - int len = getLen (call_id); + int len = getLen(call_id); + if (toCopy > len) toCopy = len; + int copied = toCopy; unsigned char *dest = (unsigned char *) buffer; - int mStart = getReadPointer (call_id); + int startPos = getReadPointer(call_id); while (toCopy) { int block = toCopy; - if (block > mBufferSize - mStart) - block = mBufferSize - mStart; - memcpy (dest, mBuffer + mStart, block); + if (block > bufferSize_ - startPos) + block = bufferSize_ - startPos; + + memcpy(dest, buffer_ + startPos, block); dest += block; - mStart = (mStart + block) % mBufferSize; + startPos = (startPos + block) % bufferSize_; toCopy -= block; } - storeReadPointer (mStart, call_id); + storeReadPointer(startPos, call_id); return copied; } int -RingBuffer::Discard (int toDiscard, const std::string &call_id) +RingBuffer::Discard(int toDiscard, const std::string &call_id) { - int len = getLen (call_id); + int len = getLen(call_id); if (toDiscard > len) toDiscard = len; - int mStart = (getReadPointer (call_id) + toDiscard) % mBufferSize; + int startPos = (getReadPointer(call_id) + toDiscard) % bufferSize_; - storeReadPointer (mStart, call_id); + storeReadPointer(startPos, call_id); return toDiscard; } diff --git a/daemon/src/audio/ringbuffer.h b/daemon/src/audio/ringbuffer.h index 804edf2d475d2388ff1fe8df0b9851f564635fb8..f22b1f7f10965248f59ffdadb4bc51576840bc0c 100644 --- a/daemon/src/audio/ringbuffer.h +++ b/daemon/src/audio/ringbuffer.h @@ -22,20 +22,19 @@ #ifndef __RING_BUFFER__ #define __RING_BUFFER__ -#include "../call.h" - #include <fstream> +#include "../call.h" +#include "noncopyable.h" typedef std::map<std::string, int> ReadPointer; -class RingBuffer -{ +class RingBuffer { public: /** * Constructor * @param size Size of the buffer to create */ - RingBuffer (int size, const std::string &call_id = Call::DEFAULT_ID); + RingBuffer(int size, const std::string &call_id = Call::DEFAULT_ID); /** * Destructor @@ -43,26 +42,26 @@ class RingBuffer ~RingBuffer(); std::string getBufferId() { - return buffer_id; + return buffer_id_; } /** * Reset the counters to 0 for this read pointer */ - void flush (const std::string &call_id = Call::DEFAULT_ID); + void flush(const std::string &call_id = Call::DEFAULT_ID); void flushAll(); /** * Get read pointer coresponding to this call */ - int getReadPointer (const std::string &call_id = Call::DEFAULT_ID); + int getReadPointer(const std::string &call_id = Call::DEFAULT_ID); /** * Get the whole readpointer list for this ringbuffer */ ReadPointer* getReadPointerList() { - return &_readpointer; + return &readpointer_; } /** @@ -73,22 +72,22 @@ class RingBuffer /** * Move readpointer forward by pointer_value */ - void storeReadPointer (int pointer_value, const std::string &call_id = Call::DEFAULT_ID); + void storeReadPointer(int pointer_value, const std::string &call_id = Call::DEFAULT_ID); /** * Add a new readpointer for this ringbuffer */ - void createReadPointer (const std::string &call_id = Call::DEFAULT_ID); + void createReadPointer(const std::string &call_id = Call::DEFAULT_ID); /** * Remove a readpointer for this ringbuffer */ - void removeReadPointer (const std::string &call_id = Call::DEFAULT_ID); + void removeReadPointer(const std::string &call_id = Call::DEFAULT_ID); /** * Test if readpointer coresponding to this call is still active */ - bool hasThisReadPointer (const std::string &call_id); + bool hasThisReadPointer(const std::string &call_id); int getNbReadPointer(); @@ -97,13 +96,13 @@ class RingBuffer * @param buffer Data to copied * @param toCopy Number of bytes to copy */ - void Put (void* buffer, int toCopy); + void Put(void* buffer, int toCopy); /** * To get how much space is available in the buffer to read in * @return int The available size */ - int AvailForGet (const std::string &call_id = Call::DEFAULT_ID); + int AvailForGet(const std::string &call_id = Call::DEFAULT_ID); /** * Get data in the ring buffer @@ -111,14 +110,14 @@ class RingBuffer * @param toCopy Number of bytes to copy * @return int Number of bytes copied */ - int Get (void* buffer, int toCopy, const std::string &call_id = Call::DEFAULT_ID); + int Get(void* buffer, int toCopy, const std::string &call_id = Call::DEFAULT_ID); /** * Discard data from the buffer * @param toDiscard Number of bytes to discard * @return int Number of bytes discarded */ - int Discard (int toDiscard, const std::string &call_id = Call::DEFAULT_ID); + int Discard(int toDiscard, const std::string &call_id = Call::DEFAULT_ID); /** * Total length of the ring buffer @@ -126,7 +125,7 @@ class RingBuffer */ int putLen(); - int getLen (const std::string &call_id = Call::DEFAULT_ID); + int getLen(const std::string &call_id = Call::DEFAULT_ID); /** * Debug function print mEnd, mStart, mBufferSize @@ -134,24 +133,17 @@ class RingBuffer void debug(); private: - // Copy Constructor - RingBuffer (const RingBuffer& rh); + NON_COPYABLE(RingBuffer); - // Assignment operator - RingBuffer& operator= (const RingBuffer& rh); - - /** Pointer on the first data */ - // int mStart; /** Pointer on the last data */ - int mEnd; + int endPos_; /** Buffer size */ - int mBufferSize; + int bufferSize_; /** Data */ - unsigned char *mBuffer; - - ReadPointer _readpointer; + unsigned char *buffer_; - std::string buffer_id; + ReadPointer readpointer_; + std::string buffer_id_; public: diff --git a/daemon/src/audio/samplerateconverter.cpp b/daemon/src/audio/samplerateconverter.cpp index 8bfcbeb68756a7c16f0aec2c85ea6467a9692c3c..3337639d50f592a3088f454ec0550c3f685bfc17 100644 --- a/daemon/src/audio/samplerateconverter.cpp +++ b/daemon/src/audio/samplerateconverter.cpp @@ -32,27 +32,28 @@ #include "manager.h" #include <cassert> -SamplerateConverter::SamplerateConverter (int freq) : _maxFreq(freq) +SamplerateConverter::SamplerateConverter(int freq) : floatBufferIn_(0), + floatBufferOut_(0), samples_(0), maxFreq_(freq), src_state_(0) { int err; - _src_state = src_new (SRC_LINEAR, 1, &err); + src_state_ = src_new(SRC_LINEAR, 1, &err); - _samples = (freq * 20) / 1000; // start with 20 ms buffers + samples_ = (freq * 20) / 1000; // start with 20 ms buffers - _floatBufferIn = new float32[_samples]; - _floatBufferOut = new float32[_samples]; + floatBufferIn_ = new float[samples_]; + floatBufferOut_ = new float[samples_]; } -SamplerateConverter::~SamplerateConverter (void) +SamplerateConverter::~SamplerateConverter() { - delete [] _floatBufferIn; - delete [] _floatBufferOut; + delete [] floatBufferIn_; + delete [] floatBufferOut_; - src_delete (_src_state); + src_delete(src_state_); } void -SamplerateConverter::Short2FloatArray (const short *in, float *out, int len) +SamplerateConverter::Short2FloatArray(const short *in, float *out, int len) { // factor is 1/(2^15), used to rescale the short int range to the // [-1.0 - 1.0] float range. @@ -61,36 +62,38 @@ SamplerateConverter::Short2FloatArray (const short *in, float *out, int len) out[len] = (float) in[len] * .000030517578125f; } -//TODO Add ifdef for int16 or float32 type -void SamplerateConverter::resample (SFLDataFormat* dataIn , SFLDataFormat* dataOut , int inputFreq , int outputFreq , int nbSamples) +void SamplerateConverter::resample(SFLDataFormat* dataIn , SFLDataFormat* dataOut , int inputFreq , int outputFreq , int nbSamples) { double sampleFactor = (double) outputFreq / inputFreq; + if (sampleFactor == 1.0) - return; + return; unsigned int outSamples = nbSamples * sampleFactor; unsigned int maxSamples = outSamples; + if (maxSamples < (unsigned int)nbSamples) - maxSamples = nbSamples; - if (maxSamples > _samples) { - /* grow buffer if needed */ - _samples = maxSamples; - delete [] _floatBufferIn; - delete [] _floatBufferOut; - _floatBufferIn = new float32[_samples]; - _floatBufferOut = new float32[_samples]; + maxSamples = nbSamples; + + if (maxSamples > samples_) { + /* grow buffer if needed */ + samples_ = maxSamples; + delete [] floatBufferIn_; + delete [] floatBufferOut_; + floatBufferIn_ = new float[samples_]; + floatBufferOut_ = new float[samples_]; } - SRC_DATA src_data; - src_data.data_in = _floatBufferIn; - src_data.data_out = _floatBufferOut; - src_data.input_frames = nbSamples; - src_data.output_frames = outSamples; - src_data.src_ratio = sampleFactor; - src_data.end_of_input = 0; // More data will come + SRC_DATA src_data; + src_data.data_in = floatBufferIn_; + src_data.data_out = floatBufferOut_; + src_data.input_frames = nbSamples; + src_data.output_frames = outSamples; + src_data.src_ratio = sampleFactor; + src_data.end_of_input = 0; // More data will come - Short2FloatArray (dataIn , _floatBufferIn, nbSamples); - src_process (_src_state, &src_data); + Short2FloatArray(dataIn , floatBufferIn_, nbSamples); + src_process(src_state_, &src_data); - src_float_to_short_array (_floatBufferOut, dataOut , outSamples); + src_float_to_short_array(floatBufferOut_, dataOut , outSamples); } diff --git a/daemon/src/audio/samplerateconverter.h b/daemon/src/audio/samplerateconverter.h index 6d17b8d671f84e056ec32cdc1a0c1a5f9fd17af2..ae4b3d28a1094ccb10a3b94fb80d6ab9aa6c346e 100644 --- a/daemon/src/audio/samplerateconverter.h +++ b/daemon/src/audio/samplerateconverter.h @@ -32,13 +32,12 @@ #define _SAMPLE_RATE_H #include <samplerate.h> -#include <math.h> +#include <cmath> #include "global.h" +#include "noncopyable.h" - -class SamplerateConverter -{ +class SamplerateConverter { public: /** * Samplerate converter is used for several situation: @@ -47,10 +46,10 @@ class SamplerateConverter * internal buffer size. Converter must be reinitialized * every time these parameters change */ - SamplerateConverter (int freq); + SamplerateConverter(int freq); /** Destructor */ - ~SamplerateConverter (void); + ~SamplerateConverter(); /** * resample from the samplerate1 to the samplerate2 @@ -59,7 +58,7 @@ class SamplerateConverter * @param SamplerateConverter2 The desired sample rate * @param nbSamples The number of samples to process */ - void resample (SFLDataFormat* dataIn , SFLDataFormat* dataOut , int samplerate1 , int samplerate2 , int nbSamples); + void resample(SFLDataFormat* dataIn , SFLDataFormat* dataOut , int samplerate1 , int samplerate2 , int nbSamples); /** * Convert short table to floats for audio processing @@ -67,23 +66,19 @@ class SamplerateConverter * @param out The resulting (float) array * @param len The number of elements in both tables */ - void Short2FloatArray (const short *in, float *out, int len); + void Short2FloatArray(const short *in, float *out, int len); private: - // Copy Constructor - SamplerateConverter (const SamplerateConverter& rh); - - // Assignment Operator - SamplerateConverter& operator= (const SamplerateConverter& rh); + NON_COPYABLE(SamplerateConverter); /* temporary buffers */ - float32* _floatBufferIn; - float32* _floatBufferOut; - size_t _samples; // size in samples of temporary buffers - int _maxFreq; // maximal output frequency + float * floatBufferIn_; + float * floatBufferOut_; + size_t samples_; // size in samples of temporary buffers + int maxFreq_; // maximal output frequency - SRC_STATE* _src_state; + SRC_STATE* src_state_; }; #endif //_SAMPLE_RATE_H diff --git a/daemon/src/audio/sound/audiofile.cpp b/daemon/src/audio/sound/audiofile.cpp index c744aca12eb7e06cbce7c5f2a1a0a8115ebc3920..0dd1c336d861b3022b7bb7c3e97ea3d1c78d626d 100644 --- a/daemon/src/audio/sound/audiofile.cpp +++ b/daemon/src/audio/sound/audiofile.cpp @@ -44,184 +44,180 @@ #include "manager.h" RawFile::RawFile(const std::string& name, sfl::AudioCodec* codec, unsigned int sampleRate) - : audioCodec (codec) + : audioCodec_(codec) { - filepath = name; - if (filepath.empty()) + filepath_ = name; + + if (filepath_.empty()) throw AudioFileException("Unable to open audio file: filename is empty"); std::fstream file; - file.open (filepath.c_str(), std::fstream::in); + file.open(filepath_.c_str(), std::fstream::in); + if (!file.is_open()) throw AudioFileException("Unable to open audio file"); - file.seekg (0, std::ios::end); + file.seekg(0, std::ios::end); size_t length = file.tellg(); - file.seekg (0, std::ios::beg); + file.seekg(0, std::ios::beg); char *fileBuffer = new char[length]; - file.read (fileBuffer,length); + file.read(fileBuffer,length); file.close(); - unsigned int frameSize = audioCodec->getFrameSize(); - unsigned int bitrate = audioCodec->getBitRate() * 1000 / 8; - unsigned int audioRate = audioCodec->getClockRate(); + unsigned int frameSize = audioCodec_->getFrameSize(); + unsigned int bitrate = audioCodec_->getBitRate() * 1000 / 8; + unsigned int audioRate = audioCodec_->getClockRate(); unsigned int encFrameSize = frameSize * bitrate / audioRate; unsigned int decodedSize = length * (frameSize / encFrameSize); SFLDataFormat *monoBuffer = new SFLDataFormat[decodedSize]; SFLDataFormat *bufpos = monoBuffer; unsigned char *filepos = reinterpret_cast<unsigned char *>(fileBuffer); - _size = decodedSize; - while(length >= encFrameSize) { - bufpos += audioCodec->decode (bufpos, filepos, encFrameSize); - filepos += encFrameSize; - length -= encFrameSize; + size_ = decodedSize; + + while (length >= encFrameSize) { + bufpos += audioCodec_->decode(bufpos, filepos, encFrameSize); + filepos += encFrameSize; + length -= encFrameSize; } - delete[] fileBuffer; - - if (sampleRate == audioRate) { -#ifdef DATAFORMAT_IS_FLOAT - _buffer = new SFLDataFormat[_size]; - src_short_to_float_array (monoBuffer, _buffer, _size); - delete[] monoBuffer; -#else - _buffer = monoBuffer; -#endif - - } else { + + delete [] fileBuffer; + + if (sampleRate == audioRate) + buffer_ = monoBuffer; + else { double factord = (double) sampleRate / audioRate; - float* floatBufferIn = new float[_size]; - int sizeOut = ceil(factord*_size); - src_short_to_float_array (monoBuffer, floatBufferIn, _size); - delete[] monoBuffer; - SFLDataFormat* _buffer = new SFLDataFormat[sizeOut]; + float* floatBufferIn = new float[size_]; + int sizeOut = ceil(factord * size_); + src_short_to_float_array(monoBuffer, floatBufferIn, size_); + delete [] monoBuffer; + delete [] buffer_; + buffer_ = new SFLDataFormat[sizeOut]; SRC_DATA src_data; src_data.data_in = floatBufferIn; - src_data.input_frames = _size; + src_data.input_frames = size_; src_data.output_frames = sizeOut; src_data.src_ratio = factord; -#ifdef DATAFORMAT_IS_FLOAT - src_data.data_out = _buffer; - src_simple (&src_data, SRC_SINC_BEST_QUALITY, 1); -#else float* floatBufferOut = new float[sizeOut]; src_data.data_out = floatBufferOut; - src_simple (&src_data, SRC_SINC_BEST_QUALITY, 1); - src_float_to_short_array (floatBufferOut, _buffer, src_data.output_frames_gen); + src_simple(&src_data, SRC_SINC_BEST_QUALITY, 1); + src_float_to_short_array(floatBufferOut, buffer_, src_data.output_frames_gen); delete [] floatBufferOut; -#endif delete [] floatBufferIn; - _size = src_data.output_frames_gen; + size_ = src_data.output_frames_gen; } } -WaveFile::WaveFile (const std::string& fileName, unsigned int audioSamplingRate) +WaveFile::WaveFile(const std::string& fileName, unsigned int audioSamplingRate) { - std::fstream fs (fileName.c_str(), std::ios_base::in); - if (!fs) + std::fstream fs(fileName.c_str(), std::ios_base::in); + + if (!fs) throw AudioFileException("File " + fileName + " doesn't exist"); - filepath = fileName; + filepath_ = fileName; std::fstream fileStream; - fileStream.open (fileName.c_str(), std::ios::in | std::ios::binary); + fileStream.open(fileName.c_str(), std::ios::in | std::ios::binary); char riff[4] = { 0, 0, 0, 0 }; - fileStream.read (riff, 4); - if (strncmp ("RIFF", riff, 4) != 0) + fileStream.read(riff, 4); + + if (strncmp("RIFF", riff, 4) != 0) throw AudioFileException("File is not of RIFF format"); char fmt[4] = { 0, 0, 0, 0 }; int maxIteration = 10; - while (maxIteration-- && strncmp ("fmt ", fmt, 4)) - fileStream.read (fmt, 4); - if(maxIteration == 0) + while (maxIteration-- && strncmp("fmt ", fmt, 4)) + fileStream.read(fmt, 4); + + if (maxIteration == 0) throw AudioFileException("Could not find \"fmt \" chunk"); SINT32 chunk_size; // fmt chunk size unsigned short formatTag; // data compression tag - fileStream.read ( (char*) &chunk_size, 4); // Read fmt chunk size. - fileStream.read ( (char*) &formatTag, 2); + fileStream.read(reinterpret_cast<char*>(&chunk_size), 4); // Read fmt chunk size. + fileStream.read(reinterpret_cast<char*>(&formatTag), 2); if (formatTag != 1) // PCM = 1, FLOAT = 3 throw AudioFileException("File contains an unsupported data format type"); // Get number of channels from the header. SINT16 chan; - fileStream.read ( (char*) &chan, 2); + fileStream.read((char*) &chan, 2); - if(chan > 2) - throw AudioFileException("WaveFile: unsupported number of channels"); + if (chan > 2) + throw AudioFileException("WaveFile: unsupported number of channels"); // Get file sample rate from the header. SINT32 srate; - fileStream.read ( (char*) &srate, 4); + fileStream.read((char*) &srate, 4); SINT32 avgb; - fileStream.read ( (char*) &avgb, 4); + fileStream.read((char*) &avgb, 4); SINT16 blockal; - fileStream.read ( (char*) &blockal, 2); + fileStream.read((char*) &blockal, 2); // Determine the data type SINT16 dt; - fileStream.read ( (char*) &dt, 2); - if (dt != 8 && dt != 16 && dt != 32) - throw AudioFileException("File's bits per sample with is not supported"); + fileStream.read((char*) &dt, 2); + + if (dt != 8 && dt != 16 && dt != 32) + throw AudioFileException("File's bits per sample with is not supported"); // Find the "data" chunk char data[4] = { 0, 0, 0, 0 }; maxIteration = 10; - while (maxIteration-- && strncmp ("data", data, 4)) - fileStream.read (data, 4); + + while (maxIteration-- && strncmp("data", data, 4)) + fileStream.read(data, 4); // Sample rate converter initialized with 88200 sample long int converterSamples = ((unsigned int)srate > audioSamplingRate) ? srate : audioSamplingRate; - SamplerateConverter _converter (converterSamples); + SamplerateConverter converter_(converterSamples); // Get length of data from the header. SINT32 bytes; - fileStream.read ( (char*) &bytes, 4); + fileStream.read((char*) &bytes, 4); unsigned long nbSamples = 8 * bytes / dt / chan; // sample frames - _debug ("WaveFile: frame size %ld, data size %d align %d rate %d avgbyte %d chunk size %d dt %d", - nbSamples, bytes, blockal, srate, avgb, chunk_size, dt); + DEBUG("WaveFile: frame size %ld, data size %d align %d rate %d avgbyte %d chunk size %d dt %d", + nbSamples, bytes, blockal, srate, avgb, chunk_size, dt); // Should not be longer than a minute - if (nbSamples > (unsigned int) (60*srate)) - nbSamples = 60*srate; + if (nbSamples > static_cast<unsigned int>(60 * srate)) + nbSamples = 60 * srate; SFLDataFormat *tempBuffer = new SFLDataFormat[nbSamples]; - if (!tempBuffer) - throw AudioFileException("Could not allocate temporary buffer"); - fileStream.read ( (char *) tempBuffer, nbSamples*sizeof (SFLDataFormat)); + fileStream.read(reinterpret_cast<char *>(tempBuffer), nbSamples * sizeof(SFLDataFormat)); // mix two channels together if stereo - if(chan == 2) { - for(unsigned int i = 0; i < nbSamples-1; i+=2) - tempBuffer[i/2] = (tempBuffer[i] + tempBuffer[i+1]) / 2; - nbSamples /= 2; - } + if (chan == 2) { + for (unsigned int i = 0; i < nbSamples - 1; i += 2) + tempBuffer[static_cast<size_t>(i * 0.5)] = (tempBuffer[i] + tempBuffer[i + 1]) * 0.5; - if ((unsigned int)srate != audioSamplingRate) { - int outSamples = ((float) nbSamples * ( (float) audioSamplingRate / (float) srate)); - _buffer = new SFLDataFormat[outSamples]; - _converter.resample (tempBuffer, _buffer, srate, audioSamplingRate, nbSamples); - delete[] tempBuffer; - } else { - _buffer = tempBuffer; + nbSamples *= 0.5; } - _size = nbSamples; - _sampleRate = audioSamplingRate; + if ((unsigned int) srate != audioSamplingRate) { + int outSamples = ((float) nbSamples * ((float) audioSamplingRate / (float) srate)); + buffer_ = new SFLDataFormat[outSamples]; + converter_.resample(tempBuffer, buffer_, srate, audioSamplingRate, nbSamples); + delete [] tempBuffer; + } else + buffer_ = tempBuffer; + + size_ = nbSamples; + sampleRate_ = audioSamplingRate; } diff --git a/daemon/src/audio/sound/audiofile.h b/daemon/src/audio/sound/audiofile.h index a51f84d91899aff435b90cbf518c26930f466eb3..5c00aea6896cecebc2fdb554d8d552f3eb396b58 100644 --- a/daemon/src/audio/sound/audiofile.h +++ b/daemon/src/audio/sound/audiofile.h @@ -35,45 +35,34 @@ #define __AUDIOFILE_H__ #include <stdexcept> -#include <fstream> - #include "audio/audioloop.h" namespace sfl { class AudioCodec; } -class AudioFileException : public std::runtime_error -{ -public: - AudioFileException (const std::string& str="") : - std::runtime_error("AudioFile: AudioFileException occured: " + str) {} +class AudioFileException : public std::runtime_error { + public: + AudioFileException(const std::string& str = "") : + std::runtime_error("AudioFile: AudioFileException occured: " + str) {} }; /** * @brief Abstract interface for file readers */ -class AudioFile : public AudioLoop -{ -public: - const std::string &getFilePath(void) const{ - return filepath; - } - -protected: - /** The absolute path to the sound file */ - std::string filepath; +class AudioFile : public AudioLoop { + public: + AudioFile() : filepath_() {} + std::string getFilePath() const { + return filepath_; + } + + protected: + /** The absolute path to the sound file */ + std::string filepath_; }; - - -/** - * @file audiofile.h - * @brief A class to manage sound files - */ - -class RawFile : public AudioFile -{ +class RawFile : public AudioFile { public: /** * Constructor @@ -81,26 +70,20 @@ class RawFile : public AudioFile RawFile(const std::string& name, sfl::AudioCodec* codec, unsigned int sampleRate = 8000); private: - // Copy Constructor - RawFile (const RawFile& rh); - - // Assignment Operator - RawFile& operator= (const RawFile& rh); + NON_COPYABLE(RawFile); /** Your preferred codec */ - sfl::AudioCodec* audioCodec; + sfl::AudioCodec* audioCodec_; }; -class WaveFile : public AudioFile -{ - +class WaveFile : public AudioFile { public: - /** - * Load a sound file in memory - * @param filename The absolute path to the file - * @param sampleRate The sample rate to read it - */ - WaveFile(const std::string&, unsigned int); + /** + * Load a sound file in memory + * @param filename The absolute path to the file + * @param sampleRate The sample rate to read it + */ + WaveFile(const std::string&, unsigned int); }; -#endif +#endif // __AUDIOFILE_H__ diff --git a/daemon/src/audio/sound/dtmf.cpp b/daemon/src/audio/sound/dtmf.cpp index 72d27f1700931879579e984d514d9c3839867eea..914e616efcec7c2ade4e7c500b860069931ef576 100644 --- a/daemon/src/audio/sound/dtmf.cpp +++ b/daemon/src/audio/sound/dtmf.cpp @@ -34,55 +34,48 @@ #include "dtmf.h" -DTMF::DTMF (unsigned int sampleRate) - : currentTone (0), newTone (0), dtmfgenerator (sampleRate) -{ -} +DTMF::DTMF(unsigned int sampleRate) + : currentTone_(0), newTone_(0), dtmfgenerator_(sampleRate) +{} -DTMF::~DTMF (void) +void DTMF::startTone(char code) { + newTone_ = code; } -void -DTMF::startTone (char code) -{ - newTone = code; -} - -bool -DTMF::generateDTMF (SFLDataFormat* buffer, size_t n) +bool DTMF::generateDTMF(SFLDataFormat* buffer, size_t n) { if (!buffer) return false; try { - if (currentTone != 0) { + if (currentTone_ != 0) { // Currently generating a DTMF tone - if (currentTone == newTone) { + if (currentTone_ == newTone_) { // Continue generating the same tone - dtmfgenerator.getNextSamples (buffer, n); + dtmfgenerator_.getNextSamples(buffer, n); return true; - } else if (newTone != 0) { + } else if (newTone_ != 0) { // New tone requested - dtmfgenerator.getSamples (buffer, n, newTone); - currentTone = newTone; + dtmfgenerator_.getSamples(buffer, n, newTone_); + currentTone_ = newTone_; return true; } else { // Stop requested - currentTone = newTone; + currentTone_ = newTone_; return false; } } else { // Not generating any DTMF tone - if (newTone) { + if (newTone_) { // Requested to generate a DTMF tone - dtmfgenerator.getSamples (buffer, n, newTone); - currentTone = newTone; + dtmfgenerator_.getSamples(buffer, n, newTone_); + currentTone_ = newTone_; return true; } - - return false; + else + return false; } - } catch (DTMFException e) { + } catch (const DTMFException &e) { // invalid key return false; } diff --git a/daemon/src/audio/sound/dtmf.h b/daemon/src/audio/sound/dtmf.h index 89116853d179193ac10d194e3a5fe9891080f8c6..90b17715b82eaee2cc7c0fd636497e7543f78c47 100644 --- a/daemon/src/audio/sound/dtmf.h +++ b/daemon/src/audio/sound/dtmf.h @@ -42,37 +42,32 @@ * @file dtmf.h * @brief DMTF library to generate a dtmf sample */ -class DTMF -{ +class DTMF { public: /** * Create a new DTMF. * @param sampleRate frequency of the sample (ex: 8000 hz) */ - DTMF (unsigned int sampleRate); - - /** - * Destructor - */ - ~DTMF (void); + DTMF(unsigned int sampleRate); /** * Start the done for th given dtmf * @param code The DTMF code */ - void startTone (char code); + void startTone(char code); /** * Copy the sound inside the sampling* buffer * @param buffer : a SFLDataFormat* buffer * @param n : The size to generate */ - bool generateDTMF (SFLDataFormat* buffer, size_t n); + bool generateDTMF(SFLDataFormat* buffer, size_t n); - char currentTone; - char newTone; + private: + char currentTone_; + char newTone_; - DTMFGenerator dtmfgenerator; + DTMFGenerator dtmfgenerator_; }; #endif // __KEY_DTMF_H_ diff --git a/daemon/src/audio/sound/dtmfgenerator.cpp b/daemon/src/audio/sound/dtmfgenerator.cpp index 940a5c5c3d933fe4f760f57337080b9ee31d5bf6..60274bafa5feaf44a413f2f8bd891d7b72cc2ec2 100644 --- a/daemon/src/audio/sound/dtmfgenerator.cpp +++ b/daemon/src/audio/sound/dtmfgenerator.cpp @@ -33,16 +33,16 @@ * as that of the covered work. */ -#include <math.h> +#include <cmath> +#include <cassert> #include "dtmfgenerator.h" #include "global.h" - /* * Tone frequencies */ -const DTMFGenerator::DTMFTone DTMFGenerator::tones[NUM_TONES] = { +const DTMFGenerator::DTMFTone DTMFGenerator::tones_[NUM_TONES] = { {'0', 941, 1336}, {'1', 697, 1209}, {'2', 697, 1336}, @@ -65,169 +65,83 @@ const DTMFGenerator::DTMFTone DTMFGenerator::tones[NUM_TONES] = { /* * Initialize the generator */ -DTMFGenerator::DTMFGenerator (unsigned int sampleRate) : state(), _sampleRate (sampleRate), tone ("", sampleRate) +DTMFGenerator::DTMFGenerator(unsigned int sampleRate) : state(), sampleRate_(sampleRate), tone_("", sampleRate) { state.offset = 0; state.sample = 0; - for (int i = 0; i < NUM_TONES; i++) { - samples[i] = generateSample (i); - } + for (int i = 0; i < NUM_TONES; i++) + toneBuffers_[i] = fillToneBuffer(i); } DTMFGenerator::~DTMFGenerator() { - for (int i = 0; i < NUM_TONES; i++) { - delete[] samples[i]; - samples[i] = NULL; - } + for (int i = 0; i < NUM_TONES; i++) + delete[] toneBuffers_[i]; } /* * Get n samples of the signal of code code */ -void DTMFGenerator::getSamples (SFLDataFormat* buffer, size_t n, unsigned char code) throw (DTMFException) +void DTMFGenerator::getSamples(SFLDataFormat* buffer, size_t n, unsigned char code) { - size_t i; - - if (!buffer) { - throw DTMFException ("Invalid parameter value"); - } - - switch (code) { - - case '0': - state.sample = samples[0]; - break; - - case '1': - state.sample = samples[1]; - break; - - case '2': - state.sample = samples[2]; - break; - - case '3': - state.sample = samples[3]; - break; - - case '4': - state.sample = samples[4]; - break; - - case '5': - state.sample = samples[5]; - break; - - case '6': - state.sample = samples[6]; - break; - - case '7': - state.sample = samples[7]; - break; - - case '8': - state.sample = samples[8]; - break; - - case '9': - state.sample = samples[9]; - break; - - case 'A': - - case 'a': - state.sample = samples[10]; - break; - - case 'B': - - case 'b': - state.sample = samples[11]; - break; - - case 'C': - - case 'c': - state.sample = samples[12]; - break; - - case 'D': - - case 'd': - state.sample = samples[13]; - break; - - case '*': - state.sample = samples[14]; - break; - - case '#': - state.sample = samples[15]; - break; - - default: - throw DTMFException ("Invalid code"); - return; - break; + if (!buffer) + throw DTMFException("Invalid parameter value"); + + code = toupper(code); + + if (code >= '0' and code <= '9') + state.sample = toneBuffers_[code - '0']; + else if (code >= 'A' and code <= 'D') + state.sample = toneBuffers_[code - 'A' + 10]; + else { + switch (code) { + case '*': + state.sample = toneBuffers_[14]; + break; + + case '#': + state.sample = toneBuffers_[15]; + break; + + default: + throw DTMFException("Invalid code"); + break; + } } - for (i = 0; i < n; i++) { - buffer[i] = state.sample[i % _sampleRate]; - } + size_t i; + for (i = 0; i < n; ++i) + buffer[i] = state.sample[i % sampleRate_]; - state.offset = i % _sampleRate; + state.offset = i % sampleRate_; } - /* * Get next n samples (continues where previous call to * genSample or genNextSamples stopped */ -void DTMFGenerator::getNextSamples (SFLDataFormat* buffer, size_t n) throw (DTMFException) +void DTMFGenerator::getNextSamples(SFLDataFormat* buffer, size_t n) { size_t i; - if (!buffer) { - throw DTMFException ("Invalid parameter"); - } + if (!buffer) + throw DTMFException("Invalid parameter"); - if (state.sample == 0) { - throw DTMFException ("DTMF generator not initialized"); - } + if (state.sample == 0) + throw DTMFException("DTMF generator not initialized"); - for (i = 0; i < n; i++) { - buffer[i] = state.sample[ (state.offset + i) % _sampleRate]; - } + for (i = 0; i < n; i++) + buffer[i] = state.sample[(state.offset + i) % sampleRate_]; - state.offset = (state.offset + i) % _sampleRate; + state.offset = (state.offset + i) % sampleRate_; } - -/* - * Generate a tone sample - */ -SFLDataFormat* DTMFGenerator::generateSample (unsigned char code) throw (DTMFException) +SFLDataFormat* DTMFGenerator::fillToneBuffer(int index) { - SFLDataFormat* ptr; - - try { - ptr = new SFLDataFormat[_sampleRate]; - - if (!ptr) { - throw new DTMFException ("No memory left"); - return 0; - } - - tone.genSin (ptr, tones[code].higher, tones[code].lower, _sampleRate); - - return ptr; - } catch (...) { - throw new DTMFException ("No memory left"); - return 0; - } - + assert(index >= 0 and index < NUM_TONES); + SFLDataFormat* ptr = new SFLDataFormat[sampleRate_]; + tone_.genSin(ptr, tones_[index].higher, tones_[index].lower, sampleRate_); + return ptr; } diff --git a/daemon/src/audio/sound/dtmfgenerator.h b/daemon/src/audio/sound/dtmfgenerator.h index bb6e6460ffb5c0cebde2f75f3ebe53f26a1556b6..9eb8105db567fc05513b5ad28ec5d025b18d8074 100644 --- a/daemon/src/audio/sound/dtmfgenerator.h +++ b/daemon/src/audio/sound/dtmfgenerator.h @@ -37,8 +37,8 @@ #define DTMFGENERATOR_H #include <stdexcept> -#include <string.h> - +#include <string> +#include "noncopyable.h" #include "tone.h" #define NUM_TONES 16 @@ -47,8 +47,7 @@ * @file dtmfgenerator.h * @brief DMTF Generator Exception */ -class DTMFException : public std::runtime_error -{ +class DTMFException : public std::runtime_error { public: DTMFException(const std::string& str) : std::runtime_error(str) {}; }; @@ -57,8 +56,7 @@ class DTMFException : public std::runtime_error * @file dtmfgenerator.h * @brief DTMF Tone Generator */ -class DTMFGenerator -{ +class DTMFGenerator { private: /** Struct to handle a DTMF */ struct DTMFTone { @@ -77,16 +75,16 @@ class DTMFGenerator DTMFState state; /** The different kind of tones */ - static const DTMFTone tones[NUM_TONES]; + static const DTMFTone tones_[NUM_TONES]; - /** Generated samples */ - SFLDataFormat* samples[NUM_TONES]; + /** Generated samples for each tone */ + SFLDataFormat* toneBuffers_[NUM_TONES]; /** Sampling rate of generated dtmf */ - int _sampleRate; + int sampleRate_; /** A tone object */ - Tone tone; + Tone tone_; public: /** @@ -94,19 +92,11 @@ class DTMFGenerator * and can build one DTMF. * @param sampleRate frequency of the sample (ex: 8000 hz) */ - DTMFGenerator (unsigned int sampleRate); + DTMFGenerator(unsigned int sampleRate); - /** - * Destructor - */ ~DTMFGenerator(); - - // Copy Constructor - DTMFGenerator (const DTMFGenerator& rh); - - // Assignment Operator - DTMFGenerator& operator= (const DTMFGenerator& rh); + NON_COPYABLE(DTMFGenerator); /* * Get n samples of the signal of code code @@ -114,7 +104,7 @@ class DTMFGenerator * @param n number of sampling to get, should be lower or equal to buffer size * @param code dtmf code to get sound */ - void getSamples (SFLDataFormat* buffer, size_t n, unsigned char code) throw (DTMFException); + void getSamples(SFLDataFormat* buffer, size_t n, unsigned char code); /* * Get next n samples (continues where previous call to @@ -122,16 +112,16 @@ class DTMFGenerator * @param buffer a SFLDataFormat pointer to an allocated buffer * @param n number of sampling to get, should be lower or equal to buffer size */ - void getNextSamples (SFLDataFormat* buffer, size_t n) throw (DTMFException); + void getNextSamples(SFLDataFormat* buffer, size_t n); private: /** - * Generate samples for a specific dtmf code - * @param code The code + * Fill tone buffer for a given index of the array of tones. + * @param index of the tone in the array tones_ * @return SFLDataFormat* The generated data */ - SFLDataFormat* generateSample (unsigned char code) throw (DTMFException); + SFLDataFormat* fillToneBuffer(int index); }; #endif // DTMFGENERATOR_H diff --git a/daemon/src/audio/sound/tone.cpp b/daemon/src/audio/sound/tone.cpp index d45064ef43a9d65b921a813601c1af642cfdd094..0e233c2eef65929a28c8332fca18e9b348241402 100644 --- a/daemon/src/audio/sound/tone.cpp +++ b/daemon/src/audio/sound/tone.cpp @@ -35,31 +35,26 @@ * YM: 2006-11-15: changes unsigned int to std::string::size_type, thanks to Pierre Pomes (AMD64 compilation) */ #include "tone.h" -#include <math.h> +#include <cmath> #include <cstdlib> #include <cstring> -#define TABLE_LENGTH 4096 -double TWOPI = 2 * M_PI; +static const double TWOPI = 2.0 * M_PI; -Tone::Tone (const std::string& definition, unsigned int sampleRate) : AudioLoop(), _sampleRate (sampleRate), _xhigher (0.0), _xlower (0.0) +Tone::Tone(const std::string& definition, unsigned int sampleRate) : + sampleRate_(sampleRate), xhigher_(0.0), xlower_(0.0) { fillWavetable(); - genBuffer (definition); // allocate memory with definition parameter -} - -Tone::~Tone() -{ + genBuffer(definition); // allocate memory with definition parameter } void -Tone::genBuffer (const std::string& definition) +Tone::genBuffer(const std::string& definition) { - if (definition.empty()) { + if (definition.empty()) return; - } - _size = 0; + size_ = 0; SFLDataFormat* buffer = new SFLDataFormat[SIZEBUF]; //1kb SFLDataFormat* bufferPos = buffer; @@ -74,69 +69,63 @@ Tone::genBuffer (const std::string& definition) std::string::size_type deflen = definition.length(); do { - posEnd = definition.find (',', posStart); + posEnd = definition.find(',', posStart); - if (posEnd == std::string::npos) { + if (posEnd == std::string::npos) posEnd = deflen; - } + /* begin scope */ { // Sample string: "350+440" or "350+440/2000,244+655/2000" int freq1, freq2, time; - s = definition.substr (posStart, posEnd-posStart); + s = definition.substr(posStart, posEnd-posStart); // The 1st frequency is before the first + or the / - std::string::size_type pos_plus = s.find ('+'); - std::string::size_type pos_slash = s.find ('/'); - std::string::size_type len = s.length(); - std::string::size_type endfrequency = 0; + size_t pos_plus = s.find('+'); + size_t pos_slash = s.find('/'); + size_t len = s.length(); + size_t endfrequency = 0; if (pos_slash == std::string::npos) { time = 0; endfrequency = len; } else { - time = atoi ( (s.substr (pos_slash+1,len-pos_slash-1)).data()); + time = atoi(s.substr(pos_slash + 1, len - pos_slash - 1).c_str()); endfrequency = pos_slash; } // without a plus = 1 frequency if (pos_plus == std::string::npos) { - freq1 = atoi ( (s.substr (0,endfrequency)).data()); + freq1 = atoi(s.substr(0, endfrequency).c_str()); freq2 = 0; } else { - freq1 = atoi ( (s.substr (0,pos_plus)).data()); - freq2 = atoi ( (s.substr (pos_plus+1, endfrequency-pos_plus-1)).data()); + freq1 = atoi(s.substr(0, pos_plus).c_str()); + freq2 = atoi(s.substr(pos_plus + 1, endfrequency - pos_plus - 1).c_str()); } // If there is time or if it's unlimited - if (time == 0) { - count = _sampleRate; - } else { - count = (_sampleRate * time) / 1000; - } + if (time == 0) + count = sampleRate_; + else + count = (sampleRate_ * time) / 1000; // Generate SAMPLING_RATE samples of sinus, buffer is the result - _debug ("genSin(%d, %d)", freq1, freq2); - genSin (bufferPos, freq1, freq2, count); + DEBUG("genSin(%d, %d)", freq1, freq2); + genSin(bufferPos, freq1, freq2, count); // To concatenate the different buffers for each section. - _size += (count); + size_ += count; + bufferPos += count; + } /* end scope */ - bufferPos += (count); - } - - posStart = posEnd+1; + posStart = posEnd + 1; } while (posStart < deflen); - _buffer = new SFLDataFormat[_size]; - - memcpy (_buffer, buffer, _size*sizeof (SFLDataFormat)); // copy char, not SFLDataFormat. - - delete[] buffer; + buffer_ = new SFLDataFormat[size_]; - buffer=0; + memcpy(buffer_, buffer, size_ * sizeof(SFLDataFormat)); // copy char, not SFLDataFormat. - bufferPos=0; + delete [] buffer; } void @@ -144,65 +133,62 @@ Tone::fillWavetable() { double tableSize = (double) TABLE_LENGTH; - for (int i = 0; i < TABLE_LENGTH; i++) { - _wavetable[i] = sin ( ( (double) i / (tableSize - 1.0)) * TWOPI); - } + for (int i = 0; i < TABLE_LENGTH; ++i) + wavetable_[i] = sin((static_cast<double>(i) / (tableSize - 1.0)) * TWOPI); } double -Tone::interpolate (double x) +Tone::interpolate(double x) { int xi_0, xi_1; double yi_0, yi_1, A, B; xi_0 = (int) x; - xi_1 = xi_0+1; + xi_1 = xi_0 + 1; - yi_0 =_wavetable[xi_0]; - yi_1 = _wavetable[xi_1]; + yi_0 = wavetable_[xi_0]; + yi_1 = wavetable_[xi_1]; A = (x - xi_0); B = 1.0 - A; - return A*yi_0 + B*yi_1; + return (A * yi_0) + (B * yi_1); } void -Tone::genSin (SFLDataFormat* buffer, int frequency1, int frequency2, int nb) +Tone::genSin(SFLDataFormat* buffer, int frequency1, int frequency2, int nb) { - _xhigher = 0.0; - _xlower = 0.0; + xhigher_ = 0.0; + xlower_ = 0.0; - double sr = (double) _sampleRate; + double sr = (double) sampleRate_; double tableSize = (double) TABLE_LENGTH; - double N_h = sr / (double) (frequency1); - double N_l = sr / (double) (frequency2); + double N_h = sr / (double)(frequency1); + double N_l = sr / (double)(frequency2); double dx_h = tableSize / N_h; double dx_l = tableSize / N_l; - double x_h = _xhigher; - double x_l = _xlower; + double x_h = xhigher_; + double x_l = xlower_; - double amp = (double) SFLDataAmplitude; + static const double DATA_AMPLITUDE = 2047; + double amp = DATA_AMPLITUDE; for (int t = 0; t < nb; t ++) { - buffer[t] = (int16) (amp* (interpolate (x_h) + interpolate (x_l))); + buffer[t] = static_cast<SFLDataFormat>(amp * (interpolate(x_h) + interpolate(x_l))); x_h += dx_h; x_l += dx_l; - if (x_h > tableSize) { + while (x_h > tableSize) x_h -= tableSize; - } - if (x_l > tableSize) { + while (x_l > tableSize) x_l -= tableSize; - } } - _xhigher = x_h; - _xlower = x_l; - + xhigher_ = x_h; + xlower_ = x_l; } diff --git a/daemon/src/audio/sound/tone.h b/daemon/src/audio/sound/tone.h index 1cfa3348411298b0afef9b042ee6065202c06666..be9c6c0cbe270308fb924cf45c4d3ceabac2755f 100644 --- a/daemon/src/audio/sound/tone.h +++ b/daemon/src/audio/sound/tone.h @@ -36,26 +36,18 @@ #include <string> #include "audio/audioloop.h" -#define TABLE_LENGTH 4096 - /** * @file tone.h * @brief Tone sample (dial, busy, ring, congestion) */ -class Tone : public AudioLoop -{ +class Tone : public AudioLoop { public: /** * Constructor * @param definition String that contain frequency/time of the tone * @param sampleRate SampleRating of audio tone */ - Tone (const std::string& definition, unsigned int sampleRate); - - /** - * Destructor - */ - ~Tone(); + Tone(const std::string& definition, unsigned int sampleRate); /** The different kind of tones */ enum TONEID { @@ -74,17 +66,17 @@ class Tone : public AudioLoop * @param nb are the number of int16 (mono) to generate * by example nb=5 generate 10 int16, 5 for the left, 5 for the right */ - void genSin (SFLDataFormat* buffer, int frequency1, int frequency2, int nb); + void genSin(SFLDataFormat* buffer, int frequency1, int frequency2, int nb); /** * */ - void fillWavetable (void); + void fillWavetable(); /** * */ - double interpolate (double x); + double interpolate(double x); private: @@ -93,15 +85,16 @@ class Tone : public AudioLoop * allocate the memory with the definition * @param definition String that contain frequency/time of the tone. */ - void genBuffer (const std::string& definition); + void genBuffer(const std::string& definition); /** Sample rate */ - unsigned int _sampleRate; + unsigned int sampleRate_; - double _wavetable[TABLE_LENGTH]; + static const int TABLE_LENGTH = 4096; + double wavetable_[TABLE_LENGTH]; - double _xhigher; - double _xlower; + double xhigher_; + double xlower_; }; #endif // __TONE_H__ diff --git a/daemon/src/audio/sound/tonelist.cpp b/daemon/src/audio/sound/tonelist.cpp index c08dba566f1c3653701a9466a8d262dc1629428b..4878db4db427d7d8ea3d27abb4e6c641d3386957 100644 --- a/daemon/src/audio/sound/tonelist.cpp +++ b/daemon/src/audio/sound/tonelist.cpp @@ -33,95 +33,102 @@ #include "tonelist.h" static const char *toneZone[TelephoneTone::ZID_COUNTRIES][Tone::TONE_NULL] = { - { // ZID_NORTH_AMERICA - "350+440", //Tone::TONE_DIALTONE - "480+620/500,0/500", //Tone::TONE_BUSY - "440+480/2000,0/4000", //Tone::TONE_RINGTONE - "480+620/250,0/250", //Tone::TONE_CONGESTION - }, - { //ZID_FRANCE - "440", - "440/500,0/500", - "440/1500,0/3500", - "440/250,0/250", - }, - { //ZID_AUSTRALIA - "413+438", - "425/375,0/375", - "413+438/400,0/200,413+438/400,0/2000", - "425/375,0/375,420/375,8/375", - }, - { //ZID_UNITED_KINGDOM - "350+440", - "400/375,0/375", - "400+450/400,0/200,400+450/400,0/2000", - "400/400,0/350,400/225,0/525", - }, - { //ZID_SPAIN - "425", - "425/200,0/200", - "425/1500,0/3000", - "425/200,0/200,425/200,0/200,425/200,0/600", - }, - { //ZID_ITALY - "425/600,0/1000,425/200,0/200", - "425/500,0/500", - "425/1000,0/4000", - "425/200,0/200", - }, - { //ZID_JAPAN - "400", - "400/500,0/500", - "400+15/1000,0/2000", - "400/500,0/500", - } + { + // ZID_NORTH_AMERICA + "350+440", //Tone::TONE_DIALTONE + "480+620/500,0/500", //Tone::TONE_BUSY + "440+480/2000,0/4000", //Tone::TONE_RINGTONE + "480+620/250,0/250", //Tone::TONE_CONGESTION + }, + { + //ZID_FRANCE + "440", + "440/500,0/500", + "440/1500,0/3500", + "440/250,0/250", + }, + { + //ZID_AUSTRALIA + "413+438", + "425/375,0/375", + "413+438/400,0/200,413+438/400,0/2000", + "425/375,0/375,420/375,8/375", + }, + { + //ZID_UNITED_KINGDOM + "350+440", + "400/375,0/375", + "400+450/400,0/200,400+450/400,0/2000", + "400/400,0/350,400/225,0/525", + }, + { + //ZID_SPAIN + "425", + "425/200,0/200", + "425/1500,0/3000", + "425/200,0/200,425/200,0/200,425/200,0/600", + }, + { + //ZID_ITALY + "425/600,0/1000,425/200,0/200", + "425/500,0/500", + "425/1000,0/4000", + "425/200,0/200", + }, + { + //ZID_JAPAN + "400", + "400/500,0/500", + "400+15/1000,0/2000", + "400/500,0/500", + } }; TelephoneTone::COUNTRYID -TelephoneTone::getCountryId (const std::string& countryName) +TelephoneTone::getCountryId(const std::string& countryName) { - if (countryName == "North America") return ZID_NORTH_AMERICA; - if (countryName == "France") return ZID_FRANCE; - if (countryName == "Australia") return ZID_AUSTRALIA; - if (countryName == "United Kingdom") return ZID_UNITED_KINGDOM; - if (countryName == "Spain") return ZID_SPAIN; - if (countryName == "Italy") return ZID_ITALY; - if (countryName == "Japan") return ZID_JAPAN; - return ZID_NORTH_AMERICA; // default + if (countryName == "North America") return ZID_NORTH_AMERICA; + else if (countryName == "France") return ZID_FRANCE; + else if (countryName == "Australia") return ZID_AUSTRALIA; + else if (countryName == "United Kingdom") return ZID_UNITED_KINGDOM; + else if (countryName == "Spain") return ZID_SPAIN; + else if (countryName == "Italy") return ZID_ITALY; + else if (countryName == "Japan") return ZID_JAPAN; + else return ZID_NORTH_AMERICA; // default } -TelephoneTone::TelephoneTone (const std::string& countryName, unsigned int sampleRate) : - _currentTone (Tone::TONE_NULL) +TelephoneTone::TelephoneTone(const std::string& countryName, unsigned int sampleRate) : + currentTone_(Tone::TONE_NULL) { - TelephoneTone::COUNTRYID countryId = getCountryId (countryName); + TelephoneTone::COUNTRYID countryId = getCountryId(countryName); - _tone[Tone::TONE_DIALTONE] = new Tone (toneZone[countryId][Tone::TONE_DIALTONE], sampleRate); - _tone[Tone::TONE_BUSY] = new Tone (toneZone[countryId][Tone::TONE_BUSY], sampleRate); - _tone[Tone::TONE_RINGTONE] = new Tone (toneZone[countryId][Tone::TONE_RINGTONE], sampleRate); - _tone[Tone::TONE_CONGESTION] = new Tone (toneZone[countryId][Tone::TONE_CONGESTION], sampleRate); + tone_[Tone::TONE_DIALTONE] = new Tone(toneZone[countryId][Tone::TONE_DIALTONE], sampleRate); + tone_[Tone::TONE_BUSY] = new Tone(toneZone[countryId][Tone::TONE_BUSY], sampleRate); + tone_[Tone::TONE_RINGTONE] = new Tone(toneZone[countryId][Tone::TONE_RINGTONE], sampleRate); + tone_[Tone::TONE_CONGESTION] = new Tone(toneZone[countryId][Tone::TONE_CONGESTION], sampleRate); } TelephoneTone::~TelephoneTone() { for (size_t i=0; i < Tone::TONE_NULL; i++) - delete _tone[i]; + delete tone_[i]; } void -TelephoneTone::setCurrentTone (Tone::TONEID toneId) +TelephoneTone::setCurrentTone(Tone::TONEID toneId) { - if (toneId != Tone::TONE_NULL && _currentTone != toneId) - _tone[toneId]->reset(); + if (toneId != Tone::TONE_NULL && currentTone_ != toneId) + tone_[toneId]->reset(); - _currentTone = toneId; + currentTone_ = toneId; } Tone* TelephoneTone::getCurrentTone() { - if (_currentTone == Tone::TONE_NULL) + if (currentTone_ == Tone::TONE_NULL) return NULL; - return _tone[_currentTone]; + return tone_[currentTone_]; } diff --git a/daemon/src/audio/sound/tonelist.h b/daemon/src/audio/sound/tonelist.h index cc8f20e78ba17e38768717c9751696f8db70cd42..c5cf440b7e389657b7b732abb374bb4d6514fced 100644 --- a/daemon/src/audio/sound/tonelist.h +++ b/daemon/src/audio/sound/tonelist.h @@ -37,39 +37,33 @@ #include "tone.h" -class TelephoneTone -{ +class TelephoneTone { public: + /** Countries */ + enum COUNTRYID { + ZID_NORTH_AMERICA = 0, + ZID_FRANCE, + ZID_AUSTRALIA, + ZID_UNITED_KINGDOM, + ZID_SPAIN, + ZID_ITALY, + ZID_JAPAN, + ZID_COUNTRIES, + }; - /** Countries */ - enum COUNTRYID { - ZID_NORTH_AMERICA = 0, - ZID_FRANCE, - ZID_AUSTRALIA, - ZID_UNITED_KINGDOM, - ZID_SPAIN, - ZID_ITALY, - ZID_JAPAN, - ZID_COUNTRIES, - }; - - TelephoneTone (const std::string& countryName, unsigned int sampleRate); + TelephoneTone(const std::string& countryName, unsigned int sampleRate); ~TelephoneTone(); - void setCurrentTone (Tone::TONEID toneId); + void setCurrentTone(Tone::TONEID toneId); Tone* getCurrentTone(); private: - // Copy Constructor - TelephoneTone (const TelephoneTone& rh); - - // Assignment Operator - TelephoneTone& operator= (const TelephoneTone& rh); + NON_COPYABLE(TelephoneTone); - static COUNTRYID getCountryId (const std::string& countryName); + static COUNTRYID getCountryId(const std::string& countryName); - Tone* _tone[Tone::TONE_NULL]; - Tone::TONEID _currentTone; + Tone* tone_[Tone::TONE_NULL]; + Tone::TONEID currentTone_; }; #endif diff --git a/daemon/src/audio/speexechocancel.cpp b/daemon/src/audio/speexechocancel.cpp index ee1ab245198f3838e10ba20c57b1d47181b03d50..c5daacddafa48bead5b0b74c6b9af7e380eef5f3 100644 --- a/daemon/src/audio/speexechocancel.cpp +++ b/daemon/src/audio/speexechocancel.cpp @@ -18,7 +18,7 @@ */ #include <fstream> -#include <limits.h> +#include <climits> #include "speexechocancel.h" #include <speex/speex_echo.h> @@ -30,136 +30,98 @@ // number of sample to process, (800 Ã 4000 samples, 100 to 500 ms) #define EC_FILTER_LENGTH 800 +namespace { +const int SPEEX_SAMPLE_RATE = 8000; +const int RINGBUFFER_SIZE = 100000; +} -SpeexEchoCancel::SpeexEchoCancel() +SpeexEchoCancel::SpeexEchoCancel() : + echoDelay_(Manager::instance().getEchoCancelDelay() * SPEEX_SAMPLE_RATE / 1000), + echoTailLength_(Manager::instance().getEchoCancelTailLength() * SPEEX_SAMPLE_RATE / 1000), + echoState_(speex_echo_state_init(EC_FRAME_SIZE, echoTailLength_)), + preState_(speex_preprocess_state_init(EC_FRAME_SIZE, SPEEX_SAMPLE_RATE)), + micData_(new RingBuffer(RINGBUFFER_SIZE)), + spkrData_(new RingBuffer(RINGBUFFER_SIZE)), + spkrStopped_(true) { - int samplingRate = 8000; - - int echoDelayMs = Manager::instance().getEchoCancelDelay(); - int echoTailLengthMs = Manager::instance().getEchoCancelTailLength(); - - _echoDelay = echoDelayMs * samplingRate / 1000; - _echoTailLength = echoTailLengthMs * samplingRate / 1000; - - // _echoState = speex_echo_state_init (EC_FRAME_SIZE, EC_FILTER_LENGTH); - _echoState = speex_echo_state_init (EC_FRAME_SIZE, _echoTailLength); - _preState = speex_preprocess_state_init (EC_FRAME_SIZE, samplingRate); - - _debug("EchoCancel: Initializing echo canceller with delay: %d, filter length: %d, frame size: %d and samplerate %d", - _echoDelay, _echoTailLength, EC_FRAME_SIZE, samplingRate); - - speex_echo_ctl (_echoState, SPEEX_ECHO_SET_SAMPLING_RATE, &samplingRate); - speex_preprocess_ctl (_preState, SPEEX_PREPROCESS_SET_ECHO_STATE, _echoState); - - _micData = new RingBuffer (100000); - _spkrData = new RingBuffer (100000); + DEBUG("EchoCancel: Initializing echo canceller with delay: %d, filter length: %d, frame size: %d and samplerate %d", + echoDelay_, echoTailLength_, EC_FRAME_SIZE, SPEEX_SAMPLE_RATE); - _micData->createReadPointer(); - _spkrData->createReadPointer(); + int rate = SPEEX_SAMPLE_RATE; + speex_echo_ctl(echoState_, SPEEX_ECHO_SET_SAMPLING_RATE, &rate); + speex_preprocess_ctl(preState_, SPEEX_PREPROCESS_SET_ECHO_STATE, echoState_); -#ifdef DUMP_ECHOCANCEL_INTERNAL_DATA - micFile = new ofstream("test_mic_data.raw"); - spkrFile = new ofstream("test_spkr_data.raw"); - micProcessFile = new ofstream("test_mic_data_process.raw", std::ofstream::out); - spkrProcessFile = new ofstream("test_spkr_data_process.raw", std::ofstream::out); - echoFile = new ofstream("test_echo_data.raw"); -#endif - - _spkrStopped = true; + micData_->createReadPointer(); + spkrData_->createReadPointer(); } SpeexEchoCancel::~SpeexEchoCancel() { - speex_echo_state_destroy (_echoState); - speex_preprocess_state_destroy (_preState); - delete _micData; - delete _spkrData; -#ifdef DUMP_ECHOCANCEL_INTERNAL_DATA - delete micFile; - delete spkrFile; - delete micProcessFile; - delete spkrProcessFile; - delete echoFile; -#endif - + speex_echo_state_destroy(echoState_); + speex_preprocess_state_destroy(preState_); + delete spkrData_; + delete micData_; } -void SpeexEchoCancel::putData (SFLDataFormat *inputData, int samples) +void SpeexEchoCancel::putData(SFLDataFormat *inputData, int samples) { - if (_spkrStopped) { - _micData->flushAll(); - _spkrData->flushAll(); - _spkrStopped = false; + if (spkrStopped_) { + micData_->flushAll(); + spkrData_->flushAll(); + spkrStopped_ = false; } -#ifdef DUMP_ECHOCANCEL_INTERNAL_DATA - spkrFile->write(reinterpret_cast<char *>(inputData), samples * sizeof(SFLDataFormat)); -#endif - - _spkrData->Put (inputData, samples * sizeof(SFLDataFormat)); + spkrData_->Put(inputData, samples * sizeof(SFLDataFormat)); } -int SpeexEchoCancel::process (SFLDataFormat *inputData, SFLDataFormat *outputData, int samples) +int SpeexEchoCancel::process(SFLDataFormat *inputData, SFLDataFormat *outputData, int samples) { - if (_spkrStopped) + if (spkrStopped_) return 0; const int byteSize = EC_FRAME_SIZE * sizeof(SFLDataFormat); // init temporary buffers - memset (_tmpSpkr, 0, sizeof(_tmpSpkr)); - memset (_tmpMic, 0, sizeof(_tmpMic)); - memset (_tmpOut, 0, sizeof(_tmpOut)); - -#ifdef DUMP_ECHOCANCEL_INTERNAL_DATA - micFile->write(reinterpret_cast<char *>(inputData), nbBytes); -#endif + memset(tmpSpkr_, 0, sizeof(tmpSpkr_)); + memset(tmpMic_, 0, sizeof(tmpMic_)); + memset(tmpOut_, 0, sizeof(tmpOut_)); // Put mic data in ringbuffer - _micData->Put (inputData, samples * sizeof(SFLDataFormat)); + micData_->Put(inputData, samples * sizeof(SFLDataFormat)); // Store data for synchronization - int spkrAvail = _spkrData->AvailForGet(); - int micAvail = _micData->AvailForGet(); + int spkrAvail = spkrData_->AvailForGet(); + int micAvail = micData_->AvailForGet(); - if (spkrAvail < (_echoDelay+byteSize) || micAvail < byteSize) { - _micData->Discard(byteSize); - return 0; + if (spkrAvail < (echoDelay_+byteSize) || micAvail < byteSize) { + micData_->Discard(byteSize); + return 0; } - _spkrData->Get (_tmpSpkr, byteSize); - _micData->Get (_tmpMic, byteSize); - -#ifdef DUMP_ECHOCANCEL_INTERNAL_DATA - micProcessFile->write(reinterpret_cast<char *>(_tmpMic), byteSize); - spkrProcessFile->write(reinterpret_cast<char *>(_tmpSpkr), byteSize); -#endif + spkrData_->Get(tmpSpkr_, byteSize); + micData_->Get(tmpMic_, byteSize); - for(int i = 0; i < EC_FRAME_SIZE; i++) { - int32_t tmp = _tmpSpkr[i] * 3; - if (tmp > SHRT_MAX) - tmp = SHRT_MAX; - _tmpSpkr[i] = (int16_t)tmp; + for (int i = 0; i < EC_FRAME_SIZE; i++) { + int32_t tmp = tmpSpkr_[i] * 3; - _tmpMic[i] /= 3; - } + if (tmp > SHRT_MAX) + tmp = SHRT_MAX; + tmpSpkr_[i] = (int16_t)tmp; - speex_echo_cancellation (_echoState, _tmpMic, _tmpSpkr, _tmpOut); - speex_preprocess_run(_preState, reinterpret_cast<short *>(_tmpOut)); + tmpMic_[i] /= 3; + } -#ifdef DUMP_ECHOCANCEL_INTERNAL_DATA - echoFile->write(reinterpret_cast<char *>(_tmpOut), byteSize); -#endif + speex_echo_cancellation(echoState_, tmpMic_, tmpSpkr_, tmpOut_); + speex_preprocess_run(preState_, reinterpret_cast<short *>(tmpOut_)); - for(int i = 0; i < EC_FRAME_SIZE; i++) { - _tmpOut[i] *= 3; - } + for (int i = 0; i < EC_FRAME_SIZE; i++) + tmpOut_[i] *= 3; - memcpy (outputData, _tmpOut, byteSize); + memcpy(outputData, tmpOut_, byteSize); - spkrAvail = _spkrData->AvailForGet(); - micAvail = _micData->AvailForGet(); + spkrAvail = spkrData_->AvailForGet(); + micAvail = micData_->AvailForGet(); return EC_FRAME_SIZE; } diff --git a/daemon/src/audio/speexechocancel.h b/daemon/src/audio/speexechocancel.h index 42c5cfda5e55fa8e621df51276e786eb76497c9b..48d945384f90322897968ee7e89f166f4a09da15 100644 --- a/daemon/src/audio/speexechocancel.h +++ b/daemon/src/audio/speexechocancel.h @@ -21,6 +21,7 @@ #define SPEEXECHOCANCEL_H #include "global.h" +#include "noncopyable.h" class RingBuffer; class SpeexEchoState_; @@ -28,8 +29,7 @@ typedef SpeexEchoState_ SpeexEchoState; class SpeexPreprocessState_; typedef SpeexPreprocessState_ SpeexPreprocessState; -class SpeexEchoCancel -{ +class SpeexEchoCancel { public: SpeexEchoCancel(); @@ -39,40 +39,32 @@ class SpeexEchoCancel * Add speaker data into internal buffer * \param inputData containing far-end voice data to be sent to speakers */ - void putData (SFLDataFormat *, int samples); + void putData(SFLDataFormat *, int samples); /** * Perform echo cancellation using internal buffers * \param inputData containing mixed echo and voice data * \param outputData containing */ - int process (SFLDataFormat *, SFLDataFormat *, int samples); + int process(SFLDataFormat *, SFLDataFormat *, int samples); private: + NON_COPYABLE(SpeexEchoCancel); - SpeexEchoState *_echoState; + int echoDelay_; + int echoTailLength_; - SpeexPreprocessState *_preState; + SpeexEchoState *echoState_; + SpeexPreprocessState *preState_; - RingBuffer *_micData; - RingBuffer *_spkrData; + RingBuffer *micData_; + RingBuffer *spkrData_; - int _echoDelay; - int _echoTailLength; + bool spkrStopped_; - bool _spkrStopped; - - SFLDataFormat _tmpSpkr[5000]; - SFLDataFormat _tmpMic[5000]; - SFLDataFormat _tmpOut[5000]; - -#ifdef DUMP_ECHOCANCEL_INTERNAL_DATA - ofstream *micFile; - ofstream *spkrFile; - ofstream *micProcessFile; - ofstream *spkrProcessFile; - ofstream *echoFile; -#endif + SFLDataFormat tmpSpkr_[5000]; + SFLDataFormat tmpMic_[5000]; + SFLDataFormat tmpOut_[5000]; }; #endif diff --git a/daemon/src/call.cpp b/daemon/src/call.cpp index 9bb09f2e8a9f5e68ef4a8dda86d35d00ae2187a6..258d2ca22e8d95e4eb0bb9a72208fd1e5f055dba 100644 --- a/daemon/src/call.cpp +++ b/daemon/src/call.cpp @@ -34,94 +34,103 @@ const char * const Call::DEFAULT_ID = "audiolayer_id"; -Call::Call (const std::string& id, Call::CallType type) - : _callMutex() - , _localIPAddress ("") - , _localAudioPort (0) - , _id (id) - , _confID ("") - , _type (type) - , _connectionState (Call::Disconnected) - , _callState (Call::Inactive) - , _callConfig (Call::Classic) - , _peerName() - , _peerNumber() -{ - -} - +Call::Call(const std::string& id, Call::CallType type) + : callMutex_() + , localIPAddress_("") + , localAudioPort_(0) + , id_(id) + , confID_() + , type_(type) + , connectionState_(Call::Disconnected) + , callState_(Call::Inactive) + , callConfig_(Call::Classic) + , peerName_() + , peerNumber_() + , displayName_() +{} Call::~Call() -{ -} +{} void -Call::setConnectionState (ConnectionState state) +Call::setConnectionState(ConnectionState state) { - ost::MutexLock m (_callMutex); - _connectionState = state; + ost::MutexLock m(callMutex_); + connectionState_ = state; } Call::ConnectionState Call::getConnectionState() { - ost::MutexLock m (_callMutex); - return _connectionState; + ost::MutexLock m(callMutex_); + return connectionState_; } void -Call::setState (CallState state) +Call::setState(CallState state) { - ost::MutexLock m (_callMutex); - _callState = state; + ost::MutexLock m(callMutex_); + callState_ = state; } Call::CallState Call::getState() { - ost::MutexLock m (_callMutex); - return _callState; + ost::MutexLock m(callMutex_); + return callState_; } std::string -Call::getStateStr () +Call::getStateStr() { switch (getState()) { - case Active: - switch (getConnectionState()) { - case Ringing: return isIncoming() ? "INCOMING" : "RINGING"; - case Connected: - default: return isRecording() ? "RECORD" : "CURRENT"; - } - case Hold: return "HOLD"; - case Busy: return "BUSY"; - case Inactive: - switch (getConnectionState()) { - case Ringing: return isIncoming() ? "INCOMING" : "RINGING"; - case Connected: return "CURRENT"; - default: return "INACTIVE"; - } - case Conferencing: return "CONFERENCING"; - case Refused: - case Error: - default: return "FAILURE"; + case Active: + switch (getConnectionState()) { + case Ringing: + return isIncoming() ? "INCOMING" : "RINGING"; + case Connected: + default: + return isRecording() ? "RECORD" : "CURRENT"; + } + + case Hold: + return "HOLD"; + case Busy: + return "BUSY"; + case Inactive: + + switch (getConnectionState()) { + case Ringing: + return isIncoming() ? "INCOMING" : "RINGING"; + case Connected: + return "CURRENT"; + default: + return "INACTIVE"; + } + + case Conferencing: + return "CONFERENCING"; + case Refused: + case Error: + default: + return "FAILURE"; } } -const std::string& +std::string Call::getLocalIp() { - ost::MutexLock m (_callMutex); - return _localIPAddress; + ost::MutexLock m(callMutex_); + return localIPAddress_; } unsigned int Call::getLocalAudioPort() { - ost::MutexLock m (_callMutex); - return _localAudioPort; + ost::MutexLock m(callMutex_); + return localAudioPort_; } bool @@ -134,13 +143,13 @@ Call::setRecording() std::string process_id = Recordable::recorder.getRecorderID(); if (!recordStatus) { - mbuffer->bindHalfDuplexOut (process_id, _id); - mbuffer->bindHalfDuplexOut (process_id); + mbuffer->bindHalfDuplexOut(process_id, id_); + mbuffer->bindHalfDuplexOut(process_id); Recordable::recorder.start(); } else { - mbuffer->unBindHalfDuplexOut (process_id, _id); - mbuffer->unBindHalfDuplexOut (process_id); + mbuffer->unBindHalfDuplexOut(process_id, id_); + mbuffer->unBindHalfDuplexOut(process_id); } Manager::instance().getMainBuffer()->stateInfo(); diff --git a/daemon/src/call.h b/daemon/src/call.h index 5993fad4ab585ffee5f7e5c78ba8024cf262b050..fcb5bba7341812870785af5b04c3127a71db8d81 100644 --- a/daemon/src/call.h +++ b/daemon/src/call.h @@ -37,18 +37,12 @@ #include "audio/recordable.h" -#define SIP_SCHEME "sip:" -#define SIPS_SCHEME "sips:" - -#define CallConfigNULL 0 - /* * @file call.h * @brief A call is the base class for protocol-based calls */ -class Call: public Recordable -{ +class Call : public Recordable { public: static const char * const DEFAULT_ID; @@ -83,7 +77,7 @@ class Call: public Recordable * @param id Unique identifier of the call * @param type set definitely this call as incoming/outgoing */ - Call (const std::string& id, Call::CallType type); + Call(const std::string& id, Call::CallType type); virtual ~Call(); /** @@ -91,7 +85,7 @@ class Call: public Recordable * @return call id */ std::string getCallId() const { - return _id; + return id_; } /** @@ -99,15 +93,15 @@ class Call: public Recordable * @return call id */ std::string getConfId() const { - return _confID; + return confID_; } - void setConfId (const std::string &id) { - _confID = id; + void setConfId(const std::string &id) { + confID_ = id; } - CallType getCallType (void) const { - return _type; + CallType getCallType() const { + return type_; } /** @@ -115,8 +109,8 @@ class Call: public Recordable * not protected by mutex (when created) * @param number peer number */ - void setPeerNumber (const std::string& number) { - _peerNumber = number; + void setPeerNumber(const std::string& number) { + peerNumber_ = number; } /** @@ -124,8 +118,8 @@ class Call: public Recordable * not protected by mutex (when created) * @return std::string The peer number */ - const std::string& getPeerNumber() const { - return _peerNumber; + std::string getPeerNumber() const { + return peerNumber_; } /** @@ -133,8 +127,8 @@ class Call: public Recordable * not protected by mutex (when created) * @param name The peer name */ - void setPeerName (const std::string& name) { - _peerName = name; + void setPeerName(const std::string& name) { + peerName_ = name; } /** @@ -142,8 +136,8 @@ class Call: public Recordable * not protected by mutex (when created) * @return std::string The peer name */ - const std::string& getPeerName() const { - return _peerName; + std::string getPeerName() const { + return peerName_; } /** @@ -151,8 +145,8 @@ class Call: public Recordable * not protected by mutex (when created) * @return std::string The peer display name */ - void setDisplayName (const std::string& name) { - _displayName = name; + void setDisplayName(const std::string& name) { + displayName_ = name; } /** @@ -161,7 +155,7 @@ class Call: public Recordable * @return std::string The peer name */ const std::string& getDisplayName() const { - return _displayName; + return displayName_; } /** @@ -170,14 +164,14 @@ class Call: public Recordable * false otherwise */ bool isIncoming() { - return _type == Incoming; + return type_ == Incoming; } /** * Set the connection state of the call (protected by mutex) * @param state The connection state */ - void setConnectionState (ConnectionState state); + void setConnectionState(ConnectionState state); /** * Get the connection state of the call (protected by mutex) @@ -189,7 +183,7 @@ class Call: public Recordable * Set the state of the call (protected by mutex) * @param state The call state */ - void setState (CallState state); + void setState(CallState state); /** * Get the call state of the call (protected by mutex) @@ -197,37 +191,37 @@ class Call: public Recordable */ CallState getState(); - std::string getStateStr (); + std::string getStateStr(); - void setCallConfiguration (Call::CallConfiguration callConfig) { - _callConfig = callConfig; + void setCallConfiguration(Call::CallConfiguration callConfig) { + callConfig_ = callConfig; } - Call::CallConfiguration getCallConfiguration (void) const { - return _callConfig; + Call::CallConfiguration getCallConfiguration() const { + return callConfig_; } /** * Set my IP [not protected] * @param ip The local IP address */ - void setLocalIp (const std::string& ip) { - _localIPAddress = ip; + void setLocalIp(const std::string& ip) { + localIPAddress_ = ip; } /** * Set local audio port, as seen by me [not protected] * @param port The local audio port */ - void setLocalAudioPort (unsigned int port) { - _localAudioPort = port; + void setLocalAudioPort(unsigned int port) { + localAudioPort_ = port; } /** * Return my IP [mutex protected] * @return std::string The local IP */ - const std::string& getLocalIp(); + std::string getLocalIp(); /** * Return port used locally (for my machine) [mutex protected] @@ -235,57 +229,54 @@ class Call: public Recordable */ unsigned int getLocalAudioPort(); - std::string getRecFileId (void) const { + std::string getRecFileId() const { return getPeerName(); } - std::string getFileName (void) const { - return _peerNumber; + std::string getFileName() const { + return peerNumber_; } - virtual bool setRecording (void); + virtual bool setRecording(); private: /** Protect every attribute that can be changed by two threads */ - ost::Mutex _callMutex; + ost::Mutex callMutex_; // Informations about call socket / audio /** My IP address */ - std::string _localIPAddress; + std::string localIPAddress_; /** Local audio port, as seen by me. */ - unsigned int _localAudioPort; + unsigned int localAudioPort_; /** Unique ID of the call */ - std::string _id; + std::string id_; /** Unique conference ID, used exclusively in case of a conferece */ - std::string _confID; + std::string confID_; /** Type of the call */ - CallType _type; + CallType type_; /** Disconnected/Progressing/Trying/Ringing/Connected */ - ConnectionState _connectionState; + ConnectionState connectionState_; /** Inactive/Active/Hold/Busy/Refused/Error */ - CallState _callState; + CallState callState_; /** Direct IP-to-IP or classic call */ - CallConfiguration _callConfig; + CallConfiguration callConfig_; /** Name of the peer */ - std::string _peerName; + std::string peerName_; /** Number of the peer */ - std::string _peerNumber; + std::string peerNumber_; /** Display Name */ - std::string _displayName; - - /** File name for his call, should be peer number */ - std::string _filename; + std::string displayName_; }; #endif diff --git a/daemon/src/Codec.h b/daemon/src/codec.h similarity index 98% rename from daemon/src/Codec.h rename to daemon/src/codec.h index 0ddca0dbc361073807040f3c53c79ff0bc3a8404..95817cd371dbc8b225add5ebf73c66189f6378ed 100644 --- a/daemon/src/Codec.h +++ b/daemon/src/codec.h @@ -36,10 +36,8 @@ * Interface for both audio codecs as well as video codecs. */ namespace sfl { -class Codec -{ +class Codec { public: - Codec() {}; virtual ~Codec() {} /** * @return The mimesubtype for this codec. Eg. : "video" diff --git a/daemon/src/conference.cpp b/daemon/src/conference.cpp index 08e9d551c3d9902aaa45a05a797b9056cf2bf314..fc37157b582898a800a3fff06fccaa70689b1f5d 100644 --- a/daemon/src/conference.cpp +++ b/daemon/src/conference.cpp @@ -37,73 +37,68 @@ #include "audio/mainbuffer.h" Conference::Conference() - : _id (Manager::instance().getNewCallID()) - , _confState (ACTIVE_ATTACHED) + : id_(Manager::instance().getNewCallID()) + , confState_(ACTIVE_ATTACHED) + , participants_() { - Recordable::initRecFileName (_id); + Recordable::initRecFileName(id_); } - -Conference::~Conference() -{ -} - - -int Conference::getState() +int Conference::getState() const { - return _confState; + return confState_; } - -void Conference::setState (ConferenceState state) +void Conference::setState(ConferenceState state) { - _confState = state; + confState_ = state; } - -void Conference::add (std::string participant_id) +void Conference::add(const std::string &participant_id) { - _participants.insert (participant_id); + participants_.insert(participant_id); } - -void Conference::remove (std::string participant_id) +void Conference::remove(const std::string &participant_id) { - _participants.erase (participant_id); + participants_.erase(participant_id); } -void Conference::bindParticipant (std::string participant_id) +void Conference::bindParticipant(const std::string &participant_id) { - ParticipantSet::iterator iter; - for (iter = _participants.begin(); iter != _participants.end(); ++iter) - if (participant_id != *iter) - Manager::instance().getMainBuffer()->bindCallID (participant_id, *iter); + for (ParticipantSet::iterator iter = participants_.begin(); + iter != participants_.end(); ++iter) + if (participant_id != *iter) + Manager::instance().getMainBuffer()->bindCallID(participant_id, *iter); - Manager::instance().getMainBuffer()->bindCallID (participant_id); + Manager::instance().getMainBuffer()->bindCallID(participant_id); } - -std::string Conference::getStateStr() +std::string Conference::getStateStr() const { - switch (_confState) { - case ACTIVE_ATTACHED: return "ACTIVE_ATACHED"; - case ACTIVE_DETACHED: return "ACTIVE_DETACHED"; - case ACTIVE_ATTACHED_REC: return "ACTIVE_ATTACHED_REC"; - case ACTIVE_DETACHED_REC: return "ACTIVE_DETACHED_REC"; - case HOLD: return "HOLD"; - case HOLD_REC: return "HOLD_REC"; - default: return ""; + switch (confState_) { + case ACTIVE_ATTACHED: + return "ACTIVE_ATTACHED"; + case ACTIVE_DETACHED: + return "ACTIVE_DETACHED"; + case ACTIVE_ATTACHED_REC: + return "ACTIVE_ATTACHED_REC"; + case ACTIVE_DETACHED_REC: + return "ACTIVE_DETACHED_REC"; + case HOLD: + return "HOLD"; + case HOLD_REC: + return "HOLD_REC"; + default: + return ""; } } - -const ParticipantSet &Conference::getParticipantList() +ParticipantSet Conference::getParticipantList() const { - return _participants; + return participants_; } - - bool Conference::setRecording() { bool recordStatus = Recordable::recAudio.isRecording(); @@ -111,24 +106,31 @@ bool Conference::setRecording() Recordable::recAudio.setRecording(); MainBuffer *mbuffer = Manager::instance().getMainBuffer(); - ParticipantSet::iterator iter; - std::string process_id = Recordable::recorder.getRecorderID(); + std::string process_id(Recordable::recorder.getRecorderID()); // start recording if (!recordStatus) { - for (iter = _participants.begin(); iter != _participants.end(); ++iter) - mbuffer->bindHalfDuplexOut (process_id, *iter); + for (ParticipantSet::const_iterator iter = participants_.begin(); iter != participants_.end(); ++iter) + mbuffer->bindHalfDuplexOut(process_id, *iter); - mbuffer->bindHalfDuplexOut (process_id); + mbuffer->bindHalfDuplexOut(process_id); Recordable::recorder.start(); } else { - for (iter = _participants.begin(); iter != _participants.end(); ++iter) - mbuffer->unBindHalfDuplexOut (process_id, *iter); + for (ParticipantSet::const_iterator iter = participants_.begin(); iter != participants_.end(); ++iter) + mbuffer->unBindHalfDuplexOut(process_id, *iter); - mbuffer->unBindHalfDuplexOut (process_id); + mbuffer->unBindHalfDuplexOut(process_id); } return recordStatus; +} + +std::string Conference::getRecFileId() const { + return getConfID(); +} +std::string Conference::getConfID() const { + return id_; } + diff --git a/daemon/src/conference.h b/daemon/src/conference.h index 6a4fcce44bf327e9813d311cd4cfb3177d937655..4ce74de722d1363ceae5e4d3ae1a9935d57788ba 100644 --- a/daemon/src/conference.h +++ b/daemon/src/conference.h @@ -34,18 +34,11 @@ #include <string> #include "audio/recordable.h" -#include "call.h" - -// class ManagerImpl; -// class Call; typedef std::set<std::string> ParticipantSet; -class Conference: public Recordable -{ - +class Conference : public Recordable { public: - enum ConferenceState {ACTIVE_ATTACHED, ACTIVE_DETACHED, ACTIVE_ATTACHED_REC, ACTIVE_DETACHED_REC, HOLD, HOLD_REC}; /** @@ -53,87 +46,59 @@ class Conference: public Recordable */ Conference(); - /** - * Destructor - */ - ~Conference(); - /** * Return the conference id */ - std::string getConfID() const { - return _id; - } + std::string getConfID() const; /** * Return the current conference state */ - int getState(); + int getState() const; /** * Set conference state */ - void setState (ConferenceState state); + void setState(ConferenceState state); /** * Return a string description of the conference state */ - std::string getStateStr(); + std::string getStateStr() const; /** * Add a new participant to the conference */ - void add (std::string participant_id); + void add(const std::string &participant_id); /** * Remove a participant from the conference */ - void remove (std::string participant_id); + void remove(const std::string &participant_id); /** * Bind a participant to the conference */ - void bindParticipant (std::string participant_id); + void bindParticipant(const std::string &participant_id); /** * Get the participant list for this conference */ - const ParticipantSet &getParticipantList(); + ParticipantSet getParticipantList() const; /** * Get recording file ID */ - std::string getRecFileId() const { - return getConfID(); - } + std::string getRecFileId() const; /** * Start/stop recording toggle */ virtual bool setRecording(); - private: - - /** - * Unique ID of the conference - */ - std::string _id; - - /** - * Conference state - */ - ConferenceState _confState; - - /** - * List of participant ids - */ - ParticipantSet _participants; - - /** - * Number of participant - */ - int _nbParticipant; - + std::string id_; + ConferenceState confState_; + ParticipantSet participants_; }; #endif diff --git a/daemon/src/config/Makefile.am b/daemon/src/config/Makefile.am old mode 100755 new mode 100644 diff --git a/daemon/src/config/config.cpp b/daemon/src/config/config.cpp index b05c092c5e207c87097536445a1caa7a9eb027d1..bd3818d857eb3b499585cd96b9de8d19cb3ca02b 100644 --- a/daemon/src/config/config.cpp +++ b/daemon/src/config/config.cpp @@ -40,43 +40,34 @@ #include <string.h> #include "yamlparser.h" -namespace Conf -{ +namespace Conf { -// ctor -ConfigTree::ConfigTree() :_sections() -{ -} - -// dtor ConfigTree::~ConfigTree() { - // erase every new ItemMap (by CreateSection) - SectionMap::iterator iter = _sections.begin(); + SectionMap::iterator iter = sections_.begin(); - while (iter != _sections.end()) { + while (iter != sections_.end()) { delete iter->second; iter->second = NULL; iter++; } } -void ConfigTree::addDefaultValue (const std::pair<std::string, std::string>& token, std::string section) +void ConfigTree::addDefaultValue(const std::pair<std::string, std::string>& token, std::string section) { - _defaultValueMap.insert (token); + defaultValueMap_.insert(token); - if (section.empty() == false) { - addConfigTreeItem (section, ConfigTreeItem (token.first, token.second, token.second, "string")); - } + if (not section.empty()) + addConfigTreeItem(section, ConfigTreeItem(token.first, token.second, token.second, "string")); } -std::string ConfigTree::getDefaultValue (const std::string& key) const +std::string ConfigTree::getDefaultValue(const std::string& key) const { std::map<std::string, std::string>::const_iterator it; - it = _defaultValueMap.find (key); + it = defaultValueMap_.find(key); - if (it == _defaultValueMap.end()) + if (it == defaultValueMap_.end()) return ""; return it->second; @@ -86,26 +77,24 @@ std::string ConfigTree::getDefaultValue (const std::string& key) const * Create the section only if it doesn't exists */ void -ConfigTree::createSection (const std::string& section) +ConfigTree::createSection(const std::string& section) { // if we doesn't find the item, create it - if (_sections.find (section) == _sections.end()) { - _sections[section] = new ItemMap; - } + if (sections_.find(section) == sections_.end()) + sections_[section] = new ItemMap; } /** * Remove the section only if it exists */ void -ConfigTree::removeSection (const std::string& section) +ConfigTree::removeSection(const std::string& section) { // if we doesn't find the item, create it - SectionMap::iterator iter = _sections.find (section); + SectionMap::iterator iter = sections_.find(section); - if (iter != _sections.end()) { - _sections.erase (iter); - } + if (iter != sections_.end()) + sections_.erase(iter); } /** Retrieve the sections as an array */ @@ -114,11 +103,11 @@ ConfigTree::getSections() { TokenList sections; - SectionMap::iterator iter = _sections.begin(); + SectionMap::iterator iter = sections_.begin(); - while (iter != _sections.end()) { + while (iter != sections_.end()) { // add to token list the: iter->second; - sections.push_back (iter->first); + sections.push_back(iter->first); iter++; } @@ -130,51 +119,51 @@ ConfigTree::getSections() * If the section doesn't exists, create it */ void -ConfigTree::addConfigTreeItem (const std::string& section, const ConfigTreeItem item) +ConfigTree::addConfigTreeItem(const std::string& section, const ConfigTreeItem item) { // if we doesn't find the item, create it - SectionMap::iterator iter = _sections.find (section); + SectionMap::iterator iter = sections_.find(section); - if (iter == _sections.end()) { - _sections[section] = new ItemMap; - iter = _sections.find (section); + if (iter == sections_.end()) { + sections_[section] = new ItemMap; + iter = sections_.find(section); } // be prudent here - if (iter != _sections.end()) { - std::string name = item.getName(); + if (iter != sections_.end()) { + std::string name(item.getName()); - if (iter->second->find (name) == iter->second->end()) { - (* (iter->second)) [name] = item; + if (iter->second->find(name) == iter->second->end()) { + (*(iter->second))[name] = item; } } } std::string -ConfigTree::getConfigTreeItemValue (const std::string& section, const std::string& itemName) const +ConfigTree::getConfigTreeItemValue(const std::string& section, const std::string& itemName) const { - const ConfigTreeItem* item = getConfigTreeItem (section, itemName); + const ConfigTreeItem* item = getConfigTreeItem(section, itemName); if (item) return item->getValue(); - return getDefaultValue (itemName); + return getDefaultValue(itemName); } // throw a ConfigTreeItemException if not found int -ConfigTree::getConfigTreeItemIntValue (const std::string& section, const std::string& itemName) const +ConfigTree::getConfigTreeItemIntValue(const std::string& section, const std::string& itemName) const { - std::string configItem = getConfigTreeItemValue (section, itemName); - int retval = atoi (configItem.data()); + std::string configItem = getConfigTreeItemValue(section, itemName); + int retval = atoi(configItem.data()); return retval; } bool -ConfigTree::getConfigTreeItemBoolValue (const std::string& section, const std::string& itemName) const +ConfigTree::getConfigTreeItemBoolValue(const std::string& section, const std::string& itemName) const { - std::string configItem = getConfigTreeItemValue (section, itemName); + std::string configItem = getConfigTreeItemValue(section, itemName); if (configItem == "true") { return true; @@ -184,17 +173,17 @@ ConfigTree::getConfigTreeItemBoolValue (const std::string& section, const std::s } bool -ConfigTree::getConfigTreeItemToken (const std::string& section, const std::string& itemName, TokenList& arg) const +ConfigTree::getConfigTreeItemToken(const std::string& section, const std::string& itemName, TokenList& arg) const { - const ConfigTreeItem *item = getConfigTreeItem (section, itemName); + const ConfigTreeItem *item = getConfigTreeItem(section, itemName); if (item) { arg.clear(); - arg.push_back (section); - arg.push_back (itemName); - arg.push_back (item->getType()); - arg.push_back (item->getValue()); - arg.push_back (item->getDefaultValue()); + arg.push_back(section); + arg.push_back(itemName); + arg.push_back(item->getType()); + arg.push_back(item->getValue()); + arg.push_back(item->getDefaultValue()); return true; } @@ -205,14 +194,14 @@ ConfigTree::getConfigTreeItemToken (const std::string& section, const std::strin * Return a ConfigTreeItem or NULL if not found */ const ConfigTreeItem* -ConfigTree::getConfigTreeItem (const std::string& section, const std::string& itemName) const +ConfigTree::getConfigTreeItem(const std::string& section, const std::string& itemName) const { - SectionMap::const_iterator iter = _sections.find (section); + SectionMap::const_iterator iter = sections_.find(section); - if (iter == _sections.end()) + if (iter == sections_.end()) return NULL; - ItemMap::const_iterator iterItem = iter->second->find (itemName); + ItemMap::const_iterator iterItem = iter->second->find(itemName); if (iterItem == iter->second->end()) return NULL; @@ -227,36 +216,36 @@ ConfigTree::getConfigTreeItem (const std::string& section, const std::string& it * The true/false logic is useless here. */ bool -ConfigTree::setConfigTreeItem (const std::string& section, - const std::string& itemName, - const std::string& value) +ConfigTree::setConfigTreeItem(const std::string& section, + const std::string& itemName, + const std::string& value) { - SectionMap::iterator iter = _sections.find (section); + SectionMap::iterator iter = sections_.find(section); - if (iter == _sections.end()) { + if (iter == sections_.end()) { // Not found, create section - _sections[section] = new ItemMap; - iter = _sections.find (section); + sections_[section] = new ItemMap; + iter = sections_.find(section); } - ItemMap::iterator iterItem = iter->second->find (itemName); + ItemMap::iterator iterItem = iter->second->find(itemName); if (iterItem == iter->second->end()) { // If not found, search in our default list to find // something that would fit. - std::string defaultValue = getDefaultValue (itemName); - addConfigTreeItem (section, ConfigTreeItem (itemName, value, defaultValue)); + std::string defaultValue = getDefaultValue(itemName); + addConfigTreeItem(section, ConfigTreeItem(itemName, value, defaultValue)); return true; } // Use default value if the value is empty. if (value.empty() == true) { - iterItem->second.setValue (getDefaultValue (itemName)); + iterItem->second.setValue(getDefaultValue(itemName)); return true; } - iterItem->second.setValue (value); + iterItem->second.setValue(value); return true; } @@ -265,27 +254,26 @@ ConfigTree::setConfigTreeItem (const std::string& section, // return false if empty, no config, or enable to open // return true if everything is ok bool -ConfigTree::saveConfigTree (const std::string& fileName) +ConfigTree::saveConfigTree(const std::string& fileName) { - _debug ("ConfigTree: Save %s", fileName.c_str()); + DEBUG("ConfigTree: Save %s", fileName.c_str()); - if (fileName.empty() && _sections.begin() == _sections.end()) { + if (fileName.empty() and sections_.begin() == sections_.end()) return false; - } std::fstream file; - file.open (fileName.data(), std::fstream::out); + file.open(fileName.data(), std::fstream::out); if (!file.is_open()) { - _error ("ConfigTree: Error: Could not open %s configuration file", fileName.c_str()); + ERROR("ConfigTree: Error: Could not open %s configuration file", fileName.c_str()); return false; } // for each section, for each item... - SectionMap::iterator iter = _sections.begin(); + SectionMap::iterator iter = sections_.begin(); - while (iter != _sections.end()) { + while (iter != sections_.end()) { file << "[" << iter->first << "]" << std::endl; ItemMap::iterator iterItem = iter->second->begin(); @@ -301,9 +289,8 @@ ConfigTree::saveConfigTree (const std::string& fileName) file.close(); - if (chmod (fileName.c_str(), S_IRUSR | S_IWUSR)) { - _error ("ConfigTree: Error: Failed to set permission on configuration: %m"); - } + if (chmod(fileName.c_str(), S_IRUSR | S_IWUSR)) + ERROR("ConfigTree: Error: Failed to set permission on configuration: %m"); return true; } @@ -313,24 +300,22 @@ ConfigTree::saveConfigTree (const std::string& fileName) // 1 = OK // 2 = unable to open int -ConfigTree::populateFromFile (const std::string& fileName) +ConfigTree::populateFromFile(const std::string& fileName) { - _debug ("ConfigTree: Populate from file %s", fileName.c_str()); + DEBUG("ConfigTree: Populate from file %s", fileName.c_str()); - if (fileName.empty()) { + if (fileName.empty()) return 0; - } std::fstream file; - file.open (fileName.data(), std::fstream::in); + file.open(fileName.data(), std::fstream::in); if (!file.is_open()) { - file.open (fileName.data(), std::fstream::out); + file.open(fileName.data(), std::fstream::out); - if (!file.is_open()) { + if (!file.is_open()) return 0; - } file.close(); @@ -338,11 +323,11 @@ ConfigTree::populateFromFile (const std::string& fileName) } // get length of file: - file.seekg (0, std::ios::end); + file.seekg(0, std::ios::end); int length = file.tellg(); - file.seekg (0, std::ios::beg); + file.seekg(0, std::ios::beg); if (length == 0) { file.close(); @@ -351,49 +336,37 @@ ConfigTree::populateFromFile (const std::string& fileName) std::string line; - std::string section (""); - std::string key (""); - std::string val (""); + std::string section(""); + std::string key(""); + std::string val(""); std::string::size_type pos; while (!file.eof()) { // Read the file line by line - std::getline (file, line); + std::getline(file, line); if (!line.empty()) { if (line[0] == '[') { // If the line is a section - pos = line.find (']'); - section = line.substr (1, pos - 1); + pos = line.find(']'); + section = line.substr(1, pos - 1); } else if (line[0] != '#') { // If the line is "key=value" and doesn't begin with '#'(comments) - pos = line.find ('='); - key = line.substr (0, pos); - val = line.substr (pos + 1, line.length() - pos); - - if (key.length() > 0 && val.length() > 0) { - setConfigTreeItem (section, key, val); - } - - /* - if (key.length() > 0) { + pos = line.find('='); + key = line.substr(0, pos); + val = line.substr(pos + 1, line.length() - pos); - if(val.length() > 0) - setConfigTreeItem (section, key, val); - else - setConfigTreeItem (section, key, ""); - } - */ + if (key.length() > 0 && val.length() > 0) + setConfigTreeItem(section, key, val); } } } file.close(); - if (chmod (fileName.c_str(), S_IRUSR | S_IWUSR)) { - _debug ("Failed to set permission on configuration file because: %m"); - } + if (chmod(fileName.c_str(), S_IRUSR | S_IWUSR)) + DEBUG("Failed to set permission on configuration file because: %m"); return 1; } @@ -402,17 +375,17 @@ TokenList ConfigTreeIterator::begin() { TokenList tk; - _iter = _tree->_sections.begin(); + iter_ = tree_->sections_.begin(); - if (_iter!=_tree->_sections.end()) { - _iterItem = _iter->second->begin(); + if (iter_!=tree_->sections_.end()) { + iterItem_ = iter_->second->begin(); - if (_iterItem!=_iter->second->end()) { - tk.push_back (_iter->first); - tk.push_back (_iterItem->first); - tk.push_back (_iterItem->second.getType()); - tk.push_back (_iterItem->second.getValue()); - tk.push_back (_iterItem->second.getDefaultValue()); + if (iterItem_!=iter_->second->end()) { + tk.push_back(iter_->first); + tk.push_back(iterItem_->first); + tk.push_back(iterItem_->second.getType()); + tk.push_back(iterItem_->second.getValue()); + tk.push_back(iterItem_->second.getDefaultValue()); } } @@ -425,39 +398,36 @@ ConfigTreeIterator::next() TokenList tk; // we return tk empty if we are at the end of the list... - if (_iter==_tree->_sections.end()) { + if (iter_ == tree_->sections_.end()) return tk; - } - if (_iterItem!=_iter->second->end()) { - _iterItem++; - } + if (iterItem_ != iter_->second->end()) + iterItem_++; - if (_iterItem==_iter->second->end()) { + if (iterItem_ == iter_->second->end()) { // if we increment, and we are at the end of a section - _iter++; + iter_++; - if (_iter!=_tree->_sections.end()) { - _iterItem = _iter->second->begin(); + if (iter_ != tree_->sections_.end()) { + iterItem_ = iter_->second->begin(); - if (_iterItem!=_iter->second->end()) { - tk.push_back (_iter->first); - tk.push_back (_iterItem->first); - tk.push_back (_iterItem->second.getType()); - tk.push_back (_iterItem->second.getValue()); - tk.push_back (_iterItem->second.getDefaultValue()); + if (iterItem_ != iter_->second->end()) { + tk.push_back(iter_->first); + tk.push_back(iterItem_->first); + tk.push_back(iterItem_->second.getType()); + tk.push_back(iterItem_->second.getValue()); + tk.push_back(iterItem_->second.getDefaultValue()); } } } else { - tk.push_back (_iter->first); - tk.push_back (_iterItem->first); - tk.push_back (_iterItem->second.getType()); - tk.push_back (_iterItem->second.getValue()); - tk.push_back (_iterItem->second.getDefaultValue()); + tk.push_back(iter_->first); + tk.push_back(iterItem_->first); + tk.push_back(iterItem_->second.getType()); + tk.push_back(iterItem_->second.getValue()); + tk.push_back(iterItem_->second.getDefaultValue()); } return tk; } } // end namespace ConfigTree - diff --git a/daemon/src/config/config.h b/daemon/src/config/config.h index 0e364fa8386593c6cee3bb289744c763b7b66b8a..b91dd819c154dbce27251e7c5a10fc7a895d3be1 100644 --- a/daemon/src/config/config.h +++ b/daemon/src/config/config.h @@ -29,20 +29,20 @@ * as that of the covered work. */ -#ifndef __CONFIG_CONFIG_H_ -#define __CONFIG_CONFIG_H_ +#ifndef CONF_CONFIG_H__ +#define CONF_CONFIG_H__ #include <map> #include <string> #include <list> +#include "noncopyable.h" /** * @file config.h * @brief Configuration namespace for ConfigTree object (like .ini files) */ -namespace Conf -{ +namespace Conf { static const char * const TRUE_STR = "true"; class ConfigTreeItem; @@ -50,25 +50,12 @@ typedef std::map<std::string, ConfigTreeItem> ItemMap; typedef std::map<std::string, ItemMap*> SectionMap; typedef std::list<std::string> TokenList; -class ConfigTreeItemException -{ - - public: - /** - * Constructor - * */ - ConfigTreeItemException() {} - - /** - * Destructor - * */ - ~ConfigTreeItemException() {} +class ConfigTreeItemException { }; class ConfigTree; -class ConfigTreeIterator -{ +class ConfigTreeIterator { public: /** @@ -82,7 +69,7 @@ class ConfigTreeIterator * @return TokenList */ const TokenList& end() const { - return _endToken; + return endToken_; } /** @@ -92,24 +79,20 @@ class ConfigTreeIterator TokenList next(); private: - friend class ConfigTree; - ConfigTreeIterator (ConfigTree *configTree) : _tree (configTree), _endToken(), _iter(), _iterItem() {} + ConfigTreeIterator(ConfigTree *configTree) : tree_(configTree), endToken_(), iter_(), iterItem_() {} - ConfigTreeIterator (const Conf::ConfigTreeIterator&); - ConfigTreeIterator& operator= (const Conf::ConfigTreeIterator&); + NON_COPYABLE(ConfigTreeIterator); - ConfigTree* _tree; - TokenList _endToken; - SectionMap::iterator _iter; - ItemMap::iterator _iterItem; + ConfigTree* tree_; + TokenList endToken_; + SectionMap::iterator iter_; + ItemMap::iterator iterItem_; }; -class ConfigTree -{ - +class ConfigTree { public: - ConfigTree(); + ConfigTree() : sections_(), defaultValueMap_() {} ~ConfigTree(); /** * Add a default value for a given key. @@ -123,10 +106,10 @@ class ConfigTree value for a given key. @param token A default key/value pair. */ - void addDefaultValue (const std::pair<std::string, std::string>& token, std::string section = std::string ("")); + void addDefaultValue(const std::pair<std::string, std::string>& token, std::string section = ""); - void createSection (const std::string& section); - void removeSection (const std::string& section); + void createSection(const std::string& section); + void removeSection(const std::string& section); /** * Return an array of strings, listing the sections of the config file * @@ -137,7 +120,7 @@ class ConfigTree */ TokenList getSections(); - void addConfigTreeItem (const std::string& section, const ConfigTreeItem item); + void addConfigTreeItem(const std::string& section, const ConfigTreeItem item); /** * Set a configuration value. * @@ -145,7 +128,7 @@ class ConfigTree * @param itemName The itemName= in the .ini file * @param value The value to assign to that itemName */ - bool setConfigTreeItem (const std::string& section, const std::string& itemName, const std::string& value); + bool setConfigTreeItem(const std::string& section, const std::string& itemName, const std::string& value); /** * Get a value. @@ -159,85 +142,83 @@ class ConfigTree * @return The value of the corresponding item. The default value if the section exists * but the item doesn't. */ - std::string getConfigTreeItemValue (const std::string& section, const std::string& itemName) const; - int getConfigTreeItemIntValue (const std::string& section, const std::string& itemName) const; - bool getConfigTreeItemBoolValue (const std::string& section, const std::string& itemName) const; + std::string getConfigTreeItemValue(const std::string& section, const std::string& itemName) const; + int getConfigTreeItemIntValue(const std::string& section, const std::string& itemName) const; + bool getConfigTreeItemBoolValue(const std::string& section, const std::string& itemName) const; /** * Flush data to .ini file */ - bool saveConfigTree (const std::string& fileName); + bool saveConfigTree(const std::string& fileName); /** * Load data (and fill ConfigTree) from disk */ - int populateFromFile (const std::string& fileName); + int populateFromFile(const std::string& fileName); - bool getConfigTreeItemToken (const std::string& section, const std::string& itemName, TokenList& arg) const; + bool getConfigTreeItemToken(const std::string& section, const std::string& itemName, TokenList& arg) const; private: - std::string getDefaultValue (const std::string& key) const; - const ConfigTreeItem* getConfigTreeItem (const std::string& section, const std::string& itemName) const; + std::string getDefaultValue(const std::string& key) const; + const ConfigTreeItem* getConfigTreeItem(const std::string& section, const std::string& itemName) const; /** * List of sections. Each sections has an ItemList as child */ - SectionMap _sections; + SectionMap sections_; - std::map<std::string, std::string> _defaultValueMap; + std::map<std::string, std::string> defaultValueMap_; friend class ConfigTreeIterator; + NON_COPYABLE(ConfigTree); public: ConfigTreeIterator createIterator() { - return ConfigTreeIterator (this); + return ConfigTreeIterator(this); } }; -class ConfigTreeItem -{ +class ConfigTreeItem { public: - ConfigTreeItem() : _name (""), _value (""), _defaultValue (""), _type ("string") {} + ConfigTreeItem() : name_(""), value_(""), defaultValue_(""), type_("string") {} // defaultvalue = value - ConfigTreeItem (const std::string& name, const std::string& value, const std::string& type) : - _name (name), _value (value), - _defaultValue (value), _type (type) {} - - ConfigTreeItem (const std::string& name, const std::string& value, const std::string& defaultValue, const std::string& type) : - _name (name), _value (value), - _defaultValue (defaultValue), _type (type) {} + ConfigTreeItem(const std::string& name, const std::string& value, const std::string& type) : + name_(name), value_(value), + defaultValue_(value), type_(type) {} - ~ConfigTreeItem() {} + ConfigTreeItem(const std::string& name, const std::string& value, const std::string& defaultValue, const std::string& type) : + name_(name), value_(value), + defaultValue_(defaultValue), type_(type) {} - void setValue (const std::string& value) { - _value = value; + void setValue(const std::string& value) { + value_ = value; } const std::string getName() const { - return _name; + return name_; } const std::string getValue() const { - return _value; + return value_; } const std::string getDefaultValue() const { - return _defaultValue; + return defaultValue_; } const std::string getType() const { - return _type; + return type_; } private: - std::string _name; - std::string _value; - std::string _defaultValue; - std::string _type; + std::string name_; + std::string value_; + std::string defaultValue_; + std::string type_; }; } // end namespace ConfigTree -#endif +#endif // __CONFIG_CONFIG_H__ diff --git a/daemon/src/config/serializable.h b/daemon/src/config/serializable.h index 4b87b052ea9548b3ab7caaf1a72e4dc9477e4dc4..26684f85f3104adc3ca3cd3de723c848c8fcff4a 100644 --- a/daemon/src/config/serializable.h +++ b/daemon/src/config/serializable.h @@ -36,14 +36,13 @@ #include "yamlemitter.h" #include "yamlnode.h" -class Serializable -{ +class Serializable { public: virtual ~Serializable() {}; - virtual void serialize (Conf::YamlEmitter *emitter) = 0; + virtual void serialize(Conf::YamlEmitter *emitter) = 0; - virtual void unserialize (Conf::MappingNode *map) = 0; + virtual void unserialize(Conf::MappingNode *map) = 0; }; #endif diff --git a/daemon/src/config/yamlemitter.cpp b/daemon/src/config/yamlemitter.cpp index c617338889c64e7596c563b95ddbe9effb225e7a..cc6a93b1c874c7b1c283fe592fce8228f661e15f 100644 --- a/daemon/src/config/yamlemitter.cpp +++ b/daemon/src/config/yamlemitter.cpp @@ -32,10 +32,11 @@ #include <stdio.h> #include "../global.h" -namespace Conf -{ +namespace Conf { -YamlEmitter::YamlEmitter (const char *file) : filename (file), isFirstAccount (true) +YamlEmitter::YamlEmitter(const char *file) : filename_(file), fd_(0), + emitter_(), document_(), topLevelMapping_(0), isFirstAccount_(true), + accountSequence_(0) { open(); } @@ -45,367 +46,289 @@ YamlEmitter::~YamlEmitter() close(); } -void YamlEmitter::open() throw(YamlEmitterException) +void YamlEmitter::open() { - fd = fopen (filename.c_str(), "w"); + fd_ = fopen(filename_.c_str(), "w"); - if (!fd) - throw YamlEmitterException ("Could not open file descriptor"); + if (!fd_) + throw YamlEmitterException("Could not open file descriptor"); - if (!yaml_emitter_initialize (&emitter)) - throw YamlEmitterException ("Could not initialize emitter"); + if (!yaml_emitter_initialize(&emitter_)) + throw YamlEmitterException("Could not initialize emitter"); // Allows unescaped unicode characters - yaml_emitter_set_unicode (&emitter, 1); + yaml_emitter_set_unicode(&emitter_, 1); - yaml_emitter_set_output_file (&emitter, fd); + yaml_emitter_set_output_file(&emitter_, fd_); - if (yaml_document_initialize (&document, NULL, NULL, NULL, 0, 0) == 0) { - throw YamlEmitterException ("Could not initialize yaml document while saving configuration"); - } + if (yaml_document_initialize(&document_, NULL, NULL, NULL, 0, 0) == 0) + throw YamlEmitterException("Could not initialize yaml document while saving configuration"); // Init the main configuration mapping - if ( (topLevelMapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) { - throw YamlEmitterException ("Could not create top level mapping"); - } + if ((topLevelMapping_ = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException("Could not create top level mapping"); } -void YamlEmitter::close() throw(YamlEmitterException) +void YamlEmitter::close() { - yaml_emitter_delete (&emitter); + yaml_emitter_delete(&emitter_); - if (!fd) - throw YamlEmitterException ("File descriptor not valid"); + if (!fd_) + throw YamlEmitterException("File descriptor not valid"); - - if (fclose (fd)) - throw YamlEmitterException ("Error closing file descriptor"); + if (fclose(fd_)) + throw YamlEmitterException("Error closing file descriptor"); } -void YamlEmitter::serializeData() throw(YamlEmitterException) +void YamlEmitter::serializeData() { // Document object is destroyed once its content is emitted - if (yaml_emitter_dump (&emitter, &document) == 0) { - throw YamlEmitterException ("Error while emitting configuration yaml document"); - } + if (yaml_emitter_dump(&emitter_, &document_) == 0) + throw YamlEmitterException("Error while emitting configuration yaml document"); } -void YamlEmitter::serializeAccount (MappingNode *map) throw(YamlEmitterException) +void YamlEmitter::serializeAccount(MappingNode *map) { int accountmapping; - if (map->getType() != MAPPING) { - throw YamlEmitterException ("Node type is not a mapping while writing account"); - } + if (map->getType() != MAPPING) + throw YamlEmitterException("Node type is not a mapping while writing account"); - if (isFirstAccount) { - int accountid; - _debug("YamlEmitter: Create account sequence"); + if (isFirstAccount_) { + int accountid; + DEBUG("YamlEmitter: Create account sequence"); - // accountSequence need to be static outside this scope since reused each time an account is written - if ( (accountid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) "accounts", -1, YAML_PLAIN_SCALAR_STYLE)) == 0) { - throw YamlEmitterException ("Could not add preference scalar to document"); - } + // accountSequence_ need to be static outside this scope since reused each time an account is written + if ((accountid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) "accounts", -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException("Could not add preference scalar to document"); - if ( (accountSequence = yaml_document_add_sequence (&document, NULL, YAML_BLOCK_SEQUENCE_STYLE)) == 0) { - throw YamlEmitterException ("Could not add sequence to document"); - } + if ((accountSequence_ = yaml_document_add_sequence(&document_, NULL, YAML_BLOCK_SEQUENCE_STYLE)) == 0) + throw YamlEmitterException("Could not add sequence to document"); - if (yaml_document_append_mapping_pair (&document, topLevelMapping, accountid, accountSequence) == 0) { - throw YamlEmitterException ("Could not add mapping pair to top level mapping"); - } + if (yaml_document_append_mapping_pair(&document_, topLevelMapping_, accountid, accountSequence_) == 0) + throw YamlEmitterException("Could not add mapping pair to top level mapping"); - isFirstAccount = false; + isFirstAccount_ = false; } - if ( (accountmapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) { - throw YamlEmitterException ("Could not add account mapping to document"); - } + if ((accountmapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException("Could not add account mapping to document"); - if (yaml_document_append_sequence_item (&document, accountSequence, accountmapping) == 0) { - throw YamlEmitterException ("Could not append account mapping to sequence"); - } + if (yaml_document_append_sequence_item(&document_, accountSequence_, accountmapping) == 0) + throw YamlEmitterException("Could not append account mapping to sequence"); - try { - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter; - for(iter = internalmap->begin(); iter != internalmap->end(); ++iter) - addMappingItem (accountmapping, iter->first, iter->second); - } - catch(YamlEmitterException &e) { - throw; - } + Mapping *internalmap = map->getMapping(); + for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter) + addMappingItem(accountmapping, iter->first, iter->second); } -void YamlEmitter::serializePreference (MappingNode *map) throw(YamlEmitterException) +void YamlEmitter::serializePreference(MappingNode *map) { - std::string preferencestr ("preferences"); - - int preferenceid, preferencemapping; - if (map->getType() != MAPPING) - throw YamlEmitterException ("Node type is not a mapping while writing preferences"); + throw YamlEmitterException("Node type is not a mapping while writing preferences"); - if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException ("Could not add scalar to document"); + static const char * const PREFERENCE_STR = "preferences"; + int preferenceid; - if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException ("Could not add mapping to document"); + if ((preferenceid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) PREFERENCE_STR, -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException("Could not add scalar to document"); - if (yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping) == 0) - throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); - - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); + int preferencemapping; + if ((preferencemapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException("Could not add mapping to document"); - try { - while (iter != internalmap->end()) { - addMappingItem (preferencemapping, iter->first, iter->second); - iter++; - } - } - catch(YamlEmitterException &e) { - throw; - } + if (yaml_document_append_mapping_pair(&document_, topLevelMapping_, preferenceid, preferencemapping) == 0) + throw YamlEmitterException("Could not add mapping pair to top leve mapping"); + Mapping *internalmap = map->getMapping(); + for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter) + addMappingItem(preferencemapping, iter->first, iter->second); } -void YamlEmitter::serializeVoipPreference (MappingNode *map) throw(YamlEmitterException) +void YamlEmitter::serializeVoipPreference(MappingNode *map) { - std::string preferencestr ("voipPreferences"); - - int preferenceid, preferencemapping; - if (map->getType() != MAPPING) - throw YamlEmitterException ("Node type is not a mapping while writing preferences"); + throw YamlEmitterException("Node type is not a mapping while writing preferences"); + - if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException ("Could not add scalar to document"); + static const char *const PREFERENCE_STR = "voipPreferences"; + int preferenceid; + if ((preferenceid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) PREFERENCE_STR, -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException("Could not add scalar to document"); - if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException ("Could not add mapping to document"); + int preferencemapping; + if ((preferencemapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException("Could not add mapping to document"); - if (yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping) == 0) - throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); + if (yaml_document_append_mapping_pair(&document_, topLevelMapping_, preferenceid, preferencemapping) == 0) + throw YamlEmitterException("Could not add mapping pair to top leve mapping"); Mapping *internalmap = map->getMapping(); Mapping::iterator iter = internalmap->begin(); - try { - while (iter != internalmap->end()) { - addMappingItem (preferencemapping, iter->first, iter->second); - iter++; - } + while (iter != internalmap->end()) { + addMappingItem(preferencemapping, iter->first, iter->second); + iter++; } - catch (YamlEmitterException &e) { - throw; - } - } -void YamlEmitter::serializeAddressbookPreference (MappingNode *map) throw(YamlEmitterException) +void YamlEmitter::serializeAddressbookPreference(MappingNode *map) { - std::string preferencestr ("addressbook"); - - int preferenceid, preferencemapping; - if (map->getType() != MAPPING) - throw YamlEmitterException ("Node type is not a mapping while writing preferences"); - - if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException ("Could not add scalar to document"); + throw YamlEmitterException("Node type is not a mapping while writing preferences"); - if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException ("Could not add mapping to document"); + static const char * const PREFERENCE_STR = "addressbook"; + int preferenceid; + if ((preferenceid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) PREFERENCE_STR, -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException("Could not add scalar to document"); + int preferencemapping; + if ((preferencemapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException("Could not add mapping to document"); - if (yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping) == 0) - throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); + if (yaml_document_append_mapping_pair(&document_, topLevelMapping_, preferenceid, preferencemapping) == 0) + throw YamlEmitterException("Could not add mapping pair to top leve mapping"); Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); - - try { - while (iter != internalmap->end()) { - addMappingItem (preferencemapping, iter->first, iter->second); - iter++; - } - } - catch(YamlEmitterException &e) { - throw; - } + for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter) + addMappingItem(preferencemapping, iter->first, iter->second); } -void YamlEmitter::serializeHooksPreference (MappingNode *map) throw(YamlEmitterException) +void YamlEmitter::serializeHooksPreference(MappingNode *map) { - std::string preferencestr ("hooks"); - - int preferenceid, preferencemapping; - if (map->getType() != MAPPING) - throw YamlEmitterException ("Node type is not a mapping while writing preferences"); + throw YamlEmitterException("Node type is not a mapping while writing preferences"); - if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException ("Could not add scalar to document"); + static const char * const PREFERENCE_STR = "hooks"; + int preferenceid; + if ((preferenceid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) PREFERENCE_STR, -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException("Could not add scalar to document"); - if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException ("Could not add mapping to document"); + int preferencemapping; + if ((preferencemapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException("Could not add mapping to document"); - if (yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping) == 0) - throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); + if (yaml_document_append_mapping_pair(&document_, topLevelMapping_, preferenceid, preferencemapping) == 0) + throw YamlEmitterException("Could not add mapping pair to top leve mapping"); Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); - - try { - while (iter != internalmap->end()) { - addMappingItem (preferencemapping, iter->first, iter->second); - iter++; - } - } - catch(YamlEmitterException &e) { - throw; - } + for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter) + addMappingItem(preferencemapping, iter->first, iter->second); } -void YamlEmitter::serializeAudioPreference (MappingNode *map) throw(YamlEmitterException) +void YamlEmitter::serializeAudioPreference(MappingNode *map) { - std::string preferencestr ("audio"); + static const char *const PREFERENCE_STR = "audio"; int preferenceid, preferencemapping; if (map->getType() != MAPPING) - throw YamlEmitterException ("Node type is not a mapping while writing preferences"); + throw YamlEmitterException("Node type is not a mapping while writing preferences"); - if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException ("Could not add scalar to document"); + if ((preferenceid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) PREFERENCE_STR, -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException("Could not add scalar to document"); - if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException ("Could not add mapping to document"); + if ((preferencemapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException("Could not add mapping to document"); - if (yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping) == 0) - throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); + if (yaml_document_append_mapping_pair(&document_, topLevelMapping_, preferenceid, preferencemapping) == 0) + throw YamlEmitterException("Could not add mapping pair to top leve mapping"); Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); - - try { - while (iter != internalmap->end()) { - addMappingItem (preferencemapping, iter->first, iter->second); - iter++; - } - } - catch(YamlEmitterException &e) { - throw; - } - + for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter) + addMappingItem(preferencemapping, iter->first, iter->second); } -void YamlEmitter::serializeShortcutPreference (MappingNode *map) throw(YamlEmitterException) +void YamlEmitter::serializeShortcutPreference(MappingNode *map) { - std::string preferencestr ("shortcuts"); - - int preferenceid, preferencemapping; - if (map->getType() != MAPPING) - throw YamlEmitterException ("Node type is not a mapping while writing preferences"); + throw YamlEmitterException("Node type is not a mapping while writing preferences"); - if ( (preferenceid = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) preferencestr.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException ("Could not add scalar to document"); + static const char *const PREFERENCE_STR = "shortcuts"; + int preferenceid; + if ((preferenceid = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) PREFERENCE_STR, -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException("Could not add scalar to document"); - if ( (preferencemapping = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException ("Could not add mapping to document"); + int preferencemapping; + if ((preferencemapping = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException("Could not add mapping to document"); - if (yaml_document_append_mapping_pair (&document, topLevelMapping, preferenceid, preferencemapping) == 0) - throw YamlEmitterException ("Could not add mapping pair to top leve mapping"); + if (yaml_document_append_mapping_pair(&document_, topLevelMapping_, preferenceid, preferencemapping) == 0) + throw YamlEmitterException("Could not add mapping pair to top leve mapping"); Mapping *internalmap = map->getMapping(); - Mapping::iterator iter = internalmap->begin(); - - try { - while (iter != internalmap->end()) { - addMappingItem (preferencemapping, iter->first, iter->second); - iter++; - } - } - catch(YamlEmitterException &e) { - throw; - } + for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter) + addMappingItem(preferencemapping, iter->first, iter->second); } -void YamlEmitter::addMappingItem (int mappingid, std::string key, YamlNode *node) +void YamlEmitter::addMappingItem(int mappingid, std::string key, YamlNode *node) { - int temp1, temp2; - if (node->getType() == SCALAR) { ScalarNode *sclr = (ScalarNode *) node; - if ( (temp1 = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) key.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException ("Could not add scalar to document"); + int temp1; + if ((temp1 = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) key.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException("Could not add scalar to document"); - if ( (temp2 = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) sclr->getValue().c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException ("Could not add scalar to document"); + int temp2; + if ((temp2 = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) sclr->getValue().c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException("Could not add scalar to document"); - if (yaml_document_append_mapping_pair (&document, mappingid, temp1, temp2) == 0) - throw YamlEmitterException ("Could not append mapping pair to mapping"); + if (yaml_document_append_mapping_pair(&document_, mappingid, temp1, temp2) == 0) + throw YamlEmitterException("Could not append mapping pair to mapping"); } else if (node->getType() == MAPPING) { MappingNode *map = (MappingNode *) node; - if ( (temp1 = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) key.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException ("Could not add scalar to document"); + int temp1; + if ((temp1 = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) key.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException("Could not add scalar to document"); - if ( (temp2 = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) - throw YamlEmitterException ("Could not add scalar to document"); + int temp2; + if ((temp2 = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException("Could not add scalar to document"); - if (yaml_document_append_mapping_pair (&document, mappingid, temp1, temp2) == 0) - throw YamlEmitterException ("Could not add mapping pair to mapping"); + if (yaml_document_append_mapping_pair(&document_, mappingid, temp1, temp2) == 0) + throw YamlEmitterException("Could not add mapping pair to mapping"); - try { - Mapping *internalmap = map->getMapping(); - Mapping::iterator iter; + Mapping *internalmap = map->getMapping(); + for (Mapping::iterator iter = internalmap->begin(); iter != internalmap->end(); ++iter) + addMappingItem(temp2, iter->first, iter->second); - for( iter = internalmap->begin(); iter != internalmap->end(); ++iter) - addMappingItem (temp2, iter->first, iter->second); - } - catch(YamlEmitterException) { - throw; - } } else if (node->getType() == SEQUENCE) { - SequenceNode *seqnode = (SequenceNode *)node; - if ( (temp1 = yaml_document_add_scalar (&document, NULL, (yaml_char_t *) key.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) - throw YamlEmitterException ("Could not add scalar to document"); + SequenceNode *seqnode = static_cast<SequenceNode *>(node); - if ( (temp2 = yaml_document_add_sequence (&document, NULL, YAML_BLOCK_SEQUENCE_STYLE)) == 0) - throw YamlEmitterException ("Could not add scalar to document"); + int temp1; + if ((temp1 = yaml_document_add_scalar(&document_, NULL, (yaml_char_t *) key.c_str(), -1, YAML_PLAIN_SCALAR_STYLE)) == 0) + throw YamlEmitterException("Could not add scalar to document"); - if (yaml_document_append_mapping_pair (&document, mappingid, temp1, temp2) == 0) - throw YamlEmitterException ("Could not append mapping pair to mapping"); + int temp2; + if ((temp2 = yaml_document_add_sequence(&document_, NULL, YAML_BLOCK_SEQUENCE_STYLE)) == 0) + throw YamlEmitterException("Could not add scalar to document"); + + if (yaml_document_append_mapping_pair(&document_, mappingid, temp1, temp2) == 0) + throw YamlEmitterException("Could not append mapping pair to mapping"); Sequence *seq = seqnode->getSequence(); - Sequence::const_iterator it; - for (it = seq->begin(); it != seq->end(); ++it) { - YamlNode *node = *it; - int id; - if ( (id = yaml_document_add_mapping (&document, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) { - throw YamlEmitterException ("Could not add account mapping to document"); - } - - if (yaml_document_append_sequence_item (&document, temp2, id) == 0) { - throw YamlEmitterException ("Could not append account mapping to sequence"); - } - - MappingNode *mapnode = (MappingNode*)node; - Mapping *map = mapnode->getMapping(); - Mapping::iterator mapit; - for (mapit = map->begin(); mapit != map->end() ; ++mapit) - addMappingItem(id, mapit->first, mapit->second); + for (Sequence::const_iterator it = seq->begin(); it != seq->end(); ++it) { + YamlNode *yamlNode = *it; + int id; + if ((id = yaml_document_add_mapping(&document_, NULL, YAML_BLOCK_MAPPING_STYLE)) == 0) + throw YamlEmitterException("Could not add account mapping to document"); + + if (yaml_document_append_sequence_item(&document_, temp2, id) == 0) + throw YamlEmitterException("Could not append account mapping to sequence"); + + MappingNode *mapnode = static_cast<MappingNode*>(yamlNode); + Mapping *map = mapnode->getMapping(); + Mapping::iterator mapit; + + for (mapit = map->begin(); mapit != map->end() ; ++mapit) + addMappingItem(id, mapit->first, mapit->second); } - } else { - throw YamlEmitterException ("Unknown node type while adding mapping node"); - } + } else + throw YamlEmitterException("Unknown node type while adding mapping node"); } - } diff --git a/daemon/src/config/yamlemitter.h b/daemon/src/config/yamlemitter.h index c60e6fc8a45caceb496d603cb0d245989afbbae8..7cbd4f7ec516333aeebf7cd1a17545eb966e20ad 100644 --- a/daemon/src/config/yamlemitter.h +++ b/daemon/src/config/yamlemitter.h @@ -34,47 +34,44 @@ #include <yaml.h> #include <stdexcept> #include <string> +#include "noncopyable.h" #include "yamlnode.h" -namespace Conf -{ +namespace Conf { #define EMITTER_BUFFERSIZE 65536 #define EMITTER_MAXEVENT 1024 -class YamlEmitterException : public std::runtime_error -{ +class YamlEmitterException : public std::runtime_error { public: - YamlEmitterException (const std::string& str="") : + YamlEmitterException(const std::string& str="") : std::runtime_error("YamlEmitterException occured: " + str) {} }; -class YamlEmitter -{ +class YamlEmitter { public: - YamlEmitter (const char *file); - + YamlEmitter(const char *file); ~YamlEmitter(); - void open() throw(YamlEmitterException); + void open(); - void close() throw(YamlEmitterException); + void close(); - void serializeAccount (MappingNode *map) throw(YamlEmitterException); + void serializeAccount(MappingNode *map); - void serializePreference (MappingNode *map) throw(YamlEmitterException); + void serializePreference(MappingNode *map); - void serializeVoipPreference (MappingNode *map) throw(YamlEmitterException); + void serializeVoipPreference(MappingNode *map); - void serializeAddressbookPreference (MappingNode *map) throw(YamlEmitterException); + void serializeAddressbookPreference(MappingNode *map); - void serializeHooksPreference (MappingNode *map) throw(YamlEmitterException); + void serializeHooksPreference(MappingNode *map); - void serializeAudioPreference (MappingNode *map) throw(YamlEmitterException); + void serializeAudioPreference(MappingNode *map); - void serializeShortcutPreference (MappingNode *map) throw(YamlEmitterException); + void serializeShortcutPreference(MappingNode *map); void writeAudio(); @@ -82,56 +79,51 @@ class YamlEmitter void writeVoiplink(); - void serializeData() throw(YamlEmitterException); + void serializeData(); private: - void addMappingItem (int mappingid, std::string key, YamlNode *node); + NON_COPYABLE(YamlEmitter); + void addMappingItem(int mappingid, std::string key, YamlNode *node); - std::string filename; + std::string filename_; - FILE *fd; + FILE *fd_; /** * The parser structure. */ - yaml_emitter_t emitter; + yaml_emitter_t emitter_; /** * The event structure array. */ - yaml_event_t events[EMITTER_MAXEVENT]; - - /** - * - */ - unsigned char buffer[EMITTER_BUFFERSIZE]; + yaml_event_t events_[EMITTER_MAXEVENT]; + unsigned char buffer_[EMITTER_BUFFERSIZE]; /** * Main document for this serialization */ - yaml_document_t document; + yaml_document_t document_; /** * Reference id to the top levell mapping when creating */ - int topLevelMapping; + int topLevelMapping_; /** * We need to add the account sequence if this is the first account to be */ - bool isFirstAccount; + bool isFirstAccount_; /** * Reference to the account sequence */ - int accountSequence; + int accountSequence_; friend class ConfigurationTest; - }; - } #endif diff --git a/daemon/src/config/yamlnode.cpp b/daemon/src/config/yamlnode.cpp index f310fb445167ee47eb1dc51b05e677ae16872805..5bae6cf3016703496b4eda765826462a29022b2b 100644 --- a/daemon/src/config/yamlnode.cpp +++ b/daemon/src/config/yamlnode.cpp @@ -31,14 +31,13 @@ #include "yamlnode.h" #include "global.h" -namespace Conf -{ +namespace Conf { -void YamlDocument::addNode (YamlNode *node) +void YamlDocument::addNode(YamlNode *node) { Sequence::iterator it = doc.end(); - doc.insert (it, node); + doc.insert(it, node); } YamlNode *YamlDocument::popNode() @@ -56,27 +55,27 @@ void YamlDocument::deleteChildNodes() Sequence::iterator it = doc.begin(); while (it != doc.end()) { - YamlNode *yamlNode = static_cast<YamlNode *> (*it); + YamlNode *yamlNode = static_cast<YamlNode *>(*it); switch (yamlNode->getType()) { case DOCUMENT: break; case SEQUENCE: { - SequenceNode *sequence = static_cast<SequenceNode *> (yamlNode); + SequenceNode *sequence = static_cast<SequenceNode *>(yamlNode); sequence->deleteChildNodes(); delete sequence; sequence = NULL; } break; case MAPPING: { - MappingNode *mapping = static_cast<MappingNode *> (yamlNode); + MappingNode *mapping = static_cast<MappingNode *>(yamlNode); mapping->deleteChildNodes(); delete mapping; mapping = NULL; } break; case SCALAR: { - ScalarNode *scalar = static_cast<ScalarNode *> (yamlNode); + ScalarNode *scalar = static_cast<ScalarNode *>(yamlNode); delete scalar; scalar = NULL; } @@ -89,66 +88,69 @@ void YamlDocument::deleteChildNodes() } } -void MappingNode::addNode (YamlNode *node) +void MappingNode::addNode(YamlNode *node) { Mapping::iterator it = map.end(); - map.insert (it, std::pair<std::string, YamlNode *> (tmpKey, node)); + map.insert(it, std::pair<std::string, YamlNode *> (tmpKey, node)); } -void MappingNode::setKeyValue (const std::string &key, YamlNode *value) +void MappingNode::setKeyValue(const std::string &key, YamlNode *value) { Mapping::iterator it = map.end(); - map.insert (it, std::pair<std::string, YamlNode *> (key, value)); + map.insert(it, std::pair<std::string, YamlNode *> (key, value)); } -void MappingNode::removeKeyValue (const std::string &key) +void MappingNode::removeKeyValue(const std::string &key) { - Mapping::iterator it = map.find (key); - map.erase (it); + Mapping::iterator it = map.find(key); + map.erase(it); } -YamlNode *MappingNode::getValue (const std::string &key) +YamlNode *MappingNode::getValue(const std::string &key) { - Mapping::iterator it = map.find (key); + Mapping::iterator it = map.find(key); if (it != map.end()) { return it->second; } else { - _debug ("MappingNode: Could not find %s", key.c_str()); + DEBUG("MappingNode: Could not find %s", key.c_str()); return NULL; } } -void MappingNode::getValue (const std::string &key, bool *b) +void MappingNode::getValue(const std::string &key, bool *b) { - ScalarNode *node = (ScalarNode*)getValue(key); - if (!node) - return; + ScalarNode *node = (ScalarNode*)getValue(key); + + if (!node) + return; - const std::string &v = node->getValue(); - *b = v == "true"; + const std::string &v = node->getValue(); + *b = v == "true"; } -void MappingNode::getValue (const std::string &key, int *i) +void MappingNode::getValue(const std::string &key, int *i) { - ScalarNode *node = (ScalarNode*)getValue(key); - if (!node) - return; + ScalarNode *node = (ScalarNode*)getValue(key); + + if (!node) + return; - const std::string &v = node->getValue(); - *i = atoi(v.c_str()); + const std::string &v = node->getValue(); + *i = atoi(v.c_str()); } -void MappingNode::getValue (const std::string &key, std::string *v) +void MappingNode::getValue(const std::string &key, std::string *v) { - ScalarNode *node = (ScalarNode*)getValue(key); - if (!node) - return; + ScalarNode *node = (ScalarNode*)getValue(key); - *v = node->getValue(); + if (!node) + return; + + *v = node->getValue(); } @@ -157,7 +159,8 @@ void MappingNode::deleteChildNodes() Mapping::iterator it; for (it = map.begin(); it != map.end(); ++it) { - YamlNode *yamlNode = static_cast<YamlNode *> (it->second); + YamlNode *yamlNode = static_cast<YamlNode *>(it->second); + if (!yamlNode) continue; @@ -165,21 +168,21 @@ void MappingNode::deleteChildNodes() case DOCUMENT: break; case SEQUENCE: { - SequenceNode *sequence = static_cast<SequenceNode *> (yamlNode); + SequenceNode *sequence = static_cast<SequenceNode *>(yamlNode); sequence->deleteChildNodes(); delete sequence; sequence = NULL; } break; case MAPPING: { - MappingNode *mapping = static_cast<MappingNode *> (yamlNode); + MappingNode *mapping = static_cast<MappingNode *>(yamlNode); mapping->deleteChildNodes(); delete mapping; mapping = NULL; } break; case SCALAR: { - ScalarNode *scalar = static_cast<ScalarNode *> (yamlNode); + ScalarNode *scalar = static_cast<ScalarNode *>(yamlNode); delete scalar; scalar = NULL; } @@ -190,36 +193,37 @@ void MappingNode::deleteChildNodes() } } -void SequenceNode::addNode (YamlNode *node) +void SequenceNode::addNode(YamlNode *node) { Sequence::iterator it = seq.end(); - seq.insert (it, node); + seq.insert(it, node); } void SequenceNode::deleteChildNodes() { Sequence::iterator it; + for (it = seq.begin(); it != seq.end(); ++it) { - YamlNode *yamlNode = static_cast<YamlNode *> (*it); + YamlNode *yamlNode = static_cast<YamlNode *>(*it); switch (yamlNode->getType()) { case DOCUMENT: break; case SEQUENCE: { - SequenceNode *sequence = static_cast<SequenceNode *> (yamlNode); + SequenceNode *sequence = static_cast<SequenceNode *>(yamlNode); sequence->deleteChildNodes(); delete sequence; } break; case MAPPING: { - MappingNode *mapping = static_cast<MappingNode *> (yamlNode); + MappingNode *mapping = static_cast<MappingNode *>(yamlNode); mapping->deleteChildNodes(); delete mapping; } break; case SCALAR: { - ScalarNode *scalar = static_cast<ScalarNode *> (yamlNode); + ScalarNode *scalar = static_cast<ScalarNode *>(yamlNode); delete scalar; } break; diff --git a/daemon/src/config/yamlnode.h b/daemon/src/config/yamlnode.h index ab00e3b38599ee41aaf4f5a7e14e3bcdca1ace81..1a7850d0669f34e408e25bc450524614fd9d80ea 100644 --- a/daemon/src/config/yamlnode.h +++ b/daemon/src/config/yamlnode.h @@ -35,10 +35,9 @@ #include <list> #include <map> #include <stdexcept> +#include "noncopyable.h" -namespace Conf -{ - +namespace Conf { class YamlNode; @@ -47,151 +46,115 @@ typedef std::map<std::string, YamlNode *> Mapping; enum NodeType { DOCUMENT, SCALAR, MAPPING, SEQUENCE }; -class YamlNode -{ - +class YamlNode { public: - YamlNode (NodeType t, YamlNode *top=NULL) : type (t), topNode (top) {} + YamlNode(NodeType t, YamlNode *top=NULL) : type(t), topNode(top) {} - virtual ~YamlNode (void) {} + virtual ~YamlNode() {} - NodeType getType (void) { + NodeType getType() { return type; } - YamlNode *getTopNode (void) { + YamlNode *getTopNode() { return topNode; } - virtual void deleteChildNodes (void) = 0; + virtual void deleteChildNodes() = 0; private: - + NON_COPYABLE(YamlNode); NodeType type; - YamlNode *topNode; - }; -class YamlDocument : YamlNode -{ - +class YamlDocument : YamlNode { public: + YamlDocument(YamlNode* top=NULL) : YamlNode(DOCUMENT, top), doc() {} - YamlDocument (YamlNode* top=NULL) : YamlNode (DOCUMENT, top) {} - - ~YamlDocument() {} - - void addNode (YamlNode *node); + void addNode(YamlNode *node); - YamlNode *popNode (void); + YamlNode *popNode(); - Sequence *getSequence (void) { + Sequence *getSequence() { return &doc; } - virtual void deleteChildNodes (void); + virtual void deleteChildNodes(); private: - Sequence doc; - }; -class SequenceNode : public YamlNode -{ - +class SequenceNode : public YamlNode { public: - - SequenceNode (YamlNode *top) : YamlNode (SEQUENCE, top) {} - - ~SequenceNode() {} + SequenceNode(YamlNode *top) : YamlNode(SEQUENCE, top), seq() {} Sequence *getSequence() { return &seq; } - void addNode (YamlNode *node); + void addNode(YamlNode *node); - virtual void deleteChildNodes (void); + virtual void deleteChildNodes(); private: - Sequence seq; - }; -class MappingNode : public YamlNode -{ - +class MappingNode : public YamlNode { public: - - MappingNode (YamlNode *top) : YamlNode (MAPPING, top) {} - - ~MappingNode() {} + MappingNode(YamlNode *top) : YamlNode(MAPPING, top), map(), tmpKey() {} Mapping *getMapping() { return ↦ } - void addNode (YamlNode *node); + void addNode(YamlNode *node); - void setTmpKey (std::string key) { + void setTmpKey(std::string key) { tmpKey = key; } - void setKeyValue (const std::string &key, YamlNode *value); + void setKeyValue(const std::string &key, YamlNode *value); - void removeKeyValue (const std::string &key); + void removeKeyValue(const std::string &key); - YamlNode *getValue (const std::string &key); - void getValue (const std::string &key, bool *b); - void getValue (const std::string &key, int *i); - void getValue (const std::string &key, std::string *s); + YamlNode *getValue(const std::string &key); + void getValue(const std::string &key, bool *b); + void getValue(const std::string &key, int *i); + void getValue(const std::string &key, std::string *s); - virtual void deleteChildNodes (void); + virtual void deleteChildNodes(); private: - Mapping map; - std::string tmpKey; - }; - -class ScalarNode : public YamlNode -{ - +class ScalarNode : public YamlNode { public: - - ScalarNode (std::string s="", YamlNode *top=NULL) : YamlNode (SCALAR, top), str (s) {} - ScalarNode (bool b, YamlNode *top=NULL) : YamlNode (SCALAR, top), str (b ? "true" : "false") {} - - ~ScalarNode() {} + ScalarNode(std::string s="", YamlNode *top=NULL) : YamlNode(SCALAR, top), str(s) {} + ScalarNode(bool b, YamlNode *top=NULL) : YamlNode(SCALAR, top), str(b ? "true" : "false") {} const std::string &getValue() { return str; } - void setValue (const std::string &s) { + void setValue(const std::string &s) { str = s; } - virtual void deleteChildNodes (void) {} + virtual void deleteChildNodes() {} private: - std::string str; - }; - } - - #endif + diff --git a/daemon/src/config/yamlparser.cpp b/daemon/src/config/yamlparser.cpp index 4f7eed53f8a96feb28d0a7f9eed431b7e12c2f1a..44ba3e29bb10f7753ca515109a726982e3911293 100644 --- a/daemon/src/config/yamlparser.cpp +++ b/daemon/src/config/yamlparser.cpp @@ -33,451 +33,372 @@ #include "../global.h" #include "config.h" #include "yamlnode.h" -#include <stdio.h> - -namespace Conf -{ - -YamlParser::YamlParser (const char *file) : filename (file) - , events() - , eventNumber (0) - , doc (NULL) - , eventIndex (0) - , accountSequence (NULL) - , preferenceNode (NULL) - , addressbookNode (NULL) - , audioNode (NULL) - , hooksNode (NULL) - , voiplinkNode (NULL) - , shortcutNode (NULL) +#include <cstdio> + +namespace Conf { + +YamlParser::YamlParser(const char *file) : filename_(file) + , fd_(fopen(filename_.c_str(), "rb")) + , parser_() + , events_() + , eventNumber_(0) + , doc_(NULL) + , eventIndex_(0) + , accountSequence_(NULL) + , preferenceNode_(NULL) + , addressbookNode_(NULL) + , audioNode_(NULL) + , hooksNode_(NULL) + , voiplinkNode_(NULL) + , shortcutNode_(NULL) { - fd = fopen (filename.c_str(), "rb"); - if (!fd) - throw YamlParserException ("Could not open file descriptor"); + if (!fd_) + throw YamlParserException("Could not open file descriptor"); - if (!yaml_parser_initialize (&parser)) - throw YamlParserException ("Could not initialize"); + if (!yaml_parser_initialize(&parser_)) + throw YamlParserException("Could not initialize"); - yaml_parser_set_input_file (&parser, fd); + yaml_parser_set_input_file(&parser_, fd_); } YamlParser::~YamlParser() { - if (fd) { - fclose (fd); - yaml_parser_delete (&parser); + if (fd_) { + fclose(fd_); + yaml_parser_delete(&parser_); } - for (int i = 0; i < eventNumber; i++) - yaml_event_delete (&events[i]); + for (int i = 0; i < eventNumber_; ++i) + yaml_event_delete(&events_[i]); - if (doc) { - doc->deleteChildNodes(); - delete doc; + if (doc_) { + doc_->deleteChildNodes(); + delete doc_; } } -void YamlParser::serializeEvents() throw(YamlParserException) +void YamlParser::serializeEvents() { bool done = false; yaml_event_t event, copiedEvent; - try { - - while (!done) { - - if (!yaml_parser_parse (&parser, &event)) - throw YamlParserException ("Error while parsing"); + while (not done) { + if (!yaml_parser_parse(&parser_, &event)) + throw YamlParserException("Error while parsing"); - done = (event.type == YAML_STREAM_END_EVENT); + done = (event.type == YAML_STREAM_END_EVENT); - copyEvent (&copiedEvent, &event); + copyEvent(&copiedEvent, &event); - events.push_back(copiedEvent); + events_.push_back(copiedEvent); - eventNumber++; + ++eventNumber_; - yaml_event_delete (&event); - } + yaml_event_delete(&event); } - catch(YamlParserException &e) { - throw; - } - } -void YamlParser::copyEvent (yaml_event_t *event_to, yaml_event_t *event_from) throw(YamlParserException) +void YamlParser::copyEvent(yaml_event_t *event_to, yaml_event_t *event_from) { - switch (event_from->type) { case YAML_STREAM_START_EVENT: { - if(yaml_stream_start_event_initialize (event_to, - event_from->data.stream_start.encoding) == 0) { - throw YamlParserException("Error stream start event"); - } + if (yaml_stream_start_event_initialize(event_to, + event_from->data.stream_start.encoding) == 0) + throw YamlParserException("Error stream start event"); + break; } case YAML_STREAM_END_EVENT: { - if(yaml_stream_end_event_initialize (event_to) == 0) { - throw YamlParserException("Error stream end event"); - } + if (yaml_stream_end_event_initialize(event_to) == 0) + throw YamlParserException("Error stream end event"); + break; } case YAML_DOCUMENT_START_EVENT: { - if(yaml_document_start_event_initialize (event_to, + if (yaml_document_start_event_initialize(event_to, event_from->data.document_start.version_directive, event_from->data.document_start.tag_directives.start, event_from->data.document_start.tag_directives.end, - event_from->data.document_start.implicit) == 0) { - throw YamlParserException("Error document start event"); - } + event_from->data.document_start.implicit) == 0) + throw YamlParserException("Error document start event"); + break; } case YAML_DOCUMENT_END_EVENT: { - if(yaml_document_end_event_initialize (event_to, - event_from->data.document_end.implicit) == 0) { - throw YamlParserException("Error document end event"); - } + if (yaml_document_end_event_initialize(event_to, + event_from->data.document_end.implicit) == 0) + throw YamlParserException("Error document end event"); + break; } case YAML_ALIAS_EVENT: { - if (yaml_alias_event_initialize (event_to, - event_from->data.alias.anchor) == 0) { - throw YamlParserException("Error alias event initialize"); - } + if (yaml_alias_event_initialize(event_to, + event_from->data.alias.anchor) == 0) + throw YamlParserException("Error alias event initialize"); + break; } case YAML_SCALAR_EVENT: { - if(yaml_scalar_event_initialize (event_to, - event_from->data.scalar.anchor, - event_from->data.scalar.tag, - event_from->data.scalar.value, - event_from->data.scalar.length, - event_from->data.scalar.plain_implicit, - event_from->data.scalar.quoted_implicit, - event_from->data.scalar.style) == 0) { - throw YamlParserException("Error scalar event initialize"); - } + if (yaml_scalar_event_initialize(event_to, + event_from->data.scalar.anchor, + event_from->data.scalar.tag, + event_from->data.scalar.value, + event_from->data.scalar.length, + event_from->data.scalar.plain_implicit, + event_from->data.scalar.quoted_implicit, + event_from->data.scalar.style) == 0) + throw YamlParserException("Error scalar event initialize"); + break; } case YAML_SEQUENCE_START_EVENT: { - if(yaml_sequence_start_event_initialize (event_to, + if (yaml_sequence_start_event_initialize(event_to, event_from->data.sequence_start.anchor, event_from->data.sequence_start.tag, event_from->data.sequence_start.implicit, - event_from->data.sequence_start.style) == 0) { - throw YamlParserException("Error sequence start event"); - } + event_from->data.sequence_start.style) == 0) + throw YamlParserException("Error sequence start event"); + break; } case YAML_SEQUENCE_END_EVENT: { - if(yaml_sequence_end_event_initialize (event_to) == 0) { - throw YamlParserException("Error sequence end event"); - } + if (yaml_sequence_end_event_initialize(event_to) == 0) + throw YamlParserException("Error sequence end event"); + break; } case YAML_MAPPING_START_EVENT: { - if(yaml_mapping_start_event_initialize (event_to, - event_from->data.mapping_start.anchor, - event_from->data.mapping_start.tag, - event_from->data.mapping_start.implicit, - event_from->data.mapping_start.style) == 0) { - throw YamlParserException("Error mapping start event"); - } + if (yaml_mapping_start_event_initialize(event_to, + event_from->data.mapping_start.anchor, + event_from->data.mapping_start.tag, + event_from->data.mapping_start.implicit, + event_from->data.mapping_start.style) == 0) + throw YamlParserException("Error mapping start event"); break; } case YAML_MAPPING_END_EVENT: { - if(yaml_mapping_end_event_initialize (event_to) == 0) { - throw YamlParserException("Error mapping end event"); - } + if (yaml_mapping_end_event_initialize(event_to) == 0) + throw YamlParserException("Error mapping end event"); + break; } default: - break; + break; } } -YamlDocument *YamlParser::composeEvents() throw(YamlParserException) +YamlDocument *YamlParser::composeEvents() { - try { - if (eventNumber == 0) - throw YamlParserException ("No event available"); + if (eventNumber_ == 0) + throw YamlParserException("No event available"); - if (events[0].type != YAML_STREAM_START_EVENT) - throw YamlParserException ("Parsing does not start with stream start"); + if (events_[0].type != YAML_STREAM_START_EVENT) + throw YamlParserException("Parsing does not start with stream start"); - eventIndex = 0; + eventIndex_ = 0; - processStream(); - } - catch(YamlParserException &e) { - throw; - } + processStream(); - - return doc; + return doc_; } -void YamlParser::processStream () throw(YamlParserException) +void YamlParser::processStream() { - try { - while ( (eventIndex < eventNumber) && (events[eventIndex].type != YAML_STREAM_END_EVENT)) { - - if (events[eventIndex].type == YAML_DOCUMENT_START_EVENT) - processDocument(); + for (; (eventIndex_ < eventNumber_) and (events_[eventIndex_].type != YAML_STREAM_END_EVENT); ++eventIndex_) + if (events_[eventIndex_].type == YAML_DOCUMENT_START_EVENT) + processDocument(); - eventIndex++; - } - - if (events[eventIndex].type != YAML_STREAM_END_EVENT) - throw YamlParserException ("Did not found end of stream"); - } - catch(YamlParserException &e) { - throw; - } + if (events_[eventIndex_].type != YAML_STREAM_END_EVENT) + throw YamlParserException("Did not found end of stream"); } -void YamlParser::processDocument() throw(YamlParserException) +void YamlParser::processDocument() { - try { - - doc = new YamlDocument(); + doc_ = new YamlDocument(); - if (!doc) - throw YamlParserException ("Not able to create new document"); + if (!doc_) + throw YamlParserException("Not able to create new document"); - while ( (eventIndex < eventNumber) && (events[eventIndex].type != YAML_DOCUMENT_END_EVENT)) { - - switch (events[eventIndex].type) { + for (; (eventIndex_ < eventNumber_) and (events_[eventIndex_].type != YAML_DOCUMENT_END_EVENT); ++eventIndex_) { + switch (events_[eventIndex_].type) { case YAML_SCALAR_EVENT: - processScalar ( (YamlNode *) doc); - break; + processScalar((YamlNode *) doc_); + break; case YAML_SEQUENCE_START_EVENT: - processSequence ( (YamlNode *) doc); - break; + processSequence((YamlNode *) doc_); + break; case YAML_MAPPING_START_EVENT: - processMapping ( (YamlNode *) doc); + processMapping((YamlNode *) doc_); break; default: break; - } - - eventIndex++; - } - - if (events[eventIndex].type != YAML_DOCUMENT_END_EVENT) - throw YamlParserException ("Did not found end of document"); + } + } - } - catch(YamlParserException &e) { - throw; - } + if (events_[eventIndex_].type != YAML_DOCUMENT_END_EVENT) + throw YamlParserException("Did not found end of document"); } -void YamlParser::processScalar (YamlNode *topNode) throw(YamlParserException) +void YamlParser::processScalar(YamlNode *topNode) { - try { + if (!topNode) + throw YamlParserException("No container for scalar"); - if (!topNode) - throw YamlParserException ("No container for scalar"); + ScalarNode *sclr = new ScalarNode(std::string((const char*)events_[eventIndex_].data.scalar.value), topNode); - ScalarNode *sclr = new ScalarNode (std::string((const char*)events[eventIndex].data.scalar.value), topNode); - - switch (topNode->getType()) { + switch (topNode->getType()) { case DOCUMENT: - ( (YamlDocument *) (topNode))->addNode (sclr); + ((YamlDocument *)(topNode))->addNode(sclr); break; case SEQUENCE: - ( (SequenceNode *) (topNode))->addNode (sclr); + ((SequenceNode *)(topNode))->addNode(sclr); break; case MAPPING: - ( (MappingNode *) (topNode))->addNode (sclr); + ((MappingNode *)(topNode))->addNode(sclr); case SCALAR: default: break; - } - } - catch(YamlParserException &e) { - throw; - } + } } -void YamlParser::processSequence (YamlNode *topNode) throw(YamlParserException) +void YamlParser::processSequence(YamlNode *topNode) { + if (!topNode) + throw YamlParserException("No container for sequence"); - try { - - if (!topNode) - throw YamlParserException ("No container for sequence"); - - SequenceNode *seq = new SequenceNode (topNode); + SequenceNode *seq = new SequenceNode(topNode); - switch (topNode->getType()) { + switch (topNode->getType()) { case DOCUMENT: - ( (YamlDocument *) (topNode))->addNode (seq); + ((YamlDocument *)(topNode))->addNode(seq); break; case SEQUENCE: - ( (SequenceNode *) (topNode))->addNode (seq); + ((SequenceNode *)(topNode))->addNode(seq); break; case MAPPING: - ( (MappingNode *) (topNode))->addNode (seq); + ((MappingNode *)(topNode))->addNode(seq); case SCALAR: default: break; - } - - eventIndex++; + } - while ( (eventIndex < eventNumber) && (events[eventIndex].type != YAML_SEQUENCE_END_EVENT)) { + ++eventIndex_; - switch (events[eventIndex].type) { + for (; (eventIndex_ < eventNumber_) and (events_[eventIndex_].type != YAML_SEQUENCE_END_EVENT); ++eventIndex_) { + switch (events_[eventIndex_].type) { case YAML_SCALAR_EVENT: - processScalar (seq); + processScalar(seq); break; case YAML_SEQUENCE_START_EVENT: - processSequence (seq); + processSequence(seq); break; case YAML_MAPPING_START_EVENT: - processMapping (seq); + processMapping(seq); break; default: break; - } - - eventIndex++; - } - - if (events[eventIndex].type != YAML_SEQUENCE_END_EVENT) - throw YamlParserException ("Did not found end of sequence"); + } + } - } - catch(YamlParserException &e) { - throw; - } + if (events_[eventIndex_].type != YAML_SEQUENCE_END_EVENT) + throw YamlParserException("Did not found end of sequence"); } -void YamlParser::processMapping (YamlNode *topNode) throw(YamlParserException) +void YamlParser::processMapping(YamlNode *topNode) { - try { + if (!topNode) + throw YamlParserException("No container for mapping"); - if (!topNode) - throw YamlParserException ("No container for mapping"); + MappingNode *map = new MappingNode(topNode); - MappingNode *map = new MappingNode (topNode); - - switch (topNode->getType()) { + switch (topNode->getType()) { case DOCUMENT: - ( (YamlDocument *) (topNode))->addNode (map); + ((YamlDocument *)(topNode))->addNode(map); break; case SEQUENCE: - ( (SequenceNode *) (topNode))->addNode (map); + ((SequenceNode *)(topNode))->addNode(map); break; case MAPPING: - ( (MappingNode *) (topNode))->addNode (map); + ((MappingNode *)(topNode))->addNode(map); case SCALAR: default: break; - } - - eventIndex++; + } - while ( (eventIndex < eventNumber) && (events[eventIndex].type != YAML_MAPPING_END_EVENT)) { + ++eventIndex_; - if (events[eventIndex].type != YAML_SCALAR_EVENT) - throw YamlParserException ("Mapping not followed by a key"); + while ((eventIndex_ < eventNumber_) && (events_[eventIndex_].type != YAML_MAPPING_END_EVENT)) { - map->setTmpKey (std::string ((const char *)events[eventIndex].data.scalar.value)); + if (events_[eventIndex_].type != YAML_SCALAR_EVENT) + throw YamlParserException("Mapping not followed by a key"); - eventIndex++; + map->setTmpKey(std::string((const char *)events_[eventIndex_].data.scalar.value)); + ++eventIndex_; - switch (events[eventIndex].type) { + switch (events_[eventIndex_].type) { case YAML_SCALAR_EVENT: - processScalar (map); + processScalar(map); break; case YAML_SEQUENCE_START_EVENT: - processSequence (map); + processSequence(map); break; case YAML_MAPPING_START_EVENT: - processMapping (map); + processMapping(map); break; default: break; - } - - eventIndex++; - } + } - if (events[eventIndex].type != YAML_MAPPING_END_EVENT) - throw YamlParserException ("Did not found end of mapping"); + ++eventIndex_; + } - } - catch(YamlParserException &e) { - throw; - } + if (events_[eventIndex_].type != YAML_MAPPING_END_EVENT) + throw YamlParserException("Did not found end of mapping"); } -void YamlParser::constructNativeData() throw(YamlParserException) +void YamlParser::constructNativeData() { + Sequence *seq = doc_->getSequence(); - try { - Sequence *seq; - - seq = doc->getSequence(); - - Sequence::iterator iter = seq->begin(); - - while (iter != seq->end()) { - - switch ( (*iter)->getType()) { + for (Sequence::iterator iter = seq->begin(); iter != seq->end(); ++iter) { + switch ((*iter)->getType()) { case SCALAR: - // _debug("construct scalar"); - throw YamlParserException ("No scalar allowed at document level, expect a mapping"); + throw YamlParserException("No scalar allowed at document level, expect a mapping"); break; case SEQUENCE: - // _debug("construct sequence"); - throw YamlParserException ("No sequence allowed at document level, expect a mapping"); + throw YamlParserException("No sequence allowed at document level, expect a mapping"); break; case MAPPING: { - // _debug("construct mapping"); - MappingNode *map = (MappingNode *) (*iter); - mainNativeDataMapping (map); + MappingNode *map = (MappingNode *)(*iter); + mainNativeDataMapping(map); break; } default: - throw YamlParserException ("Unknown type in configuration file, expect a mapping"); + throw YamlParserException("Unknown type in configuration file, expect a mapping"); break; - } - - iter++; - - } - } - catch(YamlParserException &e) { - throw; - } - + } + } } - -void YamlParser::mainNativeDataMapping (MappingNode *map) +void YamlParser::mainNativeDataMapping(MappingNode *map) { - Mapping *mapping = map->getMapping(); - - accountSequence = (SequenceNode*)(*mapping)["accounts"]; - addressbookNode = (MappingNode*)(*mapping)["addressbook"]; - audioNode = (MappingNode*)(*mapping)["audio"]; - hooksNode = (MappingNode*)(*mapping)["hooks"]; - preferenceNode = (MappingNode*)(*mapping)["preferences"]; - voiplinkNode = (MappingNode*)(*mapping)["voipPreferences"]; - shortcutNode = (MappingNode*)(*mapping)["shortcuts"]; + Mapping *mapping = map->getMapping(); + + accountSequence_ = (SequenceNode*)(*mapping)["accounts"]; + addressbookNode_ = (MappingNode*)(*mapping)["addressbook"]; + audioNode_ = (MappingNode*)(*mapping)["audio"]; + hooksNode_ = (MappingNode*)(*mapping)["hooks"]; + preferenceNode_ = (MappingNode*)(*mapping)["preferences"]; + voiplinkNode_ = (MappingNode*)(*mapping)["voipPreferences"]; + shortcutNode_ = (MappingNode*)(*mapping)["shortcuts"]; } - } + diff --git a/daemon/src/config/yamlparser.h b/daemon/src/config/yamlparser.h index c449fe0c4c154235829652988d11545d0d331130..1c6ec4fb99932db639c57080f068cbc6e7ce07cb 100644 --- a/daemon/src/config/yamlparser.h +++ b/daemon/src/config/yamlparser.h @@ -33,132 +33,124 @@ #include "yamlnode.h" #include <yaml.h> -#include <stdio.h> +#include <cstdio> #include <stdexcept> #include <string> #include <vector> +#include "noncopyable.h" -namespace Conf -{ +namespace Conf { #define PARSER_BUFFERSIZE 65536 typedef std::vector<yaml_event_t> YamlEventVector; -class YamlParserException : public std::runtime_error -{ +class YamlParserException : public std::runtime_error { public: - YamlParserException (const std::string& str="") : + YamlParserException(const std::string& str="") : std::runtime_error("YamlParserException occured: " + str) {} }; -class YamlParser -{ +class YamlParser { public: - YamlParser (const char *file); + YamlParser(const char *file); ~YamlParser(); - void serializeEvents() throw(YamlParserException); + void serializeEvents(); - YamlDocument *composeEvents() throw(YamlParserException); + YamlDocument *composeEvents(); - void constructNativeData() throw(YamlParserException); + void constructNativeData(); - SequenceNode *getAccountSequence (void) { - return accountSequence; + SequenceNode *getAccountSequence() { + return accountSequence_; }; - MappingNode *getPreferenceNode (void) { - return preferenceNode; + MappingNode *getPreferenceNode() { + return preferenceNode_; } - MappingNode *getAddressbookNode (void) { - return addressbookNode; + MappingNode *getAddressbookNode() { + return addressbookNode_; } - MappingNode *getAudioNode (void) { - return audioNode; + MappingNode *getAudioNode() { + return audioNode_; } - MappingNode *getHookNode (void) { - return hooksNode; + MappingNode *getHookNode() { + return hooksNode_; } - MappingNode *getVoipPreferenceNode (void) { - return voiplinkNode; + MappingNode *getVoipPreferenceNode() { + return voiplinkNode_; } - MappingNode *getShortcutNode (void) { - return shortcutNode; + MappingNode *getShortcutNode() { + return shortcutNode_; } private: + NON_COPYABLE(YamlParser); /** * Copy yaml parser event in event_to according to their type. */ - void copyEvent (yaml_event_t *event_to, yaml_event_t *event_from) throw(YamlParserException); + void copyEvent(yaml_event_t *event_to, yaml_event_t *event_from); - void processStream (void) throw(YamlParserException); + void processStream(); - void processDocument (void) throw(YamlParserException); + void processDocument(); - void processScalar (YamlNode *topNode) throw(YamlParserException); + void processScalar(YamlNode *topNode); - void processSequence (YamlNode *topNode) throw(YamlParserException); + void processSequence(YamlNode *topNode); - void processMapping (YamlNode *topNode) throw(YamlParserException); + void processMapping(YamlNode *topNode); - void mainNativeDataMapping (MappingNode *map); + void mainNativeDataMapping(MappingNode *map); /** * Configuration file name */ - std::string filename; + std::string filename_; /** * Configuration file descriptor */ - FILE *fd; + FILE *fd_; /** * The parser structure. */ - yaml_parser_t parser; + yaml_parser_t parser_; /** * The event structure array. */ - YamlEventVector events; + YamlEventVector events_; /** * Number of event actually parsed */ - int eventNumber; + int eventNumber_; - YamlDocument *doc; + YamlDocument *doc_; - int eventIndex; + int eventIndex_; - SequenceNode *accountSequence; - - MappingNode *preferenceNode; - - MappingNode *addressbookNode; - - MappingNode *audioNode; - - MappingNode *hooksNode; - - MappingNode *voiplinkNode; - - MappingNode *shortcutNode; + SequenceNode *accountSequence_; + MappingNode *preferenceNode_; + MappingNode *addressbookNode_; + MappingNode *audioNode_; + MappingNode *hooksNode_; + MappingNode *voiplinkNode_; + MappingNode *shortcutNode_; }; - } #endif diff --git a/daemon/src/dbus/callmanager-introspec.xml b/daemon/src/dbus/callmanager-introspec.xml index 8b23a3f68dc04fecfce79a233b5669f4882bc7b8..46cec40068df52b9d16a50324c3947821ed7f443 100644 --- a/daemon/src/dbus/callmanager-introspec.xml +++ b/daemon/src/dbus/callmanager-introspec.xml @@ -289,7 +289,7 @@ A map containing the ID of the conferences and their states: <ul> - <li>ACTIVE_ATACHED</li> + <li>ACTIVE_ATTACHED</li> <li>ACTIVE_DETACHED</li> <li>HOLD</li> </ul> diff --git a/daemon/src/dbus/callmanager.cpp b/daemon/src/dbus/callmanager.cpp index 9c9d4dc46e30a2acb61eb3a028783df4c905dbad..3a13295efea24a9c22fdda2cfe43b1faa64b0590 100644 --- a/daemon/src/dbus/callmanager.cpp +++ b/daemon/src/dbus/callmanager.cpp @@ -35,129 +35,122 @@ #include "sip/sipcall.h" #include "sip/sipvoiplink.h" -#include "audio/audiortp/AudioRtpFactory.h" -#include "audio/audiortp/AudioZrtpSession.h" +#include "audio/audiortp/audio_rtp_factory.h" +#include "audio/audiortp/audio_zrtp_session.h" #include "manager.h" -CallManager::CallManager (DBus::Connection& connection) - : DBus::ObjectAdaptor (connection, "/org/sflphone/SFLphone/CallManager") -{ -} +CallManager::CallManager(DBus::Connection& connection) + : DBus::ObjectAdaptor(connection, "/org/sflphone/SFLphone/CallManager") +{} -void -CallManager::placeCall (const std::string& accountID, - const std::string& callID, - const std::string& to) // Check if a destination number is available +void CallManager::placeCall(const std::string& accountID, + const std::string& callID, + const std::string& to) { - - if (to == "") { - _debug ("No number entered - Call stopped"); - } else { - Manager::instance().outgoingCall (accountID, callID, to); - } + // Check if a destination number is available + if (to.empty()) + DEBUG("No number entered - Call stopped"); + else + Manager::instance().outgoingCall(accountID, callID, to); } -void -CallManager::placeCallFirstAccount (const std::string& callID, - const std::string& to) +void CallManager::placeCallFirstAccount(const std::string& callID, + const std::string& to) { - if (to == "") { - _warn ("CallManager: Warning: No number entered, call stopped"); + using std::vector; + using std::string; + + if (to.empty()) { + WARN("CallManager: Warning: No number entered, call stopped"); return; } - std::vector< std::string > accountList = Manager::instance().loadAccountOrder(); - if (accountList.size() == 0) - accountList = Manager::instance().getAccountList(); + vector<string> accountList(Manager::instance().loadAccountOrder()); - std::vector< std::string >::const_iterator iter; - for (iter = accountList.begin(); iter != accountList.end(); ++iter) { - if ((*iter != IP2IP_PROFILE) && Manager::instance().getAccount(*iter)->isEnabled()) { - Manager::instance().outgoingCall(*iter, callID, to); - return; - } - } + if (accountList.empty()) + accountList = Manager::instance().getAccountList(); + + for (vector<string>::const_iterator iter = accountList.begin(); iter != accountList.end(); ++iter) { + if ((*iter != IP2IP_PROFILE) && Manager::instance().getAccount(*iter)->isEnabled()) { + Manager::instance().outgoingCall(*iter, callID, to); + return; + } + } } void -CallManager::refuse (const std::string& callID) +CallManager::refuse(const std::string& callID) { - Manager::instance().refuseCall (callID); + Manager::instance().refuseCall(callID); } void -CallManager::accept (const std::string& callID) +CallManager::accept(const std::string& callID) { - Manager::instance().answerCall (callID); + Manager::instance().answerCall(callID); } void -CallManager::hangUp (const std::string& callID) +CallManager::hangUp(const std::string& callID) { - Manager::instance().hangupCall (callID); - + Manager::instance().hangupCall(callID); } void -CallManager::hangUpConference (const std::string& confID) +CallManager::hangUpConference(const std::string& confID) { - Manager::instance().hangupConference (confID); + Manager::instance().hangupConference(confID); } - void -CallManager::hold (const std::string& callID) +CallManager::hold(const std::string& callID) { - Manager::instance().onHoldCall (callID); + Manager::instance().onHoldCall(callID); } void -CallManager::unhold (const std::string& callID) +CallManager::unhold(const std::string& callID) { - Manager::instance().offHoldCall (callID); + Manager::instance().offHoldCall(callID); } void -CallManager::transfer (const std::string& callID, const std::string& to) +CallManager::transfer(const std::string& callID, const std::string& to) { - Manager::instance().transferCall (callID, to); + Manager::instance().transferCall(callID, to); } -void -CallManager::attendedTransfer (const std::string& transferID, const std::string& targetID) +void CallManager::attendedTransfer(const std::string& transferID, const std::string& targetID) { - Manager::instance().attendedTransfer(transferID, targetID); + Manager::instance().attendedTransfer(transferID, targetID); } -void -CallManager::setVolume (const std::string& device, const double& value) +void CallManager::setVolume(const std::string& device, const double& value) { - if (device == "speaker") { - Manager::instance().setSpkrVolume ( (int) (value*100.0)); - } else if (device == "mic") { - Manager::instance().setMicVolume ( (int) (value*100.0)); - } + if (device == "speaker") + Manager::instance().setSpkrVolume((int)(value * 100.0)); + else if (device == "mic") + Manager::instance().setMicVolume((int)(value * 100.0)); - volumeChanged (device, value); + volumeChanged(device, value); } double -CallManager::getVolume (const std::string& device) +CallManager::getVolume(const std::string& device) { - if (device == "speaker") { - return Manager::instance().getSpkrVolume() /100.0; - } else if (device == "mic") { - return Manager::instance().getMicVolume() /100.0; - } + if (device == "speaker") + return Manager::instance().getSpkrVolume() / 100.0; + else if (device == "mic") + return Manager::instance().getMicVolume() / 100.0; return 0; } void -CallManager::joinParticipant (const std::string& sel_callID, const std::string& drag_callID) +CallManager::joinParticipant(const std::string& sel_callID, const std::string& drag_callID) { - Manager::instance().joinParticipant (sel_callID, drag_callID); + Manager::instance().joinParticipant(sel_callID, drag_callID); } void @@ -167,57 +160,57 @@ CallManager::createConfFromParticipantList(const std::vector< std::string >& par } void -CallManager::addParticipant (const std::string& callID, const std::string& confID) +CallManager::addParticipant(const std::string& callID, const std::string& confID) { - Manager::instance().addParticipant (callID, confID); + Manager::instance().addParticipant(callID, confID); } void -CallManager::addMainParticipant (const std::string& confID) +CallManager::addMainParticipant(const std::string& confID) { - Manager::instance().addMainParticipant (confID); + Manager::instance().addMainParticipant(confID); } void -CallManager::detachParticipant (const std::string& callID) +CallManager::detachParticipant(const std::string& callID) { - Manager::instance().detachParticipant (callID, ""); + Manager::instance().detachParticipant(callID, ""); } void -CallManager::joinConference (const std::string& sel_confID, const std::string& drag_confID) +CallManager::joinConference(const std::string& sel_confID, const std::string& drag_confID) { - Manager::instance().joinConference (sel_confID, drag_confID); + Manager::instance().joinConference(sel_confID, drag_confID); } void -CallManager::holdConference (const std::string& confID) +CallManager::holdConference(const std::string& confID) { - Manager::instance().holdConference (confID); + Manager::instance().holdConference(confID); } void -CallManager::unholdConference (const std::string& confID) +CallManager::unholdConference(const std::string& confID) { - Manager::instance().unHoldConference (confID); + Manager::instance().unHoldConference(confID); } std::map< std::string, std::string > -CallManager::getConferenceDetails (const std::string& callID) +CallManager::getConferenceDetails(const std::string& callID) { - return Manager::instance().getConferenceDetails (callID); + return Manager::instance().getConferenceDetails(callID); } std::vector< std::string > -CallManager::getConferenceList (void) +CallManager::getConferenceList() { return Manager::instance().getConferenceList(); } std::vector< std::string > -CallManager::getParticipantList (const std::string& confID) +CallManager::getParticipantList(const std::string& confID) { - return Manager::instance().getParticipantList (confID); + return Manager::instance().getParticipantList(confID); } bool @@ -233,33 +226,33 @@ CallManager::stopRecordedFilePlayback(const std::string& filepath) } void -CallManager::setRecording (const std::string& callID) +CallManager::setRecording(const std::string& callID) { - Manager::instance().setRecordingCall (callID); + Manager::instance().setRecordingCall(callID); } bool -CallManager::getIsRecording (const std::string& callID) +CallManager::getIsRecording(const std::string& callID) { - return Manager::instance().isRecording (callID); + return Manager::instance().isRecording(callID); } std::string -CallManager::getCurrentAudioCodecName (const std::string& callID) +CallManager::getCurrentAudioCodecName(const std::string& callID) { - return Manager::instance().getCurrentCodecName (callID).c_str(); + return Manager::instance().getCurrentCodecName(callID).c_str(); } -std::map< std::string, std::string > -CallManager::getCallDetails (const std::string& callID) +std::map<std::string, std::string> +CallManager::getCallDetails(const std::string& callID) { - return Manager::instance().getCallDetails (callID); + return Manager::instance().getCallDetails(callID); } -std::vector< std::string > -CallManager::getCallList (void) +std::vector<std::string> +CallManager::getCallList() { return Manager::instance().getCallList(); } @@ -271,45 +264,45 @@ CallManager::getCurrentCallID() } void -CallManager::playDTMF (const std::string& key) +CallManager::playDTMF(const std::string& key) { - Manager::instance().sendDtmf (Manager::instance().getCurrentCallId(), key.data() [0]); + Manager::instance().sendDtmf(Manager::instance().getCurrentCallId(), key.data()[0]); } void -CallManager::startTone (const int32_t& start , const int32_t& type) +CallManager::startTone(const int32_t& start , const int32_t& type) { - if (start == true) { + if (start) { if (type == 0) Manager::instance().playTone(); else Manager::instance().playToneWithMessage(); } else - Manager::instance().stopTone (); + Manager::instance().stopTone(); } // TODO: this will have to be adapted // for conferencing in order to get // the right pointer for the given // callID. -sfl::AudioZrtpSession * CallManager::getAudioZrtpSession (const std::string& callID) +sfl::AudioZrtpSession * +CallManager::getAudioZrtpSession(const std::string& callID) { - SIPVoIPLink * link = NULL; - link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink ("")); + SIPVoIPLink * link = dynamic_cast<SIPVoIPLink *>(Manager::instance().getAccountLink("")); - if (!link) { + if (!link) throw CallManagerException("Failed to get sip link"); - } SIPCall *call; + try { call = link->getSIPCall(callID); - } - catch (const VoipLinkException &e) { + } catch (const VoipLinkException &e) { throw CallManagerException("Call id " + callID + " is not valid"); } - sfl::AudioZrtpSession * zSession = call->getAudioRtp()->getAudioZrtpSession(); + sfl::AudioZrtpSession * zSession = call->getAudioRtp().getAudioZrtpSession(); + if (!zSession) throw CallManagerException("Failed to get AudioZrtpSession"); @@ -317,86 +310,74 @@ sfl::AudioZrtpSession * CallManager::getAudioZrtpSession (const std::string& cal } void -CallManager::setSASVerified (const std::string& callID) +CallManager::setSASVerified(const std::string& callID) { try { sfl::AudioZrtpSession * zSession; - zSession = getAudioZrtpSession (callID); + zSession = getAudioZrtpSession(callID); zSession->SASVerified(); } catch (...) { - return; - // throw; } } void -CallManager::resetSASVerified (const std::string& callID) +CallManager::resetSASVerified(const std::string& callID) { try { sfl::AudioZrtpSession * zSession; - zSession = getAudioZrtpSession (callID); + zSession = getAudioZrtpSession(callID); zSession->resetSASVerified(); } catch (...) { - return; - // throw; } } void -CallManager::setConfirmGoClear (const std::string& callID) +CallManager::setConfirmGoClear(const std::string& callID) { try { sfl::AudioZrtpSession * zSession; - zSession = getAudioZrtpSession (callID); + zSession = getAudioZrtpSession(callID); zSession->goClearOk(); } catch (...) { - return; - // throw; } } void -CallManager::requestGoClear (const std::string& callID) +CallManager::requestGoClear(const std::string& callID) { try { sfl::AudioZrtpSession * zSession; - zSession = getAudioZrtpSession (callID); + zSession = getAudioZrtpSession(callID); zSession->requestGoClear(); } catch (...) { - return; - /// throw; } } void -CallManager::acceptEnrollment (const std::string& callID, const bool& accepted) +CallManager::acceptEnrollment(const std::string& callID, const bool& accepted) { try { sfl::AudioZrtpSession * zSession; - zSession = getAudioZrtpSession (callID); - zSession->acceptEnrollment (accepted); + zSession = getAudioZrtpSession(callID); + zSession->acceptEnrollment(accepted); } catch (...) { - return; - // throw; } } void -CallManager::setPBXEnrollment (const std::string& callID, const bool& yesNo) +CallManager::setPBXEnrollment(const std::string& callID, const bool& yesNo) { try { sfl::AudioZrtpSession * zSession; - zSession = getAudioZrtpSession (callID); - zSession->setPBXEnrollment (yesNo); + zSession = getAudioZrtpSession(callID); + zSession->setPBXEnrollment(yesNo); } catch (...) { - return; - // throw; } } void -CallManager::sendTextMessage (const std::string& callID, const std::string& message) +CallManager::sendTextMessage(const std::string& callID, const std::string& message) { - if (!Manager::instance().sendTextMessage (callID, message, "Me")) + if (!Manager::instance().sendTextMessage(callID, message, "Me")) throw CallManagerException(); } diff --git a/daemon/src/dbus/callmanager.h b/daemon/src/dbus/callmanager.h index 4706decd8ec0192a27de6d7836215d660aa99b26..e0592f32b4ec5f5a9134e9238c6a85c1c370f6e5 100644 --- a/daemon/src/dbus/callmanager.h +++ b/daemon/src/dbus/callmanager.h @@ -31,6 +31,7 @@ #ifndef __SFL_CALLMANAGER_H__ #define __SFL_CALLMANAGER_H__ +#include "dbus_cpp.h" #if __GNUC__ >= 4 && __GNUC_MINOR__ >= 6 /* This warning option only exists for gcc 4.6.0 and greater. */ #pragma GCC diagnostic ignored "-Wunused-but-set-variable" @@ -47,29 +48,25 @@ #pragma GCC diagnostic warning "-Wunused-but-set-variable" #endif -#include <dbus-c++/dbus.h> #include <stdexcept> -class CallManagerException: public std::runtime_error -{ +class CallManagerException: public std::runtime_error { public: CallManagerException(const std::string& str="") : std::runtime_error("A CallManagerException occured: " + str) {} }; -namespace sfl -{ +namespace sfl { class AudioZrtpSession; } class CallManager : public org::sflphone::SFLphone::CallManager_adaptor, public DBus::IntrospectableAdaptor, - public DBus::ObjectAdaptor -{ + public DBus::ObjectAdaptor { public: - CallManager (DBus::Connection& connection); + CallManager(DBus::Connection& connection); static const char* SERVER_PATH; /* methods exported by this interface, @@ -77,61 +74,61 @@ class CallManager */ /* Call related methods */ - void placeCall (const std::string& accountID, const std::string& callID, const std::string& to); - void placeCallFirstAccount (const std::string& callID, const std::string& to); - - void refuse (const std::string& callID); - void accept (const std::string& callID); - void hangUp (const std::string& callID); - void hold (const std::string& callID); - void unhold (const std::string& callID); - void transfer (const std::string& callID, const std::string& to); + void placeCall(const std::string& accountID, const std::string& callID, const std::string& to); + void placeCallFirstAccount(const std::string& callID, const std::string& to); + + void refuse(const std::string& callID); + void accept(const std::string& callID); + void hangUp(const std::string& callID); + void hold(const std::string& callID); + void unhold(const std::string& callID); + void transfer(const std::string& callID, const std::string& to); void attendedTransfer(const std::string& transferID, const std::string& targetID); - std::map< std::string, std::string > getCallDetails (const std::string& callID); - std::vector< std::string > getCallList (void); + std::map< std::string, std::string > getCallDetails(const std::string& callID); + std::vector< std::string > getCallList(); std::string getCurrentCallID(); /* Conference related methods */ - void joinParticipant (const std::string& sel_callID, const std::string& drag_callID); - void createConfFromParticipantList(const std::vector< std::string >& participants); - void addParticipant (const std::string& callID, const std::string& confID); - void addMainParticipant (const std::string& confID); - void detachParticipant (const std::string& callID); - void joinConference (const std::string& sel_confID, const std::string& drag_confID); - void hangUpConference (const std::string& confID); - void holdConference (const std::string& confID); - void unholdConference (const std::string& confID); - std::vector< std::string > getConferenceList (void); - std::vector< std::string > getParticipantList (const std::string& confID); - std::map< std::string, std::string > getConferenceDetails (const std::string& callID); - - /* File Playback methods */ - bool startRecordedFilePlayback(const std::string& filepath); - void stopRecordedFilePlayback(const std::string& filepath); + void joinParticipant(const std::string& sel_callID, const std::string& drag_callID); + void createConfFromParticipantList(const std::vector< std::string >& participants); + void addParticipant(const std::string& callID, const std::string& confID); + void addMainParticipant(const std::string& confID); + void detachParticipant(const std::string& callID); + void joinConference(const std::string& sel_confID, const std::string& drag_confID); + void hangUpConference(const std::string& confID); + void holdConference(const std::string& confID); + void unholdConference(const std::string& confID); + std::vector< std::string > getConferenceList(); + std::vector< std::string > getParticipantList(const std::string& confID); + std::map< std::string, std::string > getConferenceDetails(const std::string& callID); + + /* File Playback methods */ + bool startRecordedFilePlayback(const std::string& filepath); + void stopRecordedFilePlayback(const std::string& filepath); /* General audio methods */ - void setVolume (const std::string& device, const double& value); - double getVolume (const std::string& device); - void setRecording (const std::string& callID); - bool getIsRecording (const std::string& callID); - std::string getCurrentAudioCodecName (const std::string& callID); - void playDTMF (const std::string& key); - void startTone (const int32_t& start, const int32_t& type); + void setVolume(const std::string& device, const double& value); + double getVolume(const std::string& device); + void setRecording(const std::string& callID); + bool getIsRecording(const std::string& callID); + std::string getCurrentAudioCodecName(const std::string& callID); + void playDTMF(const std::string& key); + void startTone(const int32_t& start, const int32_t& type); /* Security related methods */ - void setSASVerified (const std::string& callID); - void resetSASVerified (const std::string& callID); - void setConfirmGoClear (const std::string& callID); - void requestGoClear (const std::string& callID); - void acceptEnrollment (const std::string& callID, const bool& accepted); - void setPBXEnrollment (const std::string& callID, const bool& yesNo); + void setSASVerified(const std::string& callID); + void resetSASVerified(const std::string& callID); + void setConfirmGoClear(const std::string& callID); + void requestGoClear(const std::string& callID); + void acceptEnrollment(const std::string& callID, const bool& accepted); + void setPBXEnrollment(const std::string& callID, const bool& yesNo); /* Instant messaging */ - void sendTextMessage (const std::string& callID, const std::string& message); + void sendTextMessage(const std::string& callID, const std::string& message); private: - sfl::AudioZrtpSession * getAudioZrtpSession (const std::string& callID); + sfl::AudioZrtpSession * getAudioZrtpSession(const std::string& callID); }; diff --git a/daemon/src/dbus/configurationmanager-introspec.xml b/daemon/src/dbus/configurationmanager-introspec.xml old mode 100755 new mode 100644 diff --git a/daemon/src/dbus/configurationmanager.cpp b/daemon/src/dbus/configurationmanager.cpp index 73b3880ec6aafb97364275498186f8e24ca306bb..056b819de1217eb56fa71529a33e9046bfc8b8fd 100644 --- a/daemon/src/dbus/configurationmanager.cpp +++ b/daemon/src/dbus/configurationmanager.cpp @@ -43,43 +43,37 @@ const char* ConfigurationManager::SERVER_PATH = "/org/sflphone/SFLphone/ConfigurationManager"; -ConfigurationManager::ConfigurationManager (DBus::Connection& connection) : - DBus::ObjectAdaptor (connection, SERVER_PATH) -{ - shortcutsKeys.push_back ("pick_up"); - shortcutsKeys.push_back ("hang_up"); - shortcutsKeys.push_back ("popup_window"); - shortcutsKeys.push_back ("toggle_pick_up_hang_up"); - shortcutsKeys.push_back ("toggle_hold"); -} +ConfigurationManager::ConfigurationManager(DBus::Connection& connection) : + DBus::ObjectAdaptor(connection, SERVER_PATH) +{} -std::map<std::string, std::string> ConfigurationManager::getIp2IpDetails (void) +std::map<std::string, std::string> ConfigurationManager::getIp2IpDetails() { std::map<std::string, std::string> ip2ipAccountDetails; - SIPAccount *sipaccount = static_cast<SIPAccount *>(Manager::instance().getAccount (IP2IP_PROFILE)); + SIPAccount *sipaccount = static_cast<SIPAccount *>(Manager::instance().getAccount(IP2IP_PROFILE)); + if (!sipaccount) { - _error ("ConfigurationManager: could not find account"); + ERROR("ConfigurationManager: could not find account"); return ip2ipAccountDetails; - } - else + } else return sipaccount->getIp2IpDetails(); std::map<std::string, std::string> tlsSettings = getTlsSettings(); - std::copy (tlsSettings.begin(), tlsSettings.end(), std::inserter ( - ip2ipAccountDetails, ip2ipAccountDetails.end())); + std::copy(tlsSettings.begin(), tlsSettings.end(), std::inserter( + ip2ipAccountDetails, ip2ipAccountDetails.end())); return ip2ipAccountDetails; } -std::map<std::string, std::string> ConfigurationManager::getAccountDetails ( +std::map<std::string, std::string> ConfigurationManager::getAccountDetails( const std::string& accountID) { - return Manager::instance().getAccountDetails (accountID); + return Manager::instance().getAccountDetails(accountID); } std::map<std::string, std::string> -ConfigurationManager::getTlsSettingsDefault () +ConfigurationManager::getTlsSettingsDefault() { std::stringstream portstr; portstr << DEFAULT_SIP_TLS_PORT; @@ -106,18 +100,20 @@ std::map<std::string, std::string> ConfigurationManager::getTlsSettings() { std::map<std::string, std::string> tlsSettings; - SIPAccount *sipaccount = (SIPAccount *) Manager::instance().getAccount (IP2IP_PROFILE); + SIPAccount *sipaccount = (SIPAccount *) Manager::instance().getAccount(IP2IP_PROFILE); if (!sipaccount) return tlsSettings; + return sipaccount->getTlsSettings(); } -void ConfigurationManager::setTlsSettings (const std::map<std::string, std::string>& details) +void ConfigurationManager::setTlsSettings(const std::map<std::string, std::string>& details) { - SIPAccount * sipaccount = (SIPAccount *) Manager::instance().getAccount (IP2IP_PROFILE); + SIPAccount * sipaccount = (SIPAccount *) Manager::instance().getAccount(IP2IP_PROFILE); + if (!sipaccount) { - _debug ("ConfigurationManager: Error: No valid account in set TLS settings"); + DEBUG("ConfigurationManager: Error: No valid account in set TLS settings"); return; } @@ -130,24 +126,24 @@ void ConfigurationManager::setTlsSettings (const std::map<std::string, std::stri } -void ConfigurationManager::setAccountDetails (const std::string& accountID, const std::map<std::string, std::string>& details) +void ConfigurationManager::setAccountDetails(const std::string& accountID, const std::map<std::string, std::string>& details) { - Manager::instance().setAccountDetails (accountID, details); + Manager::instance().setAccountDetails(accountID, details); } -void ConfigurationManager::sendRegister (const std::string& accountID, const int32_t& expire) +void ConfigurationManager::sendRegister(const std::string& accountID, const int32_t& expire) { - Manager::instance().sendRegister (accountID, expire); + Manager::instance().sendRegister(accountID, expire); } -std::string ConfigurationManager::addAccount (const std::map<std::string, std::string>& details) +std::string ConfigurationManager::addAccount(const std::map<std::string, std::string>& details) { - return Manager::instance().addAccount (details); + return Manager::instance().addAccount(details); } -void ConfigurationManager::removeAccount (const std::string& accoundID) +void ConfigurationManager::removeAccount(const std::string& accoundID) { - return Manager::instance().removeAccount (accoundID); + return Manager::instance().removeAccount(accoundID); } std::vector<std::string> ConfigurationManager::getAccountList() @@ -159,9 +155,9 @@ std::vector<std::string> ConfigurationManager::getAccountList() * Send the list of all codecs loaded to the client through DBus. * Can stay global, as only the active codecs will be set per accounts */ -std::vector<int32_t > ConfigurationManager::getAudioCodecList (void) +std::vector<int32_t > ConfigurationManager::getAudioCodecList() { - std::vector<int32_t> list(Manager::instance().audioCodecFactory.getAudioCodecList()); + std::vector<int32_t> list(Manager::instance().audioCodecFactory.getAudioCodecList()); if (list.empty()) errorAlert(CODECS_NOT_LOADED); @@ -169,40 +165,44 @@ std::vector<int32_t > ConfigurationManager::getAudioCodecList (void) return list; } -std::vector<std::string> ConfigurationManager::getSupportedTlsMethod (void) +std::vector<std::string> ConfigurationManager::getSupportedTlsMethod() { std::vector<std::string> method; - method.push_back ("Default"); - method.push_back ("TLSv1"); - method.push_back ("SSLv3"); - method.push_back ("SSLv23"); + method.push_back("Default"); + method.push_back("TLSv1"); + method.push_back("SSLv3"); + method.push_back("SSLv23"); return method; } -std::vector<std::string> ConfigurationManager::getAudioCodecDetails (const int32_t& payload) +std::vector<std::string> ConfigurationManager::getAudioCodecDetails(const int32_t& payload) { std::vector<std::string> result(Manager::instance().audioCodecFactory.getCodecSpecifications(payload)); + if (result.empty()) errorAlert(CODECS_NOT_LOADED); + return result; } -std::vector<int32_t> ConfigurationManager::getActiveAudioCodecList (const std::string& accountID) +std::vector<int32_t> ConfigurationManager::getActiveAudioCodecList(const std::string& accountID) { std::vector<int32_t> v; - Account *acc = Manager::instance().getAccount (accountID); + Account *acc = Manager::instance().getAccount(accountID); + if (acc) return acc->getActiveCodecs(); return v; } -void ConfigurationManager::setActiveAudioCodecList (const std::vector<std::string>& list, const std::string& accountID) +void ConfigurationManager::setActiveAudioCodecList(const std::vector<std::string>& list, const std::string& accountID) { - Account *acc = Manager::instance().getAccount (accountID); + Account *acc = Manager::instance().getAccount(accountID); + if (acc) { - acc->setActiveCodecs (list); + acc->setActiveCodecs(list); Manager::instance().saveConfig(); } } @@ -212,16 +212,16 @@ std::vector<std::string> ConfigurationManager::getAudioPluginList() { std::vector<std::string> v; - v.push_back (PCM_DEFAULT); - v.push_back (PCM_DMIX_DSNOOP); + v.push_back(PCM_DEFAULT); + v.push_back(PCM_DMIX_DSNOOP); return v; } -void ConfigurationManager::setAudioPlugin (const std::string& audioPlugin) +void ConfigurationManager::setAudioPlugin(const std::string& audioPlugin) { - return Manager::instance().setAudioPlugin (audioPlugin); + return Manager::instance().setAudioPlugin(audioPlugin); } std::vector<std::string> ConfigurationManager::getAudioOutputDeviceList() @@ -234,19 +234,19 @@ std::vector<std::string> ConfigurationManager::getAudioInputDeviceList() return Manager::instance().getAudioInputDeviceList(); } -void ConfigurationManager::setAudioOutputDevice (const int32_t& index) +void ConfigurationManager::setAudioOutputDevice(const int32_t& index) { - return Manager::instance().setAudioDevice (index, SFL_PCM_PLAYBACK); + return Manager::instance().setAudioDevice(index, SFL_PCM_PLAYBACK); } -void ConfigurationManager::setAudioInputDevice (const int32_t& index) +void ConfigurationManager::setAudioInputDevice(const int32_t& index) { - return Manager::instance().setAudioDevice (index, SFL_PCM_CAPTURE); + return Manager::instance().setAudioDevice(index, SFL_PCM_CAPTURE); } -void ConfigurationManager::setAudioRingtoneDevice (const int32_t& index) +void ConfigurationManager::setAudioRingtoneDevice(const int32_t& index) { - return Manager::instance().setAudioDevice (index, SFL_PCM_RINGTONE); + return Manager::instance().setAudioDevice(index, SFL_PCM_RINGTONE); } std::vector<std::string> ConfigurationManager::getCurrentAudioDevicesIndex() @@ -254,172 +254,172 @@ std::vector<std::string> ConfigurationManager::getCurrentAudioDevicesIndex() return Manager::instance().getCurrentAudioDevicesIndex(); } -int32_t ConfigurationManager::getAudioDeviceIndex (const std::string& name) +int32_t ConfigurationManager::getAudioDeviceIndex(const std::string& name) { - return Manager::instance().getAudioDeviceIndex (name); + return Manager::instance().getAudioDeviceIndex(name); } -std::string ConfigurationManager::getCurrentAudioOutputPlugin (void) +std::string ConfigurationManager::getCurrentAudioOutputPlugin() { - _debug ("ConfigurationManager: Get audio plugin %s", Manager::instance().getCurrentAudioOutputPlugin().c_str()); + DEBUG("ConfigurationManager: Get audio plugin %s", Manager::instance().getCurrentAudioOutputPlugin().c_str()); return Manager::instance().getCurrentAudioOutputPlugin(); } -std::string ConfigurationManager::getNoiseSuppressState (void) +std::string ConfigurationManager::getNoiseSuppressState() { return Manager::instance().getNoiseSuppressState(); } -void ConfigurationManager::setNoiseSuppressState (const std::string& state) +void ConfigurationManager::setNoiseSuppressState(const std::string& state) { - Manager::instance().setNoiseSuppressState (state); + Manager::instance().setNoiseSuppressState(state); } -std::string ConfigurationManager::getEchoCancelState(void) +std::string ConfigurationManager::getEchoCancelState() { - return Manager::instance().getEchoCancelState() ? "enabled" : "disabled"; + return Manager::instance().getEchoCancelState() ? "enabled" : "disabled"; } void ConfigurationManager::setEchoCancelState(const std::string& state) { - Manager::instance().setEchoCancelState(state); + Manager::instance().setEchoCancelState(state); } -int ConfigurationManager::getEchoCancelTailLength(void) +int ConfigurationManager::getEchoCancelTailLength() { - return Manager::instance().getEchoCancelTailLength(); + return Manager::instance().getEchoCancelTailLength(); } void ConfigurationManager::setEchoCancelTailLength(const int32_t& length) { - Manager::instance().setEchoCancelTailLength(length); + Manager::instance().setEchoCancelTailLength(length); } -int ConfigurationManager::getEchoCancelDelay(void) +int ConfigurationManager::getEchoCancelDelay() { - return Manager::instance().getEchoCancelDelay(); + return Manager::instance().getEchoCancelDelay(); } void ConfigurationManager::setEchoCancelDelay(const int32_t& delay) { - Manager::instance().setEchoCancelDelay(delay); + Manager::instance().setEchoCancelDelay(delay); } -int32_t ConfigurationManager::isIax2Enabled (void) +int32_t ConfigurationManager::isIax2Enabled() { return HAVE_IAX; } -std::string ConfigurationManager::getRecordPath (void) +std::string ConfigurationManager::getRecordPath() { return Manager::instance().getRecordPath(); } -void ConfigurationManager::setRecordPath (const std::string& recPath) +void ConfigurationManager::setRecordPath(const std::string& recPath) { - Manager::instance().setRecordPath (recPath); + Manager::instance().setRecordPath(recPath); } -bool ConfigurationManager::getIsAlwaysRecording(void) +bool ConfigurationManager::getIsAlwaysRecording() { - return Manager::instance().getIsAlwaysRecording(); + return Manager::instance().getIsAlwaysRecording(); } void ConfigurationManager::setIsAlwaysRecording(const bool& rec) { - Manager::instance().setIsAlwaysRecording(rec); + Manager::instance().setIsAlwaysRecording(rec); } -int32_t ConfigurationManager::getHistoryLimit (void) +int32_t ConfigurationManager::getHistoryLimit() { return Manager::instance().getHistoryLimit(); } -void ConfigurationManager::setHistoryLimit (const int32_t& days) +void ConfigurationManager::setHistoryLimit(const int32_t& days) { - Manager::instance().setHistoryLimit (days); + Manager::instance().setHistoryLimit(days); } -void ConfigurationManager::setAudioManager (const std::string& api) +void ConfigurationManager::setAudioManager(const std::string& api) { - Manager::instance().setAudioManager (api); + Manager::instance().setAudioManager(api); } -std::string ConfigurationManager::getAudioManager (void) +std::string ConfigurationManager::getAudioManager() { return Manager::instance().getAudioManager(); } -void ConfigurationManager::setMailNotify (void) +void ConfigurationManager::setMailNotify() { Manager::instance().setMailNotify(); } -int32_t ConfigurationManager::getMailNotify (void) +int32_t ConfigurationManager::getMailNotify() { return Manager::instance().getMailNotify(); } -std::map<std::string, int32_t> ConfigurationManager::getAddressbookSettings (void) +std::map<std::string, int32_t> ConfigurationManager::getAddressbookSettings() { return Manager::instance().getAddressbookSettings(); } -void ConfigurationManager::setAddressbookSettings (const std::map<std::string, int32_t>& settings) +void ConfigurationManager::setAddressbookSettings(const std::map<std::string, int32_t>& settings) { - Manager::instance().setAddressbookSettings (settings); + Manager::instance().setAddressbookSettings(settings); } -std::vector<std::string> ConfigurationManager::getAddressbookList (void) +std::vector<std::string> ConfigurationManager::getAddressbookList() { return Manager::instance().getAddressbookList(); } -void ConfigurationManager::setAddressbookList ( +void ConfigurationManager::setAddressbookList( const std::vector<std::string>& list) { - Manager::instance().setAddressbookList (list); + Manager::instance().setAddressbookList(list); } -std::map<std::string, std::string> ConfigurationManager::getHookSettings (void) +std::map<std::string, std::string> ConfigurationManager::getHookSettings() { return Manager::instance().getHookSettings(); } -void ConfigurationManager::setHookSettings (const std::map<std::string, +void ConfigurationManager::setHookSettings(const std::map<std::string, std::string>& settings) { - Manager::instance().setHookSettings (settings); + Manager::instance().setHookSettings(settings); } -void ConfigurationManager::setAccountsOrder (const std::string& order) +void ConfigurationManager::setAccountsOrder(const std::string& order) { - Manager::instance().setAccountsOrder (order); + Manager::instance().setAccountsOrder(order); } -std::vector<std::string> ConfigurationManager::getHistory (void) +std::vector<std::string> ConfigurationManager::getHistory() { return Manager::instance().getHistorySerialized(); } -void ConfigurationManager::setHistory (const std::vector<std::string>& entries) +void ConfigurationManager::setHistory(const std::vector<std::string>& entries) { Manager::instance().setHistorySerialized(entries); } -std::string ConfigurationManager::getAddrFromInterfaceName ( +std::string ConfigurationManager::getAddrFromInterfaceName( const std::string& interface) { - return SIPVoIPLink::getInterfaceAddrFromName (interface); + return SIPVoIPLink::getInterfaceAddrFromName(interface); } -std::vector<std::string> ConfigurationManager::getAllIpInterface (void) +std::vector<std::string> ConfigurationManager::getAllIpInterface() { return SIPVoIPLink::getAllIpInterface(); } -std::vector<std::string> ConfigurationManager::getAllIpInterfaceByName (void) +std::vector<std::string> ConfigurationManager::getAllIpInterfaceByName() { return SIPVoIPLink::getAllIpInterfaceByName(); } @@ -429,18 +429,19 @@ std::map<std::string, std::string> ConfigurationManager::getShortcuts() return Manager::instance().shortcutPreferences.getShortcuts(); } -void ConfigurationManager::setShortcuts ( +void ConfigurationManager::setShortcuts( const std::map<std::string, std::string>& shortcutsMap) { - Manager::instance().shortcutPreferences.setShortcuts (shortcutsMap); + Manager::instance().shortcutPreferences.setShortcuts(shortcutsMap); Manager::instance().saveConfig(); } -std::vector<std::map<std::string, std::string> > ConfigurationManager::getCredentials ( - const std::string& accountID) +std::vector<std::map<std::string, std::string> > ConfigurationManager::getCredentials( + const std::string& accountID) { - Account *account = Manager::instance().getAccount (accountID); + Account *account = Manager::instance().getAccount(accountID); std::vector<std::map<std::string, std::string> > credentialInformation; + if (!account or account->getType() != "SIP") return credentialInformation; @@ -448,10 +449,11 @@ std::vector<std::map<std::string, std::string> > ConfigurationManager::getCreden return sipaccount->getCredentials(); } -void ConfigurationManager::setCredentials (const std::string& accountID, +void ConfigurationManager::setCredentials(const std::string& accountID, const std::vector<std::map<std::string, std::string> >& details) { - Account *account = Manager::instance().getAccount (accountID); + Account *account = Manager::instance().getAccount(accountID); + if (account and account->getType() == "SIP") { SIPAccount *sipaccount = static_cast<SIPAccount*>(account); sipaccount->setCredentials(details); diff --git a/daemon/src/dbus/configurationmanager.h b/daemon/src/dbus/configurationmanager.h index 85556a3af3868a099beb3966437b21b02010598a..f3e03670176e22a0a86fdda460b9f2c3aa562512 100644 --- a/daemon/src/dbus/configurationmanager.h +++ b/daemon/src/dbus/configurationmanager.h @@ -40,108 +40,107 @@ #pragma GCC diagnostic ignored "-Wignored-qualifiers" #pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Weffc++" #include "configurationmanager-glue.h" #pragma GCC diagnostic warning "-Wignored-qualifiers" #pragma GCC diagnostic warning "-Wunused-parameter" +#pragma GCC diagnostic warning "-Weffc++" #if __GNUC__ >= 4 && __GNUC_MINOR__ >= 6 #pragma GCC diagnostic warning "-Wunused-but-set-variable" #endif -#include <dbus-c++/dbus.h> +#include "dbus_cpp.h" -class ConfigurationManager -: public org::sflphone::SFLphone::ConfigurationManager_adaptor, +class ConfigurationManager : + public org::sflphone::SFLphone::ConfigurationManager_adaptor, public DBus::IntrospectableAdaptor, - public DBus::ObjectAdaptor -{ - private: - std::vector<std::string> shortcutsKeys; + public DBus::ObjectAdaptor { public: - ConfigurationManager (DBus::Connection& connection); + ConfigurationManager(DBus::Connection& connection); static const char* SERVER_PATH; - std::map< std::string, std::string > getAccountDetails (const std::string& accountID); - void setAccountDetails (const std::string& accountID, const std::map< std::string, std::string >& details); - std::string addAccount (const std::map< std::string, std::string >& details); - void removeAccount (const std::string& accoundID); - void deleteAllCredential (const std::string& accountID); + std::map< std::string, std::string > getAccountDetails(const std::string& accountID); + void setAccountDetails(const std::string& accountID, const std::map< std::string, std::string >& details); + std::string addAccount(const std::map< std::string, std::string >& details); + void removeAccount(const std::string& accoundID); + void deleteAllCredential(const std::string& accountID); std::vector< std::string > getAccountList(); - void sendRegister (const std::string& accoundID , const int32_t& expire); + void sendRegister(const std::string& accoundID , const int32_t& expire); - std::map< std::string, std::string > getTlsSettingsDefault (void); + std::map< std::string, std::string > getTlsSettingsDefault(); - std::vector< int32_t > getAudioCodecList (void); - std::vector< std::string > getSupportedTlsMethod (void); - std::vector< std::string > getAudioCodecDetails (const int32_t& payload); - std::vector< int32_t > getActiveAudioCodecList (const std::string& accountID); - void setActiveAudioCodecList (const std::vector< std::string >& list, const std::string& accountID); + std::vector< int32_t > getAudioCodecList(); + std::vector< std::string > getSupportedTlsMethod(); + std::vector< std::string > getAudioCodecDetails(const int32_t& payload); + std::vector< int32_t > getActiveAudioCodecList(const std::string& accountID); + void setActiveAudioCodecList(const std::vector< std::string >& list, const std::string& accountID); std::vector< std::string > getAudioPluginList(); - void setAudioPlugin (const std::string& audioPlugin); + void setAudioPlugin(const std::string& audioPlugin); std::vector< std::string > getAudioOutputDeviceList(); - void setAudioOutputDevice (const int32_t& index); - void setAudioInputDevice (const int32_t& index); - void setAudioRingtoneDevice (const int32_t& index); + void setAudioOutputDevice(const int32_t& index); + void setAudioInputDevice(const int32_t& index); + void setAudioRingtoneDevice(const int32_t& index); std::vector< std::string > getAudioInputDeviceList(); std::vector< std::string > getCurrentAudioDevicesIndex(); - int32_t getAudioDeviceIndex (const std::string& name); - std::string getCurrentAudioOutputPlugin (void); - std::string getNoiseSuppressState (void); - void setNoiseSuppressState (const std::string& state); - std::string getEchoCancelState(void); + int32_t getAudioDeviceIndex(const std::string& name); + std::string getCurrentAudioOutputPlugin(); + std::string getNoiseSuppressState(); + void setNoiseSuppressState(const std::string& state); + std::string getEchoCancelState(); void setEchoCancelState(const std::string& state); void setEchoCancelTailLength(const int32_t& length); - int getEchoCancelTailLength(void); + int getEchoCancelTailLength(); void setEchoCancelDelay(const int32_t& length); - int getEchoCancelDelay(void); + int getEchoCancelDelay(); - std::string getAudioManager (void); - void setAudioManager (const std::string& api); + std::string getAudioManager(); + void setAudioManager(const std::string& api); - int32_t isIax2Enabled (void); - std::string getRecordPath (void); - void setRecordPath (const std::string& recPath); - bool getIsAlwaysRecording(void); + int32_t isIax2Enabled(); + std::string getRecordPath(); + void setRecordPath(const std::string& recPath); + bool getIsAlwaysRecording(); void setIsAlwaysRecording(const bool& rec); - void setHistoryLimit (const int32_t& days); - int32_t getHistoryLimit (void); + void setHistoryLimit(const int32_t& days); + int32_t getHistoryLimit(); - int32_t getMailNotify (void); - void setMailNotify (void); + int32_t getMailNotify(); + void setMailNotify(); - std::map<std::string, int32_t> getAddressbookSettings (void); - void setAddressbookSettings (const std::map<std::string, int32_t>& settings); - std::vector< std::string > getAddressbookList (void); - void setAddressbookList (const std::vector< std::string >& list); + std::map<std::string, int32_t> getAddressbookSettings(); + void setAddressbookSettings(const std::map<std::string, int32_t>& settings); + std::vector< std::string > getAddressbookList(); + void setAddressbookList(const std::vector< std::string >& list); - void setAccountsOrder (const std::string& order); + void setAccountsOrder(const std::string& order); - std::map<std::string, std::string> getHookSettings (void); - void setHookSettings (const std::map<std::string, std::string>& settings); + std::map<std::string, std::string> getHookSettings(); + void setHookSettings(const std::map<std::string, std::string>& settings); - std::vector<std::string> getHistory(void); - void setHistory (const std::vector<std::string> &entries); + std::vector<std::string> getHistory(); + void setHistory(const std::vector<std::string> &entries); - std::map<std::string, std::string> getTlsSettings (void); - void setTlsSettings (const std::map< std::string, std::string >& details); - std::map< std::string, std::string > getIp2IpDetails (void); + std::map<std::string, std::string> getTlsSettings(); + void setTlsSettings(const std::map< std::string, std::string >& details); + std::map< std::string, std::string > getIp2IpDetails(); - std::vector< std::map< std::string, std::string > > getCredentials (const std::string& accountID); - void setCredentials (const std::string& accountID, const std::vector< std::map< std::string, std::string > >& details); + std::vector< std::map< std::string, std::string > > getCredentials(const std::string& accountID); + void setCredentials(const std::string& accountID, const std::vector< std::map< std::string, std::string > >& details); - std::string getAddrFromInterfaceName (const std::string& interface); + std::string getAddrFromInterfaceName(const std::string& interface); - std::vector<std::string> getAllIpInterface (void); - std::vector<std::string> getAllIpInterfaceByName (void); + std::vector<std::string> getAllIpInterface(); + std::vector<std::string> getAllIpInterfaceByName(); - std::map< std::string, std::string > getShortcuts (); - void setShortcuts (const std::map< std::string, std::string >& shortcutsMap); + std::map< std::string, std::string > getShortcuts(); + void setShortcuts(const std::map< std::string, std::string >& shortcutsMap); }; - #endif//CONFIGURATIONMANAGER_H + diff --git a/daemon/src/plug-in/plugin.h b/daemon/src/dbus/dbus_cpp.h similarity index 58% rename from daemon/src/plug-in/plugin.h rename to daemon/src/dbus/dbus_cpp.h index 65cf8509bf6810394ea2de40ec9c31c23082803c..f1c9031043fda3d0683a3d84aa1593255b1708c3 100644 --- a/daemon/src/plug-in/plugin.h +++ b/daemon/src/dbus/dbus_cpp.h @@ -1,6 +1,6 @@ /* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. - * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> + * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. + * Author: Tristan Matthews <tristan.matthews@savoirfairelinux.com> * * 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 @@ -27,49 +27,17 @@ * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ - - -#ifndef PLUGIN_H -#define PLUGIN_H - -#include "global.h" - -#include "pluginmanager.h" - -/* - * @file plugin.h - * @brief Define a plugin object - */ - -class Plugin -{ - - public: - Plugin (const std::string &name) { - _name = name; - } - - virtual ~Plugin() {} - - std::string getPluginName (void) const { - return _name; - } - - /** - * Return the minimal core version required so that the plugin could work - * @return int The version required - */ - virtual int initFunc (PluginInfo **info) = 0; - - private: - Plugin &operator = (const Plugin &plugin); - - std::string _name; -}; - -typedef Plugin* createFunc (void); - -typedef void destroyFunc (Plugin*); - -#endif //PLUGIN_H - +#ifndef DBUS_CPP_WRAPPER_H_ +#define DBUS_CPP_WRAPPER_H_ + +#pragma GCC diagnostic ignored "-Wshadow" +#pragma GCC diagnostic ignored "-Wignored-qualifiers" +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Weffc++" +#include <dbus-c++/dbus.h> +#pragma GCC diagnostic warning "-Wignored-qualifiers" +#pragma GCC diagnostic warning "-Wshadow" +#pragma GCC diagnostic warning "-Wunused-parameter" +#pragma GCC diagnostic warning "-Weffc++" + +#endif // DBUS_CPP_WRAPPER_H_ diff --git a/daemon/src/dbus/dbusmanager.cpp b/daemon/src/dbus/dbusmanager.cpp index 37a12ad3b216fb8ef558690360a5545be224f5c9..5d273fab9064575af63c625cedee100725088c09 100644 --- a/daemon/src/dbus/dbusmanager.cpp +++ b/daemon/src/dbus/dbusmanager.cpp @@ -29,7 +29,7 @@ */ #include <cstdlib> -#include <dbusmanager.h> +#include "dbusmanager.h" #include "global.h" #include "manager.h" #include "instance.h" @@ -38,47 +38,53 @@ #include "configurationmanager.h" #include "networkmanager.h" -DBusManager::DBusManager() +DBusManager::DBusManager() : callManager_(0) + , configurationManager_(0) + , instanceManager_(0) + , dispatcher_() +#if USE_NETWORKMANAGER + , networkManager_(0) +#endif { try { DBus::_init_threading(); - DBus::default_dispatcher = &_dispatcher; + DBus::default_dispatcher = &dispatcher_; DBus::Connection sessionConnection = DBus::Connection::SessionBus(); - sessionConnection.request_name ("org.sflphone.SFLphone"); + sessionConnection.request_name("org.sflphone.SFLphone"); - _callManager = new CallManager (sessionConnection); - _configurationManager = new ConfigurationManager (sessionConnection); - _instanceManager = new Instance (sessionConnection); + callManager_ = new CallManager(sessionConnection); + configurationManager_ = new ConfigurationManager(sessionConnection); + instanceManager_ = new Instance(sessionConnection); #ifdef USE_NETWORKMANAGER DBus::Connection systemConnection = DBus::Connection::SystemBus(); - _networkManager = new NetworkManager (systemConnection, "/org/freedesktop/NetworkManager", ""); + networkManager_ = new NetworkManager(systemConnection, "/org/freedesktop/NetworkManager", ""); #endif } catch (const DBus::Error &err) { - _error("%s: %s, exiting\n", err.name(), err.what()); - ::exit(1); + ERROR("%s: %s, exiting\n", err.name(), err.what()); + ::exit(EXIT_FAILURE); } } DBusManager::~DBusManager() { #ifdef USE_NETWORKMANAGER - delete _networkManager; + delete networkManager_; #endif - delete _instanceManager; - delete _configurationManager; - delete _callManager; + delete instanceManager_; + delete configurationManager_; + delete callManager_; } void DBusManager::exec() { - _dispatcher.enter(); + dispatcher_.enter(); } void DBusManager::exit() { - _dispatcher.leave(); + dispatcher_.leave(); } diff --git a/daemon/src/dbus/dbusmanager.h b/daemon/src/dbus/dbusmanager.h index 61a6f57144ba390bcd3f448e8ffa069d1553b0a2..f471f3b0fb0eff174a8844cbb23f2f46dcc2b8d8 100644 --- a/daemon/src/dbus/dbusmanager.h +++ b/daemon/src/dbus/dbusmanager.h @@ -31,39 +31,37 @@ #ifndef __DBUSMANAGERIMPL_H__ #define __DBUSMANAGERIMPL_H__ -#pragma GCC diagnostic ignored "-Wignored-qualifiers" -#pragma GCC diagnostic ignored "-Wunused-parameter" -#include <dbus-c++/dbus.h> -#pragma GCC diagnostic warning "-Wignored-qualifiers" -#pragma GCC diagnostic warning "-Wunused-parameter" +#include "dbus_cpp.h" +#include "noncopyable.h" + class ConfigurationManager; class CallManager; class NetworkManager; class Instance; -class DBusManager -{ +class DBusManager { public: - DBusManager(); - ~DBusManager(); + DBusManager(); + ~DBusManager(); - CallManager * getCallManager() const { - return _callManager; + CallManager * getCallManager() { + return callManager_; }; - ConfigurationManager * getConfigurationManager() const { - return _configurationManager; + ConfigurationManager * getConfigurationManager() { + return configurationManager_; }; void exec(); void exit(); private: - CallManager* _callManager; - ConfigurationManager* _configurationManager; - Instance* _instanceManager; - DBus::BusDispatcher _dispatcher; + NON_COPYABLE(DBusManager); + CallManager* callManager_; + ConfigurationManager* configurationManager_; + Instance* instanceManager_; + DBus::BusDispatcher dispatcher_; #if USE_NETWORKMANAGER - NetworkManager* _networkManager; + NetworkManager* networkManager_; #endif }; diff --git a/daemon/src/dbus/instance.cpp b/daemon/src/dbus/instance.cpp index 266b1b86cf97309032bd2a0ee10e7b4b343cd3ed..09185ad926865dcea0ec1a8471ed533782a73764 100644 --- a/daemon/src/dbus/instance.cpp +++ b/daemon/src/dbus/instance.cpp @@ -27,28 +27,27 @@ * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ -#include <global.h> -#include <instance.h> +#include "global.h" +#include "instance.h" #include "../manager.h" -Instance::Instance (DBus::Connection& connection) - : DBus::ObjectAdaptor (connection, "/org/sflphone/SFLphone/Instance") -{ - count = 0; -} +Instance::Instance(DBus::Connection& connection) : + DBus::ObjectAdaptor(connection, "/org/sflphone/SFLphone/Instance"), + count(0) +{} void -Instance::Register (const int32_t& pid UNUSED, - const std::string& name UNUSED) +Instance::Register(const int32_t& pid UNUSED, + const std::string& name UNUSED) { - count++; + ++count; } void -Instance::Unregister (const int32_t& pid UNUSED) +Instance::Unregister(const int32_t& pid UNUSED) { - count --; + --count; if (count <= 0) { Manager::instance().terminate(); diff --git a/daemon/src/dbus/instance.h b/daemon/src/dbus/instance.h index 0258d7fdcd8f16be390979a524f83350bbe0a57c..31c82d29e96652267ef03eb6680baf43ac22797a 100644 --- a/daemon/src/dbus/instance.h +++ b/daemon/src/dbus/instance.h @@ -34,6 +34,7 @@ #if __GNUC__ >= 4 && __GNUC_MINOR__ >= 6 #pragma GCC diagnostic ignored "-Wunused-but-set-variable" #endif +#include "dbus_cpp.h" #pragma GCC diagnostic ignored "-Wignored-qualifiers" #pragma GCC diagnostic ignored "-Wunused-parameter" @@ -44,24 +45,20 @@ #pragma GCC diagnostic warning "-Wunused-but-set-variable" #endif -#include <dbus-c++/dbus.h> - - class Instance : public org::sflphone::SFLphone::Instance_adaptor, public DBus::IntrospectableAdaptor, - public DBus::ObjectAdaptor -{ + public DBus::ObjectAdaptor { private: int count; public: - Instance (DBus::Connection& connection); + Instance(DBus::Connection& connection); static const char* SERVER_PATH; - void Register (const int32_t& pid, const std::string& name); - void Unregister (const int32_t& pid); - int32_t getRegistrationCount (void); + void Register(const int32_t& pid, const std::string& name); + void Unregister(const int32_t& pid); + int32_t getRegistrationCount(); }; diff --git a/daemon/src/dbus/networkmanager.cpp b/daemon/src/dbus/networkmanager.cpp index 32b0d52e007a63c8612959bea1ce566c37fd227e..9f7288069262b05e94ad927d373d821a100c6235 100644 --- a/daemon/src/dbus/networkmanager.cpp +++ b/daemon/src/dbus/networkmanager.cpp @@ -28,33 +28,35 @@ * as that of the covered work. */ -#include <global.h> #include "networkmanager.h" + #include <iostream> -#include <instance.h> + +#include "global.h" +#include "instance.h" #include "../manager.h" const std::string NetworkManager::statesString[5] = {"unknown", "asleep", "connecting", "connected", "disconnected"}; -std::string NetworkManager::stateAsString (const uint32_t& state) +std::string NetworkManager::stateAsString(const uint32_t& state) { return statesString[state]; } -void NetworkManager::StateChanged (const uint32_t& state) +void NetworkManager::StateChanged(const uint32_t& state) { - _warn ("Network state changed: %s", stateAsString (state).c_str()); + WARN("Network state changed: %s", stateAsString(state).c_str()); } -void NetworkManager::PropertiesChanged (const std::map< std::string, ::DBus::Variant >& argin0) +void NetworkManager::PropertiesChanged(const std::map< std::string, ::DBus::Variant >& argin0) { const std::map< std::string, ::DBus::Variant >::const_iterator iter = argin0.begin(); - _warn ("Properties changed: %s", iter->first.c_str()); + WARN("Properties changed: %s", iter->first.c_str()); Manager::instance().registerAccounts(); } -NetworkManager::NetworkManager (DBus::Connection& connection, const DBus::Path& path, const char* destination) : DBus::ObjectProxy (connection, path, destination) +NetworkManager::NetworkManager(DBus::Connection& connection, const DBus::Path& dbus_path, const char* destination) : DBus::ObjectProxy(connection, dbus_path, destination) { } diff --git a/daemon/src/dbus/networkmanager.h b/daemon/src/dbus/networkmanager.h index 2c77f5dbfb7d7913981aa82aa68a4ebd9c74cfa2..4bc5ca48eefc831e46cb8f454b3bf9459403c703 100644 --- a/daemon/src/dbus/networkmanager.h +++ b/daemon/src/dbus/networkmanager.h @@ -40,14 +40,13 @@ class NetworkManager : public org::freedesktop::NetworkManager_proxy, public DBus::IntrospectableProxy, - public DBus::ObjectProxy -{ + public DBus::ObjectProxy { public: - NetworkManager (DBus::Connection&, const DBus::Path&, const char*); - void StateChanged (const uint32_t& state); - void PropertiesChanged (const std::map< std::string, ::DBus::Variant >& argin0); - std::string stateAsString (const uint32_t& state); + NetworkManager(DBus::Connection&, const DBus::Path&, const char*); + void StateChanged(const uint32_t& state); + void PropertiesChanged(const std::map< std::string, ::DBus::Variant >& argin0); + std::string stateAsString(const uint32_t& state); enum NMState { NM_STATE_UNKNOWN = 0, diff --git a/daemon/src/dbus/networkmanager_proxy.h b/daemon/src/dbus/networkmanager_proxy.h index a87e4fe6fe5ed37c2e849f88d4bb00b090542767..56ee150934c0ba08b72908d865d616bd5714e1ad 100644 --- a/daemon/src/dbus/networkmanager_proxy.h +++ b/daemon/src/dbus/networkmanager_proxy.h @@ -6,23 +6,19 @@ #ifndef __dbusxx__networkmanager_proxy_h__PROXY_MARSHAL_H #define __dbusxx__networkmanager_proxy_h__PROXY_MARSHAL_H -#include <dbus-c++/dbus.h> -#include <cassert> +#include "dbus_cpp.h" -namespace org -{ -namespace freedesktop -{ +namespace org { +namespace freedesktop { class NetworkManager_proxy - : public ::DBus::InterfaceProxy -{ + : public ::DBus::InterfaceProxy { public: NetworkManager_proxy() - : ::DBus::InterfaceProxy ("org.freedesktop.NetworkManager") { - connect_signal (NetworkManager_proxy, StateChanged, _StateChanged_stub); - connect_signal (NetworkManager_proxy, PropertiesChanged, _PropertiesChanged_stub); + : ::DBus::InterfaceProxy("org.freedesktop.NetworkManager") { + connect_signal(NetworkManager_proxy, StateChanged, _StateChanged_stub); + connect_signal(NetworkManager_proxy, PropertiesChanged, _PropertiesChanged_stub); } public: @@ -35,8 +31,8 @@ class NetworkManager_proxy */ std::vector< ::DBus::Path > GetDevices() { ::DBus::CallMessage call; - call.member ("GetDevices"); - ::DBus::Message ret = invoke_method (call); + call.member("GetDevices"); + ::DBus::Message ret = invoke_method(call); ::DBus::MessageIter ri = ret.reader(); std::vector< ::DBus::Path > argout; @@ -49,26 +45,26 @@ class NetworkManager_proxy /* signal handlers for this interface */ - virtual void StateChanged (const uint32_t& argin0) = 0; - virtual void PropertiesChanged (const std::map< std::string, ::DBus::Variant >& argin0) = 0; + virtual void StateChanged(const uint32_t& argin0) = 0; + virtual void PropertiesChanged(const std::map< std::string, ::DBus::Variant >& argin0) = 0; private: /* unmarshalers (to unpack the DBus message before calling the actual signal handler) */ - void _StateChanged_stub (const ::DBus::SignalMessage &sig) { + void _StateChanged_stub(const ::DBus::SignalMessage &sig) { ::DBus::MessageIter ri = sig.reader(); uint32_t arg0; ri >> arg0; - StateChanged (arg0); + StateChanged(arg0); } - void _PropertiesChanged_stub (const ::DBus::SignalMessage &sig) { + void _PropertiesChanged_stub(const ::DBus::SignalMessage &sig) { ::DBus::MessageIter ri = sig.reader(); std::map< std::string, ::DBus::Variant > arg0; ri >> arg0; - PropertiesChanged (arg0); + PropertiesChanged(arg0); } }; diff --git a/daemon/src/eventthread.cpp b/daemon/src/eventthread.cpp index 39db9f4087bed54042fe550d7b926503e38b95b2..bb72e8505b2ff4bab2e4ef925d7755238a92e915 100644 --- a/daemon/src/eventthread.cpp +++ b/daemon/src/eventthread.cpp @@ -32,19 +32,19 @@ #include "voiplink.h" /********************************** Voiplink thread *************************************/ -EventThread::EventThread (VoIPLink *link) - : Thread(), _link (link) +EventThread::EventThread(VoIPLink *link) + : Thread(), link_(link) { - setCancel (cancelDeferred); + setCancel(cancelDeferred); } /** * Reimplementation of run() */ -void EventThread::run (void) +void EventThread::run() { while (!testCancel()) - _link->getEvent(); + link_->getEvent(); } diff --git a/daemon/src/eventthread.h b/daemon/src/eventthread.h index 7a365b0b6b690e743884da8467ae71df8f2a52b7..34e678bc206f339574ab5c74f7b5e02ea0c88df9 100644 --- a/daemon/src/eventthread.h +++ b/daemon/src/eventthread.h @@ -32,7 +32,7 @@ #define __EVENT_THREAD_H__ #include <cc++/thread.h> - +#include "noncopyable.h" class VoIPLink; @@ -41,26 +41,21 @@ class VoIPLink; * @brief General thread to listen events continuously */ -class EventThread : public ost::Thread -{ +class EventThread : public ost::Thread { public: - /** - * Thread constructor - */ - EventThread (VoIPLink* link); + EventThread(VoIPLink* link); - ~EventThread (void) { + ~EventThread() { terminate(); } - virtual void run () ; + virtual void run() ; private: - EventThread (const EventThread& rh); // copy constructor - EventThread& operator= (const EventThread& rh); // assignment operator + NON_COPYABLE(EventThread); - /** VoIPLink is the object being called by getEvents() method */ - VoIPLink* _link; + // VoIPLink is the object being called by getEvents() method + VoIPLink* link_; }; #endif // __EVENT_THREAD_H__ diff --git a/daemon/src/fileutils.cpp b/daemon/src/fileutils.cpp index 29d1149bed5bd69042cb22535196884365f79e0d..60279ec6393284627c650804b739a785ac15c0c7 100644 --- a/daemon/src/fileutils.cpp +++ b/daemon/src/fileutils.cpp @@ -38,7 +38,7 @@ void set_program_dir(char *program_path) program_dir = dirname(program_path); } -const char *get_program_dir(void) +const char *get_program_dir() { return program_dir; } diff --git a/daemon/src/fileutils.h b/daemon/src/fileutils.h index 364e80a23323f75729edc6ba3ecab90b18fab803..92f99a6a28a17763f20cf276c78728e980d31bcc 100644 --- a/daemon/src/fileutils.h +++ b/daemon/src/fileutils.h @@ -32,6 +32,6 @@ #define __FILEUTILS_H__ void set_program_dir(char *program_path); -const char *get_program_dir(void); +const char *get_program_dir(); #endif // __FILEUTILS_H__ diff --git a/daemon/src/global.h b/daemon/src/global.h index b7d8458aa872f386a33e8e552f01b4dae30033b1..ef8b085fe4dcce223cc4c254cd4007aae3149ceb 100644 --- a/daemon/src/global.h +++ b/daemon/src/global.h @@ -49,38 +49,13 @@ #define XDG_CACHE_HOME (getenv ("XDG_CACHE_HOME")) const char * const ZRTP_ZID_FILENAME = "sfl.zid"; -typedef float float32; -typedef short int16; - //useful typedefs. typedef signed short SINT16; typedef signed int SINT32; -typedef unsigned long FILE_TYPE; -typedef unsigned long SOUND_FORMAT; - -const FILE_TYPE FILE_RAW = 1; -const FILE_TYPE FILE_WAV = 2; - -static const SOUND_FORMAT INT16 = 0x2; // TODO shold change these symbols -static const SOUND_FORMAT INT32 = 0x8; - #define PIDFILE "sfl.pid" -#ifdef DATAFORMAT_IS_FLOAT -#define SFLDataFormat float32 -#define SFLDataFormatString "Float32" -#define SFLDataAmplitude 0.05 -#else -#define SFLDataFormat int16 -#define SFLDataFormatString "Int16" -#define SFLDataAmplitude (32767 >> 4) -#endif - -#define PROGNAME "sflphoned" /** Binary name */ -#define PROGDIR "sflphone" /** Program directory */ -#define RINGDIR "ringtones" /** Ringtones directory */ -#define CODECDIR "codecs" /** Codecs directory */ +typedef short SFLDataFormat; #define SIZEBUF 400000 /** About 12 sec of buffering at 8000 Hz*/ @@ -92,19 +67,11 @@ static const SOUND_FORMAT INT32 = 0x8; #define PCM_DSNOOP "plug:dsnoop" /** Alsa plugin for microphone sharing */ #define PCM_DMIX_DSNOOP "dmix/dsnoop" /** Audio profile using Alsa dmix/dsnoop */ -#define SFL_CODEC_VALID_PREFIX "libcodec_" /** Valid prefix for codecs shared library */ -#define SFL_CODEC_VALID_EXTEN ".so" /** Valid extension for codecs shared library */ -#define CURRENT_DIR "." /** Current directory */ -#define PARENT_DIR ".." /** Parent directory */ - #define SFL_PCM_BOTH 0x0021 /** To open both playback and capture devices */ #define SFL_PCM_PLAYBACK 0x0022 /** To open playback device only */ #define SFL_PCM_CAPTURE 0x0023 /** To open capture device only */ -#define SFL_PCM_RINGTONE 0x0024 +#define SFL_PCM_RINGTONE 0x0024 -#define GSM_STRING_DESCRIPTION "gsm" /** GSM codec string description */ -#define SPEEX_STRING_DESCRIPTION "speex" /** SPEEX codec string description */ -#define ILBC_STRING_DESCRIPTION "ilbc" /** Ilbc codec string description */ #define RINGTONE_ENABLED TRUE_STR /** Custom ringtone enable or not */ #define DISPLAY_DIALPAD TRUE_STR /** Display dialpad or not */ #define DISPLAY_VOLUME_CONTROLS TRUE_STR /** Display the volume controls or not */ @@ -126,9 +93,6 @@ static const SOUND_FORMAT INT32 = 0x8; #define DEFAULT_SIP_PORT 5060 #define DEFAULT_SIP_TLS_PORT 5061 -#define HOOK_DEFAULT_SIP_FIELD "X-sflphone-url" -#define HOOK_DEFAULT_URL_COMMAND "x-www-browser" - /** Enumeration that contains known audio payloads */ enum { // http://www.iana.org/assignments/rtp-parameters diff --git a/daemon/src/history/historyitem.cpp b/daemon/src/history/historyitem.cpp index ae6440941017f62d2c776c1f52143225f651741f..738c7cf4a441b9d64e175c79d24b9b82c659a3d6 100644 --- a/daemon/src/history/historyitem.cpp +++ b/daemon/src/history/historyitem.cpp @@ -30,85 +30,84 @@ * as that of the covered work. */ -#include <historyitem.h> +#include "historyitem.h" #include <sstream> -#include "stdlib.h" -#include <manager.h> - -#define ITEM_SEPARATOR "|" - -HistoryItem::HistoryItem (std::string timestamp_start, CallType call_type, std::string timestamp_stop, std::string name, std::string number, std::string id, std::string account_id, std::string recording, std::string confID, std::string timeAdded) - : _timestamp_start (timestamp_start), - _timestamp_stop (timestamp_stop), - _call_type (call_type), - _name (name), - _number (number), - _id(id), - _account_id (account_id), - _recording_file(recording), - _confID(confID), - _timeAdded(timeAdded) +#include <cstdlib> +#include "manager.h" + +static const char * const ITEM_SEPARATOR = "|"; + +HistoryItem::HistoryItem(const std::string ×tamp_start, + CallType call_type, const std::string ×tamp_stop, + const std::string &name, const std::string &number, + const std::string &id, const std::string &account_id, + const std::string &recording, + const std::string &confID, + const std::string &timeAdded) + : timestamp_start_(timestamp_start), + timestamp_stop_(timestamp_stop), + call_type_(call_type), + name_(name), + number_(number), + id_(id), + account_id_(account_id), + recording_file_(recording), + confID_(confID), + timeAdded_(timeAdded) +{} + + +HistoryItem::HistoryItem(std::string serialized_form) : + timestamp_start_(), timestamp_stop_(), call_type_(CALL_MISSED), name_(), + number_(), id_(), account_id_(), recording_file_(), confID_(), timeAdded_() { -} - - -HistoryItem::HistoryItem (std::string serialized_form) -{ - int indice = 0; - - while (serialized_form.find (ITEM_SEPARATOR, 0) != std::string::npos) { - size_t pos = serialized_form.find (ITEM_SEPARATOR, 0); - std::string tmp = serialized_form.substr (0, pos); - serialized_form.erase (0, pos + 1); - - switch (indice) { - case 0: // The call type - _call_type = (CallType) atoi (tmp.c_str()); - break; - case 1: // The number field - _number = tmp; - break; - case 2: // The name field - _name = tmp; - if (_name == "empty") - _name = ""; - break; - case 3: // The start timestamp - _timestamp_start = tmp; - break; - case 4: // The end timestamp - _timestamp_stop = tmp; - break; - case 5: // The ID - _id = tmp; - break; - case 6: // The account ID - _account_id = tmp; - break; - case 7: // The recorded file name - _recording_file = tmp; - break; - case 8: // The conference ID - _confID = tmp; - break; - case 9: // The time - _timeAdded = tmp; - break; - default: // error - _error("Unserialized form %d not recognized\n", indice); - break; + for (int index = 0; serialized_form.find(ITEM_SEPARATOR, 0) != std::string::npos; ++index) { + size_t pos = serialized_form.find(ITEM_SEPARATOR, 0); + std::string tmp(serialized_form.substr(0, pos)); + serialized_form.erase(0, pos + 1); + + switch (index) { + case 0: // The call type + call_type_ = (CallType) atoi(tmp.c_str()); + break; + case 1: // The number field + number_ = tmp; + break; + case 2: // The name field + name_ = tmp; + + if (name_ == "empty") + name_ = ""; + break; + case 3: // The start timestamp + timestamp_start_ = tmp; + break; + case 4: // The end timestamp + timestamp_stop_ = tmp; + break; + case 5: // The ID + id_ = tmp; + break; + case 6: // The account ID + account_id_ = tmp; + break; + case 7: // The recorded file name + recording_file_ = tmp; + break; + case 8: // The conference ID + confID_ = tmp; + break; + case 9: // the time + timeAdded_ = tmp; + break; + default: // error + ERROR("Unserialized form %d not recognized\n", index); + break; } - - indice ++; } } -HistoryItem::~HistoryItem () -{ - // TODO -} - -bool HistoryItem::save (Conf::ConfigTree **history) +bool HistoryItem::save(Conf::ConfigTree **history) { std::stringstream section; std::stringstream call_type; @@ -116,57 +115,45 @@ bool HistoryItem::save (Conf::ConfigTree **history) // The section is : "[" + timestamp = "]" section << rand(); std::string sectionstr = section.str(); - call_type << _call_type; - - /* - _error("-- Unserialized type: %s", call_type.str().c_str()); - _error("-- Unserialized time start: %s", _timestamp_start.c_str()); - _error("-- Unserialized time stop: %s", _timestamp_stop.c_str()); - _error("-- Unserialized number: %s", _number.c_str()); - _error("-- Unserialized id: %s", _id.c_str()); - _error("-- Unserialized account: %s", _account_id.c_str()); - _error("-- Unserialized name: %s", _name.c_str()); - _error("-- Unserialized record file: %s", _recording_file.c_str()); - _error("-- Unserialized conference id:%s", _confID.c_str()); - _error("-- Unserialized time added: %s", _timeAdded.c_str()); - */ - - return (*history)->setConfigTreeItem (sectionstr, "type", call_type.str()) - && (*history)->setConfigTreeItem (sectionstr, "timestamp_start", _timestamp_start) - && (*history)->setConfigTreeItem (sectionstr, "timestamp_stop", _timestamp_stop) - && (*history)->setConfigTreeItem (sectionstr, "number", _number) - && (*history)->setConfigTreeItem (sectionstr, "id", _id) - && (*history)->setConfigTreeItem (sectionstr, "accountid", _account_id) - && (*history)->setConfigTreeItem (sectionstr, "name", _name) - && (*history)->setConfigTreeItem (sectionstr, "recordfile", _recording_file) - && (*history)->setConfigTreeItem (sectionstr, "confid", _confID) - && (*history)->setConfigTreeItem (sectionstr, "timeadded", _timeAdded); + call_type << call_type_; + + return (*history)->setConfigTreeItem(sectionstr, "type", call_type.str()) + && (*history)->setConfigTreeItem(sectionstr, "timestamp_start", timestamp_start_) + && (*history)->setConfigTreeItem(sectionstr, "timestamp_stop", timestamp_stop_) + && (*history)->setConfigTreeItem(sectionstr, "number", number_) + && (*history)->setConfigTreeItem(sectionstr, "id", id_) + && (*history)->setConfigTreeItem(sectionstr, "accountid", account_id_) + && (*history)->setConfigTreeItem(sectionstr, "name", name_) + && (*history)->setConfigTreeItem(sectionstr, "recordfile", recording_file_) + && (*history)->setConfigTreeItem(sectionstr, "confid", confID_) + && (*history)->setConfigTreeItem(sectionstr, "timeadded", timeAdded_); } -std::string HistoryItem::serialize (void) +std::string HistoryItem::serialize() const { - std::stringstream res; - // Replace empty string with a valid standard string value - std::string name(_name); - if (name == "") - name = "empty"; + std::string name(name_); + + if (name.empty()) + name = "empty"; // For the account ID, check also if the accountID corresponds to an existing account // ie the account may have been removed - std::string accountID(_account_id); - if (_account_id == "" || not valid_account (_account_id)) - accountID = "empty"; + std::string accountID(account_id_); + + if (account_id_.empty() or not valid_account(account_id_)) + accountID = "empty"; + std::stringstream res; // Serialize it - res << _call_type << ITEM_SEPARATOR << _number << ITEM_SEPARATOR << name << ITEM_SEPARATOR << _timestamp_start << ITEM_SEPARATOR << _timestamp_stop - << ITEM_SEPARATOR << _id << ITEM_SEPARATOR << accountID << ITEM_SEPARATOR << _recording_file << ITEM_SEPARATOR << _confID << ITEM_SEPARATOR << _timeAdded; + res << call_type_ << ITEM_SEPARATOR << number_ << ITEM_SEPARATOR << name << ITEM_SEPARATOR << timestamp_start_ << ITEM_SEPARATOR << timestamp_stop_ + << ITEM_SEPARATOR << id_ << ITEM_SEPARATOR << accountID << ITEM_SEPARATOR << recording_file_ << ITEM_SEPARATOR << confID_ << ITEM_SEPARATOR << timeAdded_; return res.str(); } -bool HistoryItem::valid_account (std::string id) +bool HistoryItem::valid_account(const std::string &id) const { - return Manager::instance().accountExists (id); + return Manager::instance().accountExists(id); } diff --git a/daemon/src/history/historyitem.h b/daemon/src/history/historyitem.h index c935c82d152c4d947b7ffb09f14d48e3223950d9..a7cfeef7b65015ae94aa06afbfee17c396f4081b 100644 --- a/daemon/src/history/historyitem.h +++ b/daemon/src/history/historyitem.h @@ -30,12 +30,11 @@ * as that of the covered work. */ -#ifndef _HISTORY_ITEM -#define _HISTORY_ITEM +#ifndef HISTORY_ITEM_H_ +#define HISTORY_ITEM_H_ #include <string> #include <config/config.h> -#include <iostream> typedef enum CallType { CALL_MISSED, @@ -43,95 +42,90 @@ typedef enum CallType { CALL_OUTGOING } CallType; - -class HistoryItem -{ +class HistoryItem { public: /* * Constructor - * + * * @param Timestamp start * @param Call type * @param Timestamp stop * @param Call name * @param Call number - * @param Call id + * @param Call id * @param Call account id - * @param Recording file name (if any recording were performed) - * @param Configuration ID - * @param time added + * @param Recording file name (if any recording were performed) + * @param Configuration ID + * @param time added */ - HistoryItem (std::string, CallType, std::string, std::string, std::string, std::string, std::string, std::string, std::string, std::string); + HistoryItem(const std::string&, CallType, const std::string&, + const std::string&, const std::string&, const std::string&, + const std::string&, const std::string&, const std::string&, + const std::string&); /* * Constructor from a serialized form - * @string contaning serialized form - */ - HistoryItem (std::string=""); - - /* - * Destructor + * @string contaning serialized form */ - ~HistoryItem (); + HistoryItem(std::string=""); - std::string get_timestamp () const { - return _timestamp_start; + std::string get_timestamp() const { + return timestamp_start_; } - bool save (Conf::ConfigTree **history); + bool save(Conf::ConfigTree **history); - std::string serialize (void); + std::string serialize() const; private: - /* * @return true if the account ID corresponds to a loaded account */ - bool valid_account (std::string); + bool valid_account(const std::string &id) const; /* * Timestamp representing the date of the call */ - std::string _timestamp_start; - std::string _timestamp_stop; + std::string timestamp_start_; + std::string timestamp_stop_; /* * Represents the type of call * Has be either CALL_MISSED, CALL_INCOMING or CALL_OUTGOING */ - CallType _call_type; + CallType call_type_; /* * The information about the callee/caller, depending on the type of call. */ - std::string _name; - std::string _number; + std::string name_; + std::string number_; - /** - * The identifier fo this item - */ - std::string _id; + /** + * The identifier fo this item + */ + std::string id_; /* * The account the call was made with */ - std::string _account_id; + std::string account_id_; /** - * Wether or not a recording exist for this call + * Whether or not a recording exist for this call */ - std::string _recording_file; + std::string recording_file_; /** - * The conference ID for this call (if any) - */ - std::string _confID; + * The conference ID for this call (if any) + */ + std::string confID_; /** - * Time added to conference + * Time added to conference */ - std::string _timeAdded; + std::string timeAdded_; }; diff --git a/daemon/src/history/historymanager.cpp b/daemon/src/history/historymanager.cpp index 5980fa43dbb69f2f9a699aed73086d1fa775fe64..28970000fcef1d53a847c4d01fa35a94cb8a2bd1 100644 --- a/daemon/src/history/historymanager.cpp +++ b/daemon/src/history/historymanager.cpp @@ -2,7 +2,7 @@ * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. * * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> - * Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com> + * Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com> * * 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 @@ -35,260 +35,187 @@ #include <cc++/file.h> #include <time.h> -namespace { -static void free_history(HistoryItemMap &history_items) -{ - HistoryItemMap::iterator iter; - for (iter = history_items.begin(); iter != history_items.end(); ++iter) - delete *iter; - - history_items.clear (); -} -} // end anonymous namespace - -HistoryManager::HistoryManager () - : _history_loaded (false), - _history_path ("") -{ -} +HistoryManager::HistoryManager() : + history_items_(), history_loaded_(false), history_path_("") +{} -HistoryManager::~HistoryManager () -{ - free_history(_history_items); -} - -int HistoryManager::load_history (int limit, std::string path) +int HistoryManager::load_history(int limit, const std::string &path) { Conf::ConfigTree history_list; - - _debug("HistoryManager: Load history"); - - create_history_path (path); - load_history_from_file (&history_list); - return load_history_items_map (&history_list, limit); + create_history_path(path); + load_history_from_file(&history_list); + return load_history_items_map(&history_list, limit); } -bool HistoryManager::save_history (void) +bool HistoryManager::save_history() { Conf::ConfigTree history_list; - - _debug("HistoryManager: Save history"); - - save_history_items_map (&history_list); - return save_history_to_file (&history_list); + save_history_items_map(&history_list); + return save_history_to_file(&history_list); } -bool HistoryManager::load_history_from_file (Conf::ConfigTree *history_list) +bool HistoryManager::load_history_from_file(Conf::ConfigTree *history_list) { - int exist; - - _debug ("HistoryManager: Load history from file %s", _history_path.c_str()); + DEBUG("HistoryManager: Load history from file %s", history_path_.c_str()); - exist = history_list->populateFromFile (_history_path.c_str()); - _history_loaded = (exist == 2) ? false : true; + int exist = history_list->populateFromFile(history_path_.c_str()); + history_loaded_ = (exist == 2) ? false : true; - return _history_loaded; + return history_loaded_; } -int HistoryManager::load_history_items_map (Conf::ConfigTree *history_list, int limit) +int HistoryManager::load_history_items_map(Conf::ConfigTree *history_list, int limit) { - - short nb_items = 0; - Conf::TokenList sections; - HistoryItem *item; - Conf::TokenList::iterator iter; - std::string number, name, callID, accountID, timestamp_start, timestamp_stop, recording_file, confID, time_added; - CallType type; - int history_limit; - time_t current_timestamp; - - _debug ("HistoryManager: Load history items"); + using std::string; // We want to save only the items recent enough (ie compared to CONFIG_HISTORY_LIMIT) // Get the current timestamp - (void) time (¤t_timestamp); - history_limit = get_unix_timestamp_equivalent (limit); - - sections = history_list->getSections(); - iter = sections.begin(); - - while (iter != sections.end()) { - - type = (CallType) getConfigInt (*iter, "type", history_list); - timestamp_start = getConfigString (*iter, "timestamp_start", history_list); - timestamp_stop = getConfigString (*iter, "timestamp_stop", history_list); - name = getConfigString (*iter, "name", history_list); - number = getConfigString (*iter, "number", history_list); - callID = getConfigString(*iter, "id", history_list); - accountID = getConfigString (*iter, "accountid", history_list); - recording_file = getConfigString(*iter, "recordfile", history_list); - confID = getConfigString(*iter, "confid", history_list); - time_added = getConfigString(*iter, "timeadded", history_list); + time_t current_timestamp; + time(¤t_timestamp); + int history_limit = get_unix_timestamp_equivalent(limit); + + Conf::TokenList sections(history_list->getSections()); + int nb_items = 0; + for (Conf::TokenList::iterator iter = sections.begin(); iter != sections.end(); ++iter) { + CallType type = (CallType) getConfigInt(*iter, "type", history_list); + string timestamp_start(getConfigString(*iter, "timestamp_start", history_list)); + string timestamp_stop(getConfigString(*iter, "timestamp_stop", history_list)); + string name(getConfigString(*iter, "name", history_list)); + string number(getConfigString(*iter, "number", history_list)); + string callID(getConfigString(*iter, "id", history_list)); + string accountID(getConfigString(*iter, "accountid", history_list)); + string recording_file(getConfigString(*iter, "recordfile", history_list)); + string confID(getConfigString(*iter, "confid", history_list)); + string timeAdded(getConfigString(*iter, "timeadded", history_list)); // Make a check on the start timestamp to know it is loadable according to CONFIG_HISTORY_LIMIT - - if (atoi (timestamp_start.c_str ()) >= ( (int) current_timestamp - history_limit)) { - item = new HistoryItem (timestamp_start, type, timestamp_stop, name, number, callID, accountID, recording_file, confID, time_added); - add_new_history_entry (item); - nb_items ++; + if (atoi(timestamp_start.c_str()) >= ((int) current_timestamp - history_limit)) { + HistoryItem item(timestamp_start, type, timestamp_stop, name, number, callID, accountID, recording_file, confID, timeAdded); + add_new_history_entry(item); + ++nb_items; } - - iter ++; } return nb_items; } -bool HistoryManager::save_history_to_file (Conf::ConfigTree *history_list) +bool HistoryManager::save_history_to_file(Conf::ConfigTree *history_list) { - _debug ("HistoryManager: Saving history in XDG directory: %s", _history_path.data()); - return history_list->saveConfigTree (_history_path.data()); + DEBUG("HistoryManager: Saving history in XDG directory: %s", history_path_.c_str()); + return history_list->saveConfigTree(history_path_.data()); } - -int HistoryManager::save_history_items_map (Conf::ConfigTree *history_list) +int HistoryManager::save_history_items_map(Conf::ConfigTree *history_list) { - HistoryItemMap::iterator iter; - HistoryItem *item; int items_saved = 0; - - _debug("HistoryManager: Save history items map"); - - iter = _history_items.begin (); - - while (iter != _history_items.end ()) { - item = *iter; - - if (item) { - if (item->save (&history_list)) - items_saved ++; - } else { - _debug("can't save NULL history item\n"); - } - - iter ++; + for (std::vector<HistoryItem>::iterator iter = history_items_.begin(); iter != history_items_.end(); ++iter) { + if (iter->save(&history_list)) + ++items_saved; + else + DEBUG("can't save NULL history item\n"); } return items_saved; } -void HistoryManager::add_new_history_entry (HistoryItem *new_item) +void HistoryManager::add_new_history_entry(const HistoryItem &new_item) { // Add it in the map - _history_items.push_back(new_item); + history_items_.push_back(new_item); } -int HistoryManager::create_history_path (std::string path) +int HistoryManager::create_history_path(std::string path) { - std::string userdata, xdg_env, xdg_data; - xdg_data = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".local/share/sflphone"; - - if (path == "") { + xdg_data = std::string(HOMEDIR) + DIR_SEPARATOR_STR + ".local/share/sflphone"; + if (path.empty()) { // If the environment variable is set (not null and not empty), we'll use it to save the history // Else we 'll the standard one, ie: XDG_DATA_HOME = $HOMEDIR/.local/share/sflphone if (XDG_DATA_HOME != NULL) { - xdg_env = std::string (XDG_DATA_HOME); - (xdg_env.length() > 0) ? userdata = xdg_env - : userdata = xdg_data; + xdg_env = std::string(XDG_DATA_HOME); + (xdg_env.length() > 0) ? userdata = xdg_env : userdata = xdg_data; } else userdata = xdg_data; - if (mkdir (userdata.data(), 0755) != 0) { + if (mkdir(userdata.data(), 0755) != 0) { // If directory creation failed if (errno != EEXIST) { - _debug ("HistoryManager: Cannot create directory: %m"); + DEBUG("HistoryManager: Cannot create directory: %m"); return -1; } } // Load user's history - _history_path = userdata + DIR_SEPARATOR_STR + "history"; + history_path_ = userdata + DIR_SEPARATOR_STR + "history"; } else - set_history_path (path); - + set_history_path(path); return 0; } // throw an Conf::ConfigTreeItemException if not found int -HistoryManager::getConfigInt (const std::string& section, const std::string& name, Conf::ConfigTree *history_list) +HistoryManager::getConfigInt(const std::string& section, const std::string& name, Conf::ConfigTree *history_list) { try { - return history_list->getConfigTreeItemIntValue (section, name); - } catch (Conf::ConfigTreeItemException& e) { - throw e; + return history_list->getConfigTreeItemIntValue(section, name); + } catch (const Conf::ConfigTreeItemException& e) { + throw; } return 0; } std::string -HistoryManager::getConfigString (const std::string& section, const std::string& name, Conf::ConfigTree *history_list) +HistoryManager::getConfigString(const std::string& section, const std::string& name, Conf::ConfigTree *history_list) { try { - return history_list->getConfigTreeItemValue (section, name); - } catch (Conf::ConfigTreeItemException& e) { - throw e; + return history_list->getConfigTreeItemValue(section, name); + } catch (const Conf::ConfigTreeItemException& e) { + throw; } return ""; } -std::vector<std::string> HistoryManager::get_history_serialized (void) +std::vector<std::string> HistoryManager::get_history_serialized() const { std::vector<std::string> serialized; - HistoryItemMap::iterator iter; - - _debug("HistoryManager: Get history serialized"); - - for (iter = _history_items.begin (); iter != _history_items.end(); ++iter) { - HistoryItem *current = *iter; - if (current) - serialized.push_back(current->serialize ()); - } + for (std::vector<HistoryItem>::const_iterator iter = history_items_.begin(); iter != history_items_.end(); ++iter) + serialized.push_back(iter->serialize()); return serialized; } -int HistoryManager::set_serialized_history (std::vector<std::string> history, int limit) +int HistoryManager::set_serialized_history(const std::vector<std::string> &history, int limit) { - std::vector<std::string>::iterator iter; - HistoryItem *new_item; - int items_added = 0; int history_limit; time_t current_timestamp; - _debug("HistoryManager: Set serialized history"); + DEBUG("HistoryManager: Set serialized history"); - // Clear the existing history - free_history(_history_items); + history_items_.clear(); // We want to save only the items recent enough (ie compared to CONFIG_HISTORY_LIMIT) // Get the current timestamp - (void) time (¤t_timestamp); - history_limit = get_unix_timestamp_equivalent (limit); + time(¤t_timestamp); + history_limit = get_unix_timestamp_equivalent(limit); - for (iter = history.begin () ; iter != history.end () ; iter ++) { - new_item = new HistoryItem(*iter); - if(new_item == NULL) { - _error("HistoryManager: Error: Could not create history item"); - } - int item_timestamp = atoi(new_item->get_timestamp().c_str()); - if (item_timestamp >= ( (int) current_timestamp - history_limit)) { - add_new_history_entry (new_item); - items_added ++; - } else { - delete new_item; + int items_added = 0; + for (std::vector<std::string>::const_iterator iter = history.begin() ; iter != history.end() ; ++iter) { + HistoryItem new_item(*iter); + int item_timestamp = atoi(new_item.get_timestamp().c_str()); + + if (item_timestamp >= ((int) current_timestamp - history_limit)) { + add_new_history_entry(new_item); + ++items_added; } } return items_added; } - diff --git a/daemon/src/history/historymanager.h b/daemon/src/history/historymanager.h index af3c924485b126650f086a0ac9c3b1ab425c2c5a..a2a82b67b898a057d82df4c78ee78582fd94eba9 100644 --- a/daemon/src/history/historymanager.h +++ b/daemon/src/history/historymanager.h @@ -38,110 +38,102 @@ #define DAY_UNIX_TIMESTAMP 86400 // Number of seconds in one day: 60 x 60 x 24 -typedef std::vector <HistoryItem *> HistoryItemMap; - -class HistoryManager -{ +class HistoryManager { public: /* * Constructor */ - HistoryManager (); - - /* - * Destructor - */ - ~HistoryManager (); + HistoryManager(); /** *@param path A specific file to use; if empty, use the global one * *@return int The number of history items successfully loaded */ - int load_history (int limit, std::string path=""); + int load_history(int limit, const std::string &path=""); /** *@return bool True if the history has been successfully saved in the file */ - bool save_history (void); + bool save_history(); /* * Load the history from a file to the dedicated data structure */ - bool load_history_from_file (Conf::ConfigTree *history_list); + bool load_history_from_file(Conf::ConfigTree *history_list); /* * @return int The number of history items loaded */ - int load_history_items_map (Conf::ConfigTree *history_list, int limit); + int load_history_items_map(Conf::ConfigTree *history_list, int limit); - /* + /* * Inverse method, ie save a data structure containing the history into a file */ - bool save_history_to_file (Conf::ConfigTree *history_list); + bool save_history_to_file(Conf::ConfigTree *history_list); /** * @return int The number of history entries successfully saved */ - int save_history_items_map (Conf::ConfigTree *history_list); + int save_history_items_map(Conf::ConfigTree *history_list); /** *@return bool True if the history file has been successfully read */ - bool is_loaded (void) const { - return _history_loaded; + bool is_loaded() const { + return history_loaded_; } - void set_history_path (const std::string &filename) { - _history_path = filename; + void set_history_path(const std::string &filename) { + history_path_ = filename; } /* *@return int The number of items found in the history file */ - int get_history_size (void) const { - return _history_items.size (); + int get_history_size() const { + return history_items_.size(); } - std::vector<std::string> get_history_serialized (void); + std::vector<std::string> get_history_serialized() const; - int set_serialized_history (std::vector<std::string> history, int limit); + int set_serialized_history(const std::vector<std::string> &history, int limit); private: - int get_unix_timestamp_equivalent (int days) const { + int get_unix_timestamp_equivalent(int days) const { return days * DAY_UNIX_TIMESTAMP; } - int getConfigInt (const std::string& section, const std::string& name, Conf::ConfigTree *history_list); - std::string getConfigString (const std::string& section, const std::string& name, Conf::ConfigTree *history_list); + int getConfigInt(const std::string& section, const std::string& name, Conf::ConfigTree *history_list); + std::string getConfigString(const std::string& section, const std::string& name, Conf::ConfigTree *history_list); /* * Set the path to the history file * * @param path A specific file to use; if empty, use the global one */ - int create_history_path (std::string path=""); + int create_history_path(std::string path=""); /* * Add a new history item in the data structure */ - void add_new_history_entry (HistoryItem *new_item); + void add_new_history_entry(const HistoryItem &new_item); /* * Map containing the history items */ - HistoryItemMap _history_items; + std::vector<HistoryItem> history_items_; /* * History has been loaded */ - bool _history_loaded; + bool history_loaded_; /* * The path to the history file */ - std::string _history_path; + std::string history_path_; friend class HistoryTest; }; diff --git a/daemon/src/hooks/urlhook.cpp b/daemon/src/hooks/urlhook.cpp index 5c515ce791178469452368cd80edff2b45278179..3093380dc1338c5d2c66840b5ff0bd42231301da 100644 --- a/daemon/src/hooks/urlhook.cpp +++ b/daemon/src/hooks/urlhook.cpp @@ -31,13 +31,14 @@ #include "urlhook.h" #include <cstdlib> -void UrlHook::runAction (std::string command, std::string args) +int UrlHook::runAction(const std::string &command, const std::string &args) { - if (args.empty()) - return; - //FIXME : use fork and execve, so no need to escape shell arguments - std::string cmd = command + "\"" + args + "\" &"; - system(cmd.c_str()); + if (args.empty()) + return 0; + + //FIXME : use fork and execve, so no need to escape shell arguments + std::string cmd = command + "\"" + args + "\" &"; + return system(cmd.c_str()); } diff --git a/daemon/src/hooks/urlhook.h b/daemon/src/hooks/urlhook.h index c29637db32f9345357a36293e45a415219917b14..abd419763ee10c1fcf75d53d68406d777ecebb29 100644 --- a/daemon/src/hooks/urlhook.h +++ b/daemon/src/hooks/urlhook.h @@ -33,10 +33,7 @@ #include <string> -class UrlHook -{ -public: - static void runAction (std::string, std::string); -}; - +namespace UrlHook { +int runAction(const std::string &command, const std::string &arg); +} #endif // URL_HOOK_H diff --git a/daemon/src/iax/iaxaccount.cpp b/daemon/src/iax/iaxaccount.cpp index b063e391c6330ae6cd2917e2b19217135237f046..eda848c4a84fc6d5b72f6eb6cb8926f7786f69b7 100644 --- a/daemon/src/iax/iaxaccount.cpp +++ b/daemon/src/iax/iaxaccount.cpp @@ -37,10 +37,10 @@ #include "iaxvoiplink.h" #include "manager.h" -IAXAccount::IAXAccount (const std::string& accountID) - : Account (accountID, "iax2") +IAXAccount::IAXAccount(const std::string& accountID) + : Account(accountID, "iax2"), password_() { - link_ = new IAXVoIPLink (accountID); + link_ = new IAXVoIPLink(accountID); } @@ -49,51 +49,51 @@ IAXAccount::~IAXAccount() delete link_; } -void IAXAccount::serialize (Conf::YamlEmitter *emitter) +void IAXAccount::serialize(Conf::YamlEmitter *emitter) { - if (emitter == NULL) { - _error("IAXAccount: Error: emitter is NULL in serialize"); - return; - } - - Conf::MappingNode accountmap (NULL); - - Conf::ScalarNode id (accountID_); - Conf::ScalarNode username (username_); - Conf::ScalarNode password (password_); - Conf::ScalarNode alias (alias_); - Conf::ScalarNode hostname (hostname_); - Conf::ScalarNode enable (enabled_); - Conf::ScalarNode type (type_); - Conf::ScalarNode mailbox (mailBox_); - - Conf::ScalarNode codecs (codecStr_); - Conf::ScalarNode displayName (displayName_); - - accountmap.setKeyValue (aliasKey, &alias); - accountmap.setKeyValue (typeKey, &type); - accountmap.setKeyValue (idKey, &id); - accountmap.setKeyValue (usernameKey, &username); - accountmap.setKeyValue (passwordKey, &password); - accountmap.setKeyValue (hostnameKey, &hostname); - accountmap.setKeyValue (accountEnableKey, &enable); - accountmap.setKeyValue (mailboxKey, &mailbox); - - accountmap.setKeyValue (displayNameKey, &displayName); - accountmap.setKeyValue (codecsKey, &codecs); + if (emitter == NULL) { + ERROR("IAXAccount: Error: emitter is NULL in serialize"); + return; + } + + Conf::MappingNode accountmap(NULL); + + Conf::ScalarNode id(accountID_); + Conf::ScalarNode username(username_); + Conf::ScalarNode password(password_); + Conf::ScalarNode alias(alias_); + Conf::ScalarNode hostname(hostname_); + Conf::ScalarNode enable(enabled_); + Conf::ScalarNode type(type_); + Conf::ScalarNode mailbox(mailBox_); + + Conf::ScalarNode codecs(codecStr_); + Conf::ScalarNode displayName(displayName_); + + accountmap.setKeyValue(aliasKey, &alias); + accountmap.setKeyValue(typeKey, &type); + accountmap.setKeyValue(idKey, &id); + accountmap.setKeyValue(usernameKey, &username); + accountmap.setKeyValue(passwordKey, &password); + accountmap.setKeyValue(hostnameKey, &hostname); + accountmap.setKeyValue(accountEnableKey, &enable); + accountmap.setKeyValue(mailboxKey, &mailbox); + + accountmap.setKeyValue(displayNameKey, &displayName); + accountmap.setKeyValue(codecsKey, &codecs); try { - emitter->serializeAccount (&accountmap); - } catch (Conf::YamlEmitterException &e) { - _error ("ConfigTree: %s", e.what()); + emitter->serializeAccount(&accountmap); + } catch (const Conf::YamlEmitterException &e) { + ERROR("ConfigTree: %s", e.what()); } } -void IAXAccount::unserialize (Conf::MappingNode *map) +void IAXAccount::unserialize(Conf::MappingNode *map) { if (map == NULL) { - _error("IAXAccount: Error: Map is NULL in unserialize"); - return; + ERROR("IAXAccount: Error: Map is NULL in unserialize"); + return; } map->getValue(aliasKey, &alias_); @@ -103,14 +103,14 @@ void IAXAccount::unserialize (Conf::MappingNode *map) map->getValue(hostnameKey, &hostname_); map->getValue(accountEnableKey, &enabled_); map->getValue(mailboxKey, &mailBox_); - map->getValue (codecsKey, &codecStr_); + map->getValue(codecsKey, &codecStr_); // Update codec list which one is used for SDP offer - setActiveCodecs (ManagerImpl::unserialize (codecStr_)); - map->getValue (displayNameKey, &displayName_); + setActiveCodecs(ManagerImpl::unserialize(codecStr_)); + map->getValue(displayNameKey, &displayName_); } -void IAXAccount::setAccountDetails (std::map<std::string, std::string> details) +void IAXAccount::setAccountDetails(std::map<std::string, std::string> details) { // Account setting common to SIP and IAX alias_ = details[CONFIG_ACCOUNT_ALIAS]; @@ -139,7 +139,7 @@ std::map<std::string, std::string> IAXAccount::getAccountDetails() const RegistrationState state(registrationState_); - a[REGISTRATION_STATUS] = mapStateNumberToString (state); + a[REGISTRATION_STATUS] = mapStateNumberToString(state); a[USERAGENT] = userAgent_; return a; @@ -147,25 +147,23 @@ std::map<std::string, std::string> IAXAccount::getAccountDetails() const void IAXAccount::registerVoIPLink() { - try { + try { link_->init(); - link_->sendRegister (this); - } - catch (const VoipLinkException &e) { - _error("IAXAccount: %s", e.what()); - } + link_->sendRegister(this); + } catch (const VoipLinkException &e) { + ERROR("IAXAccount: %s", e.what()); + } } void IAXAccount::unregisterVoIPLink() { - try { - link_->sendUnregister (this); + try { + link_->sendUnregister(this); dynamic_cast<IAXVoIPLink*>(link_)->terminate(); - } - catch (const VoipLinkException &e) { - _error("IAXAccount: %s", e.what()); - } + } catch (const VoipLinkException &e) { + ERROR("IAXAccount: %s", e.what()); + } } void @@ -173,6 +171,6 @@ IAXAccount::loadConfig() { // If IAX is not supported, do not register this account #if !HAVE_IAX - enabled_ = false; + enabled_ = false; #endif } diff --git a/daemon/src/iax/iaxaccount.h b/daemon/src/iax/iaxaccount.h index 2b14744898ac2f3fd6eacf65e8f50f7f30bcfc1a..60b9a1acee27eb704046dc45685460177534d457 100644 --- a/daemon/src/iax/iaxaccount.h +++ b/daemon/src/iax/iaxaccount.h @@ -37,45 +37,34 @@ * @file: iaxaccount.h * @brief An IAX Account specify IAX specific functions and objects (IAXCall/IAXVoIPLink) */ -class IAXAccount : public Account -{ +class IAXAccount : public Account { public: - IAXAccount (const std::string& accountID); - + IAXAccount(const std::string& accountID); ~IAXAccount(); - virtual void serialize (Conf::YamlEmitter *emitter); + virtual void serialize(Conf::YamlEmitter *emitter); - virtual void unserialize (Conf::MappingNode *map); + virtual void unserialize(Conf::MappingNode *map); - void setAccountDetails (std::map<std::string, std::string> details); + void setAccountDetails(std::map<std::string, std::string> details); std::map<std::string, std::string> getAccountDetails() const; - /** - * Actually useless, since config loading is done in init() - */ + // Actually useless, since config loading is done in init() void loadConfig(); - /** - * Register an account - */ + // Register an account void registerVoIPLink(); - /** - * Unregister an account - */ + // Unregister an account void unregisterVoIPLink(); - std::string getPassword (void) const { - return password_; + std::string getPassword() const { + return password_; } private: - - /** - * Account login information: password - */ + // Account login information: password std::string password_; }; diff --git a/daemon/src/iax/iaxcall.cpp b/daemon/src/iax/iaxcall.cpp index 2413b7a684ccaf678514c9c0934d774628a8306f..a1eb21ec93ac7f467f43094922af9eb1d4301402 100644 --- a/daemon/src/iax/iaxcall.cpp +++ b/daemon/src/iax/iaxcall.cpp @@ -35,66 +35,83 @@ #include "manager.h" namespace { - int codecToASTFormat(int c) - { - if (c == PAYLOAD_CODEC_ULAW) return AST_FORMAT_ULAW; - if (c == PAYLOAD_CODEC_GSM) return AST_FORMAT_GSM; - if (c == PAYLOAD_CODEC_ALAW) return AST_FORMAT_ALAW; - if (c == PAYLOAD_CODEC_ILBC_20) return AST_FORMAT_ILBC; - if (c == PAYLOAD_CODEC_SPEEX_8000) return AST_FORMAT_SPEEX; +int codecToASTFormat(int c) +{ + switch (c) { + case PAYLOAD_CODEC_ULAW: + return AST_FORMAT_ULAW; + case PAYLOAD_CODEC_GSM: + return AST_FORMAT_GSM; + case PAYLOAD_CODEC_ALAW: + return AST_FORMAT_ALAW; + case PAYLOAD_CODEC_ILBC_20: + return AST_FORMAT_ILBC; + case PAYLOAD_CODEC_SPEEX_8000: + return AST_FORMAT_SPEEX; - _error("Codec %d not supported!", c); - return 0; + default: + ERROR("Codec %d not supported!", c); + return 0; } } - -IAXCall::IAXCall (const std::string& id, Call::CallType type) : Call (id, type), session (NULL) -{ } -int -IAXCall::getSupportedFormat (const std::string &accountID) const +IAXCall::IAXCall(const std::string& id, Call::CallType type) : Call(id, type), + format(0), session(NULL) +{} + +int IAXCall::getSupportedFormat(const std::string &accountID) const { - Account *account = Manager::instance().getAccount (accountID); + Account *account = Manager::instance().getAccount(accountID); + + int format_mask = 0; - int format = 0; if (account) { CodecOrder map(account->getActiveCodecs()); + for (CodecOrder::const_iterator iter = map.begin(); iter != map.end(); ++iter) - format |= codecToASTFormat(*iter); - } - else - _error ("No IAx account could be found"); + format_mask |= codecToASTFormat(*iter); + } else + ERROR("No IAx account could be found"); - return format; + return format_mask; } -int IAXCall::getFirstMatchingFormat (int needles, const std::string &accountID) const +int IAXCall::getFirstMatchingFormat(int needles, const std::string &accountID) const { - Account *account = Manager::instance().getAccount (accountID); + Account *account = Manager::instance().getAccount(accountID); if (account != NULL) { CodecOrder map(account->getActiveCodecs()); + for (CodecOrder::const_iterator iter = map.begin(); iter != map.end(); ++iter) { - int format = codecToASTFormat(*iter); + int format_mask = codecToASTFormat(*iter); + // Return the first that matches - if (format & needles) - return format; + if (format_mask & needles) + return format_mask; } } else - _error ("No IAx account could be found"); + ERROR("No IAx account could be found"); return 0; } -int IAXCall::getAudioCodec(void) +int IAXCall::getAudioCodec() const { - if (format == AST_FORMAT_ULAW) return PAYLOAD_CODEC_ULAW; - if (format == AST_FORMAT_GSM) return PAYLOAD_CODEC_GSM; - if (format == AST_FORMAT_ALAW) return PAYLOAD_CODEC_ALAW; - if (format == AST_FORMAT_ILBC) return PAYLOAD_CODEC_ILBC_20; - if (format == AST_FORMAT_SPEEX) return PAYLOAD_CODEC_SPEEX_8000; - - _error("IAX: Format %d not supported!", format); - return -1; + switch (format) { + case AST_FORMAT_ULAW: + return PAYLOAD_CODEC_ULAW; + case AST_FORMAT_GSM: + return PAYLOAD_CODEC_GSM; + case AST_FORMAT_ALAW: + return PAYLOAD_CODEC_ALAW; + case AST_FORMAT_ILBC: + return PAYLOAD_CODEC_ILBC_20; + case AST_FORMAT_SPEEX: + return PAYLOAD_CODEC_SPEEX_8000; + default: + ERROR("IAX: Format %d not supported!", format); + return -1; + } } diff --git a/daemon/src/iax/iaxcall.h b/daemon/src/iax/iaxcall.h index 64765f97716dc1c95f8a31f527b4dbced43af268..b2822520398726543001c18ad02f581f2462f43e 100644 --- a/daemon/src/iax/iaxcall.h +++ b/daemon/src/iax/iaxcall.h @@ -32,7 +32,7 @@ #define IAXCALL_H #include "call.h" -#include "audio/codecs/audiocodecfactory.h" +#include "noncopyable.h" /** * @file: iaxcall.h @@ -40,20 +40,19 @@ */ class iax_session; -class IAXCall : public Call -{ +class IAXCall : public Call { public: /** * Constructor * @param id The unique ID of the call * @param type The type of the call */ - IAXCall (const std::string& id, Call::CallType type); + IAXCall(const std::string& id, Call::CallType type); /** * @return int The bitwise list of supported formats */ - int getSupportedFormat (const std::string &accountID) const; + int getSupportedFormat(const std::string &accountID) const; /** * Return a format (int) with the first matching codec selected. @@ -68,12 +67,14 @@ class IAXCall : public Call * @param needles The format(s) (bitwise) you are looking for to match * @return int The matching format, thus 0 if none matches */ - int getFirstMatchingFormat (int needles, const std::string &accountID) const; + int getFirstMatchingFormat(int needles, const std::string &accountID) const; - int getAudioCodec(void); + int getAudioCodec() const; int format; iax_session* session; + private: + NON_COPYABLE(IAXCall); }; #endif diff --git a/daemon/src/iax/iaxvoiplink.cpp b/daemon/src/iax/iaxvoiplink.cpp index 46827988746b0ce0c360ddc8123fb6d503cb535e..f8e10cb1e15f1d942e9ed41b3a925c56529cf3ae 100644 --- a/daemon/src/iax/iaxvoiplink.cpp +++ b/daemon/src/iax/iaxvoiplink.cpp @@ -31,7 +31,7 @@ #include "iaxvoiplink.h" #include "iaxcall.h" #include "eventthread.h" -#include "im/InstantMessaging.h" +#include "im/instant_messaging.h" #include "iaxaccount.h" #include "manager.h" #include "hooks/urlhook.h" @@ -41,13 +41,14 @@ #include <cmath> #include <dlfcn.h> -IAXVoIPLink::IAXVoIPLink (const std::string& accountID) : +IAXVoIPLink::IAXVoIPLink(const std::string& accountID) : evThread_(new EventThread(this)) , regSession_(NULL) , nextRefreshStamp_(0) + , mutexIAX_() , converter_(44100) , initDone_(false) - , accountID_(accountID) + , accountID_(accountID) { srand(time(NULL)); // to get random number for RANDOM_PORT } @@ -55,7 +56,7 @@ IAXVoIPLink::IAXVoIPLink (const std::string& accountID) : IAXVoIPLink::~IAXVoIPLink() { - delete evThread_; + delete evThread_; regSession_ = NULL; // shall not delete it // XXX: but why? terminate(); @@ -70,8 +71,8 @@ IAXVoIPLink::init() for (int port = IAX_DEFAULT_PORTNO, nbTry = 0; nbTry < 3 ; port = rand() % 64000 + 1024, nbTry++) { if (iax_init(port) >= 0) { evThread_->start(); - initDone_ = true; - break; + initDone_ = true; + break; } } } @@ -82,17 +83,19 @@ IAXVoIPLink::terminate() if (!initDone_) return; - ost::MutexLock m(_callMapMutex); - for (CallMap::iterator iter = _callMap.begin(); iter != _callMap.end(); ++iter) { - IAXCall *call = dynamic_cast<IAXCall*> (iter->second); + ost::MutexLock m(callMapMutex_); + + for (CallMap::iterator iter = callMap_.begin(); iter != callMap_.end(); ++iter) { + IAXCall *call = dynamic_cast<IAXCall*>(iter->second); + if (call) { - ost::MutexLock m(mutexIAX_); - iax_hangup (call->session, (char*) "Dumped Call"); + ost::MutexLock lock(mutexIAX_); + iax_hangup(call->session, const_cast<char*>("Dumped Call")); delete call; } } - _callMap.clear(); + callMap_.clear(); initDone_ = false; } @@ -100,30 +103,32 @@ IAXVoIPLink::terminate() void IAXVoIPLink::getEvent() { - mutexIAX_.enter(); - iax_event *event; - while ((event = iax_get_event(0)) != NULL) { - // If we received an 'ACK', libiax2 tells apps to ignore them. - if (event->etype == IAX_EVENT_NULL) { - iax_event_free (event); - continue; - } - - IAXCall *call = iaxFindCallBySession (event->session); - - if (call) - iaxHandleCallEvent (event, call); - else if (event->session && event->session == regSession_) - iaxHandleRegReply (event); // This is a registration session, deal with it - else // We've got an event before it's associated with any call - iaxHandlePrecallEvent (event); - - iax_event_free (event); - } - mutexIAX_.leave(); - - if (nextRefreshStamp_ && nextRefreshStamp_ < time (NULL)) - sendRegister(dynamic_cast<IAXAccount *> (Manager::instance().getAccount(accountID_))); + mutexIAX_.enter(); + iax_event *event; + + while ((event = iax_get_event(0)) != NULL) { + // If we received an 'ACK', libiax2 tells apps to ignore them. + if (event->etype == IAX_EVENT_NULL) { + iax_event_free(event); + continue; + } + + IAXCall *call = iaxFindCallBySession(event->session); + + if (call) + iaxHandleCallEvent(event, call); + else if (event->session && event->session == regSession_) + iaxHandleRegReply(event); // This is a registration session, deal with it + else // We've got an event before it's associated with any call + iaxHandlePrecallEvent(event); + + iax_event_free(event); + } + + mutexIAX_.leave(); + + if (nextRefreshStamp_ && nextRefreshStamp_ < time(NULL)) + sendRegister(dynamic_cast<IAXAccount *>(Manager::instance().getAccount(accountID_))); sendAudioFromMic(); @@ -132,72 +137,77 @@ IAXVoIPLink::getEvent() } void -IAXVoIPLink::sendAudioFromMic (void) +IAXVoIPLink::sendAudioFromMic() { - for (CallMap::const_iterator iter = _callMap.begin(); iter != _callMap.end() ; ++iter) { + for (CallMap::const_iterator iter = callMap_.begin(); iter != callMap_.end() ; ++iter) { IAXCall *currentCall = dynamic_cast<IAXCall*>(iter->second); + if (!currentCall or currentCall->getState() != Call::Active) - continue; + continue; + + int codecType = currentCall->getAudioCodec(); + sfl::AudioCodec *audioCodec = static_cast<sfl::AudioCodec *>(Manager::instance().audioCodecFactory.getCodec(codecType)); - int codecType = currentCall->getAudioCodec(); - sfl::AudioCodec *audioCodec = static_cast<sfl::AudioCodec *>(Manager::instance().audioCodecFactory.getCodec(codecType)); + if (!audioCodec) + continue; - if (!audioCodec) - continue; + Manager::instance().getMainBuffer()->setInternalSamplingRate(audioCodec->getClockRate()); - Manager::instance().getMainBuffer()->setInternalSamplingRate (audioCodec->getClockRate()); + unsigned int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); - unsigned int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); + // we have to get 20ms of data from the mic *20/1000 = /50 + // rate/50 shall be lower than IAX__20S_48KHZ_MAX + int bytesNeeded = mainBufferSampleRate * 20 / 1000 * sizeof(SFLDataFormat); - // we have to get 20ms of data from the mic *20/1000 = /50 - // rate/50 shall be lower than IAX__20S_48KHZ_MAX - int bytesNeeded = mainBufferSampleRate * 20 / 1000 * sizeof (SFLDataFormat); - if (Manager::instance().getMainBuffer()->availForGet (currentCall->getCallId()) < bytesNeeded) - continue; + if (Manager::instance().getMainBuffer()->availForGet(currentCall->getCallId()) < bytesNeeded) + continue; - // Get bytes from micRingBuffer to data_from_mic - int bytes = Manager::instance().getMainBuffer()->getData (decData, bytesNeeded, currentCall->getCallId()); + // Get bytes from micRingBuffer to data_from_mic + int bytes = Manager::instance().getMainBuffer()->getData(decData, bytesNeeded, currentCall->getCallId()); int samples = bytes / sizeof(SFLDataFormat); - int compSize; - unsigned int audioRate = audioCodec->getClockRate(); - int outSamples; - SFLDataFormat *in; - if (audioRate != mainBufferSampleRate) { - converter_.resample (decData, resampledData, audioRate, mainBufferSampleRate, samples); - in = resampledData; + int compSize; + unsigned int audioRate = audioCodec->getClockRate(); + int outSamples; + SFLDataFormat *in; + + if (audioRate != mainBufferSampleRate) { + converter_.resample(decData, resampledData, audioRate, mainBufferSampleRate, samples); + in = resampledData; outSamples = 0; - } else { - outSamples = samples; - in = decData; - } - compSize = audioCodec->encode (encodedData, in, DEC_BUFFER_SIZE); - - if (currentCall->session and bytes > 0) { - ost::MutexLock m(mutexIAX_); - if (iax_send_voice (currentCall->session, currentCall->format, encodedData, compSize, outSamples) == -1) - _error ("IAX: Error sending voice data."); - } + } else { + outSamples = samples; + in = decData; + } + + compSize = audioCodec->encode(encodedData, in, DEC_BUFFER_SIZE); + + if (currentCall->session and bytes > 0) { + ost::MutexLock m(mutexIAX_); + + if (iax_send_voice(currentCall->session, currentCall->format, encodedData, compSize, outSamples) == -1) + ERROR("IAX: Error sending voice data."); + } } } IAXCall* -IAXVoIPLink::getIAXCall (const std::string& id) +IAXVoIPLink::getIAXCall(const std::string& id) { return dynamic_cast<IAXCall*>(getCall(id)); } void -IAXVoIPLink::sendRegister (Account *a) +IAXVoIPLink::sendRegister(Account *a) { IAXAccount *account = dynamic_cast<IAXAccount*>(a); if (account->getHostname().empty()) - throw VoipLinkException("Account hostname is empty"); + throw VoipLinkException("Account hostname is empty"); if (account->getUsername().empty()) - throw VoipLinkException("Account username is empty"); + throw VoipLinkException("Account username is empty"); ost::MutexLock m(mutexIAX_); @@ -207,20 +217,20 @@ IAXVoIPLink::sendRegister (Account *a) regSession_ = iax_session_new(); if (regSession_) { - iax_register (regSession_, account->getHostname().data(), account->getUsername().data(), account->getPassword().data(), 120); - nextRefreshStamp_ = time (NULL) + 10; + iax_register(regSession_, account->getHostname().data(), account->getUsername().data(), account->getPassword().data(), 120); + nextRefreshStamp_ = time(NULL) + 10; account->setRegistrationState(Trying); } } void -IAXVoIPLink::sendUnregister (Account *a) +IAXVoIPLink::sendUnregister(Account *a) { - if (regSession_) { - ost::MutexLock m(mutexIAX_); - iax_destroy (regSession_); - regSession_ = NULL; - } + if (regSession_) { + ost::MutexLock m(mutexIAX_); + iax_destroy(regSession_); + regSession_ = NULL; + } nextRefreshStamp_ = 0; @@ -228,32 +238,32 @@ IAXVoIPLink::sendUnregister (Account *a) } Call* -IAXVoIPLink::newOutgoingCall (const std::string& id, const std::string& toUrl) +IAXVoIPLink::newOutgoingCall(const std::string& id, const std::string& toUrl) { - IAXCall* call = new IAXCall (id, Call::Outgoing); + IAXCall* call = new IAXCall(id, Call::Outgoing); - call->setPeerNumber (toUrl); - call->initRecFileName (toUrl); + call->setPeerNumber(toUrl); + call->initRecFileName(toUrl); - iaxOutgoingInvite (call); - call->setConnectionState (Call::Progressing); - call->setState (Call::Active); - addCall (call); + iaxOutgoingInvite(call); + call->setConnectionState(Call::Progressing); + call->setState(Call::Active); + addCall(call); return call; } void -IAXVoIPLink::answer (Call *c) +IAXVoIPLink::answer(Call *c) { IAXCall* call = dynamic_cast<IAXCall*>(c); - Manager::instance().addStream (call->getCallId()); + Manager::instance().addStream(call->getCallId()); - mutexIAX_.enter(); - iax_answer(call->session); - mutexIAX_.leave(); + mutexIAX_.enter(); + iax_answer(call->session); + mutexIAX_.leave(); call->setState(Call::Active); call->setConnectionState(Call::Connected); @@ -262,18 +272,19 @@ IAXVoIPLink::answer (Call *c) } void -IAXVoIPLink::hangup (const std::string& id) +IAXVoIPLink::hangup(const std::string& id) { - _debug ("IAXVoIPLink: Hangup"); + DEBUG("IAXVoIPLink: Hangup"); IAXCall* call = getIAXCall(id); + if (call == NULL) - throw VoipLinkException("Could not find call"); + throw VoipLinkException("Could not find call"); Manager::instance().getMainBuffer()->unBindAll(call->getCallId()); mutexIAX_.enter(); - iax_hangup (call->session, (char*) "Dumped Call"); + iax_hangup(call->session, (char*) "Dumped Call"); mutexIAX_.leave(); call->session = NULL; @@ -283,111 +294,119 @@ IAXVoIPLink::hangup (const std::string& id) void -IAXVoIPLink::peerHungup (const std::string& id) +IAXVoIPLink::peerHungup(const std::string& id) { - _debug ("IAXVoIPLink: Peer hung up"); + DEBUG("IAXVoIPLink: Peer hung up"); + + IAXCall* call = getIAXCall(id); - IAXCall* call = getIAXCall (id); if (call == NULL) - throw VoipLinkException("Could not find call"); + throw VoipLinkException("Could not find call"); - Manager::instance().getMainBuffer()->unBindAll (call->getCallId()); + Manager::instance().getMainBuffer()->unBindAll(call->getCallId()); call->session = NULL; - removeCall (id); + removeCall(id); } void -IAXVoIPLink::onhold (const std::string& id) +IAXVoIPLink::onhold(const std::string& id) { - IAXCall* call = getIAXCall (id); + IAXCall* call = getIAXCall(id); + if (call == NULL) - throw VoipLinkException("Call does not exist"); + throw VoipLinkException("Call does not exist"); - Manager::instance().getMainBuffer()->unBindAll (call->getCallId()); + Manager::instance().getMainBuffer()->unBindAll(call->getCallId()); mutexIAX_.enter(); - iax_quelch_moh (call->session, true); + iax_quelch_moh(call->session, true); mutexIAX_.leave(); - call->setState (Call::Hold); + call->setState(Call::Hold); } void -IAXVoIPLink::offhold (const std::string& id) +IAXVoIPLink::offhold(const std::string& id) { - IAXCall* call = getIAXCall (id); + IAXCall* call = getIAXCall(id); + if (call == NULL) - throw VoipLinkException("Call does not exist"); + throw VoipLinkException("Call does not exist"); - Manager::instance().addStream (call->getCallId()); + Manager::instance().addStream(call->getCallId()); mutexIAX_.enter(); - iax_unquelch (call->session); + iax_unquelch(call->session); mutexIAX_.leave(); Manager::instance().getAudioDriver()->startStream(); - call->setState (Call::Active); + call->setState(Call::Active); } void -IAXVoIPLink::transfer (const std::string& id, const std::string& to) +IAXVoIPLink::transfer(const std::string& id, const std::string& to) { - IAXCall* call = getIAXCall (id); + IAXCall* call = getIAXCall(id); + if (!call) - return; + return; char callto[to.length() +1]; - strcpy (callto, to.c_str()); + strcpy(callto, to.c_str()); mutexIAX_.enter(); - iax_transfer (call->session, callto); + iax_transfer(call->session, callto); mutexIAX_.leave(); } bool IAXVoIPLink::attendedTransfer(const std::string& /*transferID*/, const std::string& /*targetID*/) { - return false; // TODO + return false; // TODO } void -IAXVoIPLink::refuse (const std::string& id) +IAXVoIPLink::refuse(const std::string& id) { - IAXCall* call = getIAXCall (id); + IAXCall* call = getIAXCall(id); + if (call) { - mutexIAX_.enter(); - iax_reject (call->session, (char*) "Call rejected manually."); - mutexIAX_.leave(); + mutexIAX_.enter(); + iax_reject(call->session, (char*) "Call rejected manually."); + mutexIAX_.leave(); - removeCall (id); + removeCall(id); } } void -IAXVoIPLink::carryingDTMFdigits (const std::string& id, char code) +IAXVoIPLink::carryingDTMFdigits(const std::string& id, char code) { - IAXCall* call = getIAXCall (id); + IAXCall* call = getIAXCall(id); + if (call) { - mutexIAX_.enter(); - iax_send_dtmf (call->session, code); - mutexIAX_.leave(); + mutexIAX_.enter(); + iax_send_dtmf(call->session, code); + mutexIAX_.leave(); } } void -IAXVoIPLink::sendTextMessage (sfl::InstantMessaging *module, - const std::string& callID, const std::string& message, - const std::string& /*from*/) +IAXVoIPLink::sendTextMessage(sfl::InstantMessaging *module, + const std::string& callID, + const std::string& message, + const std::string& /*from*/) { - IAXCall* call = getIAXCall (callID); + IAXCall* call = getIAXCall(callID); + if (call) { - mutexIAX_.enter(); - module->send_iax_message (call->session, callID, message.c_str()); - mutexIAX_.leave(); + mutexIAX_.enter(); + module->send_iax_message(call->session, callID, message.c_str()); + mutexIAX_.leave(); } } @@ -402,7 +421,7 @@ IAXVoIPLink::getCurrentCodecName(Call *c) const void -IAXVoIPLink::iaxOutgoingInvite (IAXCall* call) +IAXVoIPLink::iaxOutgoingInvite(IAXCall* call) { ost::MutexLock m(mutexIAX_); @@ -417,16 +436,18 @@ IAXVoIPLink::iaxOutgoingInvite (IAXCall* call) int audio_format_capability = call->getSupportedFormat(accountID_); iax_call(call->session, username.c_str(), username.c_str(), strNum.c_str(), - NULL, 0, audio_format_preferred, audio_format_capability); + NULL, 0, audio_format_preferred, audio_format_capability); } IAXCall* -IAXVoIPLink::iaxFindCallBySession (struct iax_session* session) +IAXVoIPLink::iaxFindCallBySession(iax_session* session) { - ost::MutexLock m(_callMapMutex); - for (CallMap::const_iterator iter = _callMap.begin(); iter != _callMap.end(); ++iter) { - IAXCall* call = dynamic_cast<IAXCall*> (iter->second); + ost::MutexLock m(callMapMutex_); + + for (CallMap::const_iterator iter = callMap_.begin(); iter != callMap_.end(); ++iter) { + IAXCall* call = dynamic_cast<IAXCall*>(iter->second); + if (call and call->session == session) return call; } @@ -435,42 +456,46 @@ IAXVoIPLink::iaxFindCallBySession (struct iax_session* session) } void -IAXVoIPLink::iaxHandleCallEvent (iax_event* event, IAXCall* call) +IAXVoIPLink::iaxHandleCallEvent(iax_event* event, IAXCall* call) { std::string id = call->getCallId(); switch (event->etype) { case IAX_EVENT_HANGUP: - Manager::instance().peerHungupCall (id); + Manager::instance().peerHungupCall(id); - removeCall (id); + removeCall(id); break; case IAX_EVENT_REJECT: - call->setConnectionState (Call::Connected); - call->setState (Call::Error); - Manager::instance().callFailure (id); - removeCall (id); + call->setConnectionState(Call::Connected); + call->setState(Call::Error); + Manager::instance().callFailure(id); + removeCall(id); break; case IAX_EVENT_ACCEPT: + if (event->ies.format) call->format = event->ies.format; + break; case IAX_EVENT_ANSWER: case IAX_EVENT_TRANSFER: + if (call->getConnectionState() == Call::Connected) break; - Manager::instance().addStream (call->getCallId()); + Manager::instance().addStream(call->getCallId()); + + call->setConnectionState(Call::Connected); + call->setState(Call::Active); - call->setConnectionState (Call::Connected); - call->setState (Call::Active); if (event->ies.format) call->format = event->ies.format; - Manager::instance().peerAnsweredCall (id); + Manager::instance().peerAnsweredCall(id); Manager::instance().getAudioDriver()->startStream(); Manager::instance().getMainBuffer()->flushAllBuffers(); @@ -478,23 +503,23 @@ IAXVoIPLink::iaxHandleCallEvent (iax_event* event, IAXCall* call) break; case IAX_EVENT_BUSY: - call->setConnectionState (Call::Connected); - call->setState (Call::Busy); - Manager::instance().callBusy (id); - removeCall (id); + call->setConnectionState(Call::Connected); + call->setState(Call::Busy); + Manager::instance().callBusy(id); + removeCall(id); break; case IAX_EVENT_VOICE: - iaxHandleVoiceEvent (event, call); + iaxHandleVoiceEvent(event, call); break; case IAX_EVENT_TEXT: - Manager::instance ().incomingMessage (call->getCallId (), call->getPeerNumber(), std::string ( (const char*) event->data)); + Manager::instance().incomingMessage(call->getCallId(), call->getPeerNumber(), std::string((const char*) event->data)); break; case IAX_EVENT_RINGA: - call->setConnectionState (Call::Ringing); - Manager::instance().peerRingingCall (call->getCallId()); + call->setConnectionState(Call::Ringing); + Manager::instance().peerRingingCall(call->getCallId()); break; case IAX_IE_MSGCOUNT: @@ -504,73 +529,76 @@ IAXVoIPLink::iaxHandleCallEvent (iax_event* event, IAXCall* call) break; case IAX_EVENT_URL: - if (Manager::instance().getConfigString ("Hooks", "Hooks.iax2_enabled") == "1") - UrlHook::runAction (Manager::instance().getConfigString ("Hooks", "Hooks.url_command"), (char*) event->data); + + if (Manager::instance().getConfigString("Hooks", "Hooks.iax2_enabled") == "1") + UrlHook::runAction(Manager::instance().getConfigString("Hooks", "Hooks.url_command"), (char*) event->data); + break; } } /* Handle audio event, VOICE packet received */ -void -IAXVoIPLink::iaxHandleVoiceEvent (iax_event* event, IAXCall* call) +void IAXVoIPLink::iaxHandleVoiceEvent(iax_event* event, IAXCall* call) { // Skip this empty packet. if (!event->datalen) return; sfl::AudioCodec *audioCodec = static_cast<sfl::AudioCodec *>(Manager::instance().audioCodecFactory.getCodec(call->getAudioCodec())); + if (!audioCodec) return; - Manager::instance().getMainBuffer()->setInternalSamplingRate(audioCodec->getClockRate()); - unsigned int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); + Manager::instance().getMainBuffer()->setInternalSamplingRate(audioCodec->getClockRate()); + unsigned int mainBufferSampleRate = Manager::instance().getMainBuffer()->getInternalSamplingRate(); + + if (event->subclass) + call->format = event->subclass; - if (event->subclass) - call->format = event->subclass; + unsigned char *data = (unsigned char*) event->data; + unsigned int size = event->datalen; - unsigned char *data = (unsigned char*) event->data; - unsigned int size = event->datalen; + unsigned int max = audioCodec->getClockRate() * 20 / 1000; - unsigned int max = audioCodec->getClockRate() * 20 / 1000; + if (size > max) + size = max; - if (size > max) - size = max; + int samples = audioCodec->decode(decData, data , size); + int outSize = samples * sizeof(SFLDataFormat); + SFLDataFormat *out = decData; + unsigned int audioRate = audioCodec->getClockRate(); - int samples = audioCodec->decode (decData, data , size); - int outSize = samples * sizeof(SFLDataFormat); - SFLDataFormat *out = decData; - unsigned int audioRate = audioCodec->getClockRate(); - if (audioRate != mainBufferSampleRate) { - outSize = (double)outSize * (mainBufferSampleRate / audioRate); - converter_.resample (decData, resampledData, mainBufferSampleRate, audioRate, samples); - out = resampledData; - } - Manager::instance().getMainBuffer()->putData (out, outSize, call->getCallId()); + if (audioRate != mainBufferSampleRate) { + outSize = (double)outSize * (mainBufferSampleRate / audioRate); + converter_.resample(decData, resampledData, mainBufferSampleRate, audioRate, samples); + out = resampledData; + } + + Manager::instance().getMainBuffer()->putData(out, outSize, call->getCallId()); } /** * Handle the registration process */ -void -IAXVoIPLink::iaxHandleRegReply (iax_event* event) +void IAXVoIPLink::iaxHandleRegReply(iax_event* event) { IAXAccount *account = dynamic_cast<IAXAccount *>(Manager::instance().getAccount(accountID_)); + if (event->etype != IAX_EVENT_REGREJ && event->etype != IAX_EVENT_REGACK) - return; + return; - ost::MutexLock m(mutexIAX_); - iax_destroy(regSession_); - regSession_ = NULL; + ost::MutexLock m(mutexIAX_); + iax_destroy(regSession_); + regSession_ = NULL; - account->setRegistrationState((event->etype == IAX_EVENT_REGREJ) ? ErrorAuth : Registered); + account->setRegistrationState((event->etype == IAX_EVENT_REGREJ) ? ErrorAuth : Registered); if (event->etype == IAX_EVENT_REGACK) - nextRefreshStamp_ = time (NULL) + (event->ies.refresh ? event->ies.refresh : 60); + nextRefreshStamp_ = time(NULL) + (event->ies.refresh ? event->ies.refresh : 60); } -void -IAXVoIPLink::iaxHandlePrecallEvent (iax_event* event) +void IAXVoIPLink::iaxHandlePrecallEvent(iax_event* event) { IAXCall *call; std::string id; @@ -580,35 +608,36 @@ IAXVoIPLink::iaxHandlePrecallEvent (iax_event* event) case IAX_EVENT_CONNECT: id = Manager::instance().getNewCallID(); - call = new IAXCall (id, Call::Incoming); + call = new IAXCall(id, Call::Incoming); call->session = event->session; - call->setConnectionState (Call::Progressing); + call->setConnectionState(Call::Progressing); if (event->ies.calling_number) call->setPeerNumber(event->ies.calling_number); if (event->ies.calling_name) - call->setPeerName (std::string (event->ies.calling_name)); + call->setPeerName(std::string(event->ies.calling_name)); // if peerNumber exist append it to the name string - call->initRecFileName (std::string (event->ies.calling_number)); + call->initRecFileName(std::string(event->ies.calling_number)); Manager::instance().incomingCall(call, accountID_); - format = call->getFirstMatchingFormat (event->ies.format, accountID_); + format = call->getFirstMatchingFormat(event->ies.format, accountID_); + if (!format) - format = call->getFirstMatchingFormat (event->ies.capability, accountID_); + format = call->getFirstMatchingFormat(event->ies.capability, accountID_); - iax_accept (event->session, format); - iax_ring_announce (event->session); - addCall (call); - call->format = format; + iax_accept(event->session, format); + iax_ring_announce(event->session); + addCall(call); + call->format = format; break; case IAX_EVENT_HANGUP: id = iaxFindCallBySession(event->session)->getCallId(); - Manager::instance().peerHungupCall (id); - removeCall (id); + Manager::instance().peerHungupCall(id); + removeCall(id); break; case IAX_EVENT_TIMEOUT: // timeout for an unknown session diff --git a/daemon/src/iax/iaxvoiplink.h b/daemon/src/iax/iaxvoiplink.h index 5dab2f2dcfdd0a72019a9f9c5cb2fb20c16cb4e7..b8da8b90326376891537a65a6c6f8bf3ad38d00c 100644 --- a/daemon/src/iax/iaxvoiplink.h +++ b/daemon/src/iax/iaxvoiplink.h @@ -36,10 +36,11 @@ #include <iax-client.h> #include "audio/codecs/audiocodec.h" // for DEC_BUFFER_SIZE #include "global.h" +#include "noncopyable.h" #include "audio/samplerateconverter.h" namespace sfl { - class InstantMessaging; +class InstantMessaging; } class EventThread; @@ -56,47 +57,38 @@ class IAXAccount; * and contains IAX Call related functions */ -class IAXVoIPLink : public VoIPLink -{ +class IAXVoIPLink : public VoIPLink { public: - /** - * Constructor - * @param accountID The account containing the voip link - */ - IAXVoIPLink (const std::string& accountID); - - /** - * Destructor - */ + IAXVoIPLink(const std::string& accountID); ~IAXVoIPLink(); /** * Listen to events sent by the call manager ( asterisk, etc .. ) */ - void getEvent (void); + void getEvent(); /** * Init the voip link */ - virtual void init (void); + virtual void init(); /** * Terminate a voip link by clearing the call list */ - virtual void terminate (void); + virtual void terminate(); /** * Send out registration */ - virtual void sendRegister (Account *a); + virtual void sendRegister(Account *a); /** * Destroy registration session * @todo Send an IAX_COMMAND_REGREL to force unregistration upstream. * Urgency: low */ - virtual void sendUnregister (Account *a); + virtual void sendUnregister(Account *a); /** * Create a new outgoing call @@ -104,31 +96,31 @@ class IAXVoIPLink : public VoIPLink * @param toUrl The address to call * @return Call* A pointer on the call */ - virtual Call* newOutgoingCall (const std::string& id, const std::string& toUrl); + virtual Call* newOutgoingCall(const std::string& id, const std::string& toUrl); /** * Answer a call * @param c The call */ - virtual void answer (Call *c); + virtual void answer(Call *c); /** * Hangup a call * @param id The ID of the call */ - virtual void hangup (const std::string& id); + virtual void hangup(const std::string& id); /** * Peer Hungup a call * @param id The ID of the call */ - virtual void peerHungup (const std::string& id); + virtual void peerHungup(const std::string& id); /** * Cancel a call * @param id The ID of the call */ - virtual void cancel (const std::string& id UNUSED) {} + virtual void cancel(const std::string& id UNUSED) {} /** * Put a call on hold @@ -136,7 +128,7 @@ class IAXVoIPLink : public VoIPLink * @return bool true on success * false otherwise */ - virtual void onhold (const std::string& id); + virtual void onhold(const std::string& id); /** * Put a call off hold @@ -144,14 +136,14 @@ class IAXVoIPLink : public VoIPLink * @return bool true on success * false otherwise */ - virtual void offhold (const std::string& id); + virtual void offhold(const std::string& id); /** * Transfer a call * @param id The ID of the call * @param to The recipient of the transfer */ - virtual void transfer (const std::string& id, const std::string& to); + virtual void transfer(const std::string& id, const std::string& to); /** * Perform attended transfer @@ -165,17 +157,17 @@ class IAXVoIPLink : public VoIPLink * Refuse a call * @param id The ID of the call */ - virtual void refuse (const std::string& id); + virtual void refuse(const std::string& id); /** * Send DTMF * @param id The ID of the call * @param code The code of the DTMF */ - virtual void carryingDTMFdigits (const std::string& id, char code); + virtual void carryingDTMFdigits(const std::string& id, char code); - virtual void sendTextMessage (sfl::InstantMessaging *module, const std::string& callID, const std::string& message, const std::string& from); + virtual void sendTextMessage(sfl::InstantMessaging *module, const std::string& callID, const std::string& message, const std::string& from); /** * Return the codec protocol used for this call @@ -184,6 +176,7 @@ class IAXVoIPLink : public VoIPLink virtual std::string getCurrentCodecName(Call *c) const; private: + NON_COPYABLE(IAXVoIPLink); /* * Decode the message count IAX send. * Returns only the new messages number @@ -191,7 +184,7 @@ class IAXVoIPLink : public VoIPLink * @param msgcount The value sent by IAX in the REGACK message * @return int The number of new messages waiting for the current registered user */ - int processIAXMsgCount (int msgcount); + int processIAXMsgCount(int msgcount); /** @@ -199,57 +192,57 @@ class IAXVoIPLink : public VoIPLink * @param id CallId * @return IAXCall pointer or 0 */ - IAXCall* getIAXCall (const std::string& id); + IAXCall* getIAXCall(const std::string& id); /** * Find a iaxcall by iax session number * @param session an iax_session valid pointer * @return iaxcall or 0 if not found */ - IAXCall* iaxFindCallBySession (struct iax_session* session); + IAXCall* iaxFindCallBySession(struct iax_session* session); /** * Handle IAX Event for a call * @param event An iax_event pointer * @param call An IAXCall pointer */ - void iaxHandleCallEvent (iax_event* event, IAXCall* call); + void iaxHandleCallEvent(iax_event* event, IAXCall* call); /** * Handle the VOICE events specifically * @param event The iax_event containing the IAX_EVENT_VOICE * @param call The associated IAXCall */ - void iaxHandleVoiceEvent (iax_event* event, IAXCall* call); + void iaxHandleVoiceEvent(iax_event* event, IAXCall* call); /** * Handle IAX Registration Reply event * @param event An iax_event pointer */ - void iaxHandleRegReply (iax_event* event); + void iaxHandleRegReply(iax_event* event); /** * Handle IAX pre-call setup-related events * @param event An iax_event pointer */ - void iaxHandlePrecallEvent (iax_event* event); + void iaxHandlePrecallEvent(iax_event* event); /** * Work out the audio data from Microphone to IAX2 channel */ - void sendAudioFromMic (void); + void sendAudioFromMic(); /** * Send an outgoing call invite to iax * @param call An IAXCall pointer */ - void iaxOutgoingInvite (IAXCall* call); + void iaxOutgoingInvite(IAXCall* call); /** Threading object */ EventThread* evThread_; /** registration session : 0 if not register */ - struct iax_session* regSession_; + iax_session* regSession_; /** Timestamp of when we should refresh the registration up with * the registrar. Values can be: EPOCH timestamp, 0 if we want no registration, 1 diff --git a/daemon/src/im/InstantMessaging.cpp b/daemon/src/im/InstantMessaging.cpp deleted file mode 100644 index 28f7e587c641c5d69949a4d3e5f7fac6f7cc6dbd..0000000000000000000000000000000000000000 --- a/daemon/src/im/InstantMessaging.cpp +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. - * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> - * Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - -#include "InstantMessaging.h" -#include "logger.h" -#include "expat.h" - -namespace sfl -{ - -static void XMLCALL startElementCallback (void *userData, const char *name, const char **atts) -{ - if (strcmp (name, "entry")) - return; - - sfl::InstantMessaging::UriEntry entry = sfl::InstantMessaging::UriEntry(); - - for (const char **att = atts; *att; att += 2) - entry.insert (std::pair<std::string, std::string> (*att, *(att+1))); - - (static_cast<sfl::InstantMessaging::UriList *> (userData))->push_back(entry); -} - -static void XMLCALL endElementCallback (void * /*userData*/, const char * /*name*/) -{ -} - - -InstantMessaging::InstantMessaging() {} - - -InstantMessaging::~InstantMessaging() {} - -bool InstantMessaging::saveMessage (const std::string& message, const std::string& author, const std::string& id, int mode) -{ - std::ofstream File; - std::string filename = "im:" + id; - File.open (filename.c_str (), (std::_Ios_Openmode) mode); - - if (!File.good () || !File.is_open ()) - return false; - - File << "[" << author << "] " << message << '\n'; - File.close (); - - return true; -} - -void InstantMessaging::sip_send (pjsip_inv_session *session, const std::string& id, const std::string& text) -{ - pjsip_tx_data *tdata; - - pjsip_dialog* dialog = session->dlg; - - pjsip_dlg_inc_lock (dialog); - - pjsip_method msg_method = { PJSIP_OTHER_METHOD, pj_str((char*)"MESSAGE") }; - if (pjsip_dlg_create_request (dialog, &msg_method, -1, &tdata) != PJ_SUCCESS) { - pjsip_dlg_dec_lock (dialog); - return; - } - - const pj_str_t type = pj_str((char*)"text"); - const pj_str_t subtype = pj_str((char*)"plain"); - pj_str_t message = pj_str ( (char*) text.c_str ()); - tdata->msg->body = pjsip_msg_body_create (tdata->pool, &type, &subtype, &message); - - pjsip_dlg_send_request (dialog, tdata, -1, NULL); - pjsip_dlg_dec_lock (dialog); - - saveMessage (text, "Me", id); -} - -void InstantMessaging::send_sip_message (pjsip_inv_session *session, const std::string& id, const std::string& message) -{ - std::vector<std::string> msgs = split_message (message); - std::vector<std::string>::const_iterator iter; - for (iter = msgs.begin(); iter != msgs.end(); ++iter) - sip_send (session, id, *iter); -} - - -void InstantMessaging::send_iax_message (iax_session* session, const std::string& /* id */, const std::string& message) -{ - std::vector<std::string> msgs = split_message (message); - std::vector<std::string>::const_iterator iter; - for (iter = msgs.begin(); iter != msgs.end(); ++iter) - iax_send_text(session, (*iter).c_str()); -} - - -std::vector<std::string> InstantMessaging::split_message(std::string text) -{ - std::vector<std::string> messages; - size_t len = getMessageMaximumSize(); - - while (text.length() > len - 2) { - messages.push_back (text.substr(len - 2) + "\n\n"); - text = text.substr(len - 2); - } - - messages.push_back (text); - - return messages; -} - -std::string InstantMessaging::generateXmlUriList (UriList& list) -{ - std::string xmlbuffer = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" - "<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\" xmlns:cp=\"urn:ietf:params:xml:ns:copycontrol\">" - "<list>"; - - for (UriList::iterator iter = list.begin(); iter != list.end(); ++iter) - xmlbuffer += "<entry uri=" + (*iter)[sfl::IM_XML_URI] + " cp:copyControl=\"to\" />"; - - return xmlbuffer + "</list></resource-lists>"; -} - - -InstantMessaging::UriList InstantMessaging::parseXmlUriList (std::string& urilist) -{ - InstantMessaging::UriList list; - - XML_Parser parser = XML_ParserCreate (NULL); - XML_SetUserData (parser, &list); - XML_SetElementHandler (parser, startElementCallback, endElementCallback); - - if (XML_Parse (parser, urilist.c_str(), urilist.size(), 1) == XML_STATUS_ERROR) { - _error("%s at line %lu\n", XML_ErrorString (XML_GetErrorCode (parser)), - XML_GetCurrentLineNumber (parser)); - throw InstantMessageException ("Error while parsing uri-list xml content"); - } - - return list; -} - -std::string InstantMessaging::appendUriList (std::string text, UriList& list) -{ - return - "--boundary Content-Type: text/plain" + - text + - "--boundary Content-Type: application/resource-lists+xml" + - "Content-Disposition: recipient-list" + - generateXmlUriList (list) + - "--boundary--"; -} - -std::string InstantMessaging::findTextUriList (std::string& text) -{ - std::string ctype = "Content-Type: application/resource-lists+xml"; - std::string cdispo = "Content-Disposition: recipient-list"; - std::string boundary = ("--boundary--"); - - // init position pointer - size_t pos = 0; - size_t begin = 0; - size_t end = 0; - - // find the content type - if ( (pos = text.find (ctype)) == std::string::npos) - throw InstantMessageException ("Could not find Content-Type tag while parsing sip message for recipient-list"); - - // find the content disposition - if ( (pos = text.find (cdispo, pos)) == std::string::npos) - throw InstantMessageException ("Could not find Content-Disposition tag while parsing sip message for recipient-list"); - - // xml content start after content disposition tag (plus \n\n) - begin = pos+cdispo.size(); - - // find final boundary - if ( (end = text.find (boundary, begin)) == std::string::npos) - throw InstantMessageException ("Could not find final \"boundary\" while parsing sip message for recipient-list"); - - return text.substr (begin, end-begin); -} - -std::string InstantMessaging::findTextMessage (std::string& text) -{ - std::string ctype = "Content-Type: text/plain"; - - size_t pos = text.find (ctype); - if (pos == std::string::npos) - throw InstantMessageException ("Could not find Content-Type tag while parsing sip message for text"); - - size_t begin = pos+ctype.size(); - - size_t end = text.find ("--boundary", begin); - if (end == std::string::npos) - throw InstantMessageException ("Could not find end of text \"boundary\" while parsing sip message for text"); - - return text.substr (begin, end-begin); -} - - -} diff --git a/daemon/src/im/Makefile.am b/daemon/src/im/Makefile.am index a59fdac64525c2115e8ecc5ea0c9e03222439068..d3315a25f7468539473547c871c21aa8e72448cb 100644 --- a/daemon/src/im/Makefile.am +++ b/daemon/src/im/Makefile.am @@ -1,8 +1,5 @@ -SUBDIRS = - include $(top_srcdir)/globals.mak noinst_LTLIBRARIES = libim.la -libim_la_SOURCES = \ - InstantMessaging.cpp InstantMessaging.h +libim_la_SOURCES = instant_messaging.cpp instant_messaging.h diff --git a/daemon/src/im/instant_messaging.cpp b/daemon/src/im/instant_messaging.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c4de04741019cb3d66e5e1755d76d244c31b216 --- /dev/null +++ b/daemon/src/im/instant_messaging.cpp @@ -0,0 +1,224 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. + * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> + * Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com> + * + * 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Additional permission under GNU GPL version 3 section 7: + * + * If you modify this program, or any covered work, by linking or + * combining it with the OpenSSL project's OpenSSL library (or a + * modified version of that library), containing parts covered by the + * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. + * grants you additional permission to convey the resulting work. + * Corresponding Source for a non-source form of such a combination + * shall include the source code for the parts of OpenSSL used as well + * as that of the covered work. + */ + +#include "instant_messaging.h" +#include "logger.h" +#include "expat.h" + +namespace sfl { + +static void XMLCALL startElementCallback(void *userData, const char *name, const char **atts) +{ + if (strcmp(name, "entry")) + return; + + sfl::InstantMessaging::UriEntry entry = sfl::InstantMessaging::UriEntry(); + + for (const char **att = atts; *att; att += 2) + entry.insert(std::pair<std::string, std::string> (*att, *(att+1))); + + (static_cast<sfl::InstantMessaging::UriList *>(userData))->push_back(entry); +} + +static void XMLCALL endElementCallback(void * /*userData*/, const char * /*name*/) +{} + +bool InstantMessaging::saveMessage(const std::string& message, const std::string& author, const std::string& id, int mode) +{ + std::ofstream File; + std::string filename = "im:" + id; + File.open(filename.c_str(), (std::_Ios_Openmode) mode); + + if (!File.good() || !File.is_open()) + return false; + + File << "[" << author << "] " << message << '\n'; + File.close(); + + return true; +} + +void InstantMessaging::sip_send(pjsip_inv_session *session, const std::string& id, const std::string& text) +{ + pjsip_tx_data *tdata; + + pjsip_dialog* dialog = session->dlg; + + pjsip_dlg_inc_lock(dialog); + + pjsip_method msg_method = { PJSIP_OTHER_METHOD, pj_str((char*)"MESSAGE") }; + + if (pjsip_dlg_create_request(dialog, &msg_method, -1, &tdata) != PJ_SUCCESS) { + pjsip_dlg_dec_lock(dialog); + return; + } + + const pj_str_t type = pj_str((char*)"text"); + + const pj_str_t subtype = pj_str((char*)"plain"); + + pj_str_t message = pj_str((char*) text.c_str()); + + tdata->msg->body = pjsip_msg_body_create(tdata->pool, &type, &subtype, &message); + + pjsip_dlg_send_request(dialog, tdata, -1, NULL); + + pjsip_dlg_dec_lock(dialog); + + saveMessage(text, "Me", id); +} + +void InstantMessaging::send_sip_message(pjsip_inv_session *session, const std::string& id, const std::string& message) +{ + std::vector<std::string> msgs = split_message(message); + std::vector<std::string>::const_iterator iter; + + for (iter = msgs.begin(); iter != msgs.end(); ++iter) + sip_send(session, id, *iter); +} + + +void InstantMessaging::send_iax_message(iax_session* session, const std::string& /* id */, const std::string& message) +{ + std::vector<std::string> msgs = split_message(message); + std::vector<std::string>::const_iterator iter; + + for (iter = msgs.begin(); iter != msgs.end(); ++iter) + iax_send_text(session, (*iter).c_str()); +} + + +std::vector<std::string> InstantMessaging::split_message(std::string text) +{ + std::vector<std::string> messages; + size_t len = getMessageMaximumSize(); + + while (text.length() > len - 2) { + messages.push_back(text.substr(len - 2) + "\n\n"); + text = text.substr(len - 2); + } + + messages.push_back(text); + + return messages; +} + +std::string InstantMessaging::generateXmlUriList(UriList& list) +{ + std::string xmlbuffer = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\" xmlns:cp=\"urn:ietf:params:xml:ns:copycontrol\">" + "<list>"; + + for (UriList::iterator iter = list.begin(); iter != list.end(); ++iter) + xmlbuffer += "<entry uri=" + (*iter)[sfl::IM_XML_URI] + " cp:copyControl=\"to\" />"; + + return xmlbuffer + "</list></resource-lists>"; +} + + +InstantMessaging::UriList InstantMessaging::parseXmlUriList(std::string& urilist) +{ + InstantMessaging::UriList list; + + XML_Parser parser = XML_ParserCreate(NULL); + XML_SetUserData(parser, &list); + XML_SetElementHandler(parser, startElementCallback, endElementCallback); + + if (XML_Parse(parser, urilist.c_str(), urilist.size(), 1) == XML_STATUS_ERROR) { + ERROR("%s at line %lu\n", XML_ErrorString(XML_GetErrorCode(parser)), + XML_GetCurrentLineNumber(parser)); + throw InstantMessageException("Error while parsing uri-list xml content"); + } + + return list; +} + +std::string InstantMessaging::appendUriList(std::string text, UriList& list) +{ + return + "--boundary Content-Type: text/plain" + + text + + "--boundary Content-Type: application/resource-lists+xml" + + "Content-Disposition: recipient-list" + + generateXmlUriList(list) + + "--boundary--"; +} + +std::string InstantMessaging::findTextUriList(std::string& text) +{ + std::string ctype = "Content-Type: application/resource-lists+xml"; + std::string cdispo = "Content-Disposition: recipient-list"; + std::string boundary = ("--boundary--"); + + // init position pointer + size_t pos = 0; + size_t begin = 0; + size_t end = 0; + + // find the content type + if ((pos = text.find(ctype)) == std::string::npos) + throw InstantMessageException("Could not find Content-Type tag while parsing sip message for recipient-list"); + + // find the content disposition + if ((pos = text.find(cdispo, pos)) == std::string::npos) + throw InstantMessageException("Could not find Content-Disposition tag while parsing sip message for recipient-list"); + + // xml content start after content disposition tag (plus \n\n) + begin = pos+cdispo.size(); + + // find final boundary + if ((end = text.find(boundary, begin)) == std::string::npos) + throw InstantMessageException("Could not find final \"boundary\" while parsing sip message for recipient-list"); + + return text.substr(begin, end-begin); +} + +std::string InstantMessaging::findTextMessage(std::string& text) +{ + std::string ctype = "Content-Type: text/plain"; + + size_t pos = text.find(ctype); + + if (pos == std::string::npos) + throw InstantMessageException("Could not find Content-Type tag while parsing sip message for text"); + + size_t begin = pos+ctype.size(); + + size_t end = text.find("--boundary", begin); + + if (end == std::string::npos) + throw InstantMessageException("Could not find end of text \"boundary\" while parsing sip message for text"); + + return text.substr(begin, end-begin); +} + + +} diff --git a/daemon/src/im/InstantMessaging.h b/daemon/src/im/instant_messaging.h similarity index 76% rename from daemon/src/im/InstantMessaging.h rename to daemon/src/im/instant_messaging.h index c7005da2e24a5a1358824f697b18a08b0c8c286d..17018b56ca0a03eef17d1620de1c4e51eb8b4267 100644 --- a/daemon/src/im/InstantMessaging.h +++ b/daemon/src/im/instant_messaging.h @@ -29,8 +29,8 @@ * as that of the covered work. */ -#ifndef _INSTANT_MESSAGING_H -#define _INSTANT_MESSAGING_H +#ifndef __INSTANT_MESSAGING_H__ +#define __INSTANT_MESSAGING_H__ #include <string> #include <iostream> @@ -55,42 +55,27 @@ #define MODE_APPEND std::ios::out || std::ios::app #define MODE_TEST std::ios::out -namespace sfl -{ +namespace sfl { -const std::string IM_XML_URI ("uri"); -const std::string BOUNDARY ("--boundary"); +const std::string IM_XML_URI("uri"); +const std::string BOUNDARY("--boundary"); -class InstantMessageException : public std::runtime_error -{ +class InstantMessageException : public std::runtime_error { public: - InstantMessageException (const std::string& str="") : + InstantMessageException(const std::string& str="") : std::runtime_error("InstantMessageException occured: " + str) {} }; -class InstantMessaging -{ - +class InstantMessaging { public: - typedef std::map <std::string, std::string> UriEntry; typedef std::list <UriEntry> UriList; - /* - * Class constructor - */ - InstantMessaging(); - - /* - * Class destructor - */ - ~InstantMessaging(); - /** * Return the maximum number if character for a single SIP MESSAGE. * Longer messages should be splitted in several smaller messages using split_message */ - size_t getMessageMaximumSize (void) { + static size_t getMessageMaximumSize() { return MAXIMUM_MESSAGE_LENGTH; } @@ -102,7 +87,7 @@ class InstantMessaging * @param id The current call * @return True if the message could have been successfully saved, False otherwise */ - bool saveMessage (const std::string& message, const std::string& author, const std::string& id, int mode = MODE_APPEND); + bool saveMessage(const std::string& message, const std::string& author, const std::string& id, int mode = MODE_APPEND); /* * Send a SIP string message inside a call @@ -110,10 +95,10 @@ class InstantMessaging * @param id The call ID we will retrieve the invite session from * @param message The string message, as sent by the client */ - void sip_send (pjsip_inv_session*, const std::string& id, const std::string&); + void sip_send(pjsip_inv_session*, const std::string& id, const std::string&); - void send_sip_message (pjsip_inv_session*, const std::string& id, const std::string&); - void send_iax_message (iax_session *session, const std::string& id, const std::string&); + void send_sip_message(pjsip_inv_session*, const std::string& id, const std::string&); + void send_iax_message(iax_session *session, const std::string& id, const std::string&); std::vector<std::string> split_message(std::string); @@ -126,7 +111,7 @@ class InstantMessaging * @return A string containing the full XML formated information to be included in the * sip instant message. */ - std::string generateXmlUriList (UriList& list); + std::string generateXmlUriList(UriList& list); /** * Parse the Urilist from a SIP Instant Message provided by a UriList service. @@ -135,7 +120,7 @@ class InstantMessaging * * @return An UriList of UriEntry containing parsed XML information as a map. */ - UriList parseXmlUriList (std::string& urilist); + UriList parseXmlUriList(std::string& urilist); /** * Format text message according to RFC 5365, append recipient-list to the message @@ -145,7 +130,7 @@ class InstantMessaging * * @return formated text stored into a string to be included in sip MESSAGE */ - std::string appendUriList (std::string text, UriList& list); + std::string appendUriList(std::string text, UriList& list); /** * Retreive the xml formated uri list in formated text data according to RFC 5365 @@ -154,7 +139,7 @@ class InstantMessaging * * @return A string containing the XML content */ - std::string findTextUriList (std::string& text); + std::string findTextUriList(std::string& text); /** * Retrive the plain text message in formated text data according to RFC 5365 @@ -163,12 +148,7 @@ class InstantMessaging * * @return A string containing the actual message */ - std::string findTextMessage (std::string& text); - - private: - - InstantMessaging (const InstantMessaging&); //No Copy Constructor - InstantMessaging& operator= (const InstantMessaging&); //No Assignment Operator + std::string findTextMessage(std::string& text); }; } -#endif // _INSTANT_MESSAGING_H +#endif // __INSTANT_MESSAGING_H_ diff --git a/daemon/src/logger.cpp b/daemon/src/logger.cpp index 3379af8e301839489fe761ec83d7fe5a4c766a5a..5ac86a96449321d378cb1afb4eb66b64b56ad134 100644 --- a/daemon/src/logger.cpp +++ b/daemon/src/logger.cpp @@ -33,13 +33,12 @@ #include <string> #include <cstdio> -namespace Logger -{ +namespace Logger { bool consoleLog = false; bool debugMode = false; -void log (const int level, const char* format, ...) +void log(const int level, const char* format, ...) { if (!debugMode && level == LOG_DEBUG) return; @@ -48,6 +47,7 @@ void log (const int level, const char* format, ...) if (consoleLog) { const char *color_prefix = ""; + switch (level) { case LOG_ERR: color_prefix = RED; @@ -57,26 +57,26 @@ void log (const int level, const char* format, ...) break; } - fputs(color_prefix, stderr); + fputs(color_prefix, stderr); - va_start (ap, format); + va_start(ap, format); vfprintf(stderr, format, ap); - va_end (ap); + va_end(ap); fputs(END_COLOR"\n", stderr); } else { - va_start (ap, format); - vsyslog (level, format, ap); - va_end (ap); + va_start(ap, format); + vsyslog(level, format, ap); + va_end(ap); } } -void setConsoleLog (bool c) +void setConsoleLog(bool c) { consoleLog = c; } -void setDebugMode (bool d) +void setDebugMode(bool d) { debugMode = d; } diff --git a/daemon/src/logger.h b/daemon/src/logger.h index af5df66e20d81b26cc6f5e3dca3979c771d60ac7..9bbf6a9074f3fc38c2857ae255736ca2e5b9c8bc 100644 --- a/daemon/src/logger.h +++ b/daemon/src/logger.h @@ -33,18 +33,17 @@ #include <syslog.h> -namespace Logger -{ -void log (const int, const char*, ...); +namespace Logger { +void log(const int, const char*, ...); -void setConsoleLog (bool); -void setDebugMode (bool); +void setConsoleLog(bool); +void setDebugMode(bool); }; -#define _error(...) Logger::log(LOG_ERR, __VA_ARGS__) -#define _warn(...) Logger::log(LOG_WARNING, __VA_ARGS__) -#define _info(...) Logger::log(LOG_INFO, __VA_ARGS__) -#define _debug(...) Logger::log(LOG_DEBUG, __VA_ARGS__) +#define ERROR(...) Logger::log(LOG_ERR, __VA_ARGS__) +#define WARN(...) Logger::log(LOG_WARNING, __VA_ARGS__) +#define INFO(...) Logger::log(LOG_INFO, __VA_ARGS__) +#define DEBUG(...) Logger::log(LOG_DEBUG, __VA_ARGS__) #define BLACK "\033[22;30m" #define RED "\033[22;31m" diff --git a/daemon/src/main.cpp b/daemon/src/main.cpp index 9ea32a5c8ad61fcebc5b50400738fcaa0a44a6a0..ad6cd9fb9c536c92f26fd678a4bd1939eceda211 100644 --- a/daemon/src/main.cpp +++ b/daemon/src/main.cpp @@ -46,46 +46,46 @@ #include "audio/audiolayer.h" -ost::CommandOptionNoArg console ( +ost::CommandOptionNoArg console( "console", "c", "Log in console (instead of syslog)" ); -ost::CommandOptionNoArg debug ( +ost::CommandOptionNoArg debug( "debug", "d", "Debug mode (more verbose)" ); -ost::CommandOptionNoArg help ( +ost::CommandOptionNoArg help( "help", "h", "Print help" ); // returns true if directory exists static bool check_dir(const char *path) { - DIR *dir = opendir (path); - - if (!dir) { // doesn't exist - if (mkdir (path, 0755) != 0) { // couldn't create the dir - perror(path); - return false; - } - } else { - closedir(dir); - } - - return true; + DIR *dir = opendir(path); + + if (!dir) { // doesn't exist + if (mkdir(path, 0755) != 0) { // couldn't create the dir + perror(path); + return false; + } + } else { + closedir(dir); + } + + return true; } int -main (int argc, char **argv) +main(int argc, char **argv) { set_program_dir(argv[0]); // makeCommandOptionParse allocates the object with operator new, so // auto_ptr is fine in this context. // TODO: This should eventually be replaced with std::unique_ptr for C++0x - std::auto_ptr<ost::CommandOptionParse> args(ost::makeCommandOptionParse (argc, argv, "")); + std::auto_ptr<ost::CommandOptionParse> args(ost::makeCommandOptionParse(argc, argv, "")); - printf ("SFLphone Daemon "VERSION", by Savoir-Faire Linux 2004-2011\n" \ - "http://www.sflphone.org/\n"); + printf("SFLphone Daemon "VERSION", by Savoir-Faire Linux 2004-2011\n" \ + "http://www.sflphone.org/\n"); if (help.numSet) { std::cerr << args->printUsage(); @@ -96,50 +96,55 @@ main (int argc, char **argv) return 1; } - Logger::setConsoleLog (console.numSet); - Logger::setDebugMode (debug.numSet); + Logger::setConsoleLog(console.numSet); + Logger::setDebugMode(debug.numSet); const char *xdg_env = XDG_CACHE_HOME; - std::string path = xdg_env ? xdg_env : std::string(HOMEDIR) + DIR_SEPARATOR_STR ".cache/"; + std::string path = xdg_env ? xdg_env : std::string(HOMEDIR) + DIR_SEPARATOR_STR ".cache/"; + + if (!check_dir(path.c_str())) + return 1; - if (!check_dir(path.c_str())) - return 1; path = path + "sflphone"; - if (!check_dir(path.c_str())) - return 1; - std::string pidfile = path + "/" PIDFILE; - FILE *fp = fopen (pidfile.c_str(),"r"); + if (!check_dir(path.c_str())) + return 1; + + std::string pidfile = path + "/" PIDFILE; + FILE *fp = fopen(pidfile.c_str(),"r"); + if (fp) { // PID file exists. Check the former process still alive or not. If alive, give user a hint. - int oldPid; - if (fscanf(fp, "%d", &oldPid) != 1) { + int oldPid; + + if (fscanf(fp, "%d", &oldPid) != 1) { std::cerr << "Couldn't read pidfile " << pidfile << std::endl; - return 1; - } + return 1; + } - fclose (fp); + fclose(fp); - if (kill (oldPid, 0) == 0) { + if (kill(oldPid, 0) == 0) { std::cerr << "There is already a sflphoned daemon running in the system. Starting Failed." << std::endl; - return 1; - } - } + return 1; + } + } // write pid file - fp = fopen (pidfile.c_str(),"w"); + fp = fopen(pidfile.c_str(),"w"); + if (!fp) { - perror(pidfile.c_str()); + perror(pidfile.c_str()); return 1; } else { std::ostringstream pidstr; pidstr << getpid(); - fputs (pidstr.str().c_str() , fp); - fclose (fp); + fputs(pidstr.str().c_str() , fp); + fclose(fp); } try { - Manager::instance().init(); + Manager::instance().init(); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; return 1; @@ -148,7 +153,7 @@ main (int argc, char **argv) return 1; } - _debug ("Starting DBus event loop"); + DEBUG("Starting DBus event loop"); Manager::instance().getDbusManager()->exec(); return 0; diff --git a/daemon/src/manager.h b/daemon/src/manager.h index ca19d50f065d292682dc078ca81e9988c8e7fe1e..730b4d0b3f7376679745b83ed217119cb1b46a84 100644 --- a/daemon/src/manager.h +++ b/daemon/src/manager.h @@ -32,7 +32,7 @@ #ifndef SFLPHONE_MANAGER_H #define SFLPHONE_MANAGER_H -#include "utilspp/Singleton.hpp" +#include "utilspp/singleton.hpp" #include "managerimpl.h" typedef utilspp::SingletonHolder<ManagerImpl> Manager; diff --git a/daemon/src/managerimpl.cpp b/daemon/src/managerimpl.cpp index a59b99b4a88ae5c7755b433ce818d286251585f1..5625855a3c5c9a59f18041190373bad5cabe7729 100644 --- a/daemon/src/managerimpl.cpp +++ b/daemon/src/managerimpl.cpp @@ -40,7 +40,7 @@ #include "dbus/callmanager.h" #include "global.h" #include "sip/sipaccount.h" -#include "im/InstantMessaging.h" +#include "im/instant_messaging.h" #include "iax/iaxaccount.h" #include "numbercleaner.h" @@ -67,117 +67,116 @@ #include <sys/types.h> // mkdir(2) #include <sys/stat.h> // mkdir(2) -ManagerImpl::ManagerImpl (void) : - _hasTriedToRegister (false), _config(), _currentCallId2(), - _currentCallMutex(), _audiodriver (0), - _dtmfKey (0), _toneMutex(), - _telephoneTone (0), _audiofile (0), _spkr_volume (0), - _mic_volume (0), _waitingCall(), - _waitingCallMutex(), _nbIncomingWaitingCall (0), _path (""), - _callAccountMap(), - _callAccountMapMutex(), _callConfigMap(), _accountMap(), - _history (new HistoryManager), _imModule(new sfl::InstantMessaging) +ManagerImpl::ManagerImpl() : + preferences(), voipPreferences(), addressbookPreference(), + hookPreference(), audioPreference(), shortcutPreferences(), + hasTriedToRegister_(false), audioCodecFactory(), dbus_(), config_(), currentCallId_(), + currentCallMutex_(), audiodriver_(0), dtmfKey_(0), toneMutex_(), + telephoneTone_(0), audiofile_(0), speakerVolume_(0), micVolume_(0), + audiolayerMutex_(), waitingCall_(), waitingCallMutex_(), + nbIncomingWaitingCall_(0), path_(), callAccountMap_(), + callAccountMapMutex_(), callConfigMap_(), accountMap_(), + mainBuffer_(), conferenceMap_(), history_(new HistoryManager), + imModule_(new sfl::InstantMessaging) { // initialize random generator for call id - srand (time (NULL)); + srand(time(NULL)); } // never call if we use only the singleton... -ManagerImpl::~ManagerImpl (void) +ManagerImpl::~ManagerImpl() { - delete _imModule; - delete _history; - delete _audiofile; + delete imModule_; + delete history_; + delete audiofile_; } -void ManagerImpl::init (std::string config_file) +void ManagerImpl::init(std::string config_file) { - if (config_file.empty()) - config_file = getConfigFile(); - _path = config_file; + if (config_file.empty()) + config_file = getConfigFile(); - _debug ("Manager: configuration file path: %s", _path.c_str()); + path_ = config_file; + + DEBUG("Manager: configuration file path: %s", path_.c_str()); Conf::YamlParser *parser = NULL; - try { - parser = new Conf::YamlParser (_path.c_str()); - parser->serializeEvents(); - parser->composeEvents(); - parser->constructNativeData(); - } catch (Conf::YamlParserException &e) { - _error ("Manager: %s", e.what()); - fflush(stderr); - delete parser; - parser = NULL; - } - - loadAccountMap(parser); - delete parser; + try { + parser = new Conf::YamlParser(path_.c_str()); + parser->serializeEvents(); + parser->composeEvents(); + parser->constructNativeData(); + } catch (Conf::YamlParserException &e) { + ERROR("Manager: %s", e.what()); + fflush(stderr); + delete parser; + parser = NULL; + } + + loadAccountMap(parser); + delete parser; initVolume(); initAudioDriver(); audioLayerMutexLock(); - if (_audiodriver) { - _telephoneTone = new TelephoneTone (preferences.getZoneToneChoice(), _audiodriver->getSampleRate()); - _dtmfKey = new DTMF (8000); + if (audiodriver_) { + telephoneTone_ = new TelephoneTone(preferences.getZoneToneChoice(), audiodriver_->getSampleRate()); + dtmfKey_ = new DTMF(8000); } audioLayerMutexUnlock(); - _history->load_history (preferences.getHistoryLimit()); + history_->load_history(preferences.getHistoryLimit()); registerAccounts(); } -void ManagerImpl::terminate () +void ManagerImpl::terminate() { std::vector<std::string> callList(getCallList()); - _debug ("Manager: Hangup %zu remaining call", callList.size()); + DEBUG("Manager: Hangup %zu remaining call", callList.size()); - std::vector<std::string>::iterator iter; - for (iter = callList.begin(); iter != callList.end(); ++iter) - hangupCall (*iter); + for (std::vector<std::string>::iterator iter = callList.begin(); iter != callList.end(); ++iter) + hangupCall(*iter); unloadAccountMap(); delete SIPVoIPLink::instance(); - - delete _dtmfKey; - - delete _telephoneTone; - _telephoneTone = NULL; + delete dtmfKey_; + delete telephoneTone_; + telephoneTone_ = NULL; audioLayerMutexLock(); - delete _audiodriver; - _audiodriver = NULL; + delete audiodriver_; + audiodriver_ = NULL; audioLayerMutexUnlock(); } -bool ManagerImpl::isCurrentCall (const std::string& callId) +bool ManagerImpl::isCurrentCall(const std::string& callId) const { - return _currentCallId2 == callId; + return currentCallId_ == callId; } -bool ManagerImpl::hasCurrentCall () +bool ManagerImpl::hasCurrentCall() const { - return not _currentCallId2.empty(); + return not currentCallId_.empty(); } -const std::string& -ManagerImpl::getCurrentCallId () const +std::string +ManagerImpl::getCurrentCallId() const { - return _currentCallId2; + return currentCallId_; } -void ManagerImpl::switchCall (const std::string& id) +void ManagerImpl::switchCall(const std::string& id) { - ost::MutexLock m (_currentCallMutex); - _debug ("----- Switch current call id to %s -----", id.c_str()); - _currentCallId2 = id; + ost::MutexLock m(currentCallMutex_); + DEBUG("----- Switch current call id to %s -----", id.c_str()); + currentCallId_ = id; } /////////////////////////////////////////////////////////////////////////////// @@ -185,21 +184,23 @@ void ManagerImpl::switchCall (const std::string& id) /////////////////////////////////////////////////////////////////////////////// /* Main Thread */ -bool ManagerImpl::outgoingCall (const std::string& account_id, - const std::string& call_id, const std::string& to, const std::string& conf_id) +bool ManagerImpl::outgoingCall(const std::string& account_id, + const std::string& call_id, + const std::string& to, + const std::string& conf_id) { if (call_id.empty()) { - _debug ("Manager: New outgoing call abort, missing callid"); + DEBUG("Manager: New outgoing call abort, missing callid"); return false; } // Call ID must be unique - if (not getAccountFromCall (call_id).empty()) { - _error ("Manager: Error: Call id already exists in outgoing call"); + if (not getAccountFromCall(call_id).empty()) { + ERROR("Manager: Error: Call id already exists in outgoing call"); return false; } - _debug ("Manager: New outgoing call %s to %s", call_id.c_str(), to.c_str()); + DEBUG("Manager: New outgoing call %s to %s", call_id.c_str(), to.c_str()); stopTone(); @@ -211,52 +212,56 @@ bool ManagerImpl::outgoingCall (const std::string& account_id, std::string to_cleaned(NumberCleaner::clean(to, prefix)); - Call::CallConfiguration callConfig = (to_cleaned.find (SIP_SCHEME) == 0 or to_cleaned.find (SIPS_SCHEME) == 0) ? Call::IPtoIP : Call::Classic; + static const char * const SIP_SCHEME = "sip:"; + static const char * const SIPS_SCHEME = "sips:"; + + Call::CallConfiguration callConfig = (to_cleaned.find(SIP_SCHEME) == 0 or to_cleaned.find(SIPS_SCHEME) == 0) ? Call::IPtoIP : Call::Classic; associateConfigToCall(call_id, callConfig); // in any cases we have to detach from current communication if (hasCurrentCall()) { - _debug ("Manager: Has current call (%s) put it onhold", current_call_id.c_str()); + DEBUG("Manager: Has current call (%s) put it onhold", current_call_id.c_str()); // if this is not a conferenceand this and is not a conference participant - if (!isConference (current_call_id) && !participToConference (current_call_id)) - onHoldCall (current_call_id); - else if (isConference (current_call_id) && !participToConference (call_id)) - detachParticipant (Call::DEFAULT_ID, current_call_id); + if (not isConference(current_call_id) and not isConferenceParticipant(current_call_id)) + onHoldCall(current_call_id); + else if (isConference(current_call_id) and not isConferenceParticipant(call_id)) + detachParticipant(Call::DEFAULT_ID, current_call_id); } if (callConfig == Call::IPtoIP) { - _debug ("Manager: Start IP2IP call"); + DEBUG("Manager: Start IP2IP call"); + /* We need to retrieve the sip voiplink instance */ if (SIPVoIPLink::instance()->SIPNewIpToIpCall(call_id, to_cleaned)) { - switchCall (call_id); + switchCall(call_id); return true; } else - callFailure (call_id); + callFailure(call_id); return false; } - _debug ("Manager: Selecting account %s", account_id.c_str()); + DEBUG("Manager: Selecting account %s", account_id.c_str()); // Is this account exist - if (!accountExists (account_id)) { - _error ("Manager: Error: Account doesn't exist in new outgoing call"); + if (!accountExists(account_id)) { + ERROR("Manager: Error: Account doesn't exist in new outgoing call"); return false; } - if(!associateCallToAccount (call_id, account_id)) - _warn("Manager: Warning: Could not associate call id %s to account id %s", call_id.c_str(), account_id.c_str()); + if (!associateCallToAccount(call_id, account_id)) + WARN("Manager: Warning: Could not associate call id %s to account id %s", call_id.c_str(), account_id.c_str()); try { - Call *call = getAccountLink(account_id)->newOutgoingCall (call_id, to_cleaned); - - switchCall (call_id); + Call *call = getAccountLink(account_id)->newOutgoingCall(call_id, to_cleaned); + + switchCall(call_id); call->setConfId(conf_id); } catch (const VoipLinkException &e) { - callFailure (call_id); - _error ("Manager: %s", e.what()); + callFailure(call_id); + ERROR("Manager: %s", e.what()); return false; } @@ -266,9 +271,9 @@ bool ManagerImpl::outgoingCall (const std::string& account_id, } //THREAD=Main : for outgoing Call -bool ManagerImpl::answerCall (const std::string& call_id) +bool ManagerImpl::answerCall(const std::string& call_id) { - _debug ("Manager: Answer call %s", call_id.c_str()); + DEBUG("Manager: Answer call %s", call_id.c_str()); // If sflphone is ringing stopTone(); @@ -277,66 +282,65 @@ bool ManagerImpl::answerCall (const std::string& call_id) std::string current_call_id(getCurrentCallId()); // Retreive call coresponding to this id - std::string account_id = getAccountFromCall (call_id); - Call *call = getAccountLink (account_id)->getCall (call_id); + std::string account_id = getAccountFromCall(call_id); + Call *call = getAccountLink(account_id)->getCall(call_id); + if (call == NULL) { - _error("Manager: Error: Call is null"); + ERROR("Manager: Error: Call is null"); } // in any cases we have to detach from current communication if (hasCurrentCall()) { - _debug ("Manager: Currently conversing with %s", current_call_id.c_str()); + DEBUG("Manager: Currently conversing with %s", current_call_id.c_str()); - if (!isConference(current_call_id) && !participToConference (current_call_id)) { - // if it is not a conference and is not a conference participant - _debug ("Manager: Answer call: Put the current call (%s) on hold", current_call_id.c_str()); - onHoldCall (current_call_id); - } else if (isConference (current_call_id) && !participToConference (call_id)) { + if (not isConference(current_call_id) and not isConferenceParticipant(current_call_id)) { + DEBUG("Manager: Answer call: Put the current call (%s) on hold", current_call_id.c_str()); + onHoldCall(current_call_id); + } else if (isConference(current_call_id) and not isConferenceParticipant(call_id)) { // if we are talking to a conference and we are answering an incoming call - _debug ("Manager: Detach main participant from conference"); - detachParticipant (Call::DEFAULT_ID, current_call_id); + DEBUG("Manager: Detach main participant from conference"); + detachParticipant(Call::DEFAULT_ID, current_call_id); } } try { - getAccountLink (account_id)->answer (call); - } - catch (const VoipLinkException &e) { - _error("Manager: Error: %s", e.what()); + getAccountLink(account_id)->answer(call); + } catch (const VoipLinkException &e) { + ERROR("Manager: Error: %s", e.what()); } // if it was waiting, it's waiting no more - removeWaitingCall (call_id); + removeWaitingCall(call_id); // if we dragged this call into a conference already - if (participToConference (call_id)) - switchCall (call->getConfId()); + if (isConferenceParticipant(call_id)) + switchCall(call->getConfId()); else - switchCall (call_id); + switchCall(call_id); // Connect streams - addStream (call_id); + addStream(call_id); getMainBuffer()->stateInfo(); // Start recording if set in preference if (audioPreference.getIsAlwaysRecording()) - setRecordingCall(call_id); + setRecordingCall(call_id); // update call state on client side if (audioPreference.getIsAlwaysRecording()) - _dbus.getCallManager()->callStateChanged (call_id, "RECORD"); + dbus_.getCallManager()->callStateChanged(call_id, "RECORD"); else - _dbus.getCallManager()->callStateChanged(call_id, "CURRENT"); + dbus_.getCallManager()->callStateChanged(call_id, "CURRENT"); return true; } //THREAD=Main -void ManagerImpl::hangupCall (const std::string& callId) +void ManagerImpl::hangupCall(const std::string& callId) { - _info ("Manager: Hangup call %s", callId.c_str()); + INFO("Manager: Hangup call %s", callId.c_str()); // store the current call id std::string currentCallId(getCurrentCallId()); @@ -344,67 +348,69 @@ void ManagerImpl::hangupCall (const std::string& callId) stopTone(); /* Broadcast a signal over DBus */ - _debug ("Manager: Send DBUS call state change (HUNGUP) for id %s", callId.c_str()); - _dbus.getCallManager()->callStateChanged (callId, "HUNGUP"); + DEBUG("Manager: Send DBUS call state change (HUNGUP) for id %s", callId.c_str()); + dbus_.getCallManager()->callStateChanged(callId, "HUNGUP"); if (not isValidCall(callId) and not getConfigFromCall(callId) == Call::IPtoIP) { - _error("Manager: Error: Could not hang up call, call not valid"); + ERROR("Manager: Error: Could not hang up call, call not valid"); return; } // Disconnect streams removeStream(callId); - if (participToConference (callId)) { - Conference *conf = getConferenceFromCallID (callId); + if (isConferenceParticipant(callId)) { + Conference *conf = getConferenceFromCallID(callId); + if (conf != NULL) { // remove this participant - removeParticipant (callId); - processRemainingParticipant (currentCallId, conf); + removeParticipant(callId); + processRemainingParticipants(currentCallId, conf); } } else { - // we are not participating to a conference, current call switched to "" - if (!isConference (currentCallId)) - switchCall (""); + // we are not participating in a conference, current call switched to "" + if (not isConference(currentCallId)) + switchCall(""); } - if (getConfigFromCall (callId) == Call::IPtoIP) { + if (getConfigFromCall(callId) == Call::IPtoIP) { /* Direct IP to IP call */ try { - SIPVoIPLink::instance()->hangup (callId); + SIPVoIPLink::instance()->hangup(callId); + } catch (const VoipLinkException &e) { + ERROR("%s", e.what()); } - catch (const VoipLinkException &e) - { - _error("%s", e.what()); - } - } - else { - std::string accountId (getAccountFromCall (callId)); - getAccountLink (accountId)->hangup (callId); - removeCallAccount (callId); + } else { + std::string accountId(getAccountFromCall(callId)); + getAccountLink(accountId)->hangup(callId); + removeCallAccount(callId); } getMainBuffer()->stateInfo(); } -bool ManagerImpl::hangupConference (const std::string& id) +bool ManagerImpl::hangupConference(const std::string& id) { - _debug ("Manager: Hangup conference %s", id.c_str()); + DEBUG("Manager: Hangup conference %s", id.c_str()); - ConferenceMap::iterator iter_conf = _conferencemap.find (id); + ConferenceMap::iterator iter_conf = conferenceMap_.find(id); - std::string currentAccountId; - - if (iter_conf != _conferencemap.end()) { + if (iter_conf != conferenceMap_.end()) { Conference *conf = iter_conf->second; - const ParticipantSet &participants = conf->getParticipantList(); - ParticipantSet::const_iterator iter; - for (iter = participants.begin(); iter != participants.end(); ++iter) - hangupCall (*iter); + if (conf) { + ParticipantSet participants(conf->getParticipantList()); + + for (ParticipantSet::const_iterator iter = participants.begin(); + iter != participants.end(); ++iter) + hangupCall(*iter); + } else { + ERROR("Manager: No such conference %s", id.c_str()); + return false; + } } - switchCall (""); + switchCall(""); getMainBuffer()->stateInfo(); @@ -413,57 +419,56 @@ bool ManagerImpl::hangupConference (const std::string& id) //THREAD=Main -void ManagerImpl::onHoldCall (const std::string& callId) +void ManagerImpl::onHoldCall(const std::string& callId) { - _debug ("Manager: Put call %s on hold", callId.c_str()); + DEBUG("Manager: Put call %s on hold", callId.c_str()); stopTone(); std::string current_call_id(getCurrentCallId()); try { - if (getConfigFromCall (callId) == Call::IPtoIP) { - /* Direct IP to IP call */ - SIPVoIPLink::instance ()-> onhold (callId); - } - else { - /* Classic call, attached to an account */ - std::string account_id(getAccountFromCall (callId)); + if (getConfigFromCall(callId) == Call::IPtoIP) { + /* Direct IP to IP call */ + SIPVoIPLink::instance()-> onhold(callId); + } else { + /* Classic call, attached to an account */ + std::string account_id(getAccountFromCall(callId)); if (account_id.empty()) { - _debug ("Manager: Account ID %s or callid %s doesn't exists in call onHold", account_id.c_str(), callId.c_str()); + DEBUG("Manager: Account ID %s or callid %s doesn't exists in call onHold", account_id.c_str(), callId.c_str()); return; } - getAccountLink(account_id)->onhold(callId); - } - } - catch (const VoipLinkException &e) { - _error("Manager: Error: %s", e.what()); + + getAccountLink(account_id)->onhold(callId); + } + } catch (const VoipLinkException &e) { + ERROR("Manager: Error: %s", e.what()); } // Unbind calls in main buffer - removeStream (callId); + removeStream(callId); // Remove call from teh queue if it was still there - removeWaitingCall (callId); + removeWaitingCall(callId); // keeps current call id if the action is not holding this call or a new outgoing call // this could happen in case of a conference if (current_call_id == callId) - switchCall (""); + switchCall(""); - _dbus.getCallManager()->callStateChanged (callId, "HOLD"); + dbus_.getCallManager()->callStateChanged(callId, "HOLD"); getMainBuffer()->stateInfo(); } //THREAD=Main -void ManagerImpl::offHoldCall (const std::string& callId) +void ManagerImpl::offHoldCall(const std::string& callId) { std::string accountId; std::string codecName; - _debug ("Manager: Put call %s off hold", callId.c_str()); + DEBUG("Manager: Put call %s off hold", callId.c_str()); stopTone(); @@ -473,44 +478,43 @@ void ManagerImpl::offHoldCall (const std::string& callId) if (hasCurrentCall()) { - // if this is not a conference and this and is not a conference participant - if (!isConference (currentCallId) && !participToConference (currentCallId)) { - _debug ("Manager: Has current call (%s), put on hold", currentCallId.c_str()); - onHoldCall (currentCallId); - } else if (isConference (currentCallId) && !participToConference (callId)) - detachParticipant (Call::DEFAULT_ID, currentCallId); + if (not isConference(currentCallId) and not isConferenceParticipant(currentCallId)) { + DEBUG("Manager: Has current call (%s), put on hold", currentCallId.c_str()); + onHoldCall(currentCallId); + } else if (isConference(currentCallId) and not isConferenceParticipant(callId)) + detachParticipant(Call::DEFAULT_ID, currentCallId); } bool isRec = false; /* Direct IP to IP call */ - if (getConfigFromCall (callId) == Call::IPtoIP) - SIPVoIPLink::instance ()-> offhold (callId); + if (getConfigFromCall(callId) == Call::IPtoIP) + SIPVoIPLink::instance()-> offhold(callId); else { /* Classic call, attached to an account */ - accountId = getAccountFromCall (callId); + accountId = getAccountFromCall(callId); - _debug ("Manager: Setting offhold, Account %s, callid %s", accountId.c_str(), callId.c_str()); + DEBUG("Manager: Setting offhold, Account %s, callid %s", accountId.c_str(), callId.c_str()); - Call * call = getAccountLink (accountId)->getCall (callId); - if (call) - { + Call * call = getAccountLink(accountId)->getCall(callId); + + if (call) { isRec = call->isRecording(); getAccountLink(accountId)->offhold(callId); } } - _dbus.getCallManager()->callStateChanged (callId, isRec ? "UNHOLD_RECORD" : "UNHOLD_CURRENT"); + dbus_.getCallManager()->callStateChanged(callId, isRec ? "UNHOLD_RECORD" : "UNHOLD_CURRENT"); - if (participToConference (callId)) { + if (isConferenceParticipant(callId)) { std::string currentAccountId(getAccountFromCall(callId)); - Call *call = getAccountLink (currentAccountId)->getCall (callId); + Call *call = getAccountLink(currentAccountId)->getCall(callId); if (call) - switchCall (call->getConfId()); + switchCall(call->getConfId()); } else - switchCall (callId); + switchCall(callId); addStream(callId); @@ -518,41 +522,43 @@ void ManagerImpl::offHoldCall (const std::string& callId) } //THREAD=Main -bool ManagerImpl::transferCall (const std::string& callId, const std::string& to) +bool ManagerImpl::transferCall(const std::string& callId, const std::string& to) { - if (participToConference(callId)) { - removeParticipant (callId); - processRemainingParticipant (callId, getConferenceFromCallID(callId)); - } else if (!isConference(getCurrentCallId())) - switchCall(""); + if (isConferenceParticipant(callId)) { + removeParticipant(callId); + Conference *conf = getConferenceFromCallID(callId); + processRemainingParticipants(callId, conf); + } else if (not isConference(getCurrentCallId())) + switchCall(""); // Direct IP to IP call if (getConfigFromCall(callId) == Call::IPtoIP) - SIPVoIPLink::instance()->transfer (callId, to); + SIPVoIPLink::instance()->transfer(callId, to); else { - std::string accountid(getAccountFromCall (callId)); - if (accountid == "") + std::string accountid(getAccountFromCall(callId)); + + if (accountid.empty()) return false; - getAccountLink(accountid)->transfer (callId, to); + getAccountLink(accountid)->transfer(callId, to); } // remove waiting call in case we make transfer without even answer - removeWaitingCall (callId); + removeWaitingCall(callId); getMainBuffer()->stateInfo(); return true; } -void ManagerImpl::transferFailed () +void ManagerImpl::transferFailed() { - _dbus.getCallManager()->transferFailed(); + dbus_.getCallManager()->transferFailed(); } -void ManagerImpl::transferSucceded () +void ManagerImpl::transferSucceded() { - _dbus.getCallManager()->transferSucceded(); + dbus_.getCallManager()->transferSucceded(); } bool ManagerImpl::attendedTransfer(const std::string& transferID, const std::string& targetID) @@ -561,41 +567,43 @@ bool ManagerImpl::attendedTransfer(const std::string& transferID, const std::str return SIPVoIPLink::instance()->attendedTransfer(transferID, targetID); // Classic call, attached to an account - std::string accountid = getAccountFromCall(transferID); - if (accountid.empty()) - return false; + std::string accountid(getAccountFromCall(transferID)); + + if (accountid.empty()) + return false; - return getAccountLink(accountid)->attendedTransfer(transferID, targetID); + return getAccountLink(accountid)->attendedTransfer(transferID, targetID); } //THREAD=Main : Call:Incoming -void ManagerImpl::refuseCall (const std::string& id) +void ManagerImpl::refuseCall(const std::string& id) { stopTone(); if (getCallList().size() <= 1) { audioLayerMutexLock(); - _audiodriver->stopStream(); + audiodriver_->stopStream(); audioLayerMutexUnlock(); } /* Direct IP to IP call */ - if (getConfigFromCall (id) == Call::IPtoIP) - SIPVoIPLink::instance()->refuse (id); + if (getConfigFromCall(id) == Call::IPtoIP) + SIPVoIPLink::instance()->refuse(id); else { /* Classic call, attached to an account */ - std::string accountid = getAccountFromCall (id); + std::string accountid = getAccountFromCall(id); + if (accountid.empty()) return; getAccountLink(accountid)->refuse(id); - removeCallAccount (id); + removeCallAccount(id); } - removeWaitingCall(id); - _dbus.getCallManager()->callStateChanged(id, "HUNGUP"); + removeWaitingCall(id); + dbus_.getCallManager()->callStateChanged(id, "HUNGUP"); // Disconnect streams removeStream(id); @@ -604,118 +612,117 @@ void ManagerImpl::refuseCall (const std::string& id) } Conference* -ManagerImpl::createConference (const std::string& id1, const std::string& id2) +ManagerImpl::createConference(const std::string& id1, const std::string& id2) { - typedef std::pair<std::string, Conference*> ConferenceEntry; - _debug ("Manager: Create conference with call %s and %s", id1.c_str(), id2.c_str()); + DEBUG("Manager: Create conference with call %s and %s", id1.c_str(), id2.c_str()); Conference* conf = new Conference; - conf->add (id1); - conf->add (id2); + conf->add(id1); + conf->add(id2); // Add conference to map - _conferencemap.insert (ConferenceEntry (conf->getConfID(), conf)); + conferenceMap_.insert(std::make_pair(conf->getConfID(), conf)); // broadcast a signal over dbus - _dbus.getCallManager()->conferenceCreated (conf->getConfID()); + dbus_.getCallManager()->conferenceCreated(conf->getConfID()); return conf; } -void ManagerImpl::removeConference (const std::string& conference_id) +void ManagerImpl::removeConference(const std::string& conference_id) { - _debug ("Manager: Remove conference %s", conference_id.c_str()); + DEBUG("Manager: Remove conference %s", conference_id.c_str()); - _debug ("Manager: number of participant: %d", (int) _conferencemap.size()); - ConferenceMap::iterator iter = _conferencemap.find (conference_id); + DEBUG("Manager: number of participants: %u", conferenceMap_.size()); + ConferenceMap::iterator iter = conferenceMap_.find(conference_id); - Conference* conf = NULL; + Conference* conf = 0; - if (iter != _conferencemap.end()) + if (iter != conferenceMap_.end()) conf = iter->second; if (conf == NULL) { - _error ("Manager: Error: Conference not found"); + ERROR("Manager: Error: Conference not found"); return; } // broadcast a signal over dbus - _dbus.getCallManager()->conferenceRemoved (conference_id); + dbus_.getCallManager()->conferenceRemoved(conference_id); // We now need to bind the audio to the remain participant // Unbind main participant audio from conference - getMainBuffer()->unBindAll (Call::DEFAULT_ID); + getMainBuffer()->unBindAll(Call::DEFAULT_ID); - const ParticipantSet &participants = conf->getParticipantList(); + ParticipantSet participants(conf->getParticipantList()); // bind main participant audio to remaining conference call ParticipantSet::iterator iter_p = participants.begin(); if (iter_p != participants.end()) - getMainBuffer()->bindCallID (*iter_p, Call::DEFAULT_ID); + getMainBuffer()->bindCallID(*iter_p, Call::DEFAULT_ID); // Then remove the conference from the conference map - if (_conferencemap.erase (conference_id) == 1) - _debug ("Manager: Conference %s removed successfully", conference_id.c_str()); + if (conferenceMap_.erase(conference_id) == 1) + DEBUG("Manager: Conference %s removed successfully", conference_id.c_str()); else - _error ("Manager: Error: Cannot remove conference: %s", conference_id.c_str()); + ERROR("Manager: Error: Cannot remove conference: %s", conference_id.c_str()); delete conf; } Conference* -ManagerImpl::getConferenceFromCallID (const std::string& call_id) +ManagerImpl::getConferenceFromCallID(const std::string& call_id) { - std::string account_id; - - account_id = getAccountFromCall (call_id); - Call *call = getAccountLink (account_id)->getCall (call_id); + std::string account_id(getAccountFromCall(call_id)); + Call *call = getAccountLink(account_id)->getCall(call_id); - ConferenceMap::const_iterator iter = _conferencemap.find (call->getConfId()); + ConferenceMap::const_iterator iter(conferenceMap_.find(call->getConfId())); - if (iter != _conferencemap.end()) + if (iter != conferenceMap_.end()) return iter->second; else return NULL; } -void ManagerImpl::holdConference (const std::string& id) +void ManagerImpl::holdConference(const std::string& id) { - ConferenceMap::iterator iter_conf = _conferencemap.find (id); + ConferenceMap::iterator iter_conf = conferenceMap_.find(id); - if (iter_conf == _conferencemap.end()) - return; + if (iter_conf == conferenceMap_.end()) + return; Conference *conf = iter_conf->second; - bool isRec = conf->getState() == Conference::ACTIVE_ATTACHED_REC || - conf->getState() == Conference::ACTIVE_DETACHED_REC || - conf->getState() == Conference::HOLD_REC; + bool isRec = conf->getState() == Conference::ACTIVE_ATTACHED_REC or + conf->getState() == Conference::ACTIVE_DETACHED_REC or + conf->getState() == Conference::HOLD_REC; + + ParticipantSet participants(conf->getParticipantList()); - const ParticipantSet &participants = conf->getParticipantList(); - ParticipantSet::const_iterator iter; - for (iter = participants.begin(); iter != participants.end(); ++iter) { - switchCall (*iter); - onHoldCall (*iter); - } + for (ParticipantSet::const_iterator iter = participants.begin(); + iter != participants.end(); ++iter) { + switchCall(*iter); + onHoldCall(*iter); + } - conf->setState(isRec ? Conference::HOLD_REC : Conference::HOLD); - _dbus.getCallManager()->conferenceChanged (conf->getConfID(), conf->getStateStr()); + conf->setState(isRec ? Conference::HOLD_REC : Conference::HOLD); + dbus_.getCallManager()->conferenceChanged(conf->getConfID(), conf->getStateStr()); } -void ManagerImpl::unHoldConference (const std::string& id) +void ManagerImpl::unHoldConference(const std::string& id) { - ConferenceMap::iterator iter_conf = _conferencemap.find (id); - if (iter_conf != _conferencemap.end()) { + ConferenceMap::iterator iter_conf = conferenceMap_.find(id); + + if (iter_conf != conferenceMap_.end() and iter_conf->second) { Conference *conf = iter_conf->second; bool isRec = conf->getState() == Conference::ACTIVE_ATTACHED_REC or - conf->getState() == Conference::ACTIVE_DETACHED_REC or - conf->getState() == Conference::HOLD_REC; + conf->getState() == Conference::ACTIVE_DETACHED_REC or + conf->getState() == Conference::HOLD_REC; - const ParticipantSet &participants(conf->getParticipantList()); + ParticipantSet participants(conf->getParticipantList()); for (ParticipantSet::const_iterator iter = participants.begin(); iter!= participants.end(); ++iter) { Call *call = getAccountLink(getAccountFromCall(*iter))->getCall(*iter); @@ -723,49 +730,42 @@ void ManagerImpl::unHoldConference (const std::string& id) // if one call is currently recording, the conference is in state recording isRec |= call->isRecording(); - offHoldCall (*iter); + offHoldCall(*iter); } conf->setState(isRec ? Conference::ACTIVE_ATTACHED_REC : Conference::ACTIVE_ATTACHED); - _dbus.getCallManager()->conferenceChanged (conf->getConfID(), conf->getStateStr()); + dbus_.getCallManager()->conferenceChanged(conf->getConfID(), conf->getStateStr()); } } -bool ManagerImpl::isConference (const std::string& id) +bool ManagerImpl::isConference(const std::string& id) const { - return (_conferencemap.find(id) != _conferencemap.end()); + return conferenceMap_.find(id) != conferenceMap_.end(); } -bool ManagerImpl::participToConference (const std::string& call_id) +bool ManagerImpl::isConferenceParticipant(const std::string& call_id) { std::string accountId(getAccountFromCall(call_id)); - Call *call = getAccountLink (accountId)->getCall(call_id); - - if (call == NULL) { - _error("Manager: Error call is NULL in particip to conference"); - return false; - } - - if (call->getConfId().empty()) - return false; - - return true; + Call *call = getAccountLink(accountId)->getCall(call_id); + return call and not call->getConfId().empty(); } -void ManagerImpl::addParticipant (const std::string& callId, const std::string& conferenceId) +void ManagerImpl::addParticipant(const std::string& callId, const std::string& conferenceId) { - _debug ("Manager: Add participant %s to %s", callId.c_str(), conferenceId.c_str()); - ConferenceMap::iterator iter = _conferencemap.find (conferenceId); - if (iter == _conferencemap.end()) { - _error("Manager: Error: Conference id is not valid"); - return; + DEBUG("Manager: Add participant %s to %s", callId.c_str(), conferenceId.c_str()); + ConferenceMap::iterator iter = conferenceMap_.find(conferenceId); + + if (iter == conferenceMap_.end()) { + ERROR("Manager: Error: Conference id is not valid"); + return; } - std::string currentAccountId(getAccountFromCall (callId)); - Call *call = getAccountLink (currentAccountId)->getCall (callId); + std::string currentAccountId(getAccountFromCall(callId)); + Call *call = getAccountLink(currentAccountId)->getCall(callId); + if (call == NULL) { - _error("Manager: Error: Call id is not valid"); - return; + ERROR("Manager: Error: Call id is not valid"); + return; } // store the current call id (it will change in offHoldCall or in answerCall) @@ -773,58 +773,60 @@ void ManagerImpl::addParticipant (const std::string& callId, const std::string& // detach from prior communication and switch to this conference if (current_call_id != callId) { - if (isConference (current_call_id)) - detachParticipant (Call::DEFAULT_ID, current_call_id); + if (isConference(current_call_id)) + detachParticipant(Call::DEFAULT_ID, current_call_id); else - onHoldCall (current_call_id); + onHoldCall(current_call_id); } + // TODO: remove this ugly hack => There should be different calls when double clicking // a conference to add main participant to it, or (in this case) adding a participant // toconference - switchCall (""); + switchCall(""); // Add main participant - addMainParticipant (conferenceId); + addMainParticipant(conferenceId); Conference* conf = iter->second; - switchCall (conf->getConfID()); + switchCall(conf->getConfID()); // Add coresponding IDs in conf and call - call->setConfId (conf->getConfID()); - conf->add (callId); + call->setConfId(conf->getConfID()); + conf->add(callId); // Connect new audio streams together - getMainBuffer()->unBindAll (callId); + getMainBuffer()->unBindAll(callId); + + std::map<std::string, std::string> callDetails(getCallDetails(callId)); + std::string callState(callDetails.find("CALL_STATE")->second); - std::map<std::string, std::string> callDetails = getCallDetails (callId); - std::string callState = callDetails.find("CALL_STATE")->second; if (callState == "HOLD") { - conf->bindParticipant (callId); - offHoldCall (callId); + conf->bindParticipant(callId); + offHoldCall(callId); } else if (callState == "INCOMING") { - conf->bindParticipant (callId); - answerCall (callId); - } else if (callState == "CURRENT") { - conf->bindParticipant (callId); - } + conf->bindParticipant(callId); + answerCall(callId); + } else if (callState == "CURRENT") + conf->bindParticipant(callId); + + ParticipantSet participants(conf->getParticipantList()); - const ParticipantSet &participants(conf->getParticipantList()); if (participants.empty()) - _error("Manager: Error: Participant list is empty for this conference"); + ERROR("Manager: Error: Participant list is empty for this conference"); // reset ring buffer for all conference participant // flush conference participants only for (ParticipantSet::const_iterator iter_p = participants.begin(); iter_p != participants.end(); ++iter_p) - getMainBuffer()->flush(*iter_p); + getMainBuffer()->flush(*iter_p); - getMainBuffer()->flush (Call::DEFAULT_ID); + getMainBuffer()->flush(Call::DEFAULT_ID); // Connect stream addStream(callId); } -void ManagerImpl::addMainParticipant (const std::string& conference_id) +void ManagerImpl::addMainParticipant(const std::string& conference_id) { if (hasCurrentCall()) { std::string current_call_id(getCurrentCallId()); @@ -837,17 +839,18 @@ void ManagerImpl::addMainParticipant (const std::string& conference_id) audioLayerMutexLock(); - ConferenceMap::const_iterator iter = _conferencemap.find (conference_id); - if (iter != _conferencemap.end()) { + ConferenceMap::const_iterator iter = conferenceMap_.find(conference_id); + + if (iter != conferenceMap_.end()) { Conference *conf = iter->second; - const ParticipantSet &participants = conf->getParticipantList(); + ParticipantSet participants(conf->getParticipantList()); for (ParticipantSet::const_iterator iter_p = participants.begin(); iter_p != participants.end(); ++iter_p) { getMainBuffer()->bindCallID(*iter_p, Call::DEFAULT_ID); // Reset ringbuffer's readpointers - getMainBuffer()->flush(*iter_p); + getMainBuffer()->flush(*iter_p); } getMainBuffer()->flush(Call::DEFAULT_ID); @@ -855,110 +858,112 @@ void ManagerImpl::addMainParticipant (const std::string& conference_id) if (conf->getState() == Conference::ACTIVE_DETACHED) conf->setState(Conference::ACTIVE_ATTACHED); else if (conf->getState() == Conference::ACTIVE_DETACHED_REC) - conf->setState(Conference::ACTIVE_ATTACHED_REC); + conf->setState(Conference::ACTIVE_ATTACHED_REC); else - _warn("Manager: Warning: Invalid conference state while adding main participant"); + WARN("Manager: Warning: Invalid conference state while adding main participant"); - _dbus.getCallManager()->conferenceChanged (conference_id, conf->getStateStr()); + dbus_.getCallManager()->conferenceChanged(conference_id, conf->getStateStr()); } audioLayerMutexUnlock(); - switchCall (conference_id); + switchCall(conference_id); } -void ManagerImpl::joinParticipant (const std::string& callId1, const std::string& callId2) +void ManagerImpl::joinParticipant(const std::string& callId1, const std::string& callId2) { - _debug ("Manager: Join participants %s, %s", callId1.c_str(), callId2.c_str()); + DEBUG("Manager: Join participants %s, %s", callId1.c_str(), callId2.c_str()); - std::map<std::string, std::string> call1Details = getCallDetails (callId1); - std::map<std::string, std::string> call2Details = getCallDetails (callId2); + std::map<std::string, std::string> call1Details(getCallDetails(callId1)); + std::map<std::string, std::string> call2Details(getCallDetails(callId2)); - std::string current_call_id = getCurrentCallId(); - _debug ("Manager: Current Call ID %s", current_call_id.c_str()); + std::string current_call_id(getCurrentCallId()); + DEBUG("Manager: Current Call ID %s", current_call_id.c_str()); // detach from the conference and switch to this conference - if ( (current_call_id != callId1) && (current_call_id != callId2)) { - - if (isConference (current_call_id)) { - // If currently in a conference - detachParticipant (Call::DEFAULT_ID, current_call_id); - } - else { - // If currently in a call - onHoldCall (current_call_id); - } + if ((current_call_id != callId1) and (current_call_id != callId2)) { + // If currently in a conference + if (isConference(current_call_id)) + detachParticipant(Call::DEFAULT_ID, current_call_id); + else + onHoldCall(current_call_id); // currently in a call } - Conference *conf = createConference (callId1, callId2); + Conference *conf = createConference(callId1, callId2); // Set corresponding conference ids for call 1 - std::string currentAccountId1 = getAccountFromCall (callId1); - Call *call1 = getAccountLink (currentAccountId1)->getCall (callId1); - if(call1 == NULL) { - _error("Manager: Could not find call %s", callId1.c_str()); + std::string currentAccountId1 = getAccountFromCall(callId1); + Call *call1 = getAccountLink(currentAccountId1)->getCall(callId1); + + if (call1 == NULL) { + ERROR("Manager: Could not find call %s", callId1.c_str()); + return; } - call1->setConfId (conf->getConfID()); + + call1->setConfId(conf->getConfID()); getMainBuffer()->unBindAll(callId1); // Set corresponding conderence details - std::string currentAccountId2 = getAccountFromCall (callId2); - Call *call2 = getAccountLink (currentAccountId2)->getCall (callId2); - if(call2 == NULL) { - _error("Manager: Could not find call %s", callId2.c_str()); + std::string currentAccountId2(getAccountFromCall(callId2)); + Call *call2 = getAccountLink(currentAccountId2)->getCall(callId2); + + if (call2 == NULL) { + ERROR("Manager: Could not find call %s", callId2.c_str()); + return; } - call2->setConfId (conf->getConfID()); - getMainBuffer()->unBindAll(callId2); + call2->setConfId(conf->getConfID()); + getMainBuffer()->unBindAll(callId2); // Process call1 according to its state - std::string call1_state_str = call1Details.find ("CALL_STATE")->second; - _debug ("Manager: Process call %s state: %s", callId1.c_str(), call1_state_str.c_str()); + std::string call1_state_str(call1Details.find("CALL_STATE")->second); + DEBUG("Manager: Process call %s state: %s", callId1.c_str(), call1_state_str.c_str()); if (call1_state_str == "HOLD") { - conf->bindParticipant (callId1); - offHoldCall (callId1); + conf->bindParticipant(callId1); + offHoldCall(callId1); } else if (call1_state_str == "INCOMING") { - conf->bindParticipant (callId1); - answerCall (callId1); + conf->bindParticipant(callId1); + answerCall(callId1); } else if (call1_state_str == "CURRENT") - conf->bindParticipant (callId1); + conf->bindParticipant(callId1); else if (call1_state_str == "RECORD") - conf->bindParticipant(callId1); + conf->bindParticipant(callId1); else if (call1_state_str == "INACTIVE") { - conf->bindParticipant (callId1); - answerCall (callId1); + conf->bindParticipant(callId1); + answerCall(callId1); } else - _warn ("Manager: Call state not recognized"); + WARN("Manager: Call state not recognized"); // Process call2 according to its state - std::string call2_state_str = call2Details.find ("CALL_STATE")->second; - _debug ("Manager: Process call %s state: %s", callId2.c_str(), call2_state_str.c_str()); + std::string call2_state_str(call2Details.find("CALL_STATE")->second); + DEBUG("Manager: Process call %s state: %s", callId2.c_str(), call2_state_str.c_str()); if (call2_state_str == "HOLD") { - conf->bindParticipant (callId2); - offHoldCall (callId2); + conf->bindParticipant(callId2); + offHoldCall(callId2); } else if (call2_state_str == "INCOMING") { - conf->bindParticipant (callId2); - answerCall (callId2); + conf->bindParticipant(callId2); + answerCall(callId2); } else if (call2_state_str == "CURRENT") - conf->bindParticipant (callId2); + conf->bindParticipant(callId2); else if (call2_state_str == "RECORD") - conf->bindParticipant (callId2); + conf->bindParticipant(callId2); else if (call2_state_str == "INACTIVE") { - conf->bindParticipant (callId2); - answerCall (callId2); + conf->bindParticipant(callId2); + answerCall(callId2); } else - _warn ("Manager: Call state not recognized"); + WARN("Manager: Call state not recognized"); // Switch current call id to this conference - switchCall (conf->getConfID()); + switchCall(conf->getConfID()); conf->setState(Conference::ACTIVE_ATTACHED); // set recording sampling rate audioLayerMutexLock(); - if (_audiodriver) - conf->setRecordingSmplRate(_audiodriver->getSampleRate()); + + if (audiodriver_) + conf->setRecordingSmplRate(audiodriver_->getSampleRate()); audioLayerMutexUnlock(); @@ -969,323 +974,332 @@ void ManagerImpl::createConfFromParticipantList(const std::vector< std::string > { // we must at least have 2 participant for a conference if (participantList.size() <= 1) { - _error("Manager: Error: Participant number must be higher or equal to 2"); + ERROR("Manager: Error: Participant number must be higher or equal to 2"); return; } - Conference *conf = new Conference(); + Conference *conf = new Conference; int successCounter = 0; - for (size_t i = 0; i != participantList.size(); i++) { - std::string numberaccount(participantList[i]); - std::string tostr(numberaccount.substr(0, numberaccount.find(","))); - std::string account(numberaccount.substr(numberaccount.find(",")+1, numberaccount.size())); - std::string generatedCallID(getNewCallID()); + for (std::vector<std::string>::const_iterator iter = participantList.begin(); iter != participantList.end(); ++iter) { + std::string numberaccount(*iter); + std::string tostr(numberaccount.substr(0, numberaccount.find(","))); + std::string account(numberaccount.substr(numberaccount.find(",") + 1, numberaccount.size())); + + std::string generatedCallID(getNewCallID()); - // Manager methods may behave differently if the call id particip to a conference - conf->add(generatedCallID); + // Manager methods may behave differently if the call id participates in a conference + conf->add(generatedCallID); - switchCall(""); + switchCall(""); - // Create call - bool callSuccess = outgoingCall(account, generatedCallID, tostr, conf->getConfID()); + // Create call + bool callSuccess = outgoingCall(account, generatedCallID, tostr, conf->getConfID()); - // If not able to create call remove this participant from the conference - if (!callSuccess) - conf->remove(generatedCallID); - else { - _dbus.getCallManager()->newCallCreated(account, generatedCallID, tostr); - successCounter++; - } + // If not able to create call remove this participant from the conference + if (!callSuccess) + conf->remove(generatedCallID); + else { + dbus_.getCallManager()->newCallCreated(account, generatedCallID, tostr); + successCounter++; + } } // Create the conference if and only if at least 2 calls have been successfully created - if (successCounter >= 2 ) { - _conferencemap.insert(std::pair<std::string, Conference *> (conf->getConfID(), conf)); - _dbus.getCallManager()->conferenceCreated (conf->getConfID()); + if (successCounter >= 2) { + conferenceMap_.insert(std::make_pair(conf->getConfID(), conf)); + dbus_.getCallManager()->conferenceCreated(conf->getConfID()); - audioLayerMutexLock(); - if(_audiodriver) - conf->setRecordingSmplRate(_audiodriver->getSampleRate()); + audioLayerMutexLock(); - audioLayerMutexUnlock(); + if (audiodriver_) + conf->setRecordingSmplRate(audiodriver_->getSampleRate()); - getMainBuffer()->stateInfo(); + audioLayerMutexUnlock(); + + getMainBuffer()->stateInfo(); } else - delete conf; + delete conf; } -void ManagerImpl::detachParticipant (const std::string& call_id, - const std::string& current_id) +void ManagerImpl::detachParticipant(const std::string& call_id, + const std::string& current_id) { - _debug ("Manager: Detach participant %s (current id: %s)", call_id.c_str(), current_id.c_str()); - + DEBUG("Manager: Detach participant %s (current id: %s)", call_id.c_str(), + current_id.c_str()); std::string current_call_id(getCurrentCallId()); if (call_id != Call::DEFAULT_ID) { - - std::string currentAccountId(getAccountFromCall (call_id)); - Call *call = getAccountLink (currentAccountId)->getCall (call_id); + std::string currentAccountId(getAccountFromCall(call_id)); + Call *call = getAccountLink(currentAccountId)->getCall(call_id); if (call == NULL) { - _error("Manager: Error: Could not find call %s", call_id.c_str()); - return; + ERROR("Manager: Error: Could not find call %s", call_id.c_str()); + return; } Conference *conf = getConferenceFromCallID(call_id); + if (conf == NULL) { - _error ("Manager: Error: Call is not conferencing, cannot detach"); + ERROR("Manager: Error: Call is not conferencing, cannot detach"); return; } std::map<std::string, std::string> call_details(getCallDetails(call_id)); - std::map<std::string, std::string>::iterator iter_details(call_details.find ("CALL_STATE")); + std::map<std::string, std::string>::iterator iter_details(call_details.find("CALL_STATE")); + if (iter_details == call_details.end()) { - _error ("Manager: Error: Could not find CALL_STATE"); - return; + ERROR("Manager: Error: Could not find CALL_STATE"); + return; } if (iter_details->second == "RINGING") - removeParticipant (call_id); + removeParticipant(call_id); else { - onHoldCall (call_id); - removeParticipant (call_id); - processRemainingParticipant (current_call_id, conf); + onHoldCall(call_id); + removeParticipant(call_id); + // Conference may have been deleted and set to 0 above + processRemainingParticipants(current_call_id, conf); + if (conf == 0) { + ERROR("Manager: Error: Call is not conferencing, cannot detach"); + return; + } } - _dbus.getCallManager()->conferenceChanged (conf->getConfID(), conf->getStateStr()); + + dbus_.getCallManager()->conferenceChanged(conf->getConfID(), conf->getStateStr()); } else { - _debug ("Manager: Unbind main participant from conference %d"); - getMainBuffer()->unBindAll (Call::DEFAULT_ID); + DEBUG("Manager: Unbind main participant from conference %d"); + getMainBuffer()->unBindAll(Call::DEFAULT_ID); - if (!isConference(current_call_id)) { - _error("Manager: Warning: Current call id (%s) is not a conference", current_call_id.c_str()); - return; + if (not isConference(current_call_id)) { + ERROR("Manager: Warning: Current call id (%s) is not a conference", current_call_id.c_str()); + return; } - ConferenceMap::iterator iter = _conferencemap.find (current_call_id); - Conference *conf = iter->second; + ConferenceMap::iterator iter = conferenceMap_.find(current_call_id); - if (conf == NULL) { - _debug("Manager: Error: Conference is NULL"); - return; + if (iter == conferenceMap_.end() or iter->second == 0) { + DEBUG("Manager: Error: Conference is NULL"); + return; } + Conference *conf = iter->second; if (conf->getState() == Conference::ACTIVE_ATTACHED) - conf->setState(Conference::ACTIVE_DETACHED); - else if(conf->getState() == Conference::ACTIVE_ATTACHED_REC) - conf->setState(Conference::ACTIVE_DETACHED_REC); + conf->setState(Conference::ACTIVE_DETACHED); + else if (conf->getState() == Conference::ACTIVE_ATTACHED_REC) + conf->setState(Conference::ACTIVE_DETACHED_REC); else - _warn("Manager: Warning: Undefined behavior, invalid conference state in detach participant"); + WARN("Manager: Warning: Undefined behavior, invalid conference state in detach participant"); - _dbus.getCallManager()->conferenceChanged (conf->getConfID(), conf->getStateStr()); + dbus_.getCallManager()->conferenceChanged(conf->getConfID(), + conf->getStateStr()); - switchCall (""); + switchCall(""); } } -void ManagerImpl::removeParticipant (const std::string& call_id) +void ManagerImpl::removeParticipant(const std::string& call_id) { - _debug ("Manager: Remove participant %s", call_id.c_str()); + DEBUG("Manager: Remove participant %s", call_id.c_str()); // this call is no more a conference participant - const std::string currentAccountId(getAccountFromCall (call_id)); - Call *call = getAccountLink (currentAccountId)->getCall (call_id); + const std::string currentAccountId(getAccountFromCall(call_id)); + Call *call = getAccountLink(currentAccountId)->getCall(call_id); - ConferenceMap conf_map = _conferencemap; - ConferenceMap::iterator iter = conf_map.find (call->getConfId()); + ConferenceMap conf_map = conferenceMap_; + ConferenceMap::const_iterator iter = conf_map.find(call->getConfId()); - if (iter == conf_map.end()) { - _error ("Manager: Error: No conference with id %s, cannot remove participant", call->getConfId().c_str()); + if (iter == conf_map.end() or iter->second == 0) { + ERROR("Manager: Error: No conference with id %s, cannot remove participant", call->getConfId().c_str()); return; } Conference *conf = iter->second; - - _debug ("Manager: Remove participant %s", call_id.c_str()); + DEBUG("Manager: Remove participant %s", call_id.c_str()); conf->remove(call_id); - call->setConfId (""); + call->setConfId(""); removeStream(call_id); getMainBuffer()->stateInfo(); - _dbus.getCallManager()->conferenceChanged (conf->getConfID(), conf->getStateStr()); + dbus_.getCallManager()->conferenceChanged(conf->getConfID(), conf->getStateStr()); } -void ManagerImpl::processRemainingParticipant (const std::string ¤t_call_id, Conference *conf) +void ManagerImpl::processRemainingParticipants(const std::string ¤t_call_id, Conference * &conf) { - const ParticipantSet &participants = conf->getParticipantList(); + ParticipantSet participants(conf->getParticipantList()); size_t n = participants.size(); - _debug ("Manager: Process remaining %d participant(s) from conference %s", - n, conf->getConfID().c_str()); + DEBUG("Manager: Process remaining %d participant(s) from conference %s", + n, conf->getConfID().c_str()); if (n > 1) { // Reset ringbuffer's readpointers for (ParticipantSet::const_iterator iter_p = participants.begin(); iter_p != participants.end(); ++iter_p) - getMainBuffer()->flush (*iter_p); + getMainBuffer()->flush(*iter_p); - getMainBuffer()->flush (Call::DEFAULT_ID); + getMainBuffer()->flush(Call::DEFAULT_ID); } else if (n == 1) { ParticipantSet::iterator iter_participant = participants.begin(); // bind main participant to remaining conference call if (iter_participant != participants.end()) { - - // this call is no more a conference participant - std::string currentAccountId(getAccountFromCall (*iter_participant)); + // this call is no longer a conference participant + std::string currentAccountId(getAccountFromCall(*iter_participant)); Call *call = getAccountLink(currentAccountId)->getCall(*iter_participant); - call->setConfId (""); - - // if we are not listening to this conference - if (current_call_id != conf->getConfID()) - onHoldCall (call->getCallId()); - else - switchCall (*iter_participant); + if (call) { + call->setConfId(""); + // if we are not listening to this conference + if (current_call_id != conf->getConfID()) + onHoldCall(call->getCallId()); + else + switchCall(*iter_participant); + } } - removeConference (conf->getConfID()); + removeConference(conf->getConfID()); + conf = 0; } else { - _debug ("Manager: No remaining participant, remove conference"); - removeConference (conf->getConfID()); - switchCall (""); + DEBUG("Manager: No remaining participants, remove conference"); + removeConference(conf->getConfID()); + conf = 0; + switchCall(""); } } -void ManagerImpl::joinConference (const std::string& conf_id1, - const std::string& conf_id2) +void ManagerImpl::joinConference(const std::string& conf_id1, + const std::string& conf_id2) { - ConferenceMap::iterator iter(_conferencemap.find(conf_id1)); + ConferenceMap::iterator iter(conferenceMap_.find(conf_id1)); - if (iter == _conferencemap.end()) { - _error ("Manager: Error: Not a valid conference ID: %s", conf_id1.c_str()); + if (iter == conferenceMap_.end()) { + ERROR("Manager: Error: Not a valid conference ID: %s", conf_id1.c_str()); return; } - Conference *conf1 = iter->second; - - if (_conferencemap.find (conf_id2) != _conferencemap.end()) { - _error ("Manager: Error: Not a valid conference ID: %s", conf_id2.c_str()); + if (conferenceMap_.find(conf_id2) != conferenceMap_.end()) { + ERROR("Manager: Error: Not a valid conference ID: %s", conf_id2.c_str()); return; } - const ParticipantSet &participants(conf1->getParticipantList()); + if (iter->second) { + Conference *conf = iter->second; + ParticipantSet participants(conf->getParticipantList()); - for (ParticipantSet::const_iterator iter_p = participants.begin(); - iter_p != participants.end(); ++iter_p) { - detachParticipant (*iter_p, ""); - addParticipant (*iter_p, conf_id2); + for (ParticipantSet::const_iterator iter_p = participants.begin(); + iter_p != participants.end(); ++iter_p) { + detachParticipant(*iter_p, ""); + addParticipant(*iter_p, conf_id2); + } } } -void ManagerImpl::addStream (const std::string& call_id) +void ManagerImpl::addStream(const std::string& call_id) { - _debug ("Manager: Add audio stream %s", call_id.c_str()); + DEBUG("Manager: Add audio stream %s", call_id.c_str()); std::string currentAccountId(getAccountFromCall(call_id)); - Call *call(getAccountLink(currentAccountId)->getCall(call_id)); + Call *call = getAccountLink(currentAccountId)->getCall(call_id); - if (participToConference(call_id)) { - _debug ("Manager: Add stream to conference"); + if (call and isConferenceParticipant(call_id)) { + DEBUG("Manager: Add stream to conference"); // bind to conference participant - ConferenceMap::iterator iter = _conferencemap.find (call->getConfId()); + ConferenceMap::iterator iter = conferenceMap_.find(call->getConfId()); - if (iter != _conferencemap.end()) { + if (iter != conferenceMap_.end() and iter->second) { Conference* conf = iter->second; - conf->bindParticipant (call_id); + conf->bindParticipant(call_id); - const ParticipantSet &participants(conf->getParticipantList()); + ParticipantSet participants(conf->getParticipantList()); // reset ring buffer for all conference participant for (ParticipantSet::const_iterator iter_p = participants.begin(); iter_p != participants.end(); ++iter_p) - getMainBuffer()->flush (*iter_p); + getMainBuffer()->flush(*iter_p); - getMainBuffer()->flush (Call::DEFAULT_ID); + getMainBuffer()->flush(Call::DEFAULT_ID); } } else { - _debug ("Manager: Add stream to call"); + DEBUG("Manager: Add stream to call"); // bind to main - getMainBuffer()->bindCallID (call_id); + getMainBuffer()->bindCallID(call_id); audioLayerMutexLock(); - _audiodriver->flushUrgent(); - _audiodriver->flushMain(); + audiodriver_->flushUrgent(); + audiodriver_->flushMain(); audioLayerMutexUnlock(); } getMainBuffer()->stateInfo(); } -void ManagerImpl::removeStream (const std::string& call_id) +void ManagerImpl::removeStream(const std::string& call_id) { - _debug ("Manager: Remove audio stream %s", call_id.c_str()); - getMainBuffer()->unBindAll (call_id); + DEBUG("Manager: Remove audio stream %s", call_id.c_str()); + getMainBuffer()->unBindAll(call_id); getMainBuffer()->stateInfo(); } //THREAD=Main -void ManagerImpl::saveConfig (void) +void ManagerImpl::saveConfig() { - _debug ("Manager: Saving Configuration to XDG directory %s", _path.c_str()); - audioPreference.setVolumemic (getMicVolume()); - audioPreference.setVolumespkr (getSpkrVolume()); + DEBUG("Manager: Saving Configuration to XDG directory %s", path_.c_str()); + audioPreference.setVolumemic(getMicVolume()); + audioPreference.setVolumespkr(getSpkrVolume()); try { - // emitter = new Conf::YamlEmitter("sequenceEmitter.yml"); - emitter = new Conf::YamlEmitter (_path.c_str()); + Conf::YamlEmitter emitter(path_.c_str()); - for (AccountMap::iterator iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - // Skip the "" account ID (which refer to the IP2IP account) + for (AccountMap::iterator iter = accountMap_.begin(); iter != accountMap_.end(); ++iter) { + // Skip the "" account ID (which refer to the IP2IP account) if (iter->first.empty()) continue; else - iter->second->serialize (emitter); + iter->second->serialize(&emitter); } - preferences.serialize (emitter); - voipPreferences.serialize (emitter); - addressbookPreference.serialize (emitter); - hookPreference.serialize (emitter); - audioPreference.serialize (emitter); - shortcutPreferences.serialize (emitter); - - emitter->serializeData(); + preferences.serialize(&emitter); + voipPreferences.serialize(&emitter); + addressbookPreference.serialize(&emitter); + hookPreference.serialize(&emitter); + audioPreference.serialize(&emitter); + shortcutPreferences.serialize(&emitter); - delete emitter; - } catch (Conf::YamlEmitterException &e) { - _error ("ConfigTree: %s", e.what()); + emitter.serializeData(); + } catch (const Conf::YamlEmitterException &e) { + ERROR("ConfigTree: %s", e.what()); } } //THREAD=Main -void ManagerImpl::sendDtmf (const std::string& id, char code) +void ManagerImpl::sendDtmf(const std::string& id, char code) { std::string accountid(getAccountFromCall(id)); - playDtmf (code); - getAccountLink (accountid)->carryingDTMFdigits (id, code); + playDtmf(code); + getAccountLink(accountid)->carryingDTMFdigits(id, code); } //THREAD=Main | VoIPLink -bool ManagerImpl::playDtmf (char code) +void ManagerImpl::playDtmf(char code) { stopTone(); if (not voipPreferences.getPlayDtmf()) { - _debug ("Manager: playDtmf: Do not have to play a tone..."); - return false; + DEBUG("Manager: playDtmf: Do not have to play a tone..."); + return; } // length in milliseconds int pulselen = voipPreferences.getPulseLength(); if (pulselen == 0) { - _debug ("Manager: playDtmf: Pulse length is not set..."); - return false; + DEBUG("Manager: playDtmf: Pulse length is not set..."); + return; } audioLayerMutexLock(); @@ -1294,98 +1308,98 @@ bool ManagerImpl::playDtmf (char code) // = number of seconds * SAMPLING_RATE by SECONDS // fast return, no sound, so no dtmf - if (_audiodriver == NULL || _dtmfKey == NULL) { - _debug ("Manager: playDtmf: Error no audio layer..."); + if (audiodriver_ == NULL || dtmfKey_ == NULL) { + DEBUG("Manager: playDtmf: Error no audio layer..."); audioLayerMutexUnlock(); - return false; + return; } // number of data sampling in one pulselen depends on samplerate // size (n sampling) = time_ms * sampling/s // --------------------- // ms/s - int size = (int) ( (pulselen * (float) _audiodriver->getSampleRate()) / 1000); + int size = (int)((pulselen * (float) audiodriver_->getSampleRate()) / 1000); // this buffer is for mono // TODO <-- this should be global and hide if same size SFLDataFormat *buf = new SFLDataFormat[size]; // Handle dtmf - _dtmfKey->startTone (code); + dtmfKey_->startTone(code); // copy the sound - if (_dtmfKey->generateDTMF (buf, size)) { + if (dtmfKey_->generateDTMF(buf, size)) { // Put buffer to urgentRingBuffer // put the size in bytes... // so size * 1 channel (mono) * sizeof (bytes for the data) // audiolayer->flushUrgent(); - _audiodriver->startStream(); - _audiodriver->putUrgent (buf, size * sizeof (SFLDataFormat)); + audiodriver_->startStream(); + audiodriver_->putUrgent(buf, size * sizeof(SFLDataFormat)); } audioLayerMutexUnlock(); // TODO Cache the DTMF - delete[] buf; - return true; + delete [] buf; } // Multi-thread -bool ManagerImpl::incomingCallWaiting () +bool ManagerImpl::incomingCallWaiting() { - return _nbIncomingWaitingCall > 0; + return nbIncomingWaitingCall_ > 0; } -void ManagerImpl::addWaitingCall (const std::string& id) +void ManagerImpl::addWaitingCall(const std::string& id) { - ost::MutexLock m(_waitingCallMutex); - _waitingCall.insert (id); - _nbIncomingWaitingCall++; + ost::MutexLock m(waitingCallMutex_); + waitingCall_.insert(id); + nbIncomingWaitingCall_++; } -void ManagerImpl::removeWaitingCall (const std::string& id) +void ManagerImpl::removeWaitingCall(const std::string& id) { - ost::MutexLock m(_waitingCallMutex); - if (_waitingCall.erase(id)) - _nbIncomingWaitingCall--; + ost::MutexLock m(waitingCallMutex_); + + if (waitingCall_.erase(id)) + nbIncomingWaitingCall_--; } -bool ManagerImpl::isWaitingCall (const std::string& id) +bool ManagerImpl::isWaitingCall(const std::string& id) { - return _waitingCall.find(id) != _waitingCall.end(); + return waitingCall_.find(id) != waitingCall_.end(); } /////////////////////////////////////////////////////////////////////////////// // Management of event peer IP-phone //////////////////////////////////////////////////////////////////////////////// // SipEvent Thread -void ManagerImpl::incomingCall (Call* call, const std::string& accountId) +void ManagerImpl::incomingCall(Call* call, const std::string& accountId) { assert(call); stopTone(); - associateCallToAccount (call->getCallId(), accountId); + associateCallToAccount(call->getCallId(), accountId); - if (accountId == "") - associateConfigToCall (call->getCallId(), Call::IPtoIP); + if (accountId.empty()) + associateConfigToCall(call->getCallId(), Call::IPtoIP); else { // strip sip: which is not required and bring confusion with ip to ip calls // when placing new call from history (if call is IAX, do nothing) std::string peerNumber(call->getPeerNumber()); - size_t startIndex = peerNumber.find ("sip:"); + size_t startIndex = peerNumber.find("sip:"); if (startIndex != std::string::npos) - call->setPeerNumber (peerNumber.substr (startIndex + 4)); + call->setPeerNumber(peerNumber.substr(startIndex + 4)); } - if (!hasCurrentCall()) { - call->setConnectionState (Call::Ringing); - ringtone (accountId); + if (not hasCurrentCall()) { + call->setConnectionState(Call::Ringing); + ringtone(accountId); } - addWaitingCall (call->getCallId()); + addWaitingCall(call->getCallId()); std::string from(call->getPeerName()); std::string number(call->getPeerNumber()); @@ -1395,19 +1409,20 @@ void ManagerImpl::incomingCall (Call* call, const std::string& accountId) from += "<" + number + ">"; - _dbus.getCallManager()->incomingCall(accountId, call->getCallId(), call->getDisplayName() + " " + from); + dbus_.getCallManager()->incomingCall(accountId, call->getCallId(), call->getDisplayName() + " " + from); } //THREAD=VoIP -void ManagerImpl::incomingMessage (const std::string& callID, - const std::string& from, - const std::string& message) +void ManagerImpl::incomingMessage(const std::string& callID, + const std::string& from, + const std::string& message) { - if (participToConference (callID)) { - Conference *conf = getConferenceFromCallID (callID); + if (isConferenceParticipant(callID)) { + Conference *conf = getConferenceFromCallID(callID); + + ParticipantSet participants(conf->getParticipantList()); - const ParticipantSet &participants = conf->getParticipantList(); for (ParticipantSet::const_iterator iter_p = participants.begin(); iter_p != participants.end(); ++iter_p) { @@ -1416,33 +1431,34 @@ void ManagerImpl::incomingMessage (const std::string& callID, std::string accountId(getAccountFromCall(*iter_p)); - _debug ("Manager: Send message to %s, (%s)", (*iter_p).c_str(), accountId.c_str()); + DEBUG("Manager: Send message to %s, (%s)", (*iter_p).c_str(), accountId.c_str()); - Account *account = getAccount (accountId); + Account *account = getAccount(accountId); if (!account) { - _error("Manager: Failed to get account while sending instant message"); + ERROR("Manager: Failed to get account while sending instant message"); return; } - account->getVoIPLink()->sendTextMessage (_imModule, callID, message, from); + + account->getVoIPLink()->sendTextMessage(imModule_, callID, message, from); } // in case of a conference we must notify client using conference id - _dbus.getCallManager()->incomingMessage (conf->getConfID(), from, message); + dbus_.getCallManager()->incomingMessage(conf->getConfID(), from, message); } else - _dbus.getCallManager()->incomingMessage (callID, from, message); + dbus_.getCallManager()->incomingMessage(callID, from, message); } //THREAD=VoIP -bool ManagerImpl::sendTextMessage (const std::string& callID, const std::string& message, const std::string& from) +bool ManagerImpl::sendTextMessage(const std::string& callID, const std::string& message, const std::string& from) { - if (isConference (callID)) { - _debug ("Manager: Is a conference, send instant message to everyone"); - ConferenceMap::iterator it = _conferencemap.find (callID); + if (isConference(callID)) { + DEBUG("Manager: Is a conference, send instant message to everyone"); + ConferenceMap::iterator it = conferenceMap_.find(callID); - if (it == _conferencemap.end()) + if (it == conferenceMap_.end()) return false; Conference *conf = it->second; @@ -1450,67 +1466,67 @@ bool ManagerImpl::sendTextMessage (const std::string& callID, const std::string& if (!conf) return false; - const ParticipantSet participants = conf->getParticipantList(); + ParticipantSet participants(conf->getParticipantList()); for (ParticipantSet::const_iterator iter_p = participants.begin(); iter_p != participants.end(); ++iter_p) { - std::string accountId = getAccountFromCall (*iter_p); + std::string accountId = getAccountFromCall(*iter_p); - Account *account = getAccount (accountId); + Account *account = getAccount(accountId); if (!account) { - _debug ("Manager: Failed to get account while sending instant message"); + DEBUG("Manager: Failed to get account while sending instant message"); return false; } - account->getVoIPLink()->sendTextMessage (_imModule, *iter_p, message, from); + account->getVoIPLink()->sendTextMessage(imModule_, *iter_p, message, from); } return true; } - if (participToConference (callID)) { - _debug ("Manager: Particip to a conference, send instant message to everyone"); - - Conference *conf = getConferenceFromCallID (callID); + if (isConferenceParticipant(callID)) { + DEBUG("Manager: Call is participant in a conference, send instant message to everyone"); + Conference *conf = getConferenceFromCallID(callID); if (!conf) return false; - const ParticipantSet participants(conf->getParticipantList()); + ParticipantSet participants(conf->getParticipantList()); + for (ParticipantSet::const_iterator iter_p = participants.begin(); iter_p != participants.end(); ++iter_p) { const std::string accountId(getAccountFromCall(*iter_p)); - const Account *account = getAccount (accountId); + Account *account = getAccount(accountId); if (!account) { - _debug ("Manager: Failed to get account while sending instant message"); + DEBUG("Manager: Failed to get account while sending instant message"); return false; } - account->getVoIPLink()->sendTextMessage (_imModule, *iter_p, message, from); + account->getVoIPLink()->sendTextMessage(imModule_, *iter_p, message, from); } } else { - const Account *account = getAccount (getAccountFromCall(callID)); + Account *account = getAccount(getAccountFromCall(callID)); if (!account) { - _debug ("Manager: Failed to get account while sending instant message"); + DEBUG("Manager: Failed to get account while sending instant message"); return false; } - account->getVoIPLink()->sendTextMessage (_imModule, callID, message, from); + account->getVoIPLink()->sendTextMessage(imModule_, callID, message, from); } return true; } //THREAD=VoIP CALL=Outgoing -void ManagerImpl::peerAnsweredCall (const std::string& id) +void ManagerImpl::peerAnsweredCall(const std::string& id) { - _debug ("Manager: Peer answered call %s", id.c_str()); + DEBUG("Manager: Peer answered call %s", id.c_str()); // The if statement is usefull only if we sent two calls at the same time. if (isCurrentCall(id)) @@ -1520,294 +1536,295 @@ void ManagerImpl::peerAnsweredCall (const std::string& id) addStream(id); audioLayerMutexLock(); - _audiodriver->flushMain(); - _audiodriver->flushUrgent(); + audiodriver_->flushMain(); + audiodriver_->flushUrgent(); audioLayerMutexUnlock(); if (audioPreference.getIsAlwaysRecording()) { - setRecordingCall(id); - _dbus.getCallManager()->callStateChanged (id, "RECORD"); - } - else - _dbus.getCallManager()->callStateChanged(id, "CURRENT"); + setRecordingCall(id); + dbus_.getCallManager()->callStateChanged(id, "RECORD"); + } else + dbus_.getCallManager()->callStateChanged(id, "CURRENT"); } //THREAD=VoIP Call=Outgoing -void ManagerImpl::peerRingingCall (const std::string& id) +void ManagerImpl::peerRingingCall(const std::string& id) { - _debug ("Manager: Peer call %s ringing", id.c_str()); + DEBUG("Manager: Peer call %s ringing", id.c_str()); if (isCurrentCall(id)) ringback(); - _dbus.getCallManager()->callStateChanged (id, "RINGING"); + dbus_.getCallManager()->callStateChanged(id, "RINGING"); } //THREAD=VoIP Call=Outgoing/Ingoing -void ManagerImpl::peerHungupCall (const std::string& call_id) +void ManagerImpl::peerHungupCall(const std::string& call_id) { - _debug ("Manager: Peer hungup call %s", call_id.c_str()); - if (participToConference (call_id)) { - Conference *conf = getConferenceFromCallID (call_id); + DEBUG("Manager: Peer hungup call %s", call_id.c_str()); - if (conf != NULL) { - removeParticipant (call_id); - processRemainingParticipant (getCurrentCallId(), conf); + if (isConferenceParticipant(call_id)) { + Conference *conf = getConferenceFromCallID(call_id); + + if (conf != 0) { + removeParticipant(call_id); + processRemainingParticipants(getCurrentCallId(), conf); } } else { - if (isCurrentCall (call_id)) { + if (isCurrentCall(call_id)) { stopTone(); switchCall(""); } } /* Direct IP to IP call */ - if (getConfigFromCall (call_id) == Call::IPtoIP) - SIPVoIPLink::instance ()->hangup (call_id); + if (getConfigFromCall(call_id) == Call::IPtoIP) + SIPVoIPLink::instance()->hangup(call_id); else { - const std::string account_id(getAccountFromCall (call_id)); + const std::string account_id(getAccountFromCall(call_id)); getAccountLink(account_id)->peerHungup(call_id); } /* Broadcast a signal over DBus */ - _dbus.getCallManager()->callStateChanged (call_id, "HUNGUP"); + dbus_.getCallManager()->callStateChanged(call_id, "HUNGUP"); - removeWaitingCall (call_id); - removeCallAccount (call_id); - removeStream (call_id); + removeWaitingCall(call_id); + removeCallAccount(call_id); + removeStream(call_id); if (getCallList().empty()) { - _debug ("Manager: Stop audio stream, ther is only %d call(s) remaining", getCallList().size()); + DEBUG("Manager: Stop audio stream, there are no calls remaining"); audioLayerMutexLock(); - _audiodriver->stopStream(); + audiodriver_->stopStream(); audioLayerMutexUnlock(); } } //THREAD=VoIP -void ManagerImpl::callBusy (const std::string& id) +void ManagerImpl::callBusy(const std::string& id) { - _debug ("Manager: Call %s busy", id.c_str()); - _dbus.getCallManager()->callStateChanged (id, "BUSY"); + DEBUG("Manager: Call %s busy", id.c_str()); + dbus_.getCallManager()->callStateChanged(id, "BUSY"); - if (isCurrentCall (id)) { - playATone (Tone::TONE_BUSY); - switchCall (""); + if (isCurrentCall(id)) { + playATone(Tone::TONE_BUSY); + switchCall(""); } - removeCallAccount (id); - removeWaitingCall (id); + removeCallAccount(id); + removeWaitingCall(id); } //THREAD=VoIP -void ManagerImpl::callFailure (const std::string& call_id) +void ManagerImpl::callFailure(const std::string& call_id) { - _dbus.getCallManager()->callStateChanged (call_id, "FAILURE"); - if (isCurrentCall (call_id)) { - playATone (Tone::TONE_BUSY); - switchCall (""); + dbus_.getCallManager()->callStateChanged(call_id, "FAILURE"); + + if (isCurrentCall(call_id)) { + playATone(Tone::TONE_BUSY); + switchCall(""); } - if (participToConference (call_id)) { - _debug ("Manager: Call %s participating to a conference failed", call_id.c_str()); - Conference *conf = getConferenceFromCallID (call_id); + if (isConferenceParticipant(call_id)) { + DEBUG("Manager: Call %s participating in a conference failed", call_id.c_str()); + Conference *conf = getConferenceFromCallID(call_id); if (conf == NULL) { - _error("Manager: Could not retreive conference from call id %s", call_id.c_str()); - return; + ERROR("Manager: Could not retreive conference from call id %s", call_id.c_str()); + return; } // remove this participant - removeParticipant (call_id); - processRemainingParticipant (getCurrentCallId(), conf); + removeParticipant(call_id); + processRemainingParticipants(getCurrentCallId(), conf); } - removeCallAccount (call_id); - removeWaitingCall (call_id); + removeCallAccount(call_id); + removeWaitingCall(call_id); } //THREAD=VoIP -void ManagerImpl::startVoiceMessageNotification (const std::string& accountId, +void ManagerImpl::startVoiceMessageNotification(const std::string& accountId, int nb_msg) { - _dbus.getCallManager()->voiceMailNotify (accountId, nb_msg); + dbus_.getCallManager()->voiceMailNotify(accountId, nb_msg); } -void ManagerImpl::connectionStatusNotification () +void ManagerImpl::connectionStatusNotification() { - _dbus.getConfigurationManager()->accountsChanged(); + dbus_.getConfigurationManager()->accountsChanged(); } /** * Multi Thread */ -bool ManagerImpl::playATone (Tone::TONEID toneId) +void ManagerImpl::playATone(Tone::TONEID toneId) { if (not voipPreferences.getPlayTones()) - return false; + return; audioLayerMutexLock(); - if (_audiodriver == NULL) { - _error("Manager: Error: Audio layer not initialized"); - audioLayerMutexUnlock(); - return false; + if (audiodriver_ == NULL) { + ERROR("Manager: Error: Audio layer not initialized"); + audioLayerMutexUnlock(); + return; } - _audiodriver->flushUrgent(); - _audiodriver->startStream(); + + audiodriver_->flushUrgent(); + audiodriver_->startStream(); audioLayerMutexUnlock(); - if (_telephoneTone != 0) { - _toneMutex.enterMutex(); - _telephoneTone->setCurrentTone (toneId); - _toneMutex.leaveMutex(); + if (telephoneTone_ != 0) { + toneMutex_.enterMutex(); + telephoneTone_->setCurrentTone(toneId); + toneMutex_.leaveMutex(); } - - return true; } /** * Multi Thread */ -void ManagerImpl::stopTone () +void ManagerImpl::stopTone() { if (not voipPreferences.getPlayTones()) return; - _toneMutex.enterMutex(); + toneMutex_.enterMutex(); - if (_telephoneTone != NULL) - _telephoneTone->setCurrentTone (Tone::TONE_NULL); + if (telephoneTone_ != NULL) + telephoneTone_->setCurrentTone(Tone::TONE_NULL); - if (_audiofile) { - std::string filepath(_audiofile->getFilePath()); - _dbus.getCallManager()->recordPlaybackStopped(filepath); - delete _audiofile; - _audiofile = NULL; + if (audiofile_) { + std::string filepath(audiofile_->getFilePath()); + dbus_.getCallManager()->recordPlaybackStopped(filepath); + delete audiofile_; + audiofile_ = NULL; } - _toneMutex.leaveMutex(); + toneMutex_.leaveMutex(); } /** * Multi Thread */ -bool ManagerImpl::playTone () +void ManagerImpl::playTone() { playATone(Tone::TONE_DIALTONE); - return true; } /** * Multi Thread */ -bool ManagerImpl::playToneWithMessage () +void ManagerImpl::playToneWithMessage() { - playATone (Tone::TONE_CONGESTION); - return true; + playATone(Tone::TONE_CONGESTION); } /** * Multi Thread */ -void ManagerImpl::congestion () +void ManagerImpl::congestion() { - playATone (Tone::TONE_CONGESTION); + playATone(Tone::TONE_CONGESTION); } /** * Multi Thread */ -void ManagerImpl::ringback () +void ManagerImpl::ringback() { - playATone (Tone::TONE_RINGTONE); + playATone(Tone::TONE_RINGTONE); } /** * Multi Thread */ -void ManagerImpl::ringtone (const std::string& accountID) +void ManagerImpl::ringtone(const std::string& accountID) { - Account *account = getAccount (accountID); + Account *account = getAccount(accountID); + if (!account) { - _warn ("Manager: Warning: invalid account in ringtone"); + WARN("Manager: Warning: invalid account in ringtone"); return; } if (!account->getRingtoneEnabled()) { - ringback(); - return; + ringback(); + return; } std::string ringchoice = account->getRingtonePath(); - if (ringchoice.find (DIR_SEPARATOR_STR) == std::string::npos) { - // check inside global share directory - ringchoice = std::string (PROGSHAREDIR) + DIR_SEPARATOR_STR - + RINGDIR + DIR_SEPARATOR_STR + ringchoice; - } - - audioLayerMutexLock(); - - if (!_audiodriver) { - _error ("Manager: Error: no audio layer in ringtone"); - audioLayerMutexUnlock(); - return; - } - - int samplerate = _audiodriver->getSampleRate(); - - audioLayerMutexUnlock(); - - _toneMutex.enterMutex(); - - if (_audiofile) { - _dbus.getCallManager()->recordPlaybackStopped(_audiofile->getFilePath()); - delete _audiofile; - _audiofile = NULL; - } - - try { - if (ringchoice.find (".wav") != std::string::npos) - _audiofile = new WaveFile(ringchoice, samplerate); - else { - sfl::Codec *codec; - if (ringchoice.find (".ul") != std::string::npos || ringchoice.find (".au") != std::string::npos) - codec = audioCodecFactory.getCodec(PAYLOAD_CODEC_ULAW); - else - throw AudioFileException("Couldn't guess an appropriate decoder"); - _audiofile = new RawFile(ringchoice, static_cast<sfl::AudioCodec *>(codec), samplerate); - } - } - catch (AudioFileException &e) { - _error("Manager: Exception: %s", e.what()); - } - - _toneMutex.leaveMutex(); - - audioLayerMutexLock(); - // start audio if not started AND flush all buffers (main and urgent) - _audiodriver->startStream(); - audioLayerMutexUnlock(); + + if (ringchoice.find(DIR_SEPARATOR_STR) == std::string::npos) { + // check inside global share directory + static const char * const RINGDIR = "ringtones"; + ringchoice = std::string(PROGSHAREDIR) + DIR_SEPARATOR_STR + + RINGDIR + DIR_SEPARATOR_STR + ringchoice; + } + + audioLayerMutexLock(); + + if (!audiodriver_) { + ERROR("Manager: Error: no audio layer in ringtone"); + audioLayerMutexUnlock(); + return; + } + + int samplerate = audiodriver_->getSampleRate(); + + audioLayerMutexUnlock(); + + { + ost::MutexLock m(toneMutex_); + + if (audiofile_) { + dbus_.getCallManager()->recordPlaybackStopped(audiofile_->getFilePath()); + delete audiofile_; + audiofile_ = NULL; + } + + try { + if (ringchoice.find(".wav") != std::string::npos) + audiofile_ = new WaveFile(ringchoice, samplerate); + else { + sfl::Codec *codec; + + if (ringchoice.find(".ul") != std::string::npos or ringchoice.find(".au") != std::string::npos) + codec = audioCodecFactory.getCodec(PAYLOAD_CODEC_ULAW); + else + throw AudioFileException("Couldn't guess an appropriate decoder"); + + audiofile_ = new RawFile(ringchoice, static_cast<sfl::AudioCodec *>(codec), samplerate); + } + } catch (AudioFileException &e) { + ERROR("Manager: Exception: %s", e.what()); + } + } // leave mutex + + audioLayerMutexLock(); + // start audio if not started AND flush all buffers (main and urgent) + audiodriver_->startStream(); + audioLayerMutexUnlock(); } AudioLoop* -ManagerImpl::getTelephoneTone () +ManagerImpl::getTelephoneTone() { - if (_telephoneTone) { - ost::MutexLock m (_toneMutex); - return _telephoneTone->getCurrentTone(); - } - else + if (telephoneTone_) { + ost::MutexLock m(toneMutex_); + return telephoneTone_->getCurrentTone(); + } else return NULL; } AudioLoop* -ManagerImpl::getTelephoneFile () +ManagerImpl::getTelephoneFile() { - ost::MutexLock m (_toneMutex); + ost::MutexLock m(toneMutex_); - return _audiofile; + return audiofile_; } /////////////////////////////////////////////////////////////////////////////// @@ -1816,42 +1833,44 @@ ManagerImpl::getTelephoneFile () /** * Initialization: Main Thread */ -std::string ManagerImpl::getConfigFile (void) const +std::string ManagerImpl::getConfigFile() const { - std::string configdir = std::string (HOMEDIR) + DIR_SEPARATOR_STR + ".config" - + DIR_SEPARATOR_STR + PROGDIR; + std::string configdir = std::string(HOMEDIR) + DIR_SEPARATOR_STR + ".config" + + DIR_SEPARATOR_STR + PACKAGE; if (XDG_CONFIG_HOME != NULL) { - std::string xdg_env = std::string (XDG_CONFIG_HOME); + std::string xdg_env = std::string(XDG_CONFIG_HOME); + if (not xdg_env.empty()) - configdir = xdg_env; + configdir = xdg_env; } - if (mkdir (configdir.data(), 0700) != 0) { + if (mkdir(configdir.data(), 0700) != 0) { // If directory creation failed if (errno != EEXIST) - _debug ("Cannot create directory: %m"); + DEBUG("Cannot create directory: %m"); } + static const char * const PROGNAME = "sflphoned"; return configdir + DIR_SEPARATOR_STR + PROGNAME + ".yml"; } -std::vector<std::string> ManagerImpl::unserialize (std::string s) +std::vector<std::string> ManagerImpl::unserialize(std::string s) { std::vector<std::string> list; std::string temp; - while (s.find ("/", 0) != std::string::npos) { - size_t pos = s.find ("/", 0); - temp = s.substr (0, pos); - s.erase (0, pos + 1); - list.push_back (temp); + while (s.find("/", 0) != std::string::npos) { + size_t pos = s.find("/", 0); + temp = s.substr(0, pos); + s.erase(0, pos + 1); + list.push_back(temp); } return list; } -std::string ManagerImpl::serialize (const std::vector<std::string> &v) +std::string ManagerImpl::serialize(const std::vector<std::string> &v) { std::string res; @@ -1861,15 +1880,16 @@ std::string ManagerImpl::serialize (const std::vector<std::string> &v) return res; } -std::string ManagerImpl::getCurrentCodecName (const std::string& id) +std::string ManagerImpl::getCurrentCodecName(const std::string& id) { - std::string accountid = getAccountFromCall (id); - VoIPLink* link = getAccountLink (accountid); - Call* call = link->getCall (id); + std::string accountid = getAccountFromCall(id); + VoIPLink* link = getAccountLink(accountid); + Call* call = link->getCall(id); std::string codecName; if (call) { Call::CallState state = call->getState(); + if (state == Call::Active or state == Call::Conferencing) codecName = link->getCurrentCodecName(call); } @@ -1880,26 +1900,28 @@ std::string ManagerImpl::getCurrentCodecName (const std::string& id) /** * Set input audio plugin */ -void ManagerImpl::setAudioPlugin (const std::string& audioPlugin) +void ManagerImpl::setAudioPlugin(const std::string& audioPlugin) { - audioLayerMutexLock(); + audioLayerMutexLock(); - audioPreference.setPlugin (audioPlugin); + audioPreference.setPlugin(audioPlugin); + + AlsaLayer *alsa = dynamic_cast<AlsaLayer*>(audiodriver_); - AlsaLayer *alsa = dynamic_cast<AlsaLayer*>(_audiodriver); if (!alsa) { - _error("Can't find alsa device"); + ERROR("Can't find alsa device"); audioLayerMutexUnlock(); return ; } - bool wasStarted = _audiodriver->isStarted(); + bool wasStarted = audiodriver_->isStarted(); // Recreate audio driver with new settings - delete _audiodriver; - _audiodriver = audioPreference.createAudioLayer(); + delete audiodriver_; + audiodriver_ = audioPreference.createAudioLayer(); + if (wasStarted) - _audiodriver->startStream(); + audiodriver_->startStream(); audioLayerMutexUnlock(); } @@ -1907,39 +1929,40 @@ void ManagerImpl::setAudioPlugin (const std::string& audioPlugin) /** * Set audio output device */ -void ManagerImpl::setAudioDevice (const int index, int streamType) +void ManagerImpl::setAudioDevice(const int index, int streamType) { audioLayerMutexLock(); - AlsaLayer *alsaLayer = dynamic_cast<AlsaLayer*>(_audiodriver); + AlsaLayer *alsaLayer = dynamic_cast<AlsaLayer*>(audiodriver_); + if (!alsaLayer) { - _error("Can't find alsa device"); + ERROR("Can't find alsa device"); audioLayerMutexUnlock(); return ; } - bool wasStarted = _audiodriver->isStarted(); + bool wasStarted = audiodriver_->isStarted(); switch (streamType) { case SFL_PCM_PLAYBACK: - audioPreference.setCardout (index); + audioPreference.setCardout(index); break; case SFL_PCM_CAPTURE: - audioPreference.setCardin (index); + audioPreference.setCardin(index); break; case SFL_PCM_RINGTONE: - audioPreference.setCardring (index); + audioPreference.setCardring(index); break; default: break; } // Recreate audio driver with new settings - delete _audiodriver; - _audiodriver = audioPreference.createAudioLayer(); + delete audiodriver_; + audiodriver_ = audioPreference.createAudioLayer(); if (wasStarted) - _audiodriver->startStream(); + audiodriver_->startStream(); audioLayerMutexUnlock(); } @@ -1947,13 +1970,13 @@ void ManagerImpl::setAudioDevice (const int index, int streamType) /** * Get list of supported audio output device */ -std::vector<std::string> ManagerImpl::getAudioOutputDeviceList (void) +std::vector<std::string> ManagerImpl::getAudioOutputDeviceList() { std::vector<std::string> devices; audioLayerMutexLock(); - AlsaLayer *alsalayer = dynamic_cast<AlsaLayer*>(_audiodriver); + AlsaLayer *alsalayer = dynamic_cast<AlsaLayer*>(audiodriver_); if (alsalayer) devices = alsalayer->getSoundCardsInfo(SFL_PCM_PLAYBACK); @@ -1967,15 +1990,16 @@ std::vector<std::string> ManagerImpl::getAudioOutputDeviceList (void) /** * Get list of supported audio input device */ -std::vector<std::string> ManagerImpl::getAudioInputDeviceList (void) +std::vector<std::string> ManagerImpl::getAudioInputDeviceList() { std::vector<std::string> devices; audioLayerMutexLock(); - AlsaLayer *alsalayer = dynamic_cast<AlsaLayer *> (_audiodriver); + AlsaLayer *alsalayer = dynamic_cast<AlsaLayer *>(audiodriver_); + if (alsalayer) - devices = alsalayer->getSoundCardsInfo (SFL_PCM_CAPTURE); + devices = alsalayer->getSoundCardsInfo(SFL_PCM_CAPTURE); audioLayerMutexUnlock(); @@ -1985,21 +2009,22 @@ std::vector<std::string> ManagerImpl::getAudioInputDeviceList (void) /** * Get string array representing integer indexes of output and input device */ -std::vector<std::string> ManagerImpl::getCurrentAudioDevicesIndex () +std::vector<std::string> ManagerImpl::getCurrentAudioDevicesIndex() { audioLayerMutexLock(); std::vector<std::string> v; - AlsaLayer *alsa = dynamic_cast<AlsaLayer*>(_audiodriver); + AlsaLayer *alsa = dynamic_cast<AlsaLayer*>(audiodriver_); + if (alsa) { - std::stringstream ssi, sso, ssr; - sso << alsa->getIndexOut(); - v.push_back (sso.str()); - ssi << alsa->getIndexIn(); - v.push_back (ssi.str()); - ssr << alsa->getIndexRing(); - v.push_back (ssr.str()); + std::stringstream ssi, sso, ssr; + sso << alsa->getIndexOut(); + v.push_back(sso.str()); + ssi << alsa->getIndexIn(); + v.push_back(ssi.str()); + ssr << alsa->getIndexRing(); + v.push_back(ssr.str()); } audioLayerMutexUnlock(); @@ -2007,121 +2032,123 @@ std::vector<std::string> ManagerImpl::getCurrentAudioDevicesIndex () return v; } -int ManagerImpl::isRingtoneEnabled (const std::string& id) +int ManagerImpl::isRingtoneEnabled(const std::string& id) { - Account *account = getAccount (id); + Account *account = getAccount(id); if (!account) { - _warn ("Manager: Warning: invalid account in ringtone enabled"); + WARN("Manager: Warning: invalid account in ringtone enabled"); return 0; } return account->getRingtoneEnabled(); } -void ManagerImpl::ringtoneEnabled (const std::string& id) +void ManagerImpl::ringtoneEnabled(const std::string& id) { - Account *account = getAccount (id); + Account *account = getAccount(id); + if (!account) { - _warn ("Manager: Warning: invalid account in ringtone enabled"); + WARN("Manager: Warning: invalid account in ringtone enabled"); return; } - account->getRingtoneEnabled() ? account->setRingtoneEnabled (false) : account->setRingtoneEnabled (true); + account->getRingtoneEnabled() ? account->setRingtoneEnabled(false) : account->setRingtoneEnabled(true); } -std::string ManagerImpl::getRecordPath (void) const +std::string ManagerImpl::getRecordPath() const { return audioPreference.getRecordpath(); } -void ManagerImpl::setRecordPath (const std::string& recPath) +void ManagerImpl::setRecordPath(const std::string& recPath) { - _debug ("Manager: Set record path %s", recPath.c_str()); - audioPreference.setRecordpath (recPath); + DEBUG("Manager: Set record path %s", recPath.c_str()); + audioPreference.setRecordpath(recPath); } -bool ManagerImpl::getIsAlwaysRecording(void) const +bool ManagerImpl::getIsAlwaysRecording() const { - return audioPreference.getIsAlwaysRecording(); + return audioPreference.getIsAlwaysRecording(); } void ManagerImpl::setIsAlwaysRecording(bool isAlwaysRec) { - return audioPreference.setIsAlwaysRecording(isAlwaysRec); + return audioPreference.setIsAlwaysRecording(isAlwaysRec); } -void ManagerImpl::setRecordingCall (const std::string& id) +void ManagerImpl::setRecordingCall(const std::string& id) { Recordable* rec = NULL; - if (not isConference (id)) { - _debug ("Manager: Set recording for call %s", id.c_str()); + ConferenceMap::const_iterator it(conferenceMap_.find(id)); + if (it == conferenceMap_.end()) { + DEBUG("Manager: Set recording for call %s", id.c_str()); std::string accountid(getAccountFromCall(id)); rec = getAccountLink(accountid)->getCall(id); } else { - _debug ("Manager: Set recording for conference %s", id.c_str()); - ConferenceMap::const_iterator it(_conferencemap.find(id)); + DEBUG("Manager: Set recording for conference %s", id.c_str()); Conference *conf = it->second; - if (rec->isRecording()) - conf->setState(Conference::ACTIVE_ATTACHED); - else - conf->setState(Conference::ACTIVE_ATTACHED_REC); - rec = conf; + if (conf) { + rec = conf; + if (rec->isRecording()) + conf->setState(Conference::ACTIVE_ATTACHED); + else + conf->setState(Conference::ACTIVE_ATTACHED_REC); + } } if (rec == NULL) { - _error("Manager: Error: Could not find recordable instance %s", id.c_str()); + ERROR("Manager: Error: Could not find recordable instance %s", id.c_str()); return; } rec->setRecording(); - _dbus.getCallManager()->recordPlaybackFilepath(id, rec->getFileName()); + dbus_.getCallManager()->recordPlaybackFilepath(id, rec->getFileName()); } -bool ManagerImpl::isRecording (const std::string& id) +bool ManagerImpl::isRecording(const std::string& id) { - const std::string accountid(getAccountFromCall (id)); - Recordable* rec = getAccountLink (accountid)->getCall (id); + const std::string accountid(getAccountFromCall(id)); + Recordable* rec = getAccountLink(accountid)->getCall(id); return rec and rec->isRecording(); } bool ManagerImpl::startRecordedFilePlayback(const std::string& filepath) { - _debug("Manager: Start recorded file playback %s", filepath.c_str()); + DEBUG("Manager: Start recorded file playback %s", filepath.c_str()); audioLayerMutexLock(); - if (!_audiodriver) { - _error("Manager: Error: No audio layer in start recorded file playback"); + if (!audiodriver_) { + ERROR("Manager: Error: No audio layer in start recorded file playback"); audioLayerMutexUnlock(); return false; } - int sampleRate = _audiodriver->getSampleRate(); + int sampleRate = audiodriver_->getSampleRate(); audioLayerMutexUnlock(); - _toneMutex.enterMutex(); - - if (_audiofile) { - _dbus.getCallManager()->recordPlaybackStopped(_audiofile->getFilePath()); - delete _audiofile; - _audiofile = NULL; - } + { + ost::MutexLock m(toneMutex_); - try { - _audiofile = new WaveFile(filepath, sampleRate); - } - catch (const AudioFileException &e) { - _error("Manager: Exception: %s", e.what()); - } + if (audiofile_) { + dbus_.getCallManager()->recordPlaybackStopped(audiofile_->getFilePath()); + delete audiofile_; + audiofile_ = NULL; + } - _toneMutex.leaveMutex(); + try { + audiofile_ = new WaveFile(filepath, sampleRate); + } catch (const AudioFileException &e) { + ERROR("Manager: Exception: %s", e.what()); + } + } // release toneMutex audioLayerMutexLock(); - _audiodriver->startStream(); + audiodriver_->startStream(); audioLayerMutexUnlock(); return true; @@ -2130,53 +2157,54 @@ bool ManagerImpl::startRecordedFilePlayback(const std::string& filepath) void ManagerImpl::stopRecordedFilePlayback(const std::string& filepath) { - _debug("Manager: Stop recorded file playback %s", filepath.c_str()); + DEBUG("Manager: Stop recorded file playback %s", filepath.c_str()); audioLayerMutexLock(); - _audiodriver->stopStream(); + audiodriver_->stopStream(); audioLayerMutexUnlock(); - _toneMutex.enterMutex(); - delete _audiofile; - _audiofile = NULL; - _toneMutex.leaveMutex(); + { + ost::MutexLock m(toneMutex_); + delete audiofile_; + audiofile_ = NULL; + } } -void ManagerImpl::setHistoryLimit (int days) +void ManagerImpl::setHistoryLimit(int days) { - _debug ("Manager: Set history limit"); - preferences.setHistoryLimit (days); + DEBUG("Manager: Set history limit"); + preferences.setHistoryLimit(days); saveConfig(); } -int ManagerImpl::getHistoryLimit (void) const +int ManagerImpl::getHistoryLimit() const { return preferences.getHistoryLimit(); } -int32_t ManagerImpl::getMailNotify (void) const +int32_t ManagerImpl::getMailNotify() const { return preferences.getNotifyMails(); } -void ManagerImpl::setMailNotify (void) +void ManagerImpl::setMailNotify() { - _debug ("Manager: Set mail notify"); - preferences.getNotifyMails() ? preferences.setNotifyMails (true) : preferences.setNotifyMails (false); + DEBUG("Manager: Set mail notify"); + preferences.getNotifyMails() ? preferences.setNotifyMails(true) : preferences.setNotifyMails(false); saveConfig(); } -void ManagerImpl::setAudioManager (const std::string &api) +void ManagerImpl::setAudioManager(const std::string &api) { audioLayerMutexLock(); - if (!_audiodriver) { - audioLayerMutexUnlock(); + if (!audiodriver_) { + audioLayerMutexUnlock(); return; } if (api == audioPreference.getAudioApi()) { - _debug ("Manager: Audio manager chosen already in use. No changes made. "); + DEBUG("Manager: Audio manager chosen already in use. No changes made. "); audioLayerMutexUnlock(); return; } @@ -2188,143 +2216,142 @@ void ManagerImpl::setAudioManager (const std::string &api) saveConfig(); } -std::string ManagerImpl::getAudioManager (void) const +std::string ManagerImpl::getAudioManager() const { return audioPreference.getAudioApi(); } -int ManagerImpl::getAudioDeviceIndex (const std::string &name) +int ManagerImpl::getAudioDeviceIndex(const std::string &name) { int soundCardIndex = 0; audioLayerMutexLock(); - if (_audiodriver == NULL) { - _error("Manager: Error: Audio layer not initialized"); - audioLayerMutexUnlock(); - return soundCardIndex; + if (audiodriver_ == NULL) { + ERROR("Manager: Error: Audio layer not initialized"); + audioLayerMutexUnlock(); + return soundCardIndex; } - AlsaLayer *alsalayer = dynamic_cast<AlsaLayer *> (_audiodriver); + AlsaLayer *alsalayer = dynamic_cast<AlsaLayer *>(audiodriver_); if (alsalayer) - soundCardIndex = alsalayer -> soundCardGetIndex (name); + soundCardIndex = alsalayer -> soundCardGetIndex(name); audioLayerMutexUnlock(); return soundCardIndex; } -std::string ManagerImpl::getCurrentAudioOutputPlugin (void) const +std::string ManagerImpl::getCurrentAudioOutputPlugin() const { return audioPreference.getPlugin(); } -std::string ManagerImpl::getNoiseSuppressState (void) const +std::string ManagerImpl::getNoiseSuppressState() const { return audioPreference.getNoiseReduce() ? "enabled" : "disabled"; } -void ManagerImpl::setNoiseSuppressState (const std::string &state) +void ManagerImpl::setNoiseSuppressState(const std::string &state) { - audioPreference.setNoiseReduce (state == "enabled"); + audioPreference.setNoiseReduce(state == "enabled"); } bool ManagerImpl::getEchoCancelState() const { - return audioPreference.getEchoCancel(); + return audioPreference.getEchoCancel(); } void ManagerImpl::setEchoCancelState(const std::string &state) { - audioPreference.setEchoCancel(state == "enabled"); + audioPreference.setEchoCancel(state == "enabled"); } -int ManagerImpl::getEchoCancelTailLength(void) const +int ManagerImpl::getEchoCancelTailLength() const { - return audioPreference.getEchoCancelTailLength(); + return audioPreference.getEchoCancelTailLength(); } void ManagerImpl::setEchoCancelTailLength(int length) { - audioPreference.setEchoCancelTailLength(length); + audioPreference.setEchoCancelTailLength(length); } -int ManagerImpl::getEchoCancelDelay(void) const +int ManagerImpl::getEchoCancelDelay() const { - return audioPreference.getEchoCancelDelay(); + return audioPreference.getEchoCancelDelay(); } void ManagerImpl::setEchoCancelDelay(int delay) { - audioPreference.setEchoCancelDelay(delay); + audioPreference.setEchoCancelDelay(delay); } /** * Initialization: Main Thread */ -void ManagerImpl::initAudioDriver (void) +void ManagerImpl::initAudioDriver() { audioLayerMutexLock(); - _audiodriver = audioPreference.createAudioLayer(); + audiodriver_ = audioPreference.createAudioLayer(); audioLayerMutexUnlock(); } -void ManagerImpl::switchAudioManager (void) +void ManagerImpl::switchAudioManager() { audioLayerMutexLock(); - bool wasStarted = _audiodriver->isStarted(); - delete _audiodriver; - - _audiodriver = audioPreference.switchAndCreateAudioLayer(); + bool wasStarted = audiodriver_->isStarted(); + delete audiodriver_; + audiodriver_ = audioPreference.switchAndCreateAudioLayer(); if (wasStarted) - _audiodriver->startStream(); + audiodriver_->startStream(); audioLayerMutexUnlock(); } -void ManagerImpl::audioSamplingRateChanged (int samplerate) +void ManagerImpl::audioSamplingRateChanged(int samplerate) { audioLayerMutexLock(); - if (!_audiodriver) { - _debug("Manager: No Audio driver initialized"); - audioLayerMutexUnlock(); + if (!audiodriver_) { + DEBUG("Manager: No Audio driver initialized"); + audioLayerMutexUnlock(); return; } // Only modify internal sampling rate if new sampling rate is higher - int currentSamplerate = _mainBuffer.getInternalSamplingRate(); + int currentSamplerate = mainBuffer_.getInternalSamplingRate(); + if (currentSamplerate >= samplerate) { - _debug("Manager: No need to update audio layer sampling rate"); - audioLayerMutexUnlock(); - return; - } - else - _debug ("Manager: Audio sampling rate changed: %d -> %d", currentSamplerate, samplerate); + DEBUG("Manager: No need to update audio layer sampling rate"); + audioLayerMutexUnlock(); + return; + } else + DEBUG("Manager: Audio sampling rate changed: %d -> %d", currentSamplerate, samplerate); - bool wasActive = _audiodriver->isStarted(); + bool wasActive = audiodriver_->isStarted(); - _mainBuffer.setInternalSamplingRate(samplerate); + mainBuffer_.setInternalSamplingRate(samplerate); - delete _audiodriver; - _audiodriver = audioPreference.createAudioLayer(); + delete audiodriver_; + audiodriver_ = audioPreference.createAudioLayer(); - unsigned int sampleRate = _audiodriver->getSampleRate(); + unsigned int sampleRate = audiodriver_->getSampleRate(); - delete _telephoneTone; - _telephoneTone = new TelephoneTone(preferences.getZoneToneChoice(), sampleRate); + delete telephoneTone_; + telephoneTone_ = new TelephoneTone(preferences.getZoneToneChoice(), sampleRate); - delete _dtmfKey; - _dtmfKey = new DTMF (sampleRate); + delete dtmfKey_; + dtmfKey_ = new DTMF(sampleRate); if (wasActive) - _audiodriver->startStream(); + audiodriver_->startStream(); audioLayerMutexUnlock(); } @@ -2333,101 +2360,83 @@ void ManagerImpl::audioSamplingRateChanged (int samplerate) * Init the volume for speakers/micro from 0 to 100 value * Initialization: Main Thread */ -void ManagerImpl::initVolume () +void ManagerImpl::initVolume() { - setSpkrVolume (audioPreference.getVolumespkr()); - setMicVolume (audioPreference.getVolumemic()); + setSpkrVolume(audioPreference.getVolumespkr()); + setMicVolume(audioPreference.getVolumemic()); } -void ManagerImpl::setSpkrVolume (unsigned short spkr_vol) +void ManagerImpl::setSpkrVolume(unsigned short spkr_vol) { - _spkr_volume = spkr_vol; + speakerVolume_ = spkr_vol; } -void ManagerImpl::setMicVolume (unsigned short mic_vol) +void ManagerImpl::setMicVolume(unsigned short mic_vol) { - _mic_volume = mic_vol; + micVolume_ = mic_vol; } -int ManagerImpl::getLocalIp2IpPort (void) const +int ManagerImpl::getLocalIp2IpPort() const { return preferences.getPortNum(); } //THREAD=Main -bool ManagerImpl::getConfig (const std::string& section, - const std::string& name, TokenList& arg) const +bool ManagerImpl::getConfig(const std::string& section, + const std::string& name, TokenList& arg) const { - return _config.getConfigTreeItemToken (section, name, arg); + return config_.getConfigTreeItemToken(section, name, arg); } //THREAD=Main // throw an Conf::ConfigTreeItemException if not found -int ManagerImpl::getConfigInt (const std::string& section, - const std::string& name) const +int ManagerImpl::getConfigInt(const std::string& section, + const std::string& name) const { - try { - return _config.getConfigTreeItemIntValue (section, name); - } catch (const Conf::ConfigTreeItemException& e) { - throw; - } - - return 0; + return config_.getConfigTreeItemIntValue(section, name); } -bool ManagerImpl::getConfigBool (const std::string& section, - const std::string& name) const +bool ManagerImpl::getConfigBool(const std::string& section, + const std::string& name) const { - try { - return _config.getConfigTreeItemValue (section, name) == Conf::TRUE_STR; - } catch (const Conf::ConfigTreeItemException& e) { - throw; - } - - return false; + return config_.getConfigTreeItemValue(section, name) == Conf::TRUE_STR; } //THREAD=Main -std::string ManagerImpl::getConfigString (const std::string& section, +std::string ManagerImpl::getConfigString(const std::string& section, const std::string& name) const { - try { - return _config.getConfigTreeItemValue (section, name); - } catch (const Conf::ConfigTreeItemException& e) { - throw; - } - - return ""; + return config_.getConfigTreeItemValue(section, name); } //THREAD=Main -bool ManagerImpl::setConfig (const std::string& section, - const std::string& name, const std::string& value) +bool ManagerImpl::setConfig(const std::string& section, + const std::string& name, const std::string& value) { - return _config.setConfigTreeItem (section, name, value); + return config_.setConfigTreeItem(section, name, value); } //THREAD=Main -bool ManagerImpl::setConfig (const std::string& section, - const std::string& name, int value) +bool ManagerImpl::setConfig(const std::string& section, + const std::string& name, int value) { std::ostringstream valueStream; valueStream << value; - return _config.setConfigTreeItem (section, name, valueStream.str()); + return config_.setConfigTreeItem(section, name, valueStream.str()); } -void ManagerImpl::setAccountsOrder (const std::string& order) +void ManagerImpl::setAccountsOrder(const std::string& order) { - _debug ("Manager: Set accounts order : %s", order.c_str()); + DEBUG("Manager: Set accounts order : %s", order.c_str()); // Set the new config - preferences.setAccountOrder (order); + preferences.setAccountOrder(order); saveConfig(); } -std::vector<std::string> ManagerImpl::getAccountList () const +std::vector<std::string> ManagerImpl::getAccountList() const { using std::vector; using std::string; @@ -2435,56 +2444,60 @@ std::vector<std::string> ManagerImpl::getAccountList () const // The IP2IP profile is always available, and first in the list - vector<string> v; + AccountMap::const_iterator ip2ip_iter = accountMap_.find(IP2IP_PROFILE); - AccountMap::const_iterator ip2ip_iter = _accountMap.find (IP2IP_PROFILE); + vector<string> v; if (ip2ip_iter->second) - v.push_back (ip2ip_iter->second->getAccountID()); + v.push_back(ip2ip_iter->second->getAccountID()); else - _error ("Manager: could not find IP2IP profile in getAccount list"); + ERROR("Manager: could not find IP2IP profile in getAccount list"); // If no order has been set, load the default one ie according to the creation date. if (account_order.empty()) { - for (AccountMap::const_iterator iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - if (iter->first == IP2IP_PROFILE || iter->first.empty()) - continue; + for (AccountMap::const_iterator iter = accountMap_.begin(); iter != accountMap_.end(); ++iter) { + if (iter->first == IP2IP_PROFILE || iter->first.empty()) + continue; + if (iter->second) - v.push_back (iter->second->getAccountID()); + v.push_back(iter->second->getAccountID()); } - return v; } + else { + for (vector<string>::const_iterator iter = account_order.begin(); iter != account_order.end(); ++iter) { + if (*iter == IP2IP_PROFILE or iter->empty()) + continue; - for (vector<string>::const_iterator iter = account_order.begin(); iter != account_order.end(); ++iter) { - if (*iter == IP2IP_PROFILE || *iter == "") - continue; - AccountMap::const_iterator account_iter = _accountMap.find (*iter); - if (account_iter != _accountMap.end() && account_iter->second) - v.push_back (account_iter->second->getAccountID()); - } + AccountMap::const_iterator account_iter = accountMap_.find(*iter); + + if (account_iter != accountMap_.end() and account_iter->second) + v.push_back(account_iter->second->getAccountID()); + } + } return v; } -std::map<std::string, std::string> ManagerImpl::getAccountDetails ( +std::map<std::string, std::string> ManagerImpl::getAccountDetails( const std::string& accountID) const { // Default account used to get default parameters if requested by client (to build new account) static const SIPAccount DEFAULT_ACCOUNT("default"); if (accountID.empty()) { - _debug ("Manager: Returning default account settings"); + DEBUG("Manager: Returning default account settings"); return DEFAULT_ACCOUNT.getAccountDetails(); } - AccountMap::const_iterator iter = _accountMap.find(accountID); + AccountMap::const_iterator iter = accountMap_.find(accountID); Account * account = 0; - if (iter != _accountMap.end()) + + if (iter != accountMap_.end()) account = iter->second; if (account) return account->getAccountDetails(); else { - _debug ("Manager: Get account details on a non-existing accountID %s. Returning default", accountID.c_str()); + DEBUG("Manager: Get account details on a non-existing accountID %s. Returning default", accountID.c_str()); return DEFAULT_ACCOUNT.getAccountDetails(); } } @@ -2492,18 +2505,19 @@ std::map<std::string, std::string> ManagerImpl::getAccountDetails ( // method to reduce the if/else mess. // Even better, switch to XML ! -void ManagerImpl::setAccountDetails (const std::string& accountID, - const std::map<std::string, std::string>& details) +void ManagerImpl::setAccountDetails(const std::string& accountID, + const std::map<std::string, std::string>& details) { - _debug ("Manager: Set account details for %s", accountID.c_str()); + DEBUG("Manager: Set account details for %s", accountID.c_str()); Account* account = getAccount(accountID); + if (account == NULL) { - _error ("Manager: Error: Could not find account %s", accountID.c_str()); + ERROR("Manager: Error: Could not find account %s", accountID.c_str()); return; } - account->setAccountDetails (details); + account->setAccountDetails(details); // Serialize configuration to disk once it is done saveConfig(); @@ -2514,117 +2528,119 @@ void ManagerImpl::setAccountDetails (const std::string& accountID, account->unregisterVoIPLink(); // Update account details to the client side - _dbus.getConfigurationManager()->accountsChanged(); + dbus_.getConfigurationManager()->accountsChanged(); } -std::string ManagerImpl::addAccount ( - const std::map<std::string, std::string>& details) +std::string ManagerImpl::addAccount(const std::map<std::string, std::string>& details) { - /** @todo Deal with both the _accountMap and the Configuration */ - std::string accountType, account_list; + /** @todo Deal with both the accountMap_ and the Configuration */ std::stringstream accountID; - accountID << "Account:" << time (NULL); + accountID << "Account:" << time(NULL); std::string newAccountID(accountID.str()); // Get the type - accountType = (*details.find (CONFIG_ACCOUNT_TYPE)).second; + std::string accountType((*details.find(CONFIG_ACCOUNT_TYPE)).second); - _debug ("Manager: Adding account %s", newAccountID.c_str()); + DEBUG("Manager: Adding account %s", newAccountID.c_str()); /** @todo Verify the uniqueness, in case a program adds accounts, two in a row. */ Account* newAccount = NULL; - if (accountType == "SIP") { + + if (accountType == "SIP") newAccount = new SIPAccount(newAccountID); - } else if (accountType == "IAX") { + else if (accountType == "IAX") newAccount = new IAXAccount(newAccountID); - } else { - _error ("Unknown %s param when calling addAccount(): %s", - CONFIG_ACCOUNT_TYPE, accountType.c_str()); + else { + ERROR("Unknown %s param when calling addAccount(): %s", + CONFIG_ACCOUNT_TYPE, accountType.c_str()); return ""; } - _accountMap[newAccountID] = newAccount; + accountMap_[newAccountID] = newAccount; - newAccount->setAccountDetails (details); + newAccount->setAccountDetails(details); // Add the newly created account in the account order list - account_list = preferences.getAccountOrder(); + std::string accountList(preferences.getAccountOrder()); - if (not account_list.empty()) { + if (not accountList.empty()) { newAccountID += "/"; // Prepend the new account - account_list.insert (0, newAccountID); - preferences.setAccountOrder (account_list); + accountList.insert(0, newAccountID); + preferences.setAccountOrder(accountList); } else { newAccountID += "/"; - account_list = newAccountID; - preferences.setAccountOrder (account_list); + accountList = newAccountID; + preferences.setAccountOrder(accountList); } - _debug ("AccountMap: %s", account_list.c_str()); + DEBUG("AccountMap: %s", accountList.c_str()); newAccount->registerVoIPLink(); saveConfig(); - _dbus.getConfigurationManager()->accountsChanged(); + dbus_.getConfigurationManager()->accountsChanged(); return accountID.str(); } -void ManagerImpl::removeAccount (const std::string& accountID) +void ManagerImpl::removeAccount(const std::string& accountID) { // Get it down and dying - Account* remAccount = getAccount (accountID); + Account* remAccount = getAccount(accountID); if (remAccount != NULL) { remAccount->unregisterVoIPLink(); - _accountMap.erase (accountID); + accountMap_.erase(accountID); // http://projects.savoirfairelinux.net/issues/show/2355 // delete remAccount; } - _config.removeSection (accountID); + config_.removeSection(accountID); saveConfig(); - _dbus.getConfigurationManager()->accountsChanged(); + dbus_.getConfigurationManager()->accountsChanged(); } // ACCOUNT handling -bool ManagerImpl::associateCallToAccount (const std::string& callID, +bool ManagerImpl::associateCallToAccount(const std::string& callID, const std::string& accountID) { if (getAccountFromCall(callID).empty() and accountExists(accountID)) { // account id exist in AccountMap - ost::MutexLock m (_callAccountMapMutex); - _callAccountMap[callID] = accountID; - _debug ("Manager: Associate Call %s with Account %s", callID.data(), accountID.data()); + ost::MutexLock m(callAccountMapMutex_); + callAccountMap_[callID] = accountID; + DEBUG("Manager: Associate Call %s with Account %s", callID.data(), accountID.data()); return true; } + return false; } std::string ManagerImpl::getAccountFromCall(const std::string& callID) { - ost::MutexLock m (_callAccountMapMutex); - CallAccountMap::iterator iter = _callAccountMap.find (callID); + ost::MutexLock m(callAccountMapMutex_); + CallAccountMap::iterator iter = callAccountMap_.find(callID); - return (iter == _callAccountMap.end()) ? "" : iter->second; + return (iter == callAccountMap_.end()) ? "" : iter->second; } -void ManagerImpl::removeCallAccount (const std::string& callID) +void ManagerImpl::removeCallAccount(const std::string& callID) { - ost::MutexLock m (_callAccountMapMutex); - _callAccountMap.erase (callID); + ost::MutexLock m(callAccountMapMutex_); + callAccountMap_.erase(callID); // Stop audio layer if there is no call anymore - if (_callAccountMap.empty()) { - audioLayerMutexLock(); - if(_audiodriver) - _audiodriver->stopStream(); + if (callAccountMap_.empty()) { + audioLayerMutexLock(); + + if (audiodriver_) + audiodriver_->stopStream(); + audioLayerMutexUnlock(); } @@ -2632,19 +2648,19 @@ void ManagerImpl::removeCallAccount (const std::string& callID) bool ManagerImpl::isValidCall(const std::string& callID) { - ost::MutexLock m(_callAccountMapMutex); - return _callAccountMap.find (callID) != _callAccountMap.end(); + ost::MutexLock m(callAccountMapMutex_); + return callAccountMap_.find(callID) != callAccountMap_.end(); } -std::string ManagerImpl::getNewCallID () +std::string ManagerImpl::getNewCallID() { - std::ostringstream random_id ("s"); + std::ostringstream random_id("s"); random_id << (unsigned) rand(); // when it's not found, it return "" // generate, something like s10000s20000s4394040 - while (not getAccountFromCall (random_id.str()).empty()) { + while (not getAccountFromCall(random_id.str()).empty()) { random_id.clear(); random_id << "s"; random_id << (unsigned) rand(); @@ -2653,27 +2669,28 @@ std::string ManagerImpl::getNewCallID () return random_id.str(); } -std::vector<std::string> ManagerImpl::loadAccountOrder (void) const +std::vector<std::string> ManagerImpl::loadAccountOrder() const { - return unserialize (preferences.getAccountOrder()); + return unserialize(preferences.getAccountOrder()); } void ManagerImpl::loadAccountMap(Conf::YamlParser *parser) { // build a default IP2IP account with default parameters Account *ip2ip = new SIPAccount(IP2IP_PROFILE); - _accountMap[IP2IP_PROFILE] = ip2ip; + accountMap_[IP2IP_PROFILE] = ip2ip; // If configuration file parsed, load saved preferences if (parser) { Conf::Sequence *seq = parser->getAccountSequence()->getSequence(); + for (Conf::Sequence::const_iterator iter = seq->begin(); iter != seq->end(); ++iter) { - Conf::MappingNode *map = (Conf::MappingNode *) (*iter); + Conf::MappingNode *map = (Conf::MappingNode *)(*iter); std::string accountid; - map->getValue ("id", &accountid); + map->getValue("id", &accountid); if (accountid == "IP2IP") { - ip2ip->unserialize (map); + ip2ip->unserialize(map); break; } } @@ -2688,113 +2705,115 @@ void ManagerImpl::loadAccountMap(Conf::YamlParser *parser) ip2ip->registerVoIPLink(); if (!parser) - return; + return; - // build preferences - preferences.unserialize (parser->getPreferenceNode()); - voipPreferences.unserialize (parser->getVoipPreferenceNode()); - addressbookPreference.unserialize (parser->getAddressbookNode()); - hookPreference.unserialize (parser->getHookNode()); - audioPreference.unserialize (parser->getAudioNode()); - shortcutPreferences.unserialize (parser->getShortcutNode()); + // build preferences + preferences.unserialize(parser->getPreferenceNode()); + voipPreferences.unserialize(parser->getVoipPreferenceNode()); + addressbookPreference.unserialize(parser->getAddressbookNode()); + hookPreference.unserialize(parser->getHookNode()); + audioPreference.unserialize(parser->getAudioNode()); + shortcutPreferences.unserialize(parser->getShortcutNode()); Conf::Sequence *seq = parser->getAccountSequence()->getSequence(); // Each element in sequence is a new account to create for (Conf::Sequence::const_iterator iter = seq->begin(); iter != seq->end(); ++iter) { - Conf::MappingNode *map = (Conf::MappingNode *) (*iter); + Conf::MappingNode *map = (Conf::MappingNode *)(*iter); std::string accountType; - map->getValue ("type", &accountType); + map->getValue("type", &accountType); std::string accountid; - map->getValue ("id", &accountid); + map->getValue("id", &accountid); std::string accountAlias; - map->getValue ("alias", &accountAlias); + map->getValue("alias", &accountAlias); if (accountid.empty() or accountAlias.empty() or accountid == IP2IP_PROFILE) continue; Account *a; + if (accountType == "IAX") - a = new IAXAccount(accountid); + a = new IAXAccount(accountid); else // assume SIP - a = new SIPAccount(accountid); + a = new SIPAccount(accountid); - _accountMap[accountid] = a; + accountMap_[accountid] = a; - a->unserialize (map); + a->unserialize(map); } } -void ManagerImpl::unloadAccountMap () +void ManagerImpl::unloadAccountMap() { - AccountMap::iterator iter; - for (iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { + for (AccountMap::iterator iter = accountMap_.begin(); iter != accountMap_.end(); ++iter) { // Avoid removing the IP2IP account twice - if (iter->first != "") + if (not iter->first.empty()) { delete iter->second; + iter->second = 0; + } } - _accountMap.clear(); + accountMap_.clear(); } -bool ManagerImpl::accountExists (const std::string& accountID) +bool ManagerImpl::accountExists(const std::string& accountID) { - return _accountMap.find (accountID) != _accountMap.end(); + return accountMap_.find(accountID) != accountMap_.end(); } Account* -ManagerImpl::getAccount (const std::string& accountID) const +ManagerImpl::getAccount(const std::string& accountID) { - AccountMap::const_iterator iter = _accountMap.find(accountID); - if (iter != _accountMap.end()) - return iter->second; + AccountMap::const_iterator iter = accountMap_.find(accountID); + if (iter != accountMap_.end()) + return iter->second; return getAccount(IP2IP_PROFILE); } -std::string ManagerImpl::getAccountIdFromNameAndServer ( - const std::string& userName, const std::string& server) const +std::string ManagerImpl::getAccountIdFromNameAndServer(const std::string& userName, const std::string& server) const { - _info ("Manager : username = %s , server = %s", userName.c_str(), server.c_str()); + INFO("Manager : username = %s, server = %s", userName.c_str(), server.c_str()); // Try to find the account id from username and server name by full match - for (AccountMap::const_iterator iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - SIPAccount *account = dynamic_cast<SIPAccount *> (iter->second); - if (account and account->isEnabled() and account->fullMatch (userName, server)) { - _debug ("Manager: Matching account id in request is a fullmatch %s@%s", userName.c_str(), server.c_str()); + for (AccountMap::const_iterator iter = accountMap_.begin(); iter != accountMap_.end(); ++iter) { + SIPAccount *account = dynamic_cast<SIPAccount *>(iter->second); + + if (account and account->isEnabled() and account->fullMatch(userName, server)) { + DEBUG("Manager: Matching account id in request is a fullmatch %s@%s", userName.c_str(), server.c_str()); return iter->first; } } // We failed! Then only match the hostname - for (AccountMap::const_iterator iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - SIPAccount *account = dynamic_cast<SIPAccount *> (iter->second); + for (AccountMap::const_iterator iter = accountMap_.begin(); iter != accountMap_.end(); ++iter) { + SIPAccount *account = dynamic_cast<SIPAccount *>(iter->second); - if (account and account->isEnabled() and account->hostnameMatch (server)) { - _debug ("Manager: Matching account id in request with hostname %s", server.c_str()); + if (account and account->isEnabled() and account->hostnameMatch(server)) { + DEBUG("Manager: Matching account id in request with hostname %s", server.c_str()); return iter->first; } } // We failed! Then only match the username - for (AccountMap::const_iterator iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - SIPAccount *account = dynamic_cast<SIPAccount *> (iter->second); + for (AccountMap::const_iterator iter = accountMap_.begin(); iter != accountMap_.end(); ++iter) { + SIPAccount *account = dynamic_cast<SIPAccount *>(iter->second); - if (account and account->isEnabled() and account->userMatch (userName)) { - _debug ("Manager: Matching account id in request with username %s", userName.c_str()); + if (account and account->isEnabled() and account->userMatch(userName)) { + DEBUG("Manager: Matching account id in request with username %s", userName.c_str()); return iter->first; } } - _debug ("Manager: Username %s or server %s doesn't match any account, using IP2IP", userName.c_str(), server.c_str()); + DEBUG("Manager: Username %s or server %s doesn't match any account, using IP2IP", userName.c_str(), server.c_str()); return ""; } -std::map<std::string, int32_t> ManagerImpl::getAddressbookSettings () const +std::map<std::string, int32_t> ManagerImpl::getAddressbookSettings() const { std::map<std::string, int32_t> settings; @@ -2808,15 +2827,14 @@ std::map<std::string, int32_t> ManagerImpl::getAddressbookSettings () const return settings; } -void ManagerImpl::setAddressbookSettings ( - const std::map<std::string, int32_t>& settings) +void ManagerImpl::setAddressbookSettings(const std::map<std::string, int32_t>& settings) { - addressbookPreference.setEnabled (settings.find ("ADDRESSBOOK_ENABLE")->second == 1); - addressbookPreference.setMaxResults (settings.find ("ADDRESSBOOK_MAX_RESULTS")->second); - addressbookPreference.setPhoto (settings.find ("ADDRESSBOOK_DISPLAY_CONTACT_PHOTO")->second == 1); - addressbookPreference.setBusiness (settings.find ("ADDRESSBOOK_DISPLAY_PHONE_BUSINESS")->second == 1); - addressbookPreference.setHone (settings.find ("ADDRESSBOOK_DISPLAY_PHONE_HOME")->second == 1); - addressbookPreference.setMobile (settings.find ("ADDRESSBOOK_DISPLAY_PHONE_MOBILE")->second == 1); + addressbookPreference.setEnabled(settings.find("ADDRESSBOOK_ENABLE")->second == 1); + addressbookPreference.setMaxResults(settings.find("ADDRESSBOOK_MAX_RESULTS")->second); + addressbookPreference.setPhoto(settings.find("ADDRESSBOOK_DISPLAY_CONTACT_PHOTO")->second == 1); + addressbookPreference.setBusiness(settings.find("ADDRESSBOOK_DISPLAY_PHONE_BUSINESS")->second == 1); + addressbookPreference.setHone(settings.find("ADDRESSBOOK_DISPLAY_PHONE_HOME")->second == 1); + addressbookPreference.setMobile(settings.find("ADDRESSBOOK_DISPLAY_PHONE_MOBILE")->second == 1); // Write it to the configuration file // TODO save config is called for updateAddressbookSettings, updateHookSettings, setHistoryLimit each called @@ -2824,19 +2842,18 @@ void ManagerImpl::setAddressbookSettings ( // saveConfig(); } -void ManagerImpl::setAddressbookList (const std::vector<std::string>& list) +void ManagerImpl::setAddressbookList(const std::vector<std::string>& list) { - addressbookPreference.setList (ManagerImpl::serialize (list)); - + addressbookPreference.setList(ManagerImpl::serialize(list)); saveConfig(); } -std::vector<std::string> ManagerImpl::getAddressbookList (void) const +std::vector<std::string> ManagerImpl::getAddressbookList() const { - return unserialize (addressbookPreference.getList()); + return unserialize(addressbookPreference.getList()); } -std::map<std::string, std::string> ManagerImpl::getHookSettings () const +std::map<std::string, std::string> ManagerImpl::getHookSettings() const { std::map<std::string, std::string> settings; @@ -2850,14 +2867,14 @@ std::map<std::string, std::string> ManagerImpl::getHookSettings () const return settings; } -void ManagerImpl::setHookSettings (const std::map<std::string, std::string>& settings) +void ManagerImpl::setHookSettings(const std::map<std::string, std::string>& settings) { - hookPreference.setIax2Enabled (settings.find ("URLHOOK_IAX2_ENABLED")->second == "true"); - hookPreference.setNumberAddPrefix (settings.find ("PHONE_NUMBER_HOOK_ADD_PREFIX")->second); - hookPreference.setNumberEnabled (settings.find ("PHONE_NUMBER_HOOK_ENABLED")->second == "true"); - hookPreference.setSipEnabled (settings.find ("URLHOOK_SIP_ENABLED")->second == "true"); - hookPreference.setUrlCommand (settings.find ("URLHOOK_COMMAND")->second); - hookPreference.setUrlSipField (settings.find ("URLHOOK_SIP_FIELD")->second); + hookPreference.setIax2Enabled(settings.find("URLHOOK_IAX2_ENABLED")->second == "true"); + hookPreference.setNumberAddPrefix(settings.find("PHONE_NUMBER_HOOK_ADD_PREFIX")->second); + hookPreference.setNumberEnabled(settings.find("PHONE_NUMBER_HOOK_ENABLED")->second == "true"); + hookPreference.setSipEnabled(settings.find("URLHOOK_SIP_ENABLED")->second == "true"); + hookPreference.setUrlCommand(settings.find("URLHOOK_COMMAND")->second); + hookPreference.setUrlSipField(settings.find("URLHOOK_SIP_FIELD")->second); // Write it to the configuration file // TODO save config is called for updateAddressbookSettings, updateHookSettings, setHistoryLimit each called @@ -2865,51 +2882,53 @@ void ManagerImpl::setHookSettings (const std::map<std::string, std::string>& set // saveConfig(); } -bool ManagerImpl::associateConfigToCall (const std::string& callID, - Call::CallConfiguration config) +bool ManagerImpl::associateConfigToCall(const std::string& callID, + Call::CallConfiguration config) { - if (getConfigFromCall (callID) == CallConfigNULL) { // nothing with the same ID - _callConfigMap[callID] = config; - _debug ("Manager: Associate call %s with config %d", callID.c_str(), config); + if (getConfigFromCall(callID) == 0) { // nothing with the same ID + callConfigMap_[callID] = config; + DEBUG("Manager: Associate call %s with config %d", callID.c_str(), config); return true; } else return false; } -Call::CallConfiguration ManagerImpl::getConfigFromCall (const std::string& callID) const +Call::CallConfiguration ManagerImpl::getConfigFromCall(const std::string& callID) const { - CallConfigMap::const_iterator iter = _callConfigMap.find (callID); + CallConfigMap::const_iterator iter = callConfigMap_.find(callID); - if (iter == _callConfigMap.end()) - return (Call::CallConfiguration) CallConfigNULL; + if (iter == callConfigMap_.end()) + return (Call::CallConfiguration) 0; else return iter->second; } -bool ManagerImpl::removeCallConfig (const std::string& callID) +bool ManagerImpl::removeCallConfig(const std::string& callID) { - return _callConfigMap.erase (callID); + return callConfigMap_.erase(callID); } -std::map<std::string, std::string> ManagerImpl::getCallDetails (const std::string& callID) +std::map<std::string, std::string> ManagerImpl::getCallDetails(const std::string& callID) { // We need here to retrieve the call information attached to the call ID // To achieve that, we need to get the voip link attached to the call // But to achieve that, we need to get the account the call was made with // So first we fetch the account - const std::string accountid(getAccountFromCall (callID)); + const std::string accountid(getAccountFromCall(callID)); // Then the VoIP link this account is linked with (IAX2 or SIP) Call *call = NULL; - if (Account *account = getAccount (accountid)) { + + if (Account *account = getAccount(accountid)) { VoIPLink *link = account->getVoIPLink(); if (link) - call = link->getCall (callID); + call = link->getCall(callID); } std::map<std::string, std::string> call_details; + if (call) { std::ostringstream type; type << call->getCallType(); @@ -2920,7 +2939,7 @@ std::map<std::string, std::string> ManagerImpl::getCallDetails (const std::strin call_details["CALL_STATE"] = call->getStateStr(); call_details["CALL_TYPE"] = type.str(); } else { - _error ("Manager: Error: getCallDetails()"); + ERROR("Manager: Error: getCallDetails()"); call_details["ACCOUNTID"] = ""; call_details["PEER_NUMBER"] = "Unknown"; call_details["PEER_NAME"] = "Unknown"; @@ -2932,42 +2951,40 @@ std::map<std::string, std::string> ManagerImpl::getCallDetails (const std::strin return call_details; } -std::vector<std::string> ManagerImpl::getHistorySerialized(void) const +std::vector<std::string> ManagerImpl::getHistorySerialized() const { - return _history->get_history_serialized(); + return history_->get_history_serialized(); } void ManagerImpl::setHistorySerialized(std::vector<std::string> history) { - _history->set_serialized_history (history, preferences.getHistoryLimit());; - _history->save_history(); + history_->set_serialized_history(history, preferences.getHistoryLimit());; + history_->save_history(); } namespace { template <typename M, typename V> void vectorFromMapKeys(const M &m, V &v) { - for (typename M::const_iterator it = m.begin(); it != m.end(); ++it ) + for (typename M::const_iterator it = m.begin(); it != m.end(); ++it) v.push_back(it->first); } } -std::vector<std::string> ManagerImpl::getCallList (void) const +std::vector<std::string> ManagerImpl::getCallList() const { std::vector<std::string> v; - vectorFromMapKeys(_callAccountMap, v); + vectorFromMapKeys(callAccountMap_, v); return v; } -std::map<std::string, std::string> ManagerImpl::getConferenceDetails ( +std::map<std::string, std::string> ManagerImpl::getConferenceDetails( const std::string& confID) const { std::map<std::string, std::string> conf_details; - ConferenceMap::const_iterator iter_conf; - - iter_conf = _conferencemap.find (confID); + ConferenceMap::const_iterator iter_conf = conferenceMap_.find(confID); - if (iter_conf != _conferencemap.end()) { + if (iter_conf != conferenceMap_.end()) { conf_details["CONFID"] = confID; conf_details["CONF_STATE"] = iter_conf->second->getStateStr(); } @@ -2975,23 +2992,24 @@ std::map<std::string, std::string> ManagerImpl::getConferenceDetails ( return conf_details; } -std::vector<std::string> ManagerImpl::getConferenceList (void) const +std::vector<std::string> ManagerImpl::getConferenceList() const { std::vector<std::string> v; - vectorFromMapKeys(_conferencemap, v); + vectorFromMapKeys(conferenceMap_, v); return v; } -std::vector<std::string> ManagerImpl::getParticipantList (const std::string& confID) const +std::vector<std::string> ManagerImpl::getParticipantList(const std::string& confID) const { std::vector<std::string> v; - ConferenceMap::const_iterator iter_conf = _conferencemap.find (confID); - if (iter_conf != _conferencemap.end()) { - const ParticipantSet &participants = iter_conf->second->getParticipantList(); + ConferenceMap::const_iterator iter_conf = conferenceMap_.find(confID); + + if (iter_conf != conferenceMap_.end()) { + const ParticipantSet participants(iter_conf->second->getParticipantList()); std::copy(participants.begin(), participants.end(), std::back_inserter(v));; } else - _warn ("Manager: Warning: Did not found conference %s", confID.c_str()); + WARN("Manager: Warning: Did not find conference %s", confID.c_str()); return v; } diff --git a/daemon/src/managerimpl.h b/daemon/src/managerimpl.h index 653739ec4c845e92d6b50508bbda442eff9eaba9..fff615a48d8072889eab549693efdb7d3b49712a 100644 --- a/daemon/src/managerimpl.h +++ b/daemon/src/managerimpl.h @@ -48,18 +48,19 @@ #include "conference.h" #include "audio/sound/tone.h" // for Tone::TONEID declaration -#include "audio/codecs/audiocodecfactory.h" +#include "audio/codecs/audiocodecfactory.h" #include "audio/mainbuffer.h" #include "preferences.h" +#include "noncopyable.h" namespace sfl { - class InstantMessaging; +class InstantMessaging; } namespace Conf { - class YamlParser; - class YamlEmitter; +class YamlParser; +class YamlEmitter; } class DTMF; @@ -86,21 +87,16 @@ typedef std::map<std::string, Call::CallConfiguration> CallConfigMap; /** To send multiple string */ typedef std::list<std::string> TokenList; -/** To store conference objects by call ids - used to retreive the conference according to a call */ -typedef std::map<std::string, Conference*> ConferenceCallMap; - /** To store conference objects by conference ids */ typedef std::map<std::string, Conference*> ConferenceMap; -static std::string default_conf = "conf"; +static const char * const default_conf = "conf"; /** Manager (controller) of sflphone daemon */ -class ManagerImpl -{ +class ManagerImpl { public: - ManagerImpl (void); - ~ManagerImpl (void); + ManagerImpl(); + ~ManagerImpl(); /** @@ -137,20 +133,20 @@ class ManagerImpl * Initialisation of thread (sound) and map. * Init a new VoIPLink, audio codec and audio driver */ - void init (std::string config_file=""); + void init(std::string config_file=""); /** * Terminate all thread (sound, link) and unload AccountMap */ - void terminate (void); + void terminate(); /** * Accessor to audiodriver. * it's multi-thread and use mutex internally * @return AudioLayer* The audio layer object */ - AudioLayer* getAudioDriver (void) const { - return _audiodriver; + AudioLayer* getAudioDriver() { + return audiodriver_; } /** @@ -163,21 +159,21 @@ class ManagerImpl * @return bool true on success * false otherwise */ - bool outgoingCall (const std::string&, const std::string&, const std::string&, const std::string& = ""); + bool outgoingCall(const std::string&, const std::string&, const std::string&, const std::string& = ""); /** * Functions which occur with a user's action * Answer the call * @param id The call identifier */ - bool answerCall (const std::string& id); + bool answerCall(const std::string& id); /** * Functions which occur with a user's action * Hangup the call * @param id The call identifier */ - void hangupCall (const std::string& id); + void hangupCall(const std::string& id); /** @@ -185,21 +181,21 @@ class ManagerImpl * Hangup the conference (hangup every participants) * @param id The call identifier */ - bool hangupConference (const std::string& id); + bool hangupConference(const std::string& id); /** * Functions which occur with a user's action * Put the call on hold * @param id The call identifier */ - void onHoldCall (const std::string& id); + void onHoldCall(const std::string& id); /** * Functions which occur with a user's action * Put the call off hold * @param id The call identifier */ - void offHoldCall (const std::string& id); + void offHoldCall(const std::string& id); /** * Functions which occur with a user's action @@ -207,7 +203,7 @@ class ManagerImpl * @param id The call identifier * @param to The recipient of the transfer */ - bool transferCall (const std::string& id, const std::string& to); + bool transferCall(const std::string& id, const std::string& to); /** * Attended transfer @@ -231,134 +227,130 @@ class ManagerImpl * Refuse the call * @param id The call identifier */ - void refuseCall (const std::string& id); + void refuseCall(const std::string& id); /** * Create a new conference given two participant * @param the first participant ID * @param the second participant ID */ - Conference* createConference (const std::string& id1, const std::string& id2); + Conference* createConference(const std::string& id1, const std::string& id2); /** * Delete this conference * @param the conference ID */ - void removeConference (const std::string& conference_id); + void removeConference(const std::string& conference_id); /** * Return the conference id for which this call is attached * @ param the call id */ - Conference* getConferenceFromCallID (const std::string& call_id); + Conference* getConferenceFromCallID(const std::string& call_id); /** * Hold every participant to a conference * @param the conference id */ - void holdConference (const std::string& conference_id); + void holdConference(const std::string& conference_id); /** * Unhold all conference participants * @param the conference id */ - void unHoldConference (const std::string& conference_id); + void unHoldConference(const std::string& conference_id); /** * Test if this id is a conference (usefull to test current call) * @param the call id */ - bool isConference (const std::string& call_id); + bool isConference(const std::string& call_id) const; /** - * Test if a call id particips to this conference + * Test if a call id corresponds to a conference participant * @param the call id */ - bool participToConference (const std::string& call_id); + bool isConferenceParticipant(const std::string& call_id); /** * Add a participant to a conference * @param the call id * @param the conference id */ - void addParticipant (const std::string& call_id, const std::string& conference_id); + void addParticipant(const std::string& call_id, const std::string& conference_id); /** * Bind the main participant to a conference (mainly called on a double click action) * @param the conference id */ - void addMainParticipant (const std::string& conference_id); + void addMainParticipant(const std::string& conference_id); /** * Join two participants to create a conference * @param the fist call id * @param the second call id */ - void joinParticipant (const std::string& call_id1, const std::string& call_id2); + void joinParticipant(const std::string& call_id1, const std::string& call_id2); - /** - * Create a conference from a list of participant - * @param A vector containing the list of participant - */ - void createConfFromParticipantList(const std::vector< std::string > &); + /** + * Create a conference from a list of participant + * @param A vector containing the list of participant + */ + void createConfFromParticipantList(const std::vector< std::string > &); /** * Detach a participant from a conference, put the call on hold, do not hangup it * @param call id * @param the current call id */ - void detachParticipant (const std::string& call_id, const std::string& current_call_id); + void detachParticipant(const std::string& call_id, const std::string& current_call_id); /** * Remove the conference participant from a conference * @param call id */ - void removeParticipant (const std::string& call_id); + void removeParticipant(const std::string& call_id); /** * Join two conference together into one unique conference */ - void joinConference (const std::string& conf_id1, const std::string& conf_id2); + void joinConference(const std::string& conf_id1, const std::string& conf_id2); - void addStream (const std::string& call_id); + void addStream(const std::string& call_id); - void removeStream (const std::string& call_id); + void removeStream(const std::string& call_id); /** * Save config to file */ - void saveConfig (void); + void saveConfig(); /** * @return true if we tried to register once */ - bool _hasTriedToRegister; + bool hasTriedToRegister_; /** * Handle choice of the DTMF-send-way * @param id: callid of the line. * @param code: pressed key. */ - void sendDtmf (const std::string& id, char code); + void sendDtmf(const std::string& id, char code); /** * Play a ringtone - * @return bool True on success - * false otherwise */ - bool playTone (); + void playTone(); /** * Play a special ringtone ( BUSY ) if there's at least one message on the voice mail - * @return bool True on success - * false otherwise */ - bool playToneWithMessage (); + void playToneWithMessage(); /** * Acts on the audio streams and audio files */ - void stopTone (void); + void stopTone(); /** * When receiving a new incoming call, add it to the callaccount map @@ -366,34 +358,34 @@ class ManagerImpl * @param call A call pointer * @param accountId an account id */ - void incomingCall (Call* call, const std::string& accountId); + void incomingCall(Call* call, const std::string& accountId); /** * Notify the user that the recipient of the call has answered and the put the * call in Current state * @param id The call identifier */ - void peerAnsweredCall (const std::string& id); + void peerAnsweredCall(const std::string& id); /** * Rings back because the outgoing call is ringing and the put the * call in Ringing state * @param id The call identifier */ - void peerRingingCall (const std::string& id); + void peerRingingCall(const std::string& id); /** * Put the call in Hungup state, remove the call from the list * @param id The call identifier */ - void peerHungupCall (const std::string& id); + void peerHungupCall(const std::string& id); /** * Notify the client with an incoming message * @param accountId The account identifier * @param message The content of the message */ - void incomingMessage (const std::string& callID, const std::string& from, const std::string& message); + void incomingMessage(const std::string& callID, const std::string& from, const std::string& message); /** @@ -402,19 +394,19 @@ class ManagerImpl * @param message The content of the message * @param from The sender of this message (could be another participant of a conference) */ - bool sendTextMessage (const std::string& callID, const std::string& message, const std::string& from); + bool sendTextMessage(const std::string& callID, const std::string& message, const std::string& from); /** * Notify the client he has voice mails * @param accountId The account identifier * @param nb_msg The number of messages */ - void startVoiceMessageNotification (const std::string& accountId, int nb_msg); + void startVoiceMessageNotification(const std::string& accountId, int nb_msg); /** * Notify the client through DBus that registration state has been updated */ - void connectionStatusNotification (void); + void connectionStatusNotification(); /** * ConfigurationManager - Send registration request @@ -423,58 +415,58 @@ class ManagerImpl * 0 for unregistration request * 1 for registration request */ - void sendRegister (const ::std::string& accountId , const int32_t& enable); + void sendRegister(const ::std::string& accountId , const int32_t& enable); /** * Get account list * @return std::vector<std::string> A list of accoundIDs */ - std::vector< std::string > getAccountList() const; + std::vector<std::string> getAccountList() const; /** * Set the account order in the config file */ - void setAccountsOrder (const std::string& order); + void setAccountsOrder(const std::string& order); /** * Retrieve details about a given account * @param accountID The account identifier * @return std::map< std::string, std::string > The account details */ - std::map< std::string, std::string > getAccountDetails (const std::string& accountID) const; + std::map<std::string, std::string> getAccountDetails(const std::string& accountID) const; /** * Retrieve details about a given call * @param callID The account identifier * @return std::map< std::string, std::string > The call details */ - std::map< std::string, std::string > getCallDetails (const std::string& callID); + std::map<std::string, std::string> getCallDetails(const std::string& callID); /** * Get call list * @return std::vector<std::string> A list of call IDs */ - std::vector< std::string > getCallList (void) const; + std::vector<std::string> getCallList() const; /** * Retrieve details about a given call * @param callID The account identifier * @return std::map< std::string, std::string > The call details */ - std::map< std::string, std::string > getConferenceDetails (const std::string& callID) const; + std::map<std::string, std::string> getConferenceDetails(const std::string& callID) const; /** * Get call list * @return std::vector<std::string> A list of call IDs */ - std::vector< std::string > getConferenceList (void) const; + std::vector<std::string> getConferenceList() const; /** * Get a list of participant to a conference * @return std::vector<std::string> A list of call IDs */ - std::vector< std::string > getParticipantList (const std::string& confID) const; + std::vector<std::string> getParticipantList(const std::string& confID) const; /** * Save the details of an existing account, given the account ID @@ -483,54 +475,54 @@ class ManagerImpl * @param accountID The account identifier * @param details The account parameters */ - void setAccountDetails (const ::std::string& accountID, - const std::map< ::std::string, ::std::string >& details); + void setAccountDetails(const std::string& accountID, + const std::map<std::string, ::std::string > &details); /** * Add a new account, and give it a new account ID automatically * @param details The new account parameters * @return The account Id given to the new account */ - std::string addAccount (const std::map< ::std::string, ::std::string >& details); + std::string addAccount(const std::map<std::string, std::string> &details); /** * Delete an existing account, unregister VoIPLink associated, and * purge from configuration. * @param accountID The account unique ID */ - void removeAccount (const std::string& accountID); + void removeAccount(const std::string& accountID); /** * Get current codec name * @param call id * @return std::string The codec name */ - std::string getCurrentCodecName (const std::string& id); + std::string getCurrentCodecName(const std::string& id); /** * Set input audio plugin * @param audioPlugin The audio plugin */ - void setAudioPlugin (const std::string& audioPlugin); + void setAudioPlugin(const std::string& audioPlugin); /** * Set audio device * @param index The index of the soundcard * @param the type of stream, either SFL_PCM_PLAYBACK, SFL_PCM_CAPTURE, SFL_PCM_RINGTONE */ - void setAudioDevice (const int index, const int streamType); + void setAudioDevice(const int index, const int streamType); /** * Get list of supported audio output device * @return std::vector<std::string> A list of the audio devices supporting playback */ - std::vector<std::string> getAudioOutputDeviceList (void); + std::vector<std::string> getAudioOutputDeviceList(); /** * Get list of supported audio input device * @return std::vector<std::string> A list of the audio devices supporting capture */ - std::vector<std::string> getAudioInputDeviceList (void); + std::vector<std::string> getAudioInputDeviceList(); /** * Get string array representing integer indexes of output, input, and ringtone device @@ -543,42 +535,42 @@ class ManagerImpl * @param name The string description of an audio device * @return int His index */ - int getAudioDeviceIndex (const std::string &name); + int getAudioDeviceIndex(const std::string &name); /** * Get current alsa plugin * @return std::string The Alsa plugin */ - std::string getCurrentAudioOutputPlugin (void) const; + std::string getCurrentAudioOutputPlugin() const; /** * Get the noise reduction engin state from * the current audio layer. */ - std::string getNoiseSuppressState (void) const; + std::string getNoiseSuppressState() const; /** * Set the noise reduction engin state in the current * audio layer. */ - void setNoiseSuppressState (const std::string &state); + void setNoiseSuppressState(const std::string &state); /** * Get the echo canceller engin state from * the current audio layer */ - bool getEchoCancelState(void) const; + bool getEchoCancelState() const; /** * Set the echo canceller engin state */ void setEchoCancelState(const std::string &state); - int getEchoCancelTailLength(void) const; + int getEchoCancelTailLength() const; void setEchoCancelTailLength(int); - int getEchoCancelDelay(void) const; + int getEchoCancelDelay() const; void setEchoCancelDelay(int); @@ -587,9 +579,9 @@ class ManagerImpl * Required format: payloads separated with one slash. * @return std::string The serializabled string */ - static std::string serialize (const std::vector<std::string> &v); + static std::string serialize(const std::vector<std::string> &v); - static std::vector<std::string> unserialize (std::string v); + static std::vector<std::string> unserialize(std::string v); /** * Ringtone option. @@ -597,30 +589,30 @@ class ManagerImpl * @return int 1 if enabled * 0 otherwise */ - int isRingtoneEnabled (const std::string& id); + int isRingtoneEnabled(const std::string& id); /** * Set the ringtone option * Inverse current value */ - void ringtoneEnabled (const std::string& id); + void ringtoneEnabled(const std::string& id); /** * Get the recording path from configuration tree * @return the string correspoding to the path */ - std::string getRecordPath (void) const; + std::string getRecordPath() const; /** * Set the recoding path in the configuration tree * @param a string reresenting the path */ - void setRecordPath (const std::string& recPath); + void setRecordPath(const std::string& recPath); /** * Get is always recording functionality */ - bool getIsAlwaysRecording(void) const; + bool getIsAlwaysRecording() const; /** * Set is always recording functionality, every calls will then be set in RECORDING mode @@ -633,85 +625,85 @@ class ManagerImpl * Start recording * @param id The call identifier */ - void setRecordingCall (const std::string& id); + void setRecordingCall(const std::string& id); /** * Return true if the call is currently recorded */ - bool isRecording (const std::string& id); + bool isRecording(const std::string& id); - /** - * Start playback fo a recorded file if and only if audio layer is not already started. - * @param File path of the file to play - */ + /** + * Start playback fo a recorded file if and only if audio layer is not already started. + * @param File path of the file to play + */ bool startRecordedFilePlayback(const std::string&); - /** - * Stop playback of recorded file - * @param File of the file to stop - */ + /** + * Stop playback of recorded file + * @param File of the file to stop + */ void stopRecordedFilePlayback(const std::string&); /** * Set the maximum number of days to keep in the history * @param calls The number of days */ - void setHistoryLimit (int days); + void setHistoryLimit(int days); /** * Get the maximum number of days to keep in the history * @return double The number of days */ - int getHistoryLimit (void) const; + int getHistoryLimit() const; /** * Configure the start-up option * @return int 1 if SFLphone should start in the system tray * 0 otherwise */ - int isStartHidden (void); + int isStartHidden(); /** * Configure the start-up option * At startup, SFLphone can be displayed or start hidden in the system tray */ - void startHidden (void); + void startHidden(); /** * Set the desktop mail notification level */ - void setMailNotify (void); + void setMailNotify(); /** * Addressbook configuration */ - std::map<std::string, int32_t> getAddressbookSettings (void) const; + std::map<std::string, int32_t> getAddressbookSettings() const; /** * Addressbook configuration */ - void setAddressbookSettings (const std::map<std::string, int32_t>& settings); + void setAddressbookSettings(const std::map<std::string, int32_t>& settings); /** * Addressbook list */ - void setAddressbookList (const std::vector< std::string >& list); + void setAddressbookList(const std::vector< std::string >& list); /** * Addressbook list */ - std::vector <std::string> getAddressbookList (void) const; + std::vector <std::string> getAddressbookList() const; /** * Hook configuration */ - std::map<std::string, std::string> getHookSettings (void) const; + std::map<std::string, std::string> getHookSettings() const; /** * Hook configuration */ - void setHookSettings (const std::map<std::string, std::string>& settings); + void setHookSettings(const std::map<std::string, std::string>& settings); /** @@ -720,32 +712,32 @@ class ManagerImpl * "alsa" * "pulseaudio" */ - std::string getAudioManager (void) const; + std::string getAudioManager() const; /** * Set the audio manager */ - void setAudioManager (const std::string &api); + void setAudioManager(const std::string &api); - void switchAudioManager (void); + void switchAudioManager(); /** * Set the internal audio sampling rate change. Should close the audio layer and * reopen stream at different rate, */ - void audioSamplingRateChanged (int); + void audioSamplingRateChanged(int); /** * Get the desktop mail notification level * @return int The mail notification level */ - int32_t getMailNotify (void) const; + int32_t getMailNotify() const; /** * Get the list of the active codecs * @return std::vector< ::std::string > The list of active codecs */ - std::vector< ::std::string > getActiveCodecList (void) const; + std::vector<std::string> getActiveCodecList() const; /** * Retrieve in the configuration tree the value of a parameter in a specific section @@ -755,7 +747,7 @@ class ManagerImpl * @return bool true on success * false otherwise */ - bool getConfig (const std::string& section, const std::string& name, TokenList& arg) const; + bool getConfig(const std::string& section, const std::string& name, TokenList& arg) const; /** * Change a specific value in the configuration tree. @@ -766,7 +758,7 @@ class ManagerImpl * @return bool true on success * false otherwise */ - bool setConfig (const std::string& section, const std::string& name, const std::string& value); + bool setConfig(const std::string& section, const std::string& name, const std::string& value); /** * Change a specific value in the configuration tree. @@ -777,7 +769,7 @@ class ManagerImpl * @return bool true on success * false otherwise */ - bool setConfig (const std::string& section, const std::string& name, int value); + bool setConfig(const std::string& section, const std::string& name, int value); /** * Get a int from the configuration tree @@ -787,7 +779,7 @@ class ManagerImpl * @return int The int value */ - int getConfigInt (const std::string& section, const std::string& name) const; + int getConfigInt(const std::string& section, const std::string& name) const; /** * Get a bool from the configuration tree @@ -797,7 +789,7 @@ class ManagerImpl * @return bool The bool value */ - bool getConfigBool (const std::string& section, const std::string& name) const; + bool getConfigBool(const std::string& section, const std::string& name) const; /** * Get a string from the configuration tree @@ -806,40 +798,40 @@ class ManagerImpl * @param name The parameter name * @return sdt::string The string value */ - std::string getConfigString (const std::string& section, const std::string& name) const; + std::string getConfigString(const std::string& section, const std::string& name) const; /** * Retrieve the soundcards index in the user config file and try to open audio devices * with a specific alsa plugin. * Set the audio layer sample rate */ - void selectAudioDriver (void); + void selectAudioDriver(); /** * Handle audio sounds heard by a caller while they wait for their * connection to a called party to be completed. */ - void ringback (); + void ringback(); /** * Handle played music when an incoming call occurs */ - void ringtone (const std::string& accountID); + void ringtone(const std::string& accountID); /** * Handle played music when a congestion occurs */ - void congestion (); + void congestion(); /** * Handle played sound when a call can not be conpleted because of a busy recipient */ - void callBusy (const std::string& id); + void callBusy(const std::string& id); /** * Handle played sound when a failure occurs */ - void callFailure (const std::string& id); + void callFailure(const std::string& id); /** * Retrieve the current telephone tone @@ -857,7 +849,7 @@ class ManagerImpl * @return true is there is one or many incoming call waiting * new call, not anwsered or refused */ - bool incomingCallWaiting (void); + bool incomingCallWaiting(); /* * Inline functions to manage speaker volume control @@ -865,8 +857,8 @@ class ManagerImpl * Write by main thread only * @return unsigned short The volume value */ - unsigned short getSpkrVolume (void) const { - return _spkr_volume; + unsigned short getSpkrVolume() const { + return speakerVolume_; } /* @@ -875,7 +867,7 @@ class ManagerImpl * Write by main thread only * @param spkr_vol The volume value */ - void setSpkrVolume (unsigned short spkr_vol); + void setSpkrVolume(unsigned short spkr_vol); /* * Inline functions to manage mic volume control @@ -883,8 +875,8 @@ class ManagerImpl * Write by main thread only * @return unsigned short The volume value */ - unsigned short getMicVolume (void) const { - return _mic_volume; + unsigned short getMicVolume() const { + return micVolume_; } /* @@ -893,7 +885,7 @@ class ManagerImpl * Write by main thread only * @param mic_vol The volume value */ - void setMicVolume (unsigned short mic_vol); + void setMicVolume(unsigned short mic_vol); /** * Return a new random callid that is not present in the list @@ -905,26 +897,30 @@ class ManagerImpl * Get the current call id * @return std::string The call id or "" */ - const std::string& getCurrentCallId() const; + std::string getCurrentCallId() const; /** * Check if a call is the current one * @param callId the new callid * @return bool True if the id is the current call */ - bool isCurrentCall (const std::string& callId); + bool isCurrentCall(const std::string& callId) const; - void initAudioDriver (void); + void initAudioDriver(); - void audioLayerMutexLock(void) { _audiolayerMutex.enterMutex(); } + void audioLayerMutexLock() { + audiolayerMutex_.enterMutex(); + } - void audioLayerMutexUnlock(void) { _audiolayerMutex.leaveMutex(); } + void audioLayerMutexUnlock() { + audiolayerMutex_.leaveMutex(); + } /** * Load the accounts order set by the user from the sflphonedrc config file * @return std::vector<std::string> A vector containing the account ID's */ - std::vector<std::string> loadAccountOrder () const; + std::vector<std::string> loadAccountOrder() const; // map of codec (for configlist request) const AudioCodecFactory audioCodecFactory; @@ -934,7 +930,7 @@ class ManagerImpl * Play the dtmf-associated sound * @param code The pressed key */ - bool playDtmf (char code); + void playDtmf(char code); /** * Process remaining participant given a conference and the current call id. @@ -942,18 +938,18 @@ class ManagerImpl * @param current call id * @param conference pointer */ - void processRemainingParticipant (const std::string ¤t_call_id, Conference *conf); + void processRemainingParticipants(const std::string ¤t_call_id, Conference * &conf); /** * Create config directory in home user and return configuration file path */ - std::string getConfigFile (void) const; + std::string getConfigFile() const; /* * Initialize zeroconf module and scanning */ - void initZeroconf (void); + void initZeroconf(); /* * Init the volume for speakers/micro from 0 to 100 value @@ -964,117 +960,117 @@ class ManagerImpl * Switch of current call id * @param id The new callid */ - void switchCall (const std::string& id); + void switchCall(const std::string& id); /* * Play one tone * @return false if the driver is uninitialize */ - bool playATone (Tone::TONEID toneId); + void playATone(Tone::TONEID toneId); - DBusManager _dbus; + DBusManager dbus_; /** The configuration tree. It contains accounts parameters, general user settings ,audio settings, ... */ - Conf::ConfigTree _config; + Conf::ConfigTree config_; /** Current Call ID */ - std::string _currentCallId2; + std::string currentCallId_; /** Protected current call access */ - ost::Mutex _currentCallMutex; + ost::Mutex currentCallMutex_; /** Audio layer */ - AudioLayer* _audiodriver; + AudioLayer* audiodriver_; // Main thread - DTMF* _dtmfKey; + DTMF* dtmfKey_; ///////////////////// // Protected by Mutex ///////////////////// - ost::Mutex _toneMutex; - TelephoneTone* _telephoneTone; - AudioFile *_audiofile; + ost::Mutex toneMutex_; + TelephoneTone* telephoneTone_; + AudioFile *audiofile_; // To handle volume control - short _spkr_volume; - short _mic_volume; + short speakerVolume_; + short micVolume_; // End of sound variable /** * Mutex used to protect audio layer */ - ost::Mutex _audiolayerMutex; + ost::Mutex audiolayerMutex_; /** * Waiting Call Vectors */ - CallIDSet _waitingCall; + CallIDSet waitingCall_; /** * Protect waiting call list, access by many voip/audio threads */ - ost::Mutex _waitingCallMutex; + ost::Mutex waitingCallMutex_; /** * Number of waiting call, synchronize with waitingcall callidvector */ - unsigned int _nbIncomingWaitingCall; + unsigned int nbIncomingWaitingCall_; /** * Add incoming callid to the waiting list * @param id std::string to add */ - void addWaitingCall (const std::string& id); + void addWaitingCall(const std::string& id); /** * Remove incoming callid to the waiting list * @param id std::string to remove */ - void removeWaitingCall (const std::string& id); + void removeWaitingCall(const std::string& id); /** * Tell if a call is waiting and should be remove * @param id std::string to test * @return bool True if the call is waiting */ - bool isWaitingCall (const std::string& id); + bool isWaitingCall(const std::string& id); /** Remove a CallID/std::string association * Protected by mutex * @param callID the CallID to remove */ - void removeCallAccount (const std::string& callID); + void removeCallAccount(const std::string& callID); /** * Path of the ConfigFile */ - std::string _path; + std::string path_; #ifdef USE_ZEROCONF // DNSService contain every zeroconf services // configuration detected on the network - DNSService *_DNSService; + DNSService *DNSService_; #endif /** Map to associate a CallID to the good account */ - CallAccountMap _callAccountMap; + CallAccountMap callAccountMap_; /** Mutex to lock the call account map (main thread + voiplink thread) */ - ost::Mutex _callAccountMapMutex; + ost::Mutex callAccountMapMutex_; - CallConfigMap _callConfigMap; + CallConfigMap callConfigMap_; - bool associateConfigToCall (const std::string& callID, Call::CallConfiguration config); + bool associateConfigToCall(const std::string& callID, Call::CallConfiguration config); - Call::CallConfiguration getConfigFromCall (const std::string& callID) const; + Call::CallConfiguration getConfigFromCall(const std::string& callID) const; - bool removeCallConfig (const std::string& callID); + bool removeCallConfig(const std::string& callID); /** *Contains a list of account (sip, aix, etc) and their respective voiplink/calls */ - AccountMap _accountMap; + AccountMap accountMap_; /** * Load the account from configuration @@ -1086,7 +1082,6 @@ class ManagerImpl */ void unloadAccountMap(); - /** * Instance of the MainBuffer for the whole application * @@ -1094,7 +1089,7 @@ class ManagerImpl * Audio instances must be registered into the MainBuffer and bound together via the ManagerImpl. * */ - MainBuffer _mainBuffer; + MainBuffer mainBuffer_; public: @@ -1104,7 +1099,7 @@ class ManagerImpl * @param accountID the known accountID present in accountMap * @return bool True if the new association is create */ - bool associateCallToAccount (const std::string& callID, const std::string& accountID); + bool associateCallToAccount(const std::string& callID, const std::string& accountID); /** * Test if call is a valid call, i.e. have been created and stored in @@ -1117,29 +1112,29 @@ class ManagerImpl /** * Return a pointer to the instance of the mainbuffer */ - MainBuffer *getMainBuffer (void) { - return &_mainBuffer; + MainBuffer *getMainBuffer() { + return &mainBuffer_; } /** * Return a pointer to the instance of InstantMessaging */ - sfl::InstantMessaging *getInstantMessageModule (void) const { - return _imModule; + sfl::InstantMessaging *getInstantMessageModule() { + return imModule_; } /** * Tell if there is a current call processed * @return bool True if there is a current call */ - bool hasCurrentCall(); + bool hasCurrentCall() const; /** * Return the current DBusManager * @return A pointer to the DBusManager instance */ DBusManager * getDbusManager() { - return &_dbus; + return &dbus_; } /** @@ -1148,55 +1143,52 @@ class ManagerImpl * @return bool True if the account exists * false otherwise */ - bool accountExists (const std::string& accountID); - - /** - * Get a list of serialized history entries - * @return A list of serialized entry - */ - std::vector<std::string> getHistorySerialized (void) const; + bool accountExists(const std::string& accountID); - /** - * Set a list of serialized history entries - * @param Vector of history entries + /** + * Get a list of serialized history entries + * @return A list of serialized entry */ - void setHistorySerialized (std::vector<std::string> history); + std::vector<std::string> getHistorySerialized() const; + + /** + * Set a list of serialized history entries + * @param Vector of history entries + */ + void setHistorySerialized(std::vector<std::string> history); /** * Get an account pointer * @param accountID account ID to get * @return Account* The account pointer or 0 */ - Account* getAccount (const std::string& accountID) const; + Account* getAccount(const std::string& accountID); /** Return the std::string from a CallID * Protected by mutex * @param callID the CallID in the list * @return std::string The accountID associated or "" if the callID is not found */ - std::string getAccountFromCall (const std::string& callID); + std::string getAccountFromCall(const std::string& callID); /** * Get the voip link from the account pointer * @param accountID Account ID to get * @return VoIPLink* The voip link from the account pointer or 0 */ - VoIPLink* getAccountLink (const std::string& accountID="") const; + VoIPLink* getAccountLink(const std::string& accountID=""); - std::string getAccountIdFromNameAndServer (const std::string& userName, const std::string& server) const; + std::string getAccountIdFromNameAndServer(const std::string& userName, const std::string& server) const; int getLocalIp2IpPort() const; - std::string getStunServer (void) const; - void setStunServer (const std::string &server); - - int isStunEnabled (void); - void enableStun (void); + std::string getStunServer() const; + void setStunServer(const std::string &server); - // Map containing reference between conferences and calls - ConferenceCallMap _conferencecall; + int isStunEnabled(); + void enableStun(); // Map containing conference pointers - ConferenceMap _conferencemap; + ConferenceMap conferenceMap_; /** * Send registration to all enabled accounts @@ -1204,25 +1196,18 @@ class ManagerImpl void registerAccounts(); private: - - // Copy Constructor - ManagerImpl (const ManagerImpl& rh); - - // Assignment Operator - ManagerImpl& operator= (const ManagerImpl& rh); + NON_COPYABLE(ManagerImpl); /** * To handle the persistent history */ - HistoryManager * _history; + HistoryManager * history_; /** * Instant messaging module, resposible to initiate, format, parse, * send, and receive instant messages. */ - sfl::InstantMessaging *_imModule; - - Conf::YamlEmitter *emitter; + sfl::InstantMessaging *imModule_; }; #endif // __MANAGER_H__ diff --git a/daemon/src/managerimpl_registration.cpp b/daemon/src/managerimpl_registration.cpp index 940d1e0aeb7f063729a963ba4ae74f497111b419..dbccb44eb6b5fdd7c23ad0193e1b5b7cd5393e8e 100644 --- a/daemon/src/managerimpl_registration.cpp +++ b/daemon/src/managerimpl_registration.cpp @@ -49,33 +49,35 @@ void ManagerImpl::registerAccounts() { - for (AccountMap::iterator iter = _accountMap.begin(); iter != _accountMap.end(); ++iter) { - Account *a = iter->second; + for (AccountMap::iterator iter = accountMap_.begin(); iter != accountMap_.end(); ++iter) { + Account *a = iter->second; + if (!a) - continue; + continue; a->loadConfig(); - if (a->isEnabled()) - a->registerVoIPLink(); + + if (a->isEnabled()) + a->registerVoIPLink(); } } -VoIPLink* ManagerImpl::getAccountLink (const std::string& accountID) const +VoIPLink* ManagerImpl::getAccountLink(const std::string& accountID) { if (not accountID.empty()) - return getAccount (accountID)->getVoIPLink(); + return getAccount(accountID)->getVoIPLink(); else return SIPVoIPLink::instance(); } void -ManagerImpl::sendRegister (const std::string& accountID , const int32_t& enable) +ManagerImpl::sendRegister(const std::string& accountID , const int32_t& enable) { - Account* acc = getAccount (accountID); + Account* acc = getAccount(accountID); - acc->setEnabled (enable); + acc->setEnabled(enable); acc->loadConfig(); Manager::instance().saveConfig(); diff --git a/daemon/test/rtptest.cpp b/daemon/src/noncopyable.h similarity index 64% rename from daemon/test/rtptest.cpp rename to daemon/src/noncopyable.h index d1b375a4b40c9db6c8b210ee8f9c364cdbb6eeef..9e4d678bbdde8b49780a44a942c619ea85e0ee87 100644 --- a/daemon/test/rtptest.cpp +++ b/daemon/src/noncopyable.h @@ -1,6 +1,6 @@ /* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Savoir-Faire Linux Inc. - * Author: Alexandre Savarda <alexandre.savard@savoirfairelinux.com> + * Copyright (C) 2011 Savoir-Faire Linux Inc. + * Author: Tristan Matthews <tristan.matthews@savoirfairelinux.com> * * 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 @@ -28,41 +28,19 @@ * as that of the covered work. */ -#include <cstddef> -#include <stdio.h> -#include <sstream> -#include <ccrtp/rtp.h> -#include <assert.h> -#include <string> -#include <cstring> -#include <math.h> -#include <dlfcn.h> -#include <iostream> -#include <sstream> -#include <time.h> +#ifndef NON_COPYABLE_H_ +#define NON_COPYABLE_H_ -#include "rtptest.h" -#include "audio/audiortp/AudioSymmetricRtpSession.h" - -#include <unistd.h> - -void RtpTest::setUp() -{ - -} - -bool RtpTest::pjsipInit() -{ - - return true; -} - -void RtpTest::testRtpInitClose() -{ - _debug ("-------------------- RtpTest::testRtpInitClose --------------------\n"); +/** + * @file noncopyable.h + * @brief Simple macro to hide class' copy constructor and assignment operator. + * Useful to avoid shallow copying (i.e. class' with pointer members) + * Usage: For a class named MyClass, the macro call + * NON_COPYABLE(MyClass) should go in the private section of MyClass + */ -} +#define NON_COPYABLE(ClassName) \ + ClassName(const ClassName&); \ + ClassName& operator=(const ClassName&) -void RtpTest::tearDown() -{ -} +#endif // NON_COPYABLE_H_ diff --git a/daemon/src/numbercleaner.cpp b/daemon/src/numbercleaner.cpp index 2e83b6299256117edd46d386f22d8382b9424f6c..c49c2240ed345b6b732b36327171ba52971817b0 100644 --- a/daemon/src/numbercleaner.cpp +++ b/daemon/src/numbercleaner.cpp @@ -33,12 +33,12 @@ #include <algorithm> namespace { - void strip_chars(const std::string &to_strip, std::string &num) - { - for (std::string::const_iterator iter = to_strip.begin(); - iter != to_strip.end(); ++iter) - num.erase(std::remove(num.begin(), num.end(), *iter), num.end()); - } +void strip_chars(const std::string &to_strip, std::string &num) +{ + for (std::string::const_iterator iter = to_strip.begin(); + iter != to_strip.end(); ++iter) + num.erase(std::remove(num.begin(), num.end(), *iter), num.end()); +} } std::string NumberCleaner::clean(std::string to_clean, const std::string &prefix) diff --git a/daemon/src/numbercleaner.h b/daemon/src/numbercleaner.h index 9af37c17e8ddfed9e0fc1afeffbd403cf50ebc14..d0c67b0d42edb2a135389de365ff4b6a211dd92b 100644 --- a/daemon/src/numbercleaner.h +++ b/daemon/src/numbercleaner.h @@ -34,9 +34,8 @@ #include <string> -namespace NumberCleaner -{ - std::string clean(std::string to_clean, const std::string &prefix = ""); +namespace NumberCleaner { +std::string clean(std::string to_clean, const std::string &prefix = ""); } #endif diff --git a/daemon/src/plug-in/Makefile.am b/daemon/src/plug-in/Makefile.am deleted file mode 100644 index be2aa0731b061da2fb33a3545a18e7f8e8d08156..0000000000000000000000000000000000000000 --- a/daemon/src/plug-in/Makefile.am +++ /dev/null @@ -1,12 +0,0 @@ -include ../../globals.mak - -SUBDIRS=test - -noinst_LTLIBRARIES = libplugin.la - -libplugin_la_SOURCES = \ - pluginmanager.cpp \ - librarymanager.cpp \ - pluginmanager.h librarymanager.h plugin.h - -libplugin_la_CXXFLAGS = -I $(top_srcdir)/src/plug-in diff --git a/daemon/src/plug-in/librarymanager.cpp b/daemon/src/plug-in/librarymanager.cpp deleted file mode 100644 index 08845c3b7cd9c8725adc0139dfb81d8714ceac0a..0000000000000000000000000000000000000000 --- a/daemon/src/plug-in/librarymanager.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. - * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - - -#include "librarymanager.h" - -LibraryManager::LibraryManager (const std::string &filename) - : _filename (filename), _handlePtr (NULL) -{ - _handlePtr = loadLibrary (filename); -} - -LibraryManager::~LibraryManager (void) -{ - unloadLibrary (); -} - -LibraryManager::LibraryHandle LibraryManager::loadLibrary (const std::string &filename) -{ - LibraryHandle pluginHandlePtr = NULL; - const char *error; - - _debug ("Loading dynamic library %s", filename.c_str()); - - /* Load the library */ - pluginHandlePtr = dlopen (filename.c_str(), RTLD_LAZY); - - if (!pluginHandlePtr) { - error = dlerror(); - _debug ("Error while opening plug-in: %s", error); - return NULL; - } - - dlerror(); - - return pluginHandlePtr; -} - -int LibraryManager::unloadLibrary () -{ - if (_handlePtr == NULL) - return 1; - - _debug ("Unloading dynamic library ..."); - - dlclose (_handlePtr); - - if (dlerror()) { - _debug ("Error unloading the library : %s...", dlerror()); - return 1; - } - - return 0; -} - -int LibraryManager::resolveSymbol (const std::string &symbol, SymbolHandle *symbolPtr) -{ - SymbolHandle sy = 0; - - if (_handlePtr) { - try { - sy = dlsym (_handlePtr, symbol.c_str()); - - if (sy != NULL) { - *symbolPtr = sy; - return 0; - } - } catch (...) {} - - throw LibraryManagerException (_filename, symbol, LibraryManagerException::symbolNotFound); - } else - return 1; -} - - -/************************************************************************************************/ - -LibraryManagerException::LibraryManagerException (const std::string &libraryName, const std::string &details, Reason reason) : - std::runtime_error (""), _reason (reason), _details ("") - -{ - if (_reason == loadingFailed) - _details = "Error when loading " + libraryName + "" + details; - else - _details = "Error when resolving symbol " + details + " in " + libraryName; -} - -const char* LibraryManagerException::what () const throw() -{ - return _details.c_str(); -} diff --git a/daemon/src/plug-in/librarymanager.h b/daemon/src/plug-in/librarymanager.h deleted file mode 100644 index 87d45ba260969b87f486b97c72800d80f9b237d8..0000000000000000000000000000000000000000 --- a/daemon/src/plug-in/librarymanager.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. - * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - -#ifndef LIBRARY_MANAGER_H -#define LIBRARY_MANAGER_H - -#include "dlfcn.h" -#include <stdexcept> - -#include "global.h" - -class LibraryManager -{ - - public: - typedef void* LibraryHandle; - typedef void* SymbolHandle; - - LibraryManager (const std::string &filename); - ~LibraryManager (void); - - int resolveSymbol (const std::string &symbol, SymbolHandle *ptr); - - int unloadLibrary (void); - - protected: - LibraryHandle loadLibrary (const std::string &filename); - - private: - std::string _filename; - LibraryHandle _handlePtr; -}; - -class LibraryManagerException : public std::runtime_error -{ - - public: - - typedef enum Reason { - loadingFailed = 0, - symbolNotFound - } Reason; - - LibraryManagerException (const std::string &libraryName, const std::string &details, Reason reason); - ~LibraryManagerException (void) throw() {} - - Reason getReason (void) const { - return _reason; - } - - const char* what () const throw(); - - private: - Reason _reason; - std::string _details; -}; - -#endif // LIBRARY_MANAGER_H diff --git a/daemon/src/plug-in/pluginmanager.cpp b/daemon/src/plug-in/pluginmanager.cpp deleted file mode 100644 index b34879a1780d774be39418f1f5bb64aaad79139a..0000000000000000000000000000000000000000 --- a/daemon/src/plug-in/pluginmanager.cpp +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. - * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - -#include <dirent.h> -#include <dlfcn.h> - -#include "pluginmanager.h" - -PluginManager* PluginManager::_instance = 0; - -PluginManager* -PluginManager::instance() -{ - if (!_instance) { - return new PluginManager(); - } - - return _instance; -} - -PluginManager::PluginManager() - :_loadedPlugins() -{ - _instance = this; -} - -PluginManager::~PluginManager() -{ - _instance = 0; -} - -namespace { -bool hasSharedExtension(const std::string &fn) -{ - size_t dot_position = fn.rfind("."); - return (dot_position != std::string::npos and - fn.substr(dot_position) == ".so"); -} -} - -int -PluginManager::loadPlugins (const std::string &path) -{ - std::string pluginDir, current; - DIR *dir; - dirent *dirStruct; - LibraryManager *library; - Plugin *plugin; - - const std::string pDir = ".."; - const std::string cDir = "."; - - /* The directory in which plugins are dropped. Default: /usr/lib/sflphone/plugins/ */ - if (path.empty()) - pluginDir = std::string (PLUGINS_DIR).append("/"); - else - pluginDir = path; - _debug ("Loading plugins from %s...", pluginDir.c_str()); - - dir = opendir (pluginDir.c_str()); - /* Test if the directory exists or is readable */ - - if (!dir) - return 1; - - /* Read the directory */ - while ( (dirStruct=readdir (dir))) { - /* Get the name of the current item in the directory */ - current = dirStruct->d_name; - - /* Test if the current item is not the parent or the current directory and that it ends with .so*/ - if (current == pDir || current == cDir || !hasSharedExtension(current)) - continue; - - - /* Load the dynamic library */ - library = loadDynamicLibrary (pluginDir + current); - - /* Instanciate the plugin object */ - - if (instanciatePlugin (library, &plugin) != 0) { - _debug ("Error instanciating the plugin ..."); - closedir(dir); - return 1; - } - - /* Regitering the current plugin */ - if (registerPlugin (plugin, library) != 0) { - _debug ("Error registering the plugin ..."); - closedir(dir); - return 1; - } - } - - /* Close the directory */ - closedir (dir); - - return 0; -} - -int -PluginManager::unloadPlugins (void) -{ - PluginInfo *info; - - if (_loadedPlugins.empty()) return 0; - - /* Use an iterator on the loaded plugins map */ - pluginMap::iterator iter; - - iter = _loadedPlugins.begin(); - - while (iter != _loadedPlugins.end()) { - info = iter->second; - - if (deletePlugin (info) != 0) { - _debug ("Error deleting the plugin ... "); - return 1; - } - - unloadDynamicLibrary (info->_libraryPtr); - - if (unregisterPlugin (info) != 0) { - _debug ("Error unregistering the plugin ... "); - return 1; - } - - iter++; - } - - return 0; -} - -bool -PluginManager::isPluginLoaded (const std::string &name) -{ - if (_loadedPlugins.empty()) return false; - - /* Use an iterator on the loaded plugins map */ - pluginMap::iterator iter; - - iter = _loadedPlugins.find (name); - - /* Returns map::end if the specified key has not been found */ - if (iter==_loadedPlugins.end()) - return false; - - /* Returns the plugin pointer */ - return true; -} - - -LibraryManager* -PluginManager::loadDynamicLibrary (const std::string& filename) -{ - /* Load the library through the library manager */ - return new LibraryManager (filename); -} - -int -PluginManager::unloadDynamicLibrary (LibraryManager *libraryPtr) -{ - _debug ("Unloading dynamic library ..."); - /* Close it */ - return libraryPtr->unloadLibrary (); -} - -int -PluginManager::instanciatePlugin (LibraryManager *libraryPtr, Plugin **plugin) -{ - createFunc *createPlugin; - LibraryManager::SymbolHandle symbol; - - if (libraryPtr->resolveSymbol ("createPlugin", &symbol) != 0) - return 1; - - createPlugin = (createFunc*) symbol; - - *plugin = createPlugin(); - - return 0; -} - -int -PluginManager::deletePlugin (PluginInfo *plugin) -{ - destroyFunc *destroyPlugin; - LibraryManager::SymbolHandle symbol; - - if (plugin->_libraryPtr->resolveSymbol ("destroyPlugin", &symbol) != 0) - return 1; - - destroyPlugin = (destroyFunc*) symbol; - - /* Call it */ - destroyPlugin (plugin->_plugin); - - return 0; -} - -int -PluginManager::registerPlugin (Plugin *plugin, LibraryManager *library) -{ - std::string key; - PluginInfo *p_info; - - if (plugin==0) - return 1; - - p_info = new PluginInfo(); - - /* Retrieve information from the plugin */ - plugin->initFunc (&p_info); - - key = p_info->_name; - - //p_info->_plugin = plugin; - p_info->_libraryPtr = library; - - /* Add the data in the loaded plugin map */ - _loadedPlugins[ key ] = p_info; - - return 0; -} - -int -PluginManager::unregisterPlugin (PluginInfo *plugin) -{ - pluginMap::iterator iter; - std::string key; - - key = plugin->_name; - - if (!isPluginLoaded (key)) - return 1; - - iter = _loadedPlugins.find (key); - - _loadedPlugins.erase (iter); - - return 0; -} diff --git a/daemon/src/plug-in/pluginmanager.h b/daemon/src/plug-in/pluginmanager.h deleted file mode 100644 index e2f4654ed259759f5b43895f7d29526a58d57ff2..0000000000000000000000000000000000000000 --- a/daemon/src/plug-in/pluginmanager.h +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. - * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - -#ifndef PLUGIN_MANAGER_H -#define PLUGIN_MANAGER_H - -/* - * @file pluginmanager.h - * @brief Base class of the plugin manager - */ - -#include "librarymanager.h" -#include "global.h" - -#include <map> -#include <string> -#include <vector> - -class Plugin; - -typedef struct PluginInfo { - std::string _name; - LibraryManager *_libraryPtr; - Plugin *_plugin; - int _major_version; - int _minor_version; -} PluginInfo; - -#include "plugin.h" - -class PluginManager -{ - public: - /** - * Destructor - */ - ~PluginManager(); - - /** - * Returns the unique instance of the plugin manager - */ - static PluginManager* instance(); - - /** - * Load all the plugins found in a specific directory - * @param path The absolute path to the directory - * @return int The number of items loaded - */ - int loadPlugins (const std::string &path = ""); - - int unloadPlugins (void); - - int instanciatePlugin (LibraryManager* libraryPtr, Plugin** plugin); - - /** - * Check if a plugin has been already loaded - * @param name The name of the plugin looked for - * @return bool The pointer on the plugin or NULL if not found - */ - bool isPluginLoaded (const std::string &name); - - int registerPlugin (Plugin *plugin, LibraryManager *library); - - int unregisterPlugin (PluginInfo *plugin); - - int deletePlugin (PluginInfo *plugin); - - /** - * Load a unix dynamic/shared library - * @param filename The path to the dynamic/shared library - * @return LibraryManager* A pointer on the library - */ - LibraryManager* loadDynamicLibrary (const std::string &filename); - - /** - * Unload a unix dynamic/shared library - * @param LibraryManager* The pointer on the loaded library - */ - int unloadDynamicLibrary (LibraryManager* libraryPtr); - - private: - /** - * Default constructor - */ - PluginManager(); - - /* Map of plugins associated by their string name */ - typedef std::map<std::string, PluginInfo*> pluginMap; - pluginMap _loadedPlugins; - - /* The unique static instance */ - static PluginManager* _instance; - -}; - -#endif //PLUGIN_MANAGER_H diff --git a/daemon/src/plug-in/test/Makefile.am b/daemon/src/plug-in/test/Makefile.am deleted file mode 100644 index 089aa35a82f58b1f037bdbc5b04741c01ec23709..0000000000000000000000000000000000000000 --- a/daemon/src/plug-in/test/Makefile.am +++ /dev/null @@ -1,20 +0,0 @@ -include $(top_srcdir)/globals.mak - -PLUGIN_LIB = libplugintest.so -libplugintest_so_SOURCES = pluginTest.cpp -LLIBS=$(top_builddir)/src/plug-in/libplugin.la -libplugintest_so_CXXFLAGS = -fPIC -g -Wall -I $(top_srcdir)/src/plug-in -libplugintest_so_LDFLAGS = --shared -lc -INSTALL_PLUGIN_RULE = install-libplugintest_so - -check_PROGRAMS = libplugintest.so - -install-exec-local: install-libplugintest_so -uninstall-local: uninstall-libplugintest_so - -install-libplugintest_so: libplugintest.so - mkdir -p $(sflplugindir) - $(INSTALL_PROGRAM) libplugintest.so $(sflplugindir) - -uninstall-libplugintest_so: - rm -f $(sflplugindir)/libplugintest.so diff --git a/daemon/src/preferences.cpp b/daemon/src/preferences.cpp index 359e28dd499b7b14577d4e59e2d1c41895e33005..8844bf3256cc86fad25ddd0f7fec5db73125338a 100644 --- a/daemon/src/preferences.cpp +++ b/daemon/src/preferences.cpp @@ -38,48 +38,47 @@ const char * const Preferences::DFT_ZONE = "North America"; namespace { - static const char * const DFT_PULSE_LENGTH_STR ="250"; /** Default DTMF lenght */ - static const char * const ZRTP_ZIDFILE = "zidFile"; /** The filename used for storing ZIDs */ - static const char * const ALSA_DFT_CARD = "0"; /** Default sound card index */ - static const char * const DFT_VOL_SPKR_STR = "100"; /** Default speaker volume */ - static const char * const DFT_VOL_MICRO_STR = "100"; /** Default mic volume */ +static const char * const DFT_PULSE_LENGTH_STR ="250"; /** Default DTMF lenght */ +static const char * const ZRTP_ZIDFILE = "zidFile"; /** The filename used for storing ZIDs */ +static const char * const ALSA_DFT_CARD = "0"; /** Default sound card index */ +static const char * const DFT_VOL_SPKR_STR = "100"; /** Default speaker volume */ +static const char * const DFT_VOL_MICRO_STR = "100"; /** Default mic volume */ } // end anonymous namespace -Preferences::Preferences() : _accountOrder("") - , _historyLimit(30) - , _historyMaxCalls(20) - , _notifyMails(false) - , _zoneToneChoice(DFT_ZONE) // DFT_ZONE - , _registrationExpire(180) - , _portNum(5060) - , _searchBarDisplay(true) - , _zeroConfenable(false) - , _md5Hash(false) -{ -} +Preferences::Preferences() : accountOrder_("") + , historyLimit_(30) + , historyMaxCalls_(20) + , notifyMails_(false) + , zoneToneChoice_(DFT_ZONE) // DFT_ZONE + , registrationExpire_(180) + , portNum_(5060) + , searchBarDisplay_(true) + , zeroConfenable_(false) + , md5Hash_(false) +{} void Preferences::serialize(Conf::YamlEmitter *emiter) { - Conf::MappingNode preferencemap(NULL); + Conf::MappingNode preferencemap(NULL); - Conf::ScalarNode order(_accountOrder); + Conf::ScalarNode order(accountOrder_); std::stringstream histlimitstr; - histlimitstr << _historyLimit; + histlimitstr << historyLimit_; Conf::ScalarNode historyLimit(histlimitstr.str()); std::stringstream histmaxstr; - histmaxstr << _historyMaxCalls; + histmaxstr << historyMaxCalls_; Conf::ScalarNode historyMaxCalls(histmaxstr.str()); - Conf::ScalarNode notifyMails(_notifyMails); - Conf::ScalarNode zoneToneChoice(_zoneToneChoice); + Conf::ScalarNode notifyMails(notifyMails_); + Conf::ScalarNode zoneToneChoice(zoneToneChoice_); std::stringstream expirestr; - expirestr << _registrationExpire; + expirestr << registrationExpire_; Conf::ScalarNode registrationExpire(expirestr.str()); std::stringstream portstr; - portstr << _portNum; + portstr << portNum_; Conf::ScalarNode portNum(portstr.str()); - Conf::ScalarNode searchBarDisplay(_searchBarDisplay); - Conf::ScalarNode zeroConfenable(_zeroConfenable); - Conf::ScalarNode md5Hash(_md5Hash); + Conf::ScalarNode searchBarDisplay(searchBarDisplay_); + Conf::ScalarNode zeroConfenable(zeroConfenable_); + Conf::ScalarNode md5Hash(md5Hash_); preferencemap.setKeyValue(orderKey, &order); preferencemap.setKeyValue(historyLimitKey, &historyLimit); @@ -98,41 +97,40 @@ void Preferences::serialize(Conf::YamlEmitter *emiter) void Preferences::unserialize(Conf::MappingNode *map) { if (map == NULL) { - _error("Preference: Error: Preference map is NULL"); + ERROR("Preference: Error: Preference map is NULL"); return; } - map->getValue(orderKey, &_accountOrder); - map->getValue(historyLimitKey, &_historyLimit); - map->getValue(historyMaxCallsKey, &_historyMaxCalls); - map->getValue(notifyMailsKey, &_notifyMails); - map->getValue(zoneToneChoiceKey, &_zoneToneChoice); - map->getValue(registrationExpireKey, &_registrationExpire); - map->getValue(portNumKey, &_portNum); - map->getValue(searchBarDisplayKey, &_searchBarDisplay); - map->getValue(zeroConfenableKey, &_zeroConfenable); - map->getValue(md5HashKey, &_md5Hash); + map->getValue(orderKey, &accountOrder_); + map->getValue(historyLimitKey, &historyLimit_); + map->getValue(historyMaxCallsKey, &historyMaxCalls_); + map->getValue(notifyMailsKey, ¬ifyMails_); + map->getValue(zoneToneChoiceKey, &zoneToneChoice_); + map->getValue(registrationExpireKey, ®istrationExpire_); + map->getValue(portNumKey, &portNum_); + map->getValue(searchBarDisplayKey, &searchBarDisplay_); + map->getValue(zeroConfenableKey, &zeroConfenable_); + map->getValue(md5HashKey, &md5Hash_); } - -VoipPreference::VoipPreference() : _playDtmf(true) - , _playTones(true) - , _pulseLength(atoi(DFT_PULSE_LENGTH_STR)) // DFT_PULSE_LENGTH_STR - , _symmetricRtp(true) - , _zidFile(ZRTP_ZIDFILE) // ZRTP_ZID_FILENAME +VoipPreference::VoipPreference() : playDtmf_(true) + , playTones_(true) + , pulseLength_(atoi(DFT_PULSE_LENGTH_STR)) + , symmetricRtp_(true) + , zidFile_(ZRTP_ZIDFILE) {} void VoipPreference::serialize(Conf::YamlEmitter *emitter) { Conf::MappingNode preferencemap(NULL); - Conf::ScalarNode playDtmf(_playDtmf); - Conf::ScalarNode playTones(_playTones); + Conf::ScalarNode playDtmf(playDtmf_); + Conf::ScalarNode playTones(playTones_); std::stringstream pulselengthstr; - pulselengthstr << _pulseLength; + pulselengthstr << pulseLength_; Conf::ScalarNode pulseLength(pulselengthstr.str()); - Conf::ScalarNode symmetricRtp(_symmetricRtp); - Conf::ScalarNode zidFile(_zidFile.c_str()); + Conf::ScalarNode symmetricRtp(symmetricRtp_); + Conf::ScalarNode zidFile(zidFile_.c_str()); preferencemap.setKeyValue(playDtmfKey, &playDtmf); preferencemap.setKeyValue(playTonesKey, &playTones); @@ -146,41 +144,39 @@ void VoipPreference::serialize(Conf::YamlEmitter *emitter) void VoipPreference::unserialize(Conf::MappingNode *map) { if (!map) { - _error("VoipPreference: Error: Preference map is NULL"); + ERROR("VoipPreference: Error: Preference map is NULL"); return; } - map->getValue(playDtmfKey, &_playDtmf); - map->getValue(playTonesKey, &_playTones); - map->getValue(pulseLengthKey, &_pulseLength); - map->getValue(symmetricRtpKey, &_symmetricRtp); - map->getValue(zidFileKey, &_zidFile); + map->getValue(playDtmfKey, &playDtmf_); + map->getValue(playTonesKey, &playTones_); + map->getValue(pulseLengthKey, &pulseLength_); + map->getValue(symmetricRtpKey, &symmetricRtp_); + map->getValue(zidFileKey, &zidFile_); } - - -AddressbookPreference::AddressbookPreference() : _photo(true) - , _enabled(true) - , _list("") - , _maxResults(25) - , _business(true) - , _home(true) - , _mobile(true) +AddressbookPreference::AddressbookPreference() : photo_(true) + , enabled_(true) + , list_("") + , maxResults_(25) + , business_(true) + , home_(true) + , mobile_(true) {} void AddressbookPreference::serialize(Conf::YamlEmitter *emitter) { Conf::MappingNode preferencemap(NULL); - Conf::ScalarNode photo(_photo); - Conf::ScalarNode enabled(_enabled); - Conf::ScalarNode list(_list); + Conf::ScalarNode photo(photo_); + Conf::ScalarNode enabled(enabled_); + Conf::ScalarNode list(list_); std::stringstream maxresultstr; - maxresultstr << _maxResults; + maxresultstr << maxResults_; Conf::ScalarNode maxResults(maxresultstr.str()); - Conf::ScalarNode business(_business); - Conf::ScalarNode home(_home); - Conf::ScalarNode mobile(_mobile); + Conf::ScalarNode business(business_); + Conf::ScalarNode home(home_); + Conf::ScalarNode mobile(mobile_); preferencemap.setKeyValue(photoKey, &photo); preferencemap.setKeyValue(enabledKey, &enabled); @@ -197,40 +193,37 @@ void AddressbookPreference::serialize(Conf::YamlEmitter *emitter) void AddressbookPreference::unserialize(Conf::MappingNode *map) { if (!map) { - _error("Addressbook: Error: Preference map is NULL"); + ERROR("Addressbook: Error: Preference map is NULL"); return; } - map->getValue(photoKey, &_photo); - map->getValue(enabledKey, &_enabled); - map->getValue(listKey, &_list); - map->getValue(maxResultsKey, &_maxResults); - map->getValue(businessKey, &_business); - map->getValue(homeKey, &_home); - map->getValue(mobileKey, &_mobile); + map->getValue(photoKey, &photo_); + map->getValue(enabledKey, &enabled_); + map->getValue(listKey, &list_); + map->getValue(maxResultsKey, &maxResults_); + map->getValue(businessKey, &business_); + map->getValue(homeKey, &home_); + map->getValue(mobileKey, &mobile_); } - -HookPreference::HookPreference() : _iax2Enabled(false) - , _numberAddPrefix("") - , _numberEnabled(false) - , _sipEnabled(false) - , _urlCommand("x-www-browser") - , _urlSipField("X-sflphone-url") -{ - -} +HookPreference::HookPreference() : iax2Enabled_(false) + , numberAddPrefix_("") + , numberEnabled_(false) + , sipEnabled_(false) + , urlCommand_("x-www-browser") + , urlSipField_("X-sflphone-url") +{} void HookPreference::serialize(Conf::YamlEmitter *emitter) { Conf::MappingNode preferencemap(NULL); - Conf::ScalarNode iax2Enabled(_iax2Enabled); - Conf::ScalarNode numberAddPrefix(_numberAddPrefix); - Conf::ScalarNode numberEnabled(_numberEnabled); - Conf::ScalarNode sipEnabled(_sipEnabled); - Conf::ScalarNode urlCommand(_urlCommand); - Conf::ScalarNode urlSipField(_urlSipField); + Conf::ScalarNode iax2Enabled(iax2Enabled_); + Conf::ScalarNode numberAddPrefix(numberAddPrefix_); + Conf::ScalarNode numberEnabled(numberEnabled_); + Conf::ScalarNode sipEnabled(sipEnabled_); + Conf::ScalarNode urlCommand(urlCommand_); + Conf::ScalarNode urlSipField(urlSipField_); preferencemap.setKeyValue(iax2EnabledKey, &iax2Enabled); preferencemap.setKeyValue(numberAddPrefixKey, &numberAddPrefix); @@ -245,69 +238,68 @@ void HookPreference::serialize(Conf::YamlEmitter *emitter) void HookPreference::unserialize(Conf::MappingNode *map) { if (!map) { - _error("Hook: Error: Preference map is NULL"); + ERROR("Hook: Error: Preference map is NULL"); return; } - map->getValue(iax2EnabledKey, &_iax2Enabled); - map->getValue(numberAddPrefixKey, &_numberAddPrefix); - map->getValue(numberEnabledKey, &_numberEnabled); - map->getValue(sipEnabledKey, &_sipEnabled); - map->getValue(urlCommandKey, &_urlCommand); - map->getValue(urlSipFieldKey, &_urlSipField); + map->getValue(iax2EnabledKey, &iax2Enabled_); + map->getValue(numberAddPrefixKey, &numberAddPrefix_); + map->getValue(numberEnabledKey, &numberEnabled_); + map->getValue(sipEnabledKey, &sipEnabled_); + map->getValue(urlCommandKey, &urlCommand_); + map->getValue(urlSipFieldKey, &urlSipField_); } - - AudioPreference::AudioPreference() : - _audioApi(PULSEAUDIO_API_STR) - , _cardin(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD - , _cardout(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD - , _cardring(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD - , _plugin("default") // PCM_DEFAULT - , _smplrate(44100) // DFT_SAMPLE_RATE - , _devicePlayback("") - , _deviceRecord("") - , _deviceRingtone("") - , _recordpath("") // DFT_RECORD_PATH - , _alwaysRecording(false) - , _volumemic(atoi(DFT_VOL_SPKR_STR)) // DFT_VOL_SPKR_STR - , _volumespkr(atoi(DFT_VOL_MICRO_STR)) // DFT_VOL_MICRO_STR - , _noisereduce(true) - , _echocancel(false) - , _echoCancelTailLength(100) - , _echoCancelDelay(0) + audioApi_(PULSEAUDIO_API_STR) + , cardin_(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD + , cardout_(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD + , cardring_(atoi(ALSA_DFT_CARD)) // ALSA_DFT_CARD + , plugin_("default") // PCM_DEFAULT + , smplrate_(44100) // DFT_SAMPLE_RATE + , devicePlayback_("") + , deviceRecord_("") + , deviceRingtone_("") + , recordpath_("") // DFT_RECORD_PATH + , alwaysRecording_(false) + , volumemic_(atoi(DFT_VOL_SPKR_STR)) // DFT_VOL_SPKR_STR + , volumespkr_(atoi(DFT_VOL_MICRO_STR)) // DFT_VOL_MICRO_STR + , noisereduce_(true) + , echocancel_(false) + , echoCancelTailLength_(100) + , echoCancelDelay_(0) {} namespace { - void checkSoundCard(int &card, int stream) - { - if (not AlsaLayer::soundCardIndexExists(card, stream)) { - _warn(" Card with index %d doesn't exist or is unusable.", card); - card = ALSA_DFT_CARD_ID; - } +void checkSoundCard(int &card, int stream) +{ + if (not AlsaLayer::soundCardIndexExists(card, stream)) { + WARN(" Card with index %d doesn't exist or is unusable.", card); + card = ALSA_DFT_CARD_ID; } } +} AudioLayer* AudioPreference::createAudioLayer() { - if (_audioApi == PULSEAUDIO_API_STR and system("ps -C pulseaudio") == 0) + if (audioApi_ == PULSEAUDIO_API_STR and system("ps -C pulseaudio") == 0) return new PulseLayer; else { - _audioApi = ALSA_API_STR; - checkSoundCard(_cardin, SFL_PCM_CAPTURE); - checkSoundCard(_cardout, SFL_PCM_PLAYBACK); - checkSoundCard(_cardring, SFL_PCM_RINGTONE); + audioApi_ = ALSA_API_STR; + checkSoundCard(cardin_, SFL_PCM_CAPTURE); + checkSoundCard(cardout_, SFL_PCM_PLAYBACK); + checkSoundCard(cardring_, SFL_PCM_RINGTONE); return new AlsaLayer; } } AudioLayer* AudioPreference::switchAndCreateAudioLayer() { - if (_audioApi == PULSEAUDIO_API_STR) - _audioApi = ALSA_API_STR; + if (audioApi_ == PULSEAUDIO_API_STR) + audioApi_ = ALSA_API_STR; else - _audioApi = PULSEAUDIO_API_STR; + audioApi_ = PULSEAUDIO_API_STR; + return createAudioLayer(); } @@ -319,44 +311,44 @@ void AudioPreference::serialize(Conf::YamlEmitter *emitter) // alsa preference std::stringstream instr; - instr << _cardin; - Conf::ScalarNode cardin(instr.str()); // 0 + instr << cardin_; + Conf::ScalarNode cardin(instr.str()); std::stringstream outstr; - outstr << _cardout; - Conf::ScalarNode cardout(outstr.str()); // 0 + outstr << cardout_; + Conf::ScalarNode cardout(outstr.str()); std::stringstream ringstr; - ringstr << _cardring; - Conf::ScalarNode cardring(ringstr.str());// 0 - Conf::ScalarNode plugin(_plugin); // default + ringstr << cardring_; + Conf::ScalarNode cardring(ringstr.str()); + Conf::ScalarNode plugin(plugin_); std::stringstream ratestr; - ratestr << _smplrate; - Conf::ScalarNode smplrate(ratestr.str());// 44100 + ratestr << smplrate_; + Conf::ScalarNode smplrate(ratestr.str()); //pulseaudio preference - Conf::ScalarNode devicePlayback(_devicePlayback);//: - Conf::ScalarNode deviceRecord(_deviceRecord); //: - Conf::ScalarNode deviceRingtone(_deviceRingtone); //: + Conf::ScalarNode devicePlayback(devicePlayback_); + Conf::ScalarNode deviceRecord(deviceRecord_); + Conf::ScalarNode deviceRingtone(deviceRingtone_); // general preference - Conf::ScalarNode audioapi(_audioApi); - Conf::ScalarNode recordpath(_recordpath); //: /home/msavard/Bureau - Conf::ScalarNode alwaysRecording(_alwaysRecording); + Conf::ScalarNode audioapi(audioApi_); + Conf::ScalarNode recordpath(recordpath_); //: /home/msavard/Bureau + Conf::ScalarNode alwaysRecording(alwaysRecording_); std::stringstream micstr; - micstr << _volumemic; + micstr << volumemic_; Conf::ScalarNode volumemic(micstr.str()); //: 100 std::stringstream spkrstr; - spkrstr << _volumespkr; + spkrstr << volumespkr_; Conf::ScalarNode volumespkr(spkrstr.str()); //: 100 - Conf::ScalarNode noise(_noisereduce); - Conf::ScalarNode echo(_echocancel); + Conf::ScalarNode noise(noisereduce_); + Conf::ScalarNode echo(echocancel_); std::stringstream tailstr; - _debug("************************************************** serialize echotail %d", _echoCancelTailLength); - tailstr << _echoCancelTailLength; + DEBUG("************************************************** serialize echotail %d", echoCancelTailLength_); + tailstr << echoCancelTailLength_; Conf::ScalarNode echotail(tailstr.str()); std::stringstream delaystr; - _debug("************************************************** serialize echodelay %d", _echoCancelTailLength); - delaystr << _echoCancelDelay; + DEBUG("************************************************** serialize echodelay %d", echoCancelTailLength_); + delaystr << echoCancelDelay_; Conf::ScalarNode echodelay(delaystr.str()); preferencemap.setKeyValue(audioApiKey, &audioapi); @@ -387,42 +379,47 @@ void AudioPreference::serialize(Conf::YamlEmitter *emitter) void AudioPreference::unserialize(Conf::MappingNode *map) { - assert(map); + assert(map); - map->getValue(audioApiKey, &_audioApi); - map->getValue(recordpathKey, &_recordpath); - map->getValue(alwaysRecordingKey, &_alwaysRecording); - map->getValue(volumemicKey, &_volumemic); - map->getValue(volumespkrKey, &_volumespkr); - map->getValue(noiseReduceKey, &_noisereduce); - map->getValue(echoCancelKey, &_echocancel); + map->getValue(audioApiKey, &audioApi_); + map->getValue(recordpathKey, &recordpath_); + map->getValue(alwaysRecordingKey, &alwaysRecording_); + map->getValue(volumemicKey, &volumemic_); + map->getValue(volumespkrKey, &volumespkr_); + map->getValue(noiseReduceKey, &noisereduce_); + map->getValue(echoCancelKey, &echocancel_); Conf::MappingNode *alsamap =(Conf::MappingNode *)(map->getValue("alsa")); + if (alsamap) { - alsamap->getValue(cardinKey, &_cardin); - alsamap->getValue(cardoutKey, &_cardout); - alsamap->getValue(cardringKey, &_cardring); - alsamap->getValue(smplrateKey, &_smplrate); - alsamap->getValue(pluginKey, &_plugin); + alsamap->getValue(cardinKey, &cardin_); + alsamap->getValue(cardoutKey, &cardout_); + alsamap->getValue(cardringKey, &cardring_); + alsamap->getValue(smplrateKey, &smplrate_); + alsamap->getValue(pluginKey, &plugin_); } Conf::MappingNode *pulsemap =(Conf::MappingNode *)(map->getValue("pulse")); + if (pulsemap) { - pulsemap->getValue(devicePlaybackKey, &_devicePlayback); - pulsemap->getValue(deviceRecordKey, &_deviceRecord); - pulsemap->getValue(deviceRingtoneKey, &_deviceRingtone); + pulsemap->getValue(devicePlaybackKey, &devicePlayback_); + pulsemap->getValue(deviceRecordKey, &deviceRecord_); + pulsemap->getValue(deviceRingtoneKey, &deviceRingtone_); } } +ShortcutPreferences::ShortcutPreferences() : hangup_(), pickup_(), popup_(), + toggleHold_(), togglePickupHangup_() {} + std::map<std::string, std::string> ShortcutPreferences::getShortcuts() const { std::map<std::string, std::string> shortcutsMap; - shortcutsMap[hangupShortKey] = _hangup; - shortcutsMap[pickupShortKey] = _pickup; - shortcutsMap[popupShortKey] = _popup; - shortcutsMap[toggleHoldShortKey] = _toggleHold; - shortcutsMap[togglePickupHangupShortKey] = _togglePickupHangup; + shortcutsMap[hangupShortKey] = hangup_; + shortcutsMap[pickupShortKey] = pickup_; + shortcutsMap[popupShortKey] = popup_; + shortcutsMap[toggleHoldShortKey] = toggleHold_; + shortcutsMap[togglePickupHangupShortKey] = togglePickupHangup_; return shortcutsMap; } @@ -430,11 +427,11 @@ std::map<std::string, std::string> ShortcutPreferences::getShortcuts() const void ShortcutPreferences::setShortcuts(std::map<std::string, std::string> map) { - _hangup = map[hangupShortKey]; - _pickup = map[pickupShortKey]; - _popup = map[popupShortKey]; - _toggleHold = map[toggleHoldShortKey]; - _togglePickupHangup = map[togglePickupHangupShortKey]; + hangup_ = map[hangupShortKey]; + pickup_ = map[pickupShortKey]; + popup_ = map[popupShortKey]; + toggleHold_ = map[toggleHoldShortKey]; + togglePickupHangup_ = map[togglePickupHangupShortKey]; } @@ -442,11 +439,11 @@ void ShortcutPreferences::serialize(Conf::YamlEmitter *emitter) { Conf::MappingNode preferencemap(NULL); - Conf::ScalarNode hangup(_hangup); - Conf::ScalarNode pickup(_pickup); - Conf::ScalarNode popup(_popup); - Conf::ScalarNode toggleHold(_toggleHold); - Conf::ScalarNode togglePickupHangup(_togglePickupHangup); + Conf::ScalarNode hangup(hangup_); + Conf::ScalarNode pickup(pickup_); + Conf::ScalarNode popup(popup_); + Conf::ScalarNode toggleHold(toggleHold_); + Conf::ScalarNode togglePickupHangup(togglePickupHangup_); preferencemap.setKeyValue(hangupShortKey, &hangup); preferencemap.setKeyValue(pickupShortKey, &pickup); @@ -460,12 +457,14 @@ void ShortcutPreferences::serialize(Conf::YamlEmitter *emitter) void ShortcutPreferences::unserialize(Conf::MappingNode *map) { if (map == NULL) { - _error("ShortcutPreference: Error: Preference map is NULL"); + ERROR("ShortcutPreference: Error: Preference map is NULL"); return; } - map->getValue(hangupShortKey, &_hangup); - map->getValue(pickupShortKey, &_pickup); - map->getValue(popupShortKey, &_popup); - map->getValue(toggleHoldShortKey, &_toggleHold); - map->getValue(togglePickupHangupShortKey, &_togglePickupHangup); + + map->getValue(hangupShortKey, &hangup_); + map->getValue(pickupShortKey, &pickup_); + map->getValue(popupShortKey, &popup_); + map->getValue(toggleHoldShortKey, &toggleHold_); + map->getValue(togglePickupHangupShortKey, &togglePickupHangup_); } + diff --git a/daemon/src/preferences.h b/daemon/src/preferences.h index 0c8c3e6b7aafbfa0863dac82e504729c1896d920..b056527825de51bd6728ec758bfc04173cdfe4c1 100644 --- a/daemon/src/preferences.h +++ b/daemon/src/preferences.h @@ -99,512 +99,526 @@ static const char * const togglePickupHangupShortKey = "togglePickupHangup"; class AudioLayer; -class Preferences : public Serializable -{ - +class Preferences : public Serializable { public: - static const char * const DFT_ZONE; Preferences(); - virtual void serialize (Conf::YamlEmitter *emitter); - - virtual void unserialize (Conf::MappingNode *map); + virtual void serialize(Conf::YamlEmitter *emitter); + virtual void unserialize(Conf::MappingNode *map); - std::string getAccountOrder (void) const { - return _accountOrder; + std::string getAccountOrder() const { + return accountOrder_; } - void setAccountOrder (const std::string &ord) { - _accountOrder = ord; + + void setAccountOrder(const std::string &ord) { + accountOrder_ = ord; } - int getHistoryLimit (void) const { - return _historyLimit; + int getHistoryLimit() const { + return historyLimit_; } - void setHistoryLimit (int lim) { - _historyLimit = lim; + + void setHistoryLimit(int lim) { + historyLimit_ = lim; } - int getHistoryMaxCalls (void) const { - return _historyMaxCalls; + int getHistoryMaxCalls() const { + return historyMaxCalls_; } - void setHistoryMaxCalls (int max) { - _historyMaxCalls = max; + + void setHistoryMaxCalls(int max) { + historyMaxCalls_ = max; } - bool getNotifyMails (void) const { - return _notifyMails; + bool getNotifyMails() const { + return notifyMails_; } - void setNotifyMails (bool mails) { - _notifyMails = mails; + + void setNotifyMails(bool mails) { + notifyMails_ = mails; } - std::string getZoneToneChoice (void) const { - return _zoneToneChoice; + std::string getZoneToneChoice() const { + return zoneToneChoice_; } - void setZoneToneChoice (const std::string &str) { - _zoneToneChoice = str; + + void setZoneToneChoice(const std::string &str) { + zoneToneChoice_ = str; } - int getRegistrationExpire (void) const { - return _registrationExpire; + int getRegistrationExpire() const { + return registrationExpire_; } - void setRegistrationExpire (int exp) { - _registrationExpire = exp; + + void setRegistrationExpire(int exp) { + registrationExpire_ = exp; } - int getPortNum (void) const { - return _portNum; + int getPortNum() const { + return portNum_; } - void setPortNum (int port) { - _portNum = port; + + void setPortNum(int port) { + portNum_ = port; } - bool getSearchBarDisplay (void) const { - return _searchBarDisplay; + bool getSearchBarDisplay() const { + return searchBarDisplay_; } - void setSearchBarDisplay (bool search) { - _searchBarDisplay = search; + + void setSearchBarDisplay(bool search) { + searchBarDisplay_ = search; } - bool getZeroConfenable (void) const { - return _zeroConfenable; + bool getZeroConfenable() const { + return zeroConfenable_; } - void setZeroConfenable (bool enable) { - _zeroConfenable = enable; + void setZeroConfenable(bool enable) { + zeroConfenable_ = enable; } - bool getMd5Hash (void) const { - return _md5Hash; + bool getMd5Hash() const { + return md5Hash_; } - void setMd5Hash (bool md5) { - _md5Hash = md5; + void setMd5Hash(bool md5) { + md5Hash_ = md5; } private: - - // account order - std::string _accountOrder; - - int _historyLimit; - int _historyMaxCalls; - bool _notifyMails; - std::string _zoneToneChoice; - int _registrationExpire; - int _portNum; - bool _searchBarDisplay; - bool _zeroConfenable; - bool _md5Hash; - + std::string accountOrder_; + int historyLimit_; + int historyMaxCalls_; + bool notifyMails_; + std::string zoneToneChoice_; + int registrationExpire_; + int portNum_; + bool searchBarDisplay_; + bool zeroConfenable_; + bool md5Hash_; }; - -class VoipPreference : public Serializable -{ +class VoipPreference : public Serializable { public: VoipPreference(); - virtual void serialize (Conf::YamlEmitter *emitter); + virtual void serialize(Conf::YamlEmitter *emitter); - virtual void unserialize (Conf::MappingNode *map); + virtual void unserialize(Conf::MappingNode *map); - bool getPlayDtmf (void) const { - return _playDtmf; + bool getPlayDtmf() const { + return playDtmf_; } - void setPlayDtmf (bool dtmf) { - _playDtmf = dtmf; + + void setPlayDtmf(bool dtmf) { + playDtmf_ = dtmf; } - bool getPlayTones (void) const { - return _playTones; + bool getPlayTones() const { + return playTones_; } - void setPlayTones (bool tone) { - _playTones = tone; + + void setPlayTones(bool tone) { + playTones_ = tone; } - int getPulseLength (void) const { - return _pulseLength; + int getPulseLength() const { + return pulseLength_; } - void setPulseLength (int length) { - _pulseLength = length; + + void setPulseLength(int length) { + pulseLength_ = length; } - bool getSymmetricRtp (void) const { - return _symmetricRtp; + bool getSymmetricRtp() const { + return symmetricRtp_; } - void setSymmetricRtp (bool sym) { - _symmetricRtp = sym; + void setSymmetricRtp(bool sym) { + symmetricRtp_ = sym; } - std::string getZidFile (void) const { - return _zidFile; + std::string getZidFile() const { + return zidFile_; } - void setZidFile (const std::string &file) { - _zidFile = file; + void setZidFile(const std::string &file) { + zidFile_ = file; } private: - bool _playDtmf; - bool _playTones; - int _pulseLength; - bool _symmetricRtp; - std::string _zidFile; - + bool playDtmf_; + bool playTones_; + int pulseLength_; + bool symmetricRtp_; + std::string zidFile_; }; -class AddressbookPreference : public Serializable -{ +class AddressbookPreference : public Serializable { public: AddressbookPreference(); - virtual void serialize (Conf::YamlEmitter *emitter); + virtual void serialize(Conf::YamlEmitter *emitter); - virtual void unserialize (Conf::MappingNode *map); + virtual void unserialize(Conf::MappingNode *map); - bool getPhoto (void) const { - return _photo; + bool getPhoto() const { + return photo_; } - void setPhoto (bool p) { - _photo = p; + + void setPhoto(bool p) { + photo_ = p; } - bool getEnabled (void) const { - return _enabled; + bool getEnabled() const { + return enabled_; } - void setEnabled (bool e) { - _enabled = e; + + void setEnabled(bool e) { + enabled_ = e; } - std::string getList (void) const { - return _list; + std::string getList() const { + return list_; } - void setList (const std::string &l) { - _list = l; + + void setList(const std::string &l) { + list_ = l; } - int getMaxResults (void) const { - return _maxResults; + int getMaxResults() const { + return maxResults_; } - void setMaxResults (int r) { - _maxResults = r; + + void setMaxResults(int r) { + maxResults_ = r; } - bool getBusiness (void) const { - return _business; + bool getBusiness() const { + return business_; } - void setBusiness (bool b) { - _business = b; + + void setBusiness(bool b) { + business_ = b; } - bool getHome (void) const { - return _home; + bool getHome() const { + return home_; } - void setHone (bool h) { - _home = h; + void setHone(bool h) { + home_ = h; } - bool getMobile (void) const { - return _mobile; + bool getMobile() const { + return mobile_; } - void setMobile (bool m) { - _mobile = m; + void setMobile(bool m) { + mobile_ = m; } private: - bool _photo; - bool _enabled; - std::string _list; - int _maxResults; - bool _business; - bool _home; - bool _mobile; + bool photo_; + bool enabled_; + std::string list_; + int maxResults_; + bool business_; + bool home_; + bool mobile_; }; -class HookPreference : public Serializable -{ +class HookPreference : public Serializable { public: HookPreference(); - virtual void serialize (Conf::YamlEmitter *emitter); + virtual void serialize(Conf::YamlEmitter *emitter); - virtual void unserialize (Conf::MappingNode *map); + virtual void unserialize(Conf::MappingNode *map); - bool getIax2Enabled (void) const { - return _iax2Enabled; + bool getIax2Enabled() const { + return iax2Enabled_; } - void setIax2Enabled (bool i) { - _iax2Enabled = i; + + void setIax2Enabled(bool i) { + iax2Enabled_ = i; } - std::string getNumberAddPrefix (void) const { - return _numberAddPrefix; + std::string getNumberAddPrefix() const { + return numberAddPrefix_; } - void setNumberAddPrefix (const std::string &n) { - _numberAddPrefix = n; + + void setNumberAddPrefix(const std::string &n) { + numberAddPrefix_ = n; } - bool getNumberEnabled (void) const { - return _numberEnabled; + bool getNumberEnabled() const { + return numberEnabled_; } - void setNumberEnabled (bool n) { - _numberEnabled = n; + + void setNumberEnabled(bool n) { + numberEnabled_ = n; } - bool getSipEnabled (void) const { - return _sipEnabled; + bool getSipEnabled() const { + return sipEnabled_; } - void setSipEnabled (bool s) { - _sipEnabled = s; + + void setSipEnabled(bool s) { + sipEnabled_ = s; } - std::string getUrlCommand (void) const { - return _urlCommand; + std::string getUrlCommand() const { + return urlCommand_; } - void setUrlCommand (const std::string &u) { - _urlCommand = u; + void setUrlCommand(const std::string &u) { + urlCommand_ = u; } - std::string getUrlSipField (void) const { - return _urlSipField; + std::string getUrlSipField() const { + return urlSipField_; } - void setUrlSipField (const std::string &u) { - _urlSipField = u; + void setUrlSipField(const std::string &u) { + urlSipField_ = u; } private: - bool _iax2Enabled;// : false - std::string _numberAddPrefix;//: false - bool _numberEnabled; //: false - bool _sipEnabled; //: false - std::string _urlCommand; //: x-www-browser - std::string _urlSipField; //: X-sflphone-url + bool iax2Enabled_; + std::string numberAddPrefix_; + bool numberEnabled_; + bool sipEnabled_; + std::string urlCommand_; + std::string urlSipField_; }; -class AudioPreference : public Serializable -{ +class AudioPreference : public Serializable { public: AudioPreference(); AudioLayer *createAudioLayer(); AudioLayer *switchAndCreateAudioLayer(); - std::string getAudioApi (void) const { - return _audioApi; + std::string getAudioApi() const { + return audioApi_; } - void setAudioApi (const std::string &api) { - _audioApi = api; + void setAudioApi(const std::string &api) { + audioApi_ = api; } - virtual void serialize (Conf::YamlEmitter *emitter); - virtual void unserialize (Conf::MappingNode *map); + virtual void serialize(Conf::YamlEmitter *emitter); + + virtual void unserialize(Conf::MappingNode *map); // alsa preference - int getCardin (void) const { - return _cardin; + int getCardin() const { + return cardin_; } - void setCardin (int c) { - _cardin = c; + void setCardin(int c) { + cardin_ = c; } - int getCardout (void) const { - return _cardout; + int getCardout() const { + return cardout_; } - void setCardout (int c) { - _cardout = c; + + void setCardout(int c) { + cardout_ = c; } - int getCardring (void) const { - return _cardring; + int getCardring() const { + return cardring_; } - void setCardring (int c) { - _cardring = c; + + void setCardring(int c) { + cardring_ = c; } - std::string getPlugin (void) const { - return _plugin; + std::string getPlugin() const { + return plugin_; } - void setPlugin (const std::string &p) { - _plugin = p; + void setPlugin(const std::string &p) { + plugin_ = p; } - int getSmplrate (void) const { - return _smplrate; + int getSmplrate() const { + return smplrate_; } - void setSmplrate (int r) { - _smplrate = r; + void setSmplrate(int r) { + smplrate_ = r; } //pulseaudio preference - std::string getDevicePlayback (void) const { - return _devicePlayback; + std::string getDevicePlayback() const { + return devicePlayback_; } - void setDevicePlayback (const std::string &p) { - _devicePlayback = p; + void setDevicePlayback(const std::string &p) { + devicePlayback_ = p; } - std::string getDeviceRecord (void) const { - return _deviceRecord; + std::string getDeviceRecord() const { + return deviceRecord_; } - void setDeviceRecord (const std::string &r) { - _deviceRecord = r; + void setDeviceRecord(const std::string &r) { + deviceRecord_ = r; } - std::string getDeviceRingtone (void) const { - return _deviceRingtone; + std::string getDeviceRingtone() const { + return deviceRingtone_; } - void setDeviceRingtone (const std::string &r) { - _deviceRingtone = r; + void setDeviceRingtone(const std::string &r) { + deviceRingtone_ = r; } // general preference - std::string getRecordpath (void) const { - return _recordpath; + std::string getRecordpath() const { + return recordpath_; } - void setRecordpath (const std::string &r) { - _recordpath = r; + void setRecordpath(const std::string &r) { + recordpath_ = r; } - bool getIsAlwaysRecording(void) const { - return _alwaysRecording; + bool getIsAlwaysRecording() const { + return alwaysRecording_; } void setIsAlwaysRecording(bool rec) { - _alwaysRecording = rec; + alwaysRecording_ = rec; } - int getVolumemic (void) const { - return _volumemic; + int getVolumemic() const { + return volumemic_; } - void setVolumemic (int m) { - _volumemic = m; + void setVolumemic(int m) { + volumemic_ = m; } - int getVolumespkr (void) const { - return _volumespkr; + int getVolumespkr() const { + return volumespkr_; } - void setVolumespkr (int s) { - _volumespkr = s; + void setVolumespkr(int s) { + volumespkr_ = s; } - bool getNoiseReduce (void) const { - return _noisereduce; + bool getNoiseReduce() const { + return noisereduce_; } - void setNoiseReduce (bool noise) { - _noisereduce = noise; + void setNoiseReduce(bool noise) { + noisereduce_ = noise; } - bool getEchoCancel(void) const { - return _echocancel; + bool getEchoCancel() const { + return echocancel_; } void setEchoCancel(bool echo) { - _echocancel = echo; + echocancel_ = echo; } - int getEchoCancelTailLength(void) const { - return _echoCancelTailLength; + int getEchoCancelTailLength() const { + return echoCancelTailLength_; } void setEchoCancelTailLength(int length) { - _echoCancelTailLength = length; + echoCancelTailLength_ = length; } - int getEchoCancelDelay(void) const { - return _echoCancelDelay; + int getEchoCancelDelay() const { + return echoCancelDelay_; } void setEchoCancelDelay(int delay) { - _echoCancelDelay = delay; + echoCancelDelay_ = delay; } private: - std::string _audioApi; + std::string audioApi_; // alsa preference - int _cardin; // 0 - int _cardout; // 0 - int _cardring;// 0 - std::string _plugin; // default - int _smplrate;// 44100 + int cardin_; + int cardout_; + int cardring_; + std::string plugin_; + int smplrate_; //pulseaudio preference - std::string _devicePlayback;//: - std::string _deviceRecord; //: - std::string _deviceRingtone; //: + std::string devicePlayback_; + std::string deviceRecord_; + std::string deviceRingtone_; // general preference - std::string _recordpath; //: /home/msavard/Bureau - bool _alwaysRecording; - int _volumemic; //: 100 - int _volumespkr; //: 100 - - bool _noisereduce; - bool _echocancel; - int _echoCancelTailLength; - int _echoCancelDelay; + std::string recordpath_; //: /home/msavard/Bureau + bool alwaysRecording_; + int volumemic_; + int volumespkr_; + + bool noisereduce_; + bool echocancel_; + int echoCancelTailLength_; + int echoCancelDelay_; }; -class ShortcutPreferences : public Serializable -{ +class ShortcutPreferences : public Serializable { public: - virtual void serialize (Conf::YamlEmitter *emitter); - virtual void unserialize (Conf::MappingNode *map); + ShortcutPreferences(); + virtual void serialize(Conf::YamlEmitter *emitter); + virtual void unserialize(Conf::MappingNode *map); - void setShortcuts (std::map<std::string, std::string> shortcuts); - std::map<std::string, std::string> getShortcuts (void) const; + void setShortcuts(std::map<std::string, std::string> shortcuts); + std::map<std::string, std::string> getShortcuts() const; - std::string getHangup (void) const { - return _hangup; + std::string getHangup() const { + return hangup_; } - void setHangup (const std::string &hangup) { - _hangup = hangup; + + void setHangup(const std::string &hangup) { + hangup_ = hangup; } - std::string getPickup (void) const { - return _pickup; + std::string getPickup() const { + return pickup_; } - void setPickup (const std::string &pickup) { - _pickup = pickup; + + void setPickup(const std::string &pickup) { + pickup_ = pickup; } - std::string getPopup (void) const { - return _popup; + std::string getPopup() const { + return popup_; } - void setPopup (const std::string &popup) { - _popup = popup; + + void setPopup(const std::string &popup) { + popup_ = popup; } - std::string getToggleHold (void) const { - return _toggleHold; + std::string getToggleHold() const { + return toggleHold_; } - void setToggleHold (std::string hold) { - _toggleHold = hold; + + void setToggleHold(const std::string &hold) { + toggleHold_ = hold; } - std::string getTogglePickupHangup (void) const { - return _togglePickupHangup; + std::string getTogglePickupHangup() const { + return togglePickupHangup_; } - void setTogglePickupHangup (const std::string &toggle) { - _togglePickupHangup = toggle; + + void setTogglePickupHangup(const std::string &toggle) { + togglePickupHangup_ = toggle; } private: - std::string _hangup; - std::string _pickup; - std::string _popup; - std::string _toggleHold; - std::string _togglePickupHangup; + std::string hangup_; + std::string pickup_; + std::string popup_; + std::string toggleHold_; + std::string togglePickupHangup_; }; #endif diff --git a/daemon/src/sip/Makefile.am b/daemon/src/sip/Makefile.am index 42563e0c7a9e57e7316322caa218d269d99c1934..539a041feb29a3b10efcf1f47980c79c501b4482 100644 --- a/daemon/src/sip/Makefile.am +++ b/daemon/src/sip/Makefile.am @@ -3,16 +3,14 @@ include $(top_srcdir)/globals.mak noinst_LTLIBRARIES = libsiplink.la libsiplink_la_SOURCES = \ - Pattern.cpp \ - SdesNegotiator.cpp \ + pattern.cpp \ + sdes_negotiator.cpp \ sdp.cpp \ sipaccount.cpp \ sipcall.cpp \ - sipvoiplink.cpp - -noinst_HEADERS = \ - Pattern.h \ - SdesNegotiator.h \ + sipvoiplink.cpp \ + pattern.h \ + sdes_negotiator.h \ sdp.h \ sipaccount.h \ sipcall.h \ diff --git a/daemon/src/sip/Pattern.cpp b/daemon/src/sip/Pattern.cpp deleted file mode 100644 index d0a819133580f9a339056909bd198a85cf5007d6..0000000000000000000000000000000000000000 --- a/daemon/src/sip/Pattern.cpp +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. - * Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - -#include "Pattern.h" -#include <sstream> -#include <cstdio> - -namespace sfl -{ - -Pattern::Pattern (const std::string& pattern, const std::string& options) : - _pattern (pattern), - _re (NULL), - _ovector (NULL), - _ovectorSize (0), - _count (0), - _options (0) -{ - // Set offsets - _offset[0] = _offset[1] = 0; - - // Set options. - _optionsDescription = options; - - for (unsigned int i = 0; i < options.length(); i++) { - switch (options.at (i)) { - - case 'i': - _options |= PCRE_CASELESS; - break; - - case 'm': - _options |= PCRE_MULTILINE; - break; - - case 's': - _options |= PCRE_DOTALL; - break; - - case 'x': - _options |= PCRE_EXTENDED; - break; - } - } - - // Compile the pattern. - compile(); -} - -Pattern::~Pattern() -{ - if (_re != NULL) { - pcre_free (_re); - } - - delete[] _ovector; -} - -void Pattern::compile (void) -{ - // Compile the pattern - int offset; - const char * error; - - _re = pcre_compile (_pattern.c_str(), 0, &error, &offset, NULL); - - if (_re == NULL) { - std::string offsetStr; - std::stringstream ss; - ss << offset; - offsetStr = ss.str(); - - std::string msg ("PCRE compiling failed at offset " + offsetStr); - - throw compile_error (msg); - } - - // Allocate an appropriate amount - // of memory for the output vector. - int captureCount; - - pcre_fullinfo (_re, NULL, PCRE_INFO_CAPTURECOUNT, &captureCount); - - delete[] _ovector; - - _ovector = new int[ (captureCount + 1) *3]; - - _ovectorSize = (captureCount + 1) * 3; -} - -unsigned int Pattern::getCaptureGroupCount (void) -{ - int captureCount; - pcre_fullinfo (_re, NULL, PCRE_INFO_CAPTURECOUNT, &captureCount); - return captureCount; -} - -std::vector<std::string> Pattern::groups (void) -{ - const char ** stringList; - - pcre_get_substring_list (_subject.c_str(), - _ovector, - _count, - &stringList); - - std::vector<std::string> matchedSubstrings; - - for (int i = 1; stringList[i] != NULL; i++) - matchedSubstrings.push_back (stringList[i]); - - pcre_free_substring_list (stringList); - - return matchedSubstrings; -} - -std::string Pattern::group (int groupNumber) -{ - const char * stringPtr; - - int rc = pcre_get_substring ( - _subject.substr (_offset[0]).c_str(), - _ovector, - _count, - groupNumber, - &stringPtr); - - if (rc < 0) { - switch (rc) { - - case PCRE_ERROR_NOSUBSTRING: - throw std::out_of_range ("Invalid group reference."); - - case PCRE_ERROR_NOMEMORY: - throw match_error ("Memory exhausted."); - - default: - throw match_error ("Failed to get named substring."); - } - } - - std::string matchedStr (stringPtr); - - pcre_free_substring (stringPtr); - - return matchedStr; -} - -std::string Pattern::group (const std::string& groupName) -{ - const char * stringPtr = NULL; - - int rc = pcre_get_named_substring ( - _re, - _subject.substr (_offset[0]).c_str(), - _ovector, - _count, - groupName.c_str(), - &stringPtr); - - if (rc < 0) { - switch (rc) { - - case PCRE_ERROR_NOSUBSTRING: - - break; - - case PCRE_ERROR_NOMEMORY: - throw match_error ("Memory exhausted."); - - default: - throw match_error ("Failed to get named substring."); - } - } - - std::string matchedStr; - - if (stringPtr) { - - matchedStr = stringPtr; - pcre_free_substring (stringPtr); - } else { - - matchedStr = ""; - } - - return matchedStr; - -} - -void Pattern::start (const std::string& groupName) const -{ - int index = pcre_get_stringnumber (_re, groupName.c_str()); - start (index); -} - -size_t Pattern::start (unsigned int groupNumber) const -{ - if (groupNumber <= (unsigned int) _count) { - return _ovector[ (groupNumber + 1) * 2]; - } else { - throw std::out_of_range ("Invalid group reference."); - } -} - -size_t Pattern::start (void) const -{ - return _ovector[0] + _offset[0]; -} - -void Pattern::end (const std::string& groupName) const -{ - int index = pcre_get_stringnumber (_re, groupName.c_str()); - end (index); -} - -size_t Pattern::end (unsigned int groupNumber) const -{ - if (groupNumber <= (unsigned int) _count) { - return _ovector[ ( (groupNumber + 1) * 2) + 1 ] - 1; - } else { - throw std::out_of_range ("Invalid group reference."); - } -} - -size_t Pattern::end (void) const -{ - return (_ovector[1] - 1) + _offset[0]; -} - -bool Pattern::matches (void) throw (match_error) -{ - return matches (_subject); -} - -bool Pattern::matches (const std::string& subject) throw (match_error) -{ - - // Try to find a match for this pattern - int rc = pcre_exec ( - _re, - NULL, - subject.substr (_offset[1]).c_str(), - subject.length() - _offset[1], - 0, - _options, - _ovector, - _ovectorSize); - - - - // Matching failed. - if (rc < 0) { - _offset[0] = _offset[1] = 0; - return false; - } - - // Handle the case if matching should be done globally - if (_optionsDescription.find ("g") != std::string::npos) { - _offset[0] = _offset[1]; - // New offset is old offset + end of relative offset - _offset[1] = _ovector[1] + _offset[0]; - } - - // Matching succeded but not enough space. - if (rc == 0) { - throw match_error ("No space to store all substrings."); - // @TODO figure out something more clever to do in that case. - } - - // Matching succeeded. Keep the number of substrings for - // subsequent calls to group(). - _count = rc; - - return true; -} - -std::vector<std::string> Pattern::split (void) -{ - size_t tokenEnd = -1; - size_t tokenStart = 0; - - std::vector<std::string> substringSplitted; - - while (matches()) { - tokenStart = start(); - substringSplitted.push_back (_subject.substr (tokenEnd + 1, - tokenStart - tokenEnd - 1)); - tokenEnd = end(); - } - - substringSplitted.push_back (_subject.substr (tokenEnd + 1, tokenStart - tokenEnd - 1)); - - return substringSplitted; -} -} - - diff --git a/daemon/src/sip/SdesNegotiator.cpp b/daemon/src/sip/SdesNegotiator.cpp deleted file mode 100644 index 870f75874950e0e6c2c98c9dd61e2e0a76b0a2d6..0000000000000000000000000000000000000000 --- a/daemon/src/sip/SdesNegotiator.cpp +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. - * Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com> - * Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - -#include "SdesNegotiator.h" - -#include "Pattern.h" - -#include <cstdio> -#include <iostream> -#include <sstream> -#include <algorithm> -#include <stdexcept> - -using namespace sfl; - -SdesNegotiator::SdesNegotiator (const std::vector<CryptoSuiteDefinition>& localCapabilites, - const std::vector<std::string>& remoteAttribute) : - _remoteAttribute (remoteAttribute), - _localCapabilities (localCapabilites) -{ - -} - -std::vector<CryptoAttribute *> SdesNegotiator::parse (void) -{ - // The patterns below try to follow - // the ABNF grammar rules described in - // RFC4568 section 9.2 with the general - // syntax : - //a=crypto:tag 1*WSP crypto-suite 1*WSP key-params *(1*WSP session-param) - - Pattern - * generalSyntaxPattern, - * tagPattern, - * cryptoSuitePattern, - * keyParamsPattern; - - try { - - // used to match white space (which are used as separator) - generalSyntaxPattern = new Pattern ("[\x20\x09]+", "g"); - - tagPattern = new Pattern ("^a=crypto:(?P<tag>[0-9]{1,9})"); - - cryptoSuitePattern = new Pattern ( - "(?P<cryptoSuite>AES_CM_128_HMAC_SHA1_80|" \ - "AES_CM_128_HMAC_SHA1_32|" \ - "F8_128_HMAC_SHA1_80|" \ - "[A-Za-z0-9_]+)"); // srtp-crypto-suite-ext - - keyParamsPattern = new Pattern ( - "(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ - "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)" \ - "(\\|2\\^(?P<lifetime>[0-9]+)\\|" \ - "(?P<mkiValue>[0-9]+)\\:" \ - "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); - - /* - sessionParamPattern = new Pattern ( - "(?P<sessionParam>(kdr\\=[0-9]{1,2}|" \ - "UNENCRYPTED_SRTP|" \ - "UNENCRYPTED_SRTCP|" \ - "UNAUTHENTICATED_SRTP|" \ - "FEC_ORDER=(?P<fecOrder>FEC_SRTP|SRTP_FEC)|" \ - "FEC_KEY=(?P<fecKey>" + keyParamsPattern->getPattern() + ")|" \ - "WSH=(?P<wsh>[0-9]{1,2})|" \ - "(?<!\\-)[[:graph:]]+))*", "g"); // srtp-session-extension - */ - - } catch (compile_error& exception) { - throw parse_error ("A compile exception occured on a pattern."); - } - - - // Take each line from the vector - // and parse its content - - - std::vector<std::string>::iterator iter; - std::vector<CryptoAttribute *> cryptoAttributeVector; - - for (iter = _remoteAttribute.begin(); iter != _remoteAttribute.end(); iter++) { - - // Split the line into its component - // that we will analyze further down. - std::vector<std::string> sdesLine; - - *generalSyntaxPattern << (*iter); - - try { - sdesLine = generalSyntaxPattern->split(); - - if (sdesLine.size() < 3) { - throw parse_error ("Missing components in SDES line"); - } - } catch (match_error& exception) { - throw parse_error ("Error while analyzing the SDES line."); - } - - - // Check if the attribute starts with a=crypto - // and get the tag for this line - *tagPattern << sdesLine.at (0); - - std::string tag; - - if (tagPattern->matches()) { - try { - tag = tagPattern->group ("tag"); - } catch (match_error& exception) { - throw parse_error ("Error while parsing the tag field"); - } - } else { - return cryptoAttributeVector; - } - - // Check if the crypto suite is valid and retreive - // its value. - *cryptoSuitePattern << sdesLine.at (1); - - std::string cryptoSuite; - - if (cryptoSuitePattern->matches()) { - try { - cryptoSuite = cryptoSuitePattern->group ("cryptoSuite"); - } catch (match_error& exception) { - throw parse_error ("Error while parsing the crypto-suite field"); - } - } else { - return cryptoAttributeVector; - } - - // Parse one or more key-params field. - *keyParamsPattern << sdesLine.at (2); - - std::string srtpKeyInfo; - std::string srtpKeyMethod; - std::string lifetime; - std::string mkiLength; - std::string mkiValue; - - try { - while (keyParamsPattern->matches()) { - srtpKeyMethod = keyParamsPattern->group ("srtpKeyMethod"); - srtpKeyInfo = keyParamsPattern->group ("srtpKeyInfo"); - lifetime = keyParamsPattern->group ("lifetime"); - mkiValue = keyParamsPattern->group ("mkiValue"); - mkiLength = keyParamsPattern->group ("mkiLength"); - } - } catch (match_error& exception) { - throw parse_error ("Error while parsing the key-params field"); - } - - /** - * Parse the optional session-param fields - * @TODO Implement this ! - */ - /* - if (sdesLine.size() == 3) continue; - - int i; - for (i = 3; i < sdesLine.size(); i++) { - sessionParamPattern << sdesLine.at(i); - while (sessionpParamPattern.matches()) { - - } catch (match_error& exception) { - throw parse_error("Error while parsing the crypto-suite field"); - } - } - } */ - - // Add the new CryptoAttribute to the vector - - CryptoAttribute * cryptoAttribute = new CryptoAttribute (tag, cryptoSuite, srtpKeyMethod, srtpKeyInfo, lifetime, mkiValue, mkiLength); - cryptoAttributeVector.push_back (cryptoAttribute); - } - - return cryptoAttributeVector; -} - -bool SdesNegotiator::negotiate (void) -{ - - std::vector<CryptoAttribute *> cryptoAttributeVector = parse(); - std::vector<CryptoAttribute *>::iterator iter_offer = cryptoAttributeVector.begin(); - - std::vector<CryptoSuiteDefinition>::iterator iter_local = _localCapabilities.begin(); - - bool negotiationSuccess = false; - - try { - - while (!negotiationSuccess && (iter_offer != cryptoAttributeVector.end())) { - - /* - std::cout << "Negotiate tag: " + (*iter_offer)->getTag() << std::endl; - std::cout << "Crypto Suite: " + (*iter_offer)->getCryptoSuite() << std::endl; - std::cout << "SRTP Key Method: " + (*iter_offer)->getSrtpKeyMethod() << std::endl; - std::cout << "SRTP Key Info: " + (*iter_offer)->getSrtpKeyInfo() << std::endl; - std::cout << "Lifetime: " + (*iter_offer)->getLifetime() << std::endl; - std::cout << "MKI Value: " + (*iter_offer)->getMkiValue() << std::endl; - std::cout << "MKI Length: " + (*iter_offer)->getMkiLength() << std::endl; - */ - - iter_local = _localCapabilities.begin(); - - while (!negotiationSuccess && (iter_local != _localCapabilities.end())) { - - if ( (*iter_offer)->getCryptoSuite().compare ( (*iter_local).name)) { - - negotiationSuccess = true; - - _cryptoSuite = (*iter_offer)->getCryptoSuite(); - _srtpKeyMethod = (*iter_offer)->getSrtpKeyMethod(); - _srtpKeyInfo = (*iter_offer)->getSrtpKeyInfo(); - // TODO why does there return empty strings - // _lifetime = (*iter_offer)->getLifetime(); - // _mkiValue = (*iter_offer)->getMkiValue(); - // _mkiLength = (*iter_offer)->getMkiLength(); - - _authTagLength = _cryptoSuite.substr (_cryptoSuite.size()-2, 2); - - /* - std::cout << "Negotiate tag: " + (*iter_offer)->getTag() << std::endl; - std::cout << "Crypto Suite: " + _cryptoSuite << std::endl; - std::cout << "SRTP Key Method: " + _srtpKeyMethod << std::endl; - std::cout << "SRTP Key Info: " + _srtpKeyInfo << std::endl; - std::cout << "Lifetime: " + _lifetime << std::endl; - std::cout << "MKI Value: " + _mkiValue << std::endl; - std::cout << "MKI Length: " + _mkiLength << std::endl; - std::cout << "Auth tag length: " + _authTagLength << std::endl; - */ - } - - iter_local++; - } - - delete (*iter_offer); - - iter_offer++; - } - - } catch (parse_error& exception) { - return false; - } catch (match_error& exception) { - return false; - } - - return negotiationSuccess; -} diff --git a/daemon/src/sip/pattern.cpp b/daemon/src/sip/pattern.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d1b139cc269f204ba49b9f7c005159030eb19985 --- /dev/null +++ b/daemon/src/sip/pattern.cpp @@ -0,0 +1,289 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. + * Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com> + * + * 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Additional permission under GNU GPL version 3 section 7: + * + * If you modify this program, or any covered work, by linking or + * combining it with the OpenSSL project's OpenSSL library (or a + * modified version of that library), containing parts covered by the + * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. + * grants you additional permission to convey the resulting work. + * Corresponding Source for a non-source form of such a combination + * shall include the source code for the parts of OpenSSL used as well + * as that of the covered work. + */ + +#include "pattern.h" +#include <sstream> +#include <cstdio> + +namespace sfl { + +Pattern::Pattern(const std::string& pattern, const std::string& options) : + pattern_(pattern), + subject_(), + re_(NULL), + ovector_(NULL), + ovectorSize_(0), + count_(0), + options_(0), + optionsDescription_(options) +{ + // Set offsets + offset_[0] = offset_[1] = 0; + + for (unsigned int i = 0; i < options.length(); i++) { + switch (options.at(i)) { + case 'i': + options_ |= PCRE_CASELESS; + break; + + case 'm': + options_ |= PCRE_MULTILINE; + break; + + case 's': + options_ |= PCRE_DOTALL; + break; + + case 'x': + options_ |= PCRE_EXTENDED; + break; + } + } + + // Compile the pattern. + compile(); +} + +Pattern::~Pattern() +{ + if (re_ != NULL) + pcre_free(re_); + + delete[] ovector_; +} + +void Pattern::compile() +{ + // Compile the pattern + int offset; + const char * error; + + re_ = pcre_compile(pattern_.c_str(), 0, &error, &offset, NULL); + + if (re_ == NULL) { + std::string offsetStr; + std::stringstream ss; + ss << offset; + offsetStr = ss.str(); + + std::string msg("PCRE compiling failed at offset " + offsetStr); + + throw CompileError(msg); + } + + // Allocate an appropriate amount + // of memory for the output vector. + int captureCount; + + pcre_fullinfo(re_, NULL, PCRE_INFO_CAPTURECOUNT, &captureCount); + + delete[] ovector_; + + ovector_ = new int[(captureCount + 1) * 3]; + + ovectorSize_ = (captureCount + 1) * 3; +} + +unsigned int Pattern::getCaptureGroupCount() +{ + int captureCount; + pcre_fullinfo(re_, NULL, PCRE_INFO_CAPTURECOUNT, &captureCount); + return captureCount; +} + +std::vector<std::string> Pattern::groups() +{ + const char ** stringList; + + pcre_get_substring_list(subject_.c_str(), + ovector_, + count_, + &stringList); + + std::vector<std::string> matchedSubstrings; + + for (int i = 1; stringList[i] != NULL; i++) + matchedSubstrings.push_back(stringList[i]); + + pcre_free_substring_list(stringList); + + return matchedSubstrings; +} + +std::string Pattern::group(int groupNumber) +{ + const char * stringPtr; + + int rc = pcre_get_substring(subject_.substr(offset_[0]).c_str(), ovector_, + count_, groupNumber, &stringPtr); + + if (rc < 0) { + switch (rc) { + case PCRE_ERROR_NOSUBSTRING: + throw std::out_of_range("Invalid group reference."); + + case PCRE_ERROR_NOMEMORY: + throw MatchError("Memory exhausted."); + + default: + throw MatchError("Failed to get named substring."); + } + } + + std::string matchedStr(stringPtr); + + pcre_free_substring(stringPtr); + + return matchedStr; +} + +std::string Pattern::group(const std::string& groupName) +{ + const char * stringPtr = NULL; + int rc = pcre_get_named_substring(re_, subject_.substr(offset_[0]).c_str(), + ovector_, count_, groupName.c_str(), + &stringPtr); + + if (rc < 0) { + switch (rc) { + case PCRE_ERROR_NOSUBSTRING: + break; + + case PCRE_ERROR_NOMEMORY: + throw MatchError("Memory exhausted."); + + default: + throw MatchError("Failed to get named substring."); + } + } + + std::string matchedStr; + + if (stringPtr) { + matchedStr = stringPtr; + pcre_free_substring(stringPtr); + } + + return matchedStr; +} + +void Pattern::start(const std::string& groupName) const +{ + int index = pcre_get_stringnumber(re_, groupName.c_str()); + start(index); +} + +size_t Pattern::start(unsigned int groupNumber) const +{ + if (groupNumber <= (unsigned int) count_) + return ovector_[(groupNumber + 1) * 2]; + else + throw std::out_of_range("Invalid group reference."); +} + +size_t Pattern::start() const +{ + return ovector_[0] + offset_[0]; +} + +void Pattern::end(const std::string& groupName) const +{ + int index = pcre_get_stringnumber(re_, groupName.c_str()); + end(index); +} + +size_t Pattern::end(unsigned int groupNumber) const +{ + if (groupNumber <= (unsigned int) count_) + return ovector_[((groupNumber + 1) * 2) + 1 ] - 1; + else + throw std::out_of_range("Invalid group reference."); +} + +size_t Pattern::end() const +{ + return (ovector_[1] - 1) + offset_[0]; +} + +bool Pattern::matches() +{ + return matches(subject_); +} + +bool Pattern::matches(const std::string& subject) +{ + // Try to find a match for this pattern + int rc = pcre_exec(re_, NULL, subject.substr(offset_[1]).c_str(), + subject.length() - offset_[1], 0, options_, ovector_, + ovectorSize_); + + // Matching failed. + if (rc < 0) { + offset_[0] = offset_[1] = 0; + return false; + } + + // Handle the case if matching should be done globally + if (optionsDescription_.find("g") != std::string::npos) { + offset_[0] = offset_[1]; + // New offset is old offset + end of relative offset + offset_[1] = ovector_[1] + offset_[0]; + } + + // Matching succeded but not enough space. + // @TODO figure out something more clever to do in this case. + if (rc == 0) + throw MatchError("No space to store all substrings."); + + // Matching succeeded. Keep the number of substrings for + // subsequent calls to group(). + count_ = rc; + + return true; +} + +std::vector<std::string> Pattern::split() +{ + size_t tokenEnd = -1; + size_t tokenStart = 0; + + std::vector<std::string> substringSplitted; + + while (matches()) { + tokenStart = start(); + substringSplitted.push_back(subject_.substr(tokenEnd + 1, + tokenStart - tokenEnd - 1)); + tokenEnd = end(); + } + + substringSplitted.push_back(subject_.substr(tokenEnd + 1, + tokenStart - tokenEnd - 1)); + return substringSplitted; +} +} diff --git a/daemon/src/sip/Pattern.h b/daemon/src/sip/pattern.h similarity index 77% rename from daemon/src/sip/Pattern.h rename to daemon/src/sip/pattern.h index eafb94b5088f07e46bd09b93a8ad82802c9d466a..a33ad4eaa90c81d4c5f4a4a898847fda79034243 100644 --- a/daemon/src/sip/Pattern.h +++ b/daemon/src/sip/pattern.h @@ -26,27 +26,26 @@ * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ -#ifndef __SFL_PATTERN_H__ -#define __SFL_PATTERN_H__ +#ifndef __PATTERN_H__ +#define __PATTERN_H__ #include <stdexcept> #include <string> #include <vector> #include <pcre.h> +#include "noncopyable.h" -namespace sfl -{ +namespace sfl { /** * Exception object that is thrown when * an error occured while compiling the * regular expression. */ -class compile_error : public std::invalid_argument -{ +class CompileError : public std::invalid_argument { public: - explicit compile_error (const std::string& error) : - std::invalid_argument (error) {} + explicit CompileError(const std::string& error) : + std::invalid_argument(error) {} }; /** @@ -54,11 +53,10 @@ class compile_error : public std::invalid_argument * an error occured while mathing a * pattern to an expression. */ -class match_error : public std::invalid_argument -{ +class MatchError : public std::invalid_argument { public: - match_error (const std::string& error) : - std::invalid_argument (error) {} + MatchError(const std::string& error) : + std::invalid_argument(error) {} }; /** @@ -66,8 +64,7 @@ class match_error : public std::invalid_argument * some of the libpcre library. */ -class Pattern -{ +class Pattern { public: @@ -80,8 +77,8 @@ class Pattern * be used for this instance. */ - Pattern (const std::string& pattern, - const std::string& options = ""); + Pattern(const std::string& pattern, + const std::string& options = ""); /** * Destructor. Pcre pattern gets freed @@ -98,14 +95,16 @@ class Pattern * * @param pattern The new pattern */ - void operator= (const std::string& pattern) { - _pattern = pattern; + Pattern& operator=(const std::string& pattern) { + pattern_ = pattern; compile(); + return *this; } - void operator= (const char * pattern) { - _pattern = pattern; + Pattern& operator=(const char * pattern) { + pattern_ = pattern; compile(); + return *this; } /** @@ -113,7 +112,7 @@ class Pattern * from the pattern that was set for * this object. */ - void compile (void); + void compile(); /** * Get the currently set regular expression @@ -121,8 +120,8 @@ class Pattern * * @return The currently set pattern */ - std::string getPattern (void) const { - return _pattern; + std::string getPattern() const { + return pattern_; } /** @@ -135,7 +134,7 @@ class Pattern * */ void operator<< (const std::string& subject) { - _subject = subject; + subject_ = subject; } /** @@ -143,7 +142,7 @@ class Pattern * * @return the start position of the overall match. */ - size_t start (void) const; + size_t start() const; /** * Get the start position of the specified match. @@ -152,21 +151,21 @@ class Pattern * * @return the start position of the specified match. */ - size_t start (unsigned int groupNumber) const; + size_t start(unsigned int groupNumber) const; /** * Get the start position of the specified match. * * @param groupName The capturing group name. */ - void start (const std::string& groupName) const; + void start(const std::string& groupName) const; /** * Get the end position of the overall match. * * @return the end position of the overall match. */ - size_t end (void) const; + size_t end() const; /** * Get the end position of the specified match. @@ -175,7 +174,7 @@ class Pattern * * @return the end position of the specified match. */ - size_t end (unsigned int groupNumber) const; + size_t end(unsigned int groupNumber) const; /** * Get the end position of the specified match. @@ -184,7 +183,7 @@ class Pattern * * @return the end position of the specified match. */ - void end (const std::string& groupName) const; + void end(const std::string& groupName) const; /** * Get the number of capturing groups in the @@ -195,7 +194,7 @@ class Pattern * @pre The regular expression should have been * compiled prior to the execution of this method. */ - unsigned int getCaptureGroupCount (void); + unsigned int getCaptureGroupCount(); /** * Get the substring matched in a capturing @@ -213,7 +212,7 @@ class Pattern * regular expression designated * the group name. */ - std::string group (const std::string& groupName); + std::string group(const std::string& groupName); /** * Get the substring matched in a named group. @@ -230,7 +229,7 @@ class Pattern * regular expression designated * the group number. */ - std::string group (int groupNumber); + std::string group(int groupNumber); /** * Similar to python's MatchObject.groups. Get all @@ -245,7 +244,7 @@ class Pattern * @pre The regular expression should have been * compiled prior to the execution of this method. */ - std::vector<std::string> groups (void); + std::vector<std::string> groups(); /** * Try to match the compiled pattern with a @@ -264,7 +263,7 @@ class Pattern * with the new matches. Therefore, subsequent * calls to group may return different results. */ - bool matches (const std::string& subject) throw (match_error); + bool matches(const std::string& subject); /** * Try to match the compiled pattern with the implicit @@ -280,7 +279,7 @@ class Pattern * with the new matches. Therefore, subsequent * calls to group may return different results. */ - bool matches (void) throw (match_error); + bool matches(); /** * Split the subject into a list of substrings. @@ -294,59 +293,42 @@ class Pattern * by this operation. In other words: subject_before = * subject_after. */ - std::vector<std::string> split (void); // throw(match_error); + std::vector<std::string> split(); private: - /** - * The regular expression that represents that pattern. - */ - std::string _pattern; + NON_COPYABLE(Pattern); + // The regular expression that represents that pattern. + std::string pattern_; - /** - * The optional subject string. - */ - std::string _subject; + // The optional subject string. + std::string subject_; /** * PCRE struct that * contains the compiled regular * expression */ - pcre * _re; + pcre * re_; - /** - * The internal output vector used by PCRE. - */ - int * _ovector; + // The internal output vector used by PCRE. + int * ovector_; - /** - * The size of the _ovector - */ - int _ovectorSize; + // The size of the ovector_ + int ovectorSize_; - /** - * Current offset in the _ovector; - */ - - int _offset[2]; + // Current offset in the ovector_; + int offset_[2]; - /** - * The number of substrings matched after calling - * pcre_exec. - */ - int _count; + // The number of substrings matched after calling pcre_exec. + int count_; - /** - * PCRE options for this pattern. - */ - int _options; + // PCRE options for this pattern. + int options_; - /** - * String representation of the options. - */ - std::string _optionsDescription; + // String representation of the options. + std::string optionsDescription_; }; } +#endif // __PATTERN_H__ -#endif diff --git a/daemon/src/sip/sdes_negotiator.cpp b/daemon/src/sip/sdes_negotiator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d0d808e13dda73498234d8de8e3ae975ac543af --- /dev/null +++ b/daemon/src/sip/sdes_negotiator.cpp @@ -0,0 +1,215 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. + * Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com> + * Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com> + * + * 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Additional permission under GNU GPL version 3 section 7: + * + * If you modify this program, or any covered work, by linking or + * combining it with the OpenSSL project's OpenSSL library (or a + * modified version of that library), containing parts covered by the + * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. + * grants you additional permission to convey the resulting work. + * Corresponding Source for a non-source form of such a combination + * shall include the source code for the parts of OpenSSL used as well + * as that of the covered work. + */ + +#include "sdes_negotiator.h" +#include "pattern.h" + +#include <cstdio> +#include <iostream> +#include <sstream> +#include <algorithm> +#include <stdexcept> + +using namespace sfl; + +SdesNegotiator::SdesNegotiator(const std::vector<CryptoSuiteDefinition>& localCapabilites, + const std::vector<std::string>& remoteAttribute) : + remoteAttribute_(remoteAttribute), + localCapabilities_(localCapabilites), + cryptoSuite_(), + srtpKeyMethod_(), + srtpKeyInfo_(), + lifetime_(), + mkiValue_(), + mkiLength_(), + authTagLength_() +{} + +std::vector<CryptoAttribute *> SdesNegotiator::parse() +{ + // The patterns below try to follow + // the ABNF grammar rules described in + // RFC4568 section 9.2 with the general + // syntax : + //a=crypto:tag 1*WSP crypto-suite 1*WSP key-params *(1*WSP session-param) + + Pattern + * generalSyntaxPattern, + * tagPattern, + * cryptoSuitePattern, + * keyParamsPattern; + + try { + // used to match white space (which are used as separator) + generalSyntaxPattern = new Pattern("[\x20\x09]+", "g"); + + tagPattern = new Pattern("^a=crypto:(?P<tag>[0-9]{1,9})"); + + cryptoSuitePattern = new Pattern( + "(?P<cryptoSuite>AES_CM_128_HMAC_SHA1_80|" \ + "AES_CM_128_HMAC_SHA1_32|" \ + "F8_128_HMAC_SHA1_80|" \ + "[A-Za-z0-9_]+)"); // srtp-crypto-suite-ext + + keyParamsPattern = new Pattern( + "(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ + "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)" \ + "(\\|2\\^(?P<lifetime>[0-9]+)\\|" \ + "(?P<mkiValue>[0-9]+)\\:" \ + "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); + + } catch (const CompileError& exception) { + throw ParseError("A compile exception occured on a pattern."); + } + + + // Take each line from the vector + // and parse its content + + + std::vector<CryptoAttribute *> cryptoAttributeVector; + + for (std::vector<std::string>::iterator iter = remoteAttribute_.begin(); + iter != remoteAttribute_.end(); ++iter) { + + // Split the line into its component + // that we will analyze further down. + std::vector<std::string> sdesLine; + + *generalSyntaxPattern << (*iter); + + try { + sdesLine = generalSyntaxPattern->split(); + + if (sdesLine.size() < 3) + throw ParseError("Missing components in SDES line"); + } catch (const MatchError& exception) { + throw ParseError("Error while analyzing the SDES line."); + } + + // Check if the attribute starts with a=crypto + // and get the tag for this line + *tagPattern << sdesLine.at(0); + + std::string tag; + + if (tagPattern->matches()) { + try { + tag = tagPattern->group("tag"); + } catch (const MatchError& exception) { + throw ParseError("Error while parsing the tag field"); + } + } else + return cryptoAttributeVector; + + // Check if the crypto suite is valid and retreive + // its value. + *cryptoSuitePattern << sdesLine.at(1); + + std::string cryptoSuite; + + if (cryptoSuitePattern->matches()) { + try { + cryptoSuite = cryptoSuitePattern->group("cryptoSuite"); + } catch (const MatchError& exception) { + throw ParseError("Error while parsing the crypto-suite field"); + } + } else + return cryptoAttributeVector; + + // Parse one or more key-params field. + *keyParamsPattern << sdesLine.at(2); + + std::string srtpKeyInfo; + std::string srtpKeyMethod; + std::string lifetime; + std::string mkiLength; + std::string mkiValue; + + try { + while (keyParamsPattern->matches()) { + srtpKeyMethod = keyParamsPattern->group("srtpKeyMethod"); + srtpKeyInfo = keyParamsPattern->group("srtpKeyInfo"); + lifetime = keyParamsPattern->group("lifetime"); + mkiValue = keyParamsPattern->group("mkiValue"); + mkiLength = keyParamsPattern->group("mkiLength"); + } + } catch (const MatchError& exception) { + throw ParseError("Error while parsing the key-params field"); + } + + // Add the new CryptoAttribute to the vector + + CryptoAttribute * cryptoAttribute = new CryptoAttribute(tag, cryptoSuite, srtpKeyMethod, srtpKeyInfo, lifetime, mkiValue, mkiLength); + cryptoAttributeVector.push_back(cryptoAttribute); + } + + return cryptoAttributeVector; +} + +bool SdesNegotiator::negotiate() +{ + + std::vector<CryptoAttribute *> cryptoAttributeVector = parse(); + std::vector<CryptoAttribute *>::iterator iter_offer = cryptoAttributeVector.begin(); + + std::vector<CryptoSuiteDefinition>::iterator iter_local = localCapabilities_.begin(); + + bool negotiationSuccess = false; + + try { + while (!negotiationSuccess && (iter_offer != cryptoAttributeVector.end())) { + iter_local = localCapabilities_.begin(); + + while (!negotiationSuccess && (iter_local != localCapabilities_.end())) { + + if ((*iter_offer)->getCryptoSuite().compare((*iter_local).name)) { + negotiationSuccess = true; + + cryptoSuite_ = (*iter_offer)->getCryptoSuite(); + srtpKeyMethod_ = (*iter_offer)->getSrtpKeyMethod(); + srtpKeyInfo_ = (*iter_offer)->getSrtpKeyInfo(); + authTagLength_ = cryptoSuite_.substr(cryptoSuite_.size()-2, 2); + } + + iter_local++; + } + delete(*iter_offer); + iter_offer++; + } + + } catch (const ParseError& exception) { + return false; + } catch (const MatchError& exception) { + return false; + } + + return negotiationSuccess; +} diff --git a/daemon/src/sip/SdesNegotiator.h b/daemon/src/sip/sdes_negotiator.h similarity index 64% rename from daemon/src/sip/SdesNegotiator.h rename to daemon/src/sip/sdes_negotiator.h index d3ca5b52d3041babf9be6379622aa5a7346fd4ec..7fb4213555d670af6bd32f68073584107a886c09 100644 --- a/daemon/src/sip/SdesNegotiator.h +++ b/daemon/src/sip/sdes_negotiator.h @@ -27,26 +27,24 @@ * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ -#ifndef __SFL_SDES_NEGOTIATOR_H__ -#define __SFL_SDES_NEGOTIATOR_H__ +#ifndef __SDES_NEGOTIATOR_H__ +#define __SDES_NEGOTIATOR_H__ #include <stdexcept> #include <string> #include <vector> -namespace sfl -{ +namespace sfl { /** * General exception object that is thrown when * an error occured with a regular expression * operation. */ -class parse_error : public std::invalid_argument -{ +class ParseError : public std::invalid_argument { public: - explicit parse_error (const std::string& error) : - std::invalid_argument (error) {} + explicit ParseError(const std::string& error) : + std::invalid_argument(error) {} }; enum CipherMode { @@ -89,60 +87,58 @@ const CryptoSuiteDefinition CryptoSuites[3] = { }; -class CryptoAttribute -{ +class CryptoAttribute { public: - CryptoAttribute (std::string tag, - std::string cryptoSuite, - std::string srtpKeyMethod, - std::string srtpKeyInfo, - std::string lifetime, - std::string mkiValue, - std::string mkiLength) : - tag (tag), - cryptoSuite (cryptoSuite), - srtpKeyMethod (srtpKeyMethod), - srtpKeyInfo (srtpKeyInfo), - lifetime (lifetime), - mkiValue (mkiValue), - mkiLength (mkiLength) {}; + CryptoAttribute(const std::string &tag, + const std::string &cryptoSuite, + const std::string &srtpKeyMethod, + const std::string &srtpKeyInfo, + const std::string &lifetime, + const std::string &mkiValue, + const std::string &mkiLength) : + tag_(tag), + cryptoSuite_(cryptoSuite), + srtpKeyMethod_(srtpKeyMethod), + srtpKeyInfo_(srtpKeyInfo), + lifetime_(lifetime), + mkiValue_(mkiValue), + mkiLength_(mkiLength) {} std::string getTag() const { - return tag; - }; + return tag_; + } std::string getCryptoSuite() const { - return cryptoSuite; - }; + return cryptoSuite_; + } std::string getSrtpKeyMethod() const { - return srtpKeyMethod; - }; + return srtpKeyMethod_; + } std::string getSrtpKeyInfo() const { - return srtpKeyInfo; - }; + return srtpKeyInfo_; + } std::string getLifetime() const { - return lifetime; - }; + return lifetime_; + } std::string getMkiValue() const { - return mkiValue; - }; + return mkiValue_; + } std::string getMkiLength() const { - return mkiLength; - }; + return mkiLength_; + } private: - std::string tag; - std::string cryptoSuite; - std::string srtpKeyMethod; - std::string srtpKeyInfo; - std::string lifetime; - std::string mkiValue; - std::string mkiLength; + std::string tag_; + std::string cryptoSuite_; + std::string srtpKeyMethod_; + std::string srtpKeyInfo_; + std::string lifetime_; + std::string mkiValue_; + std::string mkiLength_; }; -class SdesNegotiator -{ +class SdesNegotiator { /** * Constructor for an SDES crypto attributes * negotiator. @@ -155,58 +151,57 @@ class SdesNegotiator */ public: - SdesNegotiator (const std::vector<CryptoSuiteDefinition>& localCapabilites, const std::vector<std::string>& remoteAttribute); - ~SdesNegotiator() { }; + SdesNegotiator(const std::vector<CryptoSuiteDefinition>& localCapabilites, const std::vector<std::string>& remoteAttribute); - bool negotiate (void); + bool negotiate(); /** * Return crypto suite after negotiation */ - std::string getCryptoSuite (void) const { - return _cryptoSuite; + std::string getCryptoSuite() const { + return cryptoSuite_; } /** * Return key method after negotiation (most likely inline:) */ - std::string getKeyMethod (void) const { - return _srtpKeyMethod; + std::string getKeyMethod() const { + return srtpKeyMethod_; } /** * Return crypto suite after negotiation */ - std::string getKeyInfo (void) const { - return _srtpKeyInfo; + std::string getKeyInfo() const { + return srtpKeyInfo_; } /** * Return key lifetime after negotiation */ - std::string getLifeTime (void) const { - return _lifetime; + std::string getLifeTime() const { + return lifetime_; } /** * Return mki value after negotiation */ - std::string getMkiValue (void) const { - return _mkiValue; + std::string getMkiValue() const { + return mkiValue_; } /** * Return mki length after negotiation */ - std::string getMkiLength (void) const { - return _mkiLength; + std::string getMkiLength() const { + return mkiLength_; } /** * Authentication tag lenth */ - std::string getAuthTagLength (void) const { - return _authTagLength; + std::string getAuthTagLength() const { + return authTagLength_; } @@ -216,46 +211,46 @@ class SdesNegotiator * Multiple crypto lines can be sent, and the * prefered method is then chosen from that list. */ - std::vector<std::string> _remoteAttribute; + std::vector<std::string> remoteAttribute_; - std::vector<CryptoSuiteDefinition> _localCapabilities; + std::vector<CryptoSuiteDefinition> localCapabilities_; /** * Selected crypto suite after negotiation */ - std::string _cryptoSuite; + std::string cryptoSuite_; /** * Selected key method after negotiation (most likely inline:) */ - std::string _srtpKeyMethod; + std::string srtpKeyMethod_; /** * Selected crypto suite after negotiation */ - std::string _srtpKeyInfo; + std::string srtpKeyInfo_; /** * Selected key lifetime after negotiation */ - std::string _lifetime; + std::string lifetime_; /** * Selected mki value after negotiation */ - std::string _mkiValue; + std::string mkiValue_; /** * Selected mki length after negotiation */ - std::string _mkiLength; + std::string mkiLength_; /** * Authenticvation tag length in byte */ - std::string _authTagLength; + std::string authTagLength_; - std::vector<CryptoAttribute *> parse (void); + std::vector<CryptoAttribute *> parse(); }; } -#endif +#endif // __SDES_NEGOTIATOR_H__ diff --git a/daemon/src/sip/sdp.cpp b/daemon/src/sip/sdp.cpp index 3c860c35e906005d1abc0f1e117ead8eaedec107..2034f39c71f43d8e527d620fe98d13246531fe04 100644 --- a/daemon/src/sip/sdp.cpp +++ b/daemon/src/sip/sdp.cpp @@ -35,102 +35,107 @@ #include "manager.h" #include <cassert> -Sdp::Sdp (pj_pool_t *pool) +Sdp::Sdp(pj_pool_t *pool) : memPool_(pool) - , negotiator_(NULL) + , negotiator_(NULL) , localSession_(NULL) - , remoteSession_(NULL) + , remoteSession_(NULL) , activeLocalSession_(NULL) , activeRemoteSession_(NULL) - , localIpAddr_("") - , remoteIpAddr_("") + , codec_list_() + , sessionAudioMedia_() + , localIpAddr_() + , remoteIpAddr_() , localAudioPort_(0) - , remoteAudioPort_(0) - , zrtpHelloHash_("") - , srtpCrypto_() + , remoteAudioPort_(0) + , zrtpHelloHash_() + , srtpCrypto_() , telephoneEventPayload_(101) // same as asterisk -{ -} +{} -void Sdp::setActiveLocalSdpSession (const pjmedia_sdp_session *sdp) +void Sdp::setActiveLocalSdpSession(const pjmedia_sdp_session *sdp) { activeLocalSession_ = (pjmedia_sdp_session*) sdp; if (activeLocalSession_->media_count < 1) - return; + return; pjmedia_sdp_media *current = activeLocalSession_->media[0]; - for (unsigned j = 0; j < current->desc.fmt_count; j++) { - static const pj_str_t STR_RTPMAP = { (char*) "rtpmap", 6 }; - pjmedia_sdp_attr *attribute = pjmedia_sdp_media_find_attr(current, &STR_RTPMAP, NULL); - if (!attribute) { - sessionAudioMedia_.clear(); - return; - } - - pjmedia_sdp_rtpmap *rtpmap; - pjmedia_sdp_attr_to_rtpmap (memPool_, attribute, &rtpmap); - - sfl::Codec *codec = Manager::instance().audioCodecFactory.getCodec((int) pj_strtoul (&rtpmap->pt)); - if (!codec) { - sessionAudioMedia_.clear(); - return; - } - - sessionAudioMedia_.push_back(codec); - } + for (unsigned j = 0; j < current->desc.fmt_count; j++) { + static const pj_str_t STR_RTPMAP = { (char*) "rtpmap", 6 }; + pjmedia_sdp_attr *attribute = pjmedia_sdp_media_find_attr(current, &STR_RTPMAP, NULL); + + if (!attribute) { + sessionAudioMedia_.clear(); + return; + } + + pjmedia_sdp_rtpmap *rtpmap; + pjmedia_sdp_attr_to_rtpmap(memPool_, attribute, &rtpmap); + + sfl::Codec *codec = Manager::instance().audioCodecFactory.getCodec((int) pj_strtoul(&rtpmap->pt)); + + if (!codec) { + sessionAudioMedia_.clear(); + return; + } + + sessionAudioMedia_.push_back(codec); + } } -void Sdp::setActiveRemoteSdpSession (const pjmedia_sdp_session *sdp) +void Sdp::setActiveRemoteSdpSession(const pjmedia_sdp_session *sdp) { activeRemoteSession_ = (pjmedia_sdp_session*) sdp; - if(!sdp) { - _error("Sdp: Error: Remote sdp is NULL while parsing telephone event attribute"); + if (!sdp) { + ERROR("Sdp: Error: Remote sdp is NULL while parsing telephone event attribute"); return; } for (unsigned i = 0; i < sdp->media_count; i++) - if(pj_stricmp2(&sdp->media[i]->desc.media, "audio") == 0) { + if (pj_stricmp2(&sdp->media[i]->desc.media, "audio") == 0) { pjmedia_sdp_media *r_media = sdp->media[i]; static const pj_str_t STR_TELEPHONE_EVENT = { (char*) "telephone-event", 15}; pjmedia_sdp_attr *attribute = pjmedia_sdp_attr_find(r_media->attr_count, r_media->attr, &STR_TELEPHONE_EVENT, NULL); + if (attribute != NULL) { pjmedia_sdp_rtpmap *rtpmap; - pjmedia_sdp_attr_to_rtpmap (memPool_, attribute, &rtpmap); - telephoneEventPayload_ = pj_strtoul (&rtpmap->pt); + pjmedia_sdp_attr_to_rtpmap(memPool_, attribute, &rtpmap); + telephoneEventPayload_ = pj_strtoul(&rtpmap->pt); } + return; } - _error("Sdp: Error: Could not found dtmf event from remote sdp"); + ERROR("Sdp: Error: Could not found dtmf event from remote sdp"); } -std::string Sdp::getCodecName(void) const +std::string Sdp::getCodecName() { - try { - sfl::AudioCodec *codec = getSessionMedia(); - return codec ? codec->getMimeSubtype() : ""; - } catch(...) { - return ""; - } + try { + sfl::AudioCodec *codec = getSessionMedia(); + return codec ? codec->getMimeSubtype() : ""; + } catch (...) { + return ""; + } } -sfl::AudioCodec* Sdp::getSessionMedia (void) const +sfl::AudioCodec* Sdp::getSessionMedia() { if (sessionAudioMedia_.size() < 1) throw SdpException("No codec description for this media"); - return static_cast<sfl::AudioCodec *>(sessionAudioMedia_[0]); + return dynamic_cast<sfl::AudioCodec *>(sessionAudioMedia_[0]); } -pjmedia_sdp_media *Sdp::setMediaDescriptorLine () +pjmedia_sdp_media *Sdp::setMediaDescriptorLine() { - pjmedia_sdp_media *med = PJ_POOL_ZALLOC_T (memPool_, pjmedia_sdp_media); + pjmedia_sdp_media *med = PJ_POOL_ZALLOC_T(memPool_, pjmedia_sdp_media); med->desc.media = pj_str((char*)"audio"); med->desc.port_count = 1; @@ -139,11 +144,12 @@ pjmedia_sdp_media *Sdp::setMediaDescriptorLine () med->desc.transport = pj_str(srtpCrypto_.empty() ? (char*)"RTP/AVP" : (char*)"RTP/SAVP"); med->desc.fmt_count = codec_list_.size(); + for (unsigned i=0; i<med->desc.fmt_count; i++) { sfl::Codec *codec = codec_list_[i]; std::ostringstream result; - result << (int)codec->getPayloadType (); + result << (int)codec->getPayloadType(); pj_strdup2(memPool_, &med->desc.fmt[i], result.str().c_str()); @@ -153,10 +159,10 @@ pjmedia_sdp_media *Sdp::setMediaDescriptorLine () // connection, the rtpmap attribute will be useful to specify for which codec it is applicable pjmedia_sdp_rtpmap rtpmap; rtpmap.pt = med->desc.fmt[i]; - rtpmap.enc_name = pj_str ( (char*) codec->getMimeSubtype().c_str()); + rtpmap.enc_name = pj_str((char*) codec->getMimeSubtype().c_str()); // G722 require G722/8000 media description even if it is 16000 codec - if (codec->getPayloadType () == 9) { + if (codec->getPayloadType() == 9) { rtpmap.clock_rate = 8000; } else { rtpmap.clock_rate = codec->getClockRate(); @@ -166,7 +172,7 @@ pjmedia_sdp_media *Sdp::setMediaDescriptorLine () rtpmap.param.slen = 0; pjmedia_sdp_attr *attr; - pjmedia_sdp_rtpmap_to_attr (memPool_, &rtpmap, &attr); + pjmedia_sdp_rtpmap_to_attr(memPool_, &rtpmap, &attr); med->attr[med->attr_count++] = attr; } @@ -174,7 +180,7 @@ pjmedia_sdp_media *Sdp::setMediaDescriptorLine () med->attr[ med->attr_count++] = pjmedia_sdp_attr_create(memPool_, "sendrecv", NULL); if (!zrtpHelloHash_.empty()) - addZrtpAttribute (med, zrtpHelloHash_); + addZrtpAttribute(med, zrtpHelloHash_); setTelephoneEventRtpmap(med); @@ -199,24 +205,36 @@ void Sdp::setTelephoneEventRtpmap(pjmedia_sdp_media *med) med->attr[med->attr_count++] = attr_fmtp; } -void Sdp::setLocalMediaCapabilities (const CodecOrder &selectedCodecs) +void Sdp::setLocalMediaCapabilities(const CodecOrder &selectedCodecs) { if (selectedCodecs.size() == 0) - _warn("No selected codec while building local SDP offer"); + WARN("No selected codec while building local SDP offer"); codec_list_.clear(); - for (CodecOrder::const_iterator iter = selectedCodecs.begin(); iter != selectedCodecs.end(); ++iter) { - sfl::Codec *codec = Manager::instance().audioCodecFactory.getCodec(*iter); - if (codec) - codec_list_.push_back(codec); - else - _warn ("SDP: Couldn't find audio codec"); - } + + for (CodecOrder::const_iterator iter = selectedCodecs.begin(); iter != selectedCodecs.end(); ++iter) { + sfl::Codec *codec = Manager::instance().audioCodecFactory.getCodec(*iter); + + if (codec) + codec_list_.push_back(codec); + else + WARN("SDP: Couldn't find audio codec"); + } } -int Sdp::createLocalSession (const CodecOrder &selectedCodecs) +namespace { + void printSession(const pjmedia_sdp_session *session) + { + char buffer[2048]; + size_t size = pjmedia_sdp_print(session, buffer, sizeof(buffer)); + std::string sessionStr(buffer, size); + DEBUG("%s", sessionStr.c_str()); + } +} + +int Sdp::createLocalSession(const CodecOrder &selectedCodecs) { - setLocalMediaCapabilities (selectedCodecs); + setLocalMediaCapabilities(selectedCodecs); localSession_ = PJ_POOL_ZALLOC_T(memPool_, pjmedia_sdp_session); localSession_->conn = PJ_POOL_ZALLOC_T(memPool_, pjmedia_sdp_conn); @@ -224,9 +242,9 @@ int Sdp::createLocalSession (const CodecOrder &selectedCodecs) /* Initialize the fields of the struct */ localSession_->origin.version = 0; pj_time_val tv; - pj_gettimeofday (&tv); + pj_gettimeofday(&tv); - localSession_->origin.user = pj_str (pj_gethostname()->ptr); + localSession_->origin.user = pj_str(pj_gethostname()->ptr); // Use Network Time Protocol format timestamp to ensure uniqueness. localSession_->origin.id = tv.sec + 2208988800UL; localSession_->origin.net_type = pj_str((char*)"IN"); @@ -250,40 +268,39 @@ int Sdp::createLocalSession (const CodecOrder &selectedCodecs) localSession_->media[0] = setMediaDescriptorLine(); if (!srtpCrypto_.empty()) - addSdesAttribute (srtpCrypto_); + addSdesAttribute(srtpCrypto_); - char buffer[1000]; - pjmedia_sdp_print(localSession_, buffer, sizeof(buffer)); - _debug("SDP: Local SDP Session:\n%s", buffer); + DEBUG("SDP: Local SDP Session:"); + printSession(localSession_); - return pjmedia_sdp_validate (localSession_); + return pjmedia_sdp_validate(localSession_); } -void Sdp::createOffer (const CodecOrder &selectedCodecs) +void Sdp::createOffer(const CodecOrder &selectedCodecs) { - if (createLocalSession (selectedCodecs) != PJ_SUCCESS) - _error ("SDP: Error: Failed to create initial offer"); - else if (pjmedia_sdp_neg_create_w_local_offer (memPool_, localSession_, &negotiator_) != PJ_SUCCESS) - _error ("SDP: Error: Failed to create an initial SDP negotiator"); + if (createLocalSession(selectedCodecs) != PJ_SUCCESS) + ERROR("SDP: Error: Failed to create initial offer"); + else if (pjmedia_sdp_neg_create_w_local_offer(memPool_, localSession_, &negotiator_) != PJ_SUCCESS) + ERROR("SDP: Error: Failed to create an initial SDP negotiator"); } -void Sdp::receiveOffer (const pjmedia_sdp_session* remote, +void Sdp::receiveOffer(const pjmedia_sdp_session* remote, const CodecOrder &selectedCodecs) { assert(remote); - char buffer[1000]; - pjmedia_sdp_print(remote, buffer, sizeof(buffer)); + DEBUG("SDP: Remote SDP Session:"); + printSession(remote); - if(localSession_ == NULL && createLocalSession (selectedCodecs) != PJ_SUCCESS) { - _error ("SDP: Failed to create initial offer"); - return; + if (localSession_ == NULL && createLocalSession(selectedCodecs) != PJ_SUCCESS) { + ERROR("SDP: Failed to create initial offer"); + return; } - remoteSession_ = pjmedia_sdp_session_clone (memPool_, remote); + remoteSession_ = pjmedia_sdp_session_clone(memPool_, remote); - pj_status_t status = pjmedia_sdp_neg_create_w_remote_offer (memPool_, localSession_, - remoteSession_, &negotiator_); + pj_status_t status = pjmedia_sdp_neg_create_w_remote_offer(memPool_, localSession_, + remoteSession_, &negotiator_); assert(status == PJ_SUCCESS); } @@ -304,46 +321,45 @@ void Sdp::startNegotiation() assert(negotiator_); if (pjmedia_sdp_neg_get_state(negotiator_) != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) - _warn("SDP: Warning: negotiator not in right state for negotiation"); + WARN("SDP: Warning: negotiator not in right state for negotiation"); - if (pjmedia_sdp_neg_negotiate (memPool_, negotiator_, 0) != PJ_SUCCESS) + if (pjmedia_sdp_neg_negotiate(memPool_, negotiator_, 0) != PJ_SUCCESS) return; if (pjmedia_sdp_neg_get_active_local(negotiator_, &active_local) != PJ_SUCCESS) - _error("SDP: Could not retrieve local active session"); + ERROR("SDP: Could not retrieve local active session"); else setActiveLocalSdpSession(active_local); if (pjmedia_sdp_neg_get_active_remote(negotiator_, &active_remote) != PJ_SUCCESS) - _error("SDP: Could not retrieve remote active session"); + ERROR("SDP: Could not retrieve remote active session"); else setActiveRemoteSdpSession(active_remote); } -void Sdp::addSdesAttribute (const std::vector<std::string>& crypto) +void Sdp::addSdesAttribute(const std::vector<std::string>& crypto) { for (std::vector<std::string>::const_iterator iter = crypto.begin(); - iter != crypto.end(); ++iter) - { - pj_str_t val = { (char*) (*iter).c_str(), (*iter).size() }; + iter != crypto.end(); ++iter) { + pj_str_t val = { (char*)(*iter).c_str(), (*iter).size() }; pjmedia_sdp_attr *attr = pjmedia_sdp_attr_create(memPool_, "crypto", &val); for (unsigned i = 0; i < localSession_->media_count; i++) - if (pjmedia_sdp_media_add_attr (localSession_->media[i], attr) != PJ_SUCCESS) - throw SdpException ("Could not add sdes attribute to media"); + if (pjmedia_sdp_media_add_attr(localSession_->media[i], attr) != PJ_SUCCESS) + throw SdpException("Could not add sdes attribute to media"); } } -void Sdp::addZrtpAttribute (pjmedia_sdp_media* media, std::string hash) +void Sdp::addZrtpAttribute(pjmedia_sdp_media* media, std::string hash) { /* Format: ":version value" */ - std::string val = "1.10 " + hash; - pj_str_t value = { (char*)val.c_str(), val.size() }; + std::string val = "1.10 " + hash; + pj_str_t value = { (char*)val.c_str(), val.size() }; pjmedia_sdp_attr *attr = pjmedia_sdp_attr_create(memPool_, "zrtp-hash", &value); - if (pjmedia_sdp_media_add_attr (media, attr) != PJ_SUCCESS) - throw SdpException ("Could not add zrtp attribute to media"); + if (pjmedia_sdp_media_add_attr(media, attr) != PJ_SUCCESS) + throw SdpException("Could not add zrtp attribute to media"); } Sdp::~Sdp() @@ -352,43 +368,44 @@ Sdp::~Sdp() void Sdp::addAttributeToLocalAudioMedia(const char *attr) { - pjmedia_sdp_media_add_attr (localSession_->media[0], pjmedia_sdp_attr_create (memPool_, attr, NULL)); + pjmedia_sdp_media_add_attr(localSession_->media[0], pjmedia_sdp_attr_create(memPool_, attr, NULL)); } void Sdp::removeAttributeFromLocalAudioMedia(const char *attr) { - pjmedia_sdp_media_remove_all_attr (localSession_->media[0], attr); + pjmedia_sdp_media_remove_all_attr(localSession_->media[0], attr); } -void Sdp::setMediaTransportInfoFromRemoteSdp () +void Sdp::setMediaTransportInfoFromRemoteSdp() { if (!activeRemoteSession_) { - _error("Sdp: Error: Remote sdp is NULL while parsing media"); + ERROR("Sdp: Error: Remote sdp is NULL while parsing media"); return; } for (unsigned i = 0; i < activeRemoteSession_->media_count; ++i) - if (pj_stricmp2 (&activeRemoteSession_->media[i]->desc.media, "audio") == 0) { + if (pj_stricmp2(&activeRemoteSession_->media[i]->desc.media, "audio") == 0) { setRemoteAudioPort(activeRemoteSession_->media[i]->desc.port); setRemoteIP(std::string(activeRemoteSession_->conn->addr.ptr, activeRemoteSession_->conn->addr.slen)); return; } - _error("SDP: No remote sdp media found in the remote offer"); + ERROR("SDP: No remote sdp media found in the remote offer"); } -void Sdp::getRemoteSdpCryptoFromOffer (const pjmedia_sdp_session* remote_sdp, CryptoOffer& crypto_offer) +void Sdp::getRemoteSdpCryptoFromOffer(const pjmedia_sdp_session* remote_sdp, CryptoOffer& crypto_offer) { CryptoOffer remoteOffer; for (unsigned i = 0; i < remote_sdp->media_count; ++i) { - pjmedia_sdp_media *media = remote_sdp->media[i]; + pjmedia_sdp_media *media = remote_sdp->media[i]; + for (unsigned j = 0; j < media->attr_count; j++) { - pjmedia_sdp_attr *attribute = media->attr[j]; + pjmedia_sdp_attr *attribute = media->attr[j]; - // @TODO our parser require the "a=crypto:" to be present - if (pj_stricmp2 (&attribute->name, "crypto") == 0) - crypto_offer.push_back ("a=crypto:" + std::string(attribute->value.ptr, attribute->value.slen)); + // @TODO our parser require the "a=crypto:" to be present + if (pj_stricmp2(&attribute->name, "crypto") == 0) + crypto_offer.push_back("a=crypto:" + std::string(attribute->value.ptr, attribute->value.slen)); } } } diff --git a/daemon/src/sip/sdp.h b/daemon/src/sip/sdp.h index f9da64630da6207deb700051caea38e4ce75766c..7c467fc5faf588e9d551052529226f4a8dcd09f7 100644 --- a/daemon/src/sip/sdp.h +++ b/daemon/src/sip/sdp.h @@ -45,23 +45,22 @@ #include <stdexcept> #include "global.h" // for CodecOrder +#include "noncopyable.h" namespace sfl { - class AudioCodec; - class Codec; +class AudioCodec; +class Codec; } -class SdpException : public std::runtime_error -{ +class SdpException : public std::runtime_error { public: - SdpException (const std::string& str="") : + SdpException(const std::string& str="") : std::runtime_error("SDP: SdpException occured: " + str) {} }; typedef std::vector<std::string> CryptoOffer; -class Sdp -{ +class Sdp { public: /* @@ -69,14 +68,14 @@ class Sdp * * @param memory pool */ - Sdp (pj_pool_t *pool); + Sdp(pj_pool_t *pool); ~Sdp(); /** * Accessor for the internal memory pool */ - pj_pool_t *getMemoryPool (void) const { + pj_pool_t *getMemoryPool() const { return memPool_; } @@ -85,7 +84,7 @@ class Sdp * * @return The structure that describes a SDP session */ - pjmedia_sdp_session *getLocalSdpSession (void) { + pjmedia_sdp_session *getLocalSdpSession() { return localSession_; } @@ -94,8 +93,8 @@ class Sdp * * @return The structure that describe the SDP session */ - pjmedia_sdp_session *getRemoteSdpSession(void) { - return remoteSession_; + pjmedia_sdp_session *getRemoteSdpSession() { + return remoteSession_; } /** @@ -103,14 +102,14 @@ class Sdp * * @param sdp the negotiated offer */ - void setActiveLocalSdpSession (const pjmedia_sdp_session *sdp); + void setActiveLocalSdpSession(const pjmedia_sdp_session *sdp); /** * read accessor. Return the negotiated local session * * @return pjmedia_sdp_session The negotiated offer */ - pjmedia_sdp_session* getActiveLocalSdpSession (void) { + pjmedia_sdp_session* getActiveLocalSdpSession() { return activeLocalSession_; } @@ -119,14 +118,14 @@ class Sdp * * @param sdp the negotiated offer */ - void setActiveRemoteSdpSession (const pjmedia_sdp_session *sdp); + void setActiveRemoteSdpSession(const pjmedia_sdp_session *sdp); /** * read accessor. Return the negotiated offer * * @return pjmedia_sdp_session The negotiated offer */ - pjmedia_sdp_session* getActiveRemoteSdpSession (void) { + pjmedia_sdp_session* getActiveRemoteSdpSession() { return activeRemoteSession_; } @@ -134,19 +133,19 @@ class Sdp /** * Return whether or not the media have been determined for this sdp session */ - bool hasSessionMedia(void) const; + bool hasSessionMedia() const; /** * Return the codec of the first media after negotiation * @throw SdpException */ - sfl::AudioCodec* getSessionMedia (void) const; + sfl::AudioCodec* getSessionMedia(); /* * On building an invite outside a dialog, build the local offer and create the * SDP negotiator instance with it. */ - void createOffer (const CodecOrder &selectedCodecs); + void createOffer(const CodecOrder &selectedCodecs); /* * On receiving an invite outside a dialog, build the local offer and create the @@ -154,49 +153,49 @@ class Sdp * * @param remote The remote offer */ - void receiveOffer (const pjmedia_sdp_session* remote, + void receiveOffer(const pjmedia_sdp_session* remote, const CodecOrder &selectedCodecs); /** * Start the sdp negotiation. */ - void startNegotiation (void); + void startNegotiation(); /** * Remove all media in the session media vector. */ - void cleanSessionMedia (void); + void cleanSessionMedia(); /** * Remove all media in local media capability vector */ - void cleanLocalMediaCapabilities (void); + void cleanLocalMediaCapabilities(); /* * Write accessor. Set the local IP address that will be used in the sdp session */ - void setLocalIP (const std::string &ip_addr) { + void setLocalIP(const std::string &ip_addr) { localIpAddr_ = ip_addr; } /* * Read accessor. Get the local IP address */ - std::string getLocalIP (void) const { + std::string getLocalIP() const { return localIpAddr_; } /** * @param Set the published audio port */ - void setLocalPublishedAudioPort (int port) { + void setLocalPublishedAudioPort(int port) { localAudioPort_ = port; } /** * @return The published audio port */ - int getLocalPublishedAudioPort (void) const { + int getLocalPublishedAudioPort() const { return localAudioPort_; } @@ -204,7 +203,7 @@ class Sdp * Set remote's IP addr. [not protected] * @param ip The remote IP address */ - void setRemoteIP (const std::string& ip) { + void setRemoteIP(const std::string& ip) { remoteIpAddr_ = ip; } @@ -220,7 +219,7 @@ class Sdp * Set remote's audio port. [not protected] * @param port The remote audio port */ - void setRemoteAudioPort (unsigned int port) { + void setRemoteAudioPort(unsigned int port) { remoteAudioPort_ = port; } @@ -247,13 +246,13 @@ class Sdp * @param remote sdp session * @param crypto offer */ - void getRemoteSdpCryptoFromOffer (const pjmedia_sdp_session* remote_sdp, CryptoOffer& crypto_offer); + void getRemoteSdpCryptoFromOffer(const pjmedia_sdp_session* remote_sdp, CryptoOffer& crypto_offer); /** * Set the SRTP master_key * @param mk The Master Key of a srtp session. */ - void setLocalSdpCrypto (const std::vector<std::string> lc) { + void setLocalSdpCrypto(const std::vector<std::string> lc) { srtpCrypto_ = lc; } @@ -263,21 +262,23 @@ class Sdp * have to set the correct zrtp-hash value in the corresponding media section. * @param hash The hello hash of a rtp session. (Only audio at the moment) */ - void setZrtpHash (const std::string& hash) { + void setZrtpHash(const std::string& hash) { zrtpHelloHash_ = hash; } unsigned int getTelephoneEventType() const { - return telephoneEventPayload_; + return telephoneEventPayload_; } void setMediaTransportInfoFromRemoteSdp(); - std::string getCodecName(void) const; + std::string getCodecName(); void receivingAnswerAfterInitialOffer(const pjmedia_sdp_session* remote); private: + NON_COPYABLE(Sdp); + /** * The pool to allocate memory, ownership to SipCall * SDP should not release the pool itself @@ -356,10 +357,6 @@ class Sdp */ unsigned int telephoneEventPayload_; - Sdp (const Sdp&); //No Copy Constructor - - Sdp& operator= (const Sdp&); //No Assignment Operator - /* * Build the sdp media section * Add rtpmap field if necessary @@ -372,19 +369,19 @@ class Sdp * Build the local media capabilities for this session * @param List of codec in preference order */ - void setLocalMediaCapabilities (const CodecOrder &selectedCodecs); + void setLocalMediaCapabilities(const CodecOrder &selectedCodecs); /* * Build the local SDP offer */ - int createLocalSession (const CodecOrder &selectedCodecs); + int createLocalSession(const CodecOrder &selectedCodecs); /* * Adds a sdes attribute to the given media section. * * @param media The media to add the srtp attribute to * @throw SdpException */ - void addSdesAttribute (const std::vector<std::string>& crypto); + void addSdesAttribute(const std::vector<std::string>& crypto); /* * Adds a zrtp-hash attribute to @@ -396,7 +393,7 @@ class Sdp * @param hash The hash to which the attribute should be set to * @throw SdpException */ - void addZrtpAttribute (pjmedia_sdp_media* media, std::string hash); + void addZrtpAttribute(pjmedia_sdp_media* media, std::string hash); }; diff --git a/daemon/src/sip/sipaccount.cpp b/daemon/src/sip/sipaccount.cpp index 7490126a1efb21a14b7e89267bde17b5ccaff402..fdd463449f0e624cae0ad0f99c1eca0473013fa3 100644 --- a/daemon/src/sip/sipaccount.cpp +++ b/daemon/src/sip/sipaccount.cpp @@ -38,50 +38,52 @@ #include <sstream> #include <cassert> -SIPAccount::SIPAccount (const std::string& accountID) - : Account (accountID, "SIP") - , transport (NULL) - , regc_ (NULL) - , bRegister_ (false) - , registrationExpire_ (600) - , interface_ ("default") - , publishedSameasLocal_ (true) - , publishedIpAddress_ ("") - , localPort_ (DEFAULT_SIP_PORT) - , publishedPort_ (DEFAULT_SIP_PORT) - , serviceRoute_ ("") - , tlsListenerPort_ (DEFAULT_SIP_TLS_PORT) - , transportType_ (PJSIP_TRANSPORT_UNSPECIFIED) - , cred_ (NULL) - , stunPort_(0) - , dtmfType_ (OVERRTP) - , tlsEnable_ ("false") - , tlsPort_ (DEFAULT_SIP_TLS_PORT) - , tlsCaListFile_ ("") - , tlsCertificateFile_ ("") - , tlsPrivateKeyFile_ ("") - , tlsPassword_ ("") - , tlsMethod_ ("TLSv1") - , tlsCiphers_ ("") - , tlsServerName_ ("") - , tlsVerifyServer_ (true) - , tlsVerifyClient_ (true) - , tlsRequireClientCertificate_ (true) - , tlsNegotiationTimeoutSec_ ("2") - , tlsNegotiationTimeoutMsec_ ("0") - , stunServer_ ("stun.sflphone.org") - , stunEnabled_ (false) - , srtpEnabled_ (false) - , srtpKeyExchange_ ("sdes") - , srtpFallback_ (false) - , zrtpDisplaySas_ (true) - , zrtpDisplaySasOnce_ (false) - , zrtpHelloHash_ (true) - , zrtpNotSuppWarning_ (true) +SIPAccount::SIPAccount(const std::string& accountID) + : Account(accountID, "SIP") + , transport_(NULL) + , credentials_() + , regc_(NULL) + , bRegister_(false) + , registrationExpire_(600) + , interface_("default") + , publishedSameasLocal_(true) + , publishedIpAddress_() + , localPort_(DEFAULT_SIP_PORT) + , publishedPort_(DEFAULT_SIP_PORT) + , serviceRoute_() + , tlsListenerPort_(DEFAULT_SIP_TLS_PORT) + , transportType_(PJSIP_TRANSPORT_UNSPECIFIED) + , cred_(NULL) + , tlsSetting_() + , stunServerName_() + , stunPort_(0) + , dtmfType_(OVERRTP) + , tlsEnable_("false") + , tlsPort_(DEFAULT_SIP_TLS_PORT) + , tlsCaListFile_() + , tlsCertificateFile_() + , tlsPrivateKeyFile_() + , tlsPassword_() + , tlsMethod_("TLSv1") + , tlsCiphers_() + , tlsServerName_(0, 0) + , tlsVerifyServer_(true) + , tlsVerifyClient_(true) + , tlsRequireClientCertificate_(true) + , tlsNegotiationTimeoutSec_("2") + , tlsNegotiationTimeoutMsec_("0") + , stunServer_("stun.sflphone.org") + , stunEnabled_(false) + , srtpEnabled_(false) + , srtpKeyExchange_("sdes") + , srtpFallback_(false) + , zrtpDisplaySas_(true) + , zrtpDisplaySasOnce_(false) + , zrtpHelloHash_(true) + , zrtpNotSuppWarning_(true) + , registrationStateDetailed_() { - stunServerName_.ptr = NULL; - stunServerName_.slen = 0; - link_ = SIPVoIPLink::instance (); + link_ = SIPVoIPLink::instance(); } SIPAccount::~SIPAccount() @@ -89,152 +91,154 @@ SIPAccount::~SIPAccount() delete[] cred_; } -void SIPAccount::serialize (Conf::YamlEmitter *emitter) +void SIPAccount::serialize(Conf::YamlEmitter *emitter) { - Conf::MappingNode accountmap (NULL); - Conf::MappingNode srtpmap (NULL); - Conf::MappingNode zrtpmap (NULL); - Conf::MappingNode tlsmap (NULL); - - Conf::ScalarNode id (Account::accountID_); - Conf::ScalarNode username (Account::username_); - Conf::ScalarNode alias (Account::alias_); - Conf::ScalarNode hostname (Account::hostname_); - Conf::ScalarNode enable (enabled_); - Conf::ScalarNode type (Account::type_); + Conf::MappingNode accountmap(NULL); + Conf::MappingNode srtpmap(NULL); + Conf::MappingNode zrtpmap(NULL); + Conf::MappingNode tlsmap(NULL); + + Conf::ScalarNode id(Account::accountID_); + Conf::ScalarNode username(Account::username_); + Conf::ScalarNode alias(Account::alias_); + Conf::ScalarNode hostname(Account::hostname_); + Conf::ScalarNode enable(enabled_); + Conf::ScalarNode type(Account::type_); std::stringstream expirevalstr; expirevalstr << registrationExpire_; - Conf::ScalarNode expire (expirevalstr); - Conf::ScalarNode interface (interface_); + Conf::ScalarNode expire(expirevalstr); + Conf::ScalarNode interface(interface_); std::stringstream portstr; portstr << localPort_; - Conf::ScalarNode port (portstr.str()); - Conf::ScalarNode serviceRoute (serviceRoute_); + Conf::ScalarNode port(portstr.str()); + Conf::ScalarNode serviceRoute(serviceRoute_); - Conf::ScalarNode mailbox (mailBox_); - Conf::ScalarNode publishAddr (publishedIpAddress_); + Conf::ScalarNode mailbox(mailBox_); + Conf::ScalarNode publishAddr(publishedIpAddress_); std::stringstream publicportstr; publicportstr << publishedPort_; - Conf::ScalarNode publishPort (publicportstr.str()); - Conf::ScalarNode sameasLocal (publishedSameasLocal_); - Conf::ScalarNode codecs (codecStr_); - Conf::ScalarNode ringtonePath (ringtonePath_); - Conf::ScalarNode ringtoneEnabled (ringtoneEnabled_); - Conf::ScalarNode stunServer (stunServer_); - Conf::ScalarNode stunEnabled (stunEnabled_); - Conf::ScalarNode displayName (displayName_); - Conf::ScalarNode dtmfType (dtmfType_==OVERRTP ? "overrtp" : "sipinfo"); + Conf::ScalarNode publishPort(publicportstr.str()); + Conf::ScalarNode sameasLocal(publishedSameasLocal_); + Conf::ScalarNode codecs(codecStr_); + Conf::ScalarNode ringtonePath(ringtonePath_); + Conf::ScalarNode ringtoneEnabled(ringtoneEnabled_); + Conf::ScalarNode stunServer(stunServer_); + Conf::ScalarNode stunEnabled(stunEnabled_); + Conf::ScalarNode displayName(displayName_); + Conf::ScalarNode dtmfType(dtmfType_==OVERRTP ? "overrtp" : "sipinfo"); std::stringstream countstr; countstr << 0; - Conf::ScalarNode count (countstr.str()); + Conf::ScalarNode count(countstr.str()); - Conf::ScalarNode srtpenabled (srtpEnabled_); - Conf::ScalarNode keyExchange (srtpKeyExchange_); - Conf::ScalarNode rtpFallback (srtpFallback_); + Conf::ScalarNode srtpenabled(srtpEnabled_); + Conf::ScalarNode keyExchange(srtpKeyExchange_); + Conf::ScalarNode rtpFallback(srtpFallback_); - Conf::ScalarNode displaySas (zrtpDisplaySas_); - Conf::ScalarNode displaySasOnce (zrtpDisplaySasOnce_); - Conf::ScalarNode helloHashEnabled (zrtpHelloHash_); - Conf::ScalarNode notSuppWarning (zrtpNotSuppWarning_); + Conf::ScalarNode displaySas(zrtpDisplaySas_); + Conf::ScalarNode displaySasOnce(zrtpDisplaySasOnce_); + Conf::ScalarNode helloHashEnabled(zrtpHelloHash_); + Conf::ScalarNode notSuppWarning(zrtpNotSuppWarning_); portstr.str(""); portstr << tlsPort_; - Conf::ScalarNode tlsport (portstr.str()); - Conf::ScalarNode certificate (tlsCertificateFile_); - Conf::ScalarNode calist (tlsCaListFile_); - Conf::ScalarNode ciphers (tlsCiphers_); - Conf::ScalarNode tlsenabled (tlsEnable_); - Conf::ScalarNode tlsmethod (tlsMethod_); - Conf::ScalarNode timeout (tlsNegotiationTimeoutSec_); - Conf::ScalarNode tlspassword (tlsPassword_); - Conf::ScalarNode privatekey (tlsPrivateKeyFile_); - Conf::ScalarNode requirecertif (tlsRequireClientCertificate_); - Conf::ScalarNode server (tlsServerName_); - Conf::ScalarNode verifyclient (tlsVerifyServer_); - Conf::ScalarNode verifyserver (tlsVerifyClient_); - - accountmap.setKeyValue (aliasKey, &alias); - accountmap.setKeyValue (typeKey, &type); - accountmap.setKeyValue (idKey, &id); - accountmap.setKeyValue (usernameKey, &username); - accountmap.setKeyValue (hostnameKey, &hostname); - accountmap.setKeyValue (accountEnableKey, &enable); - accountmap.setKeyValue (mailboxKey, &mailbox); - accountmap.setKeyValue (expireKey, &expire); - accountmap.setKeyValue (interfaceKey, &interface); - accountmap.setKeyValue (portKey, &port); - accountmap.setKeyValue (stunServerKey, &stunServer); - accountmap.setKeyValue (stunEnabledKey, &stunEnabled); - accountmap.setKeyValue (publishAddrKey, &publishAddr); - accountmap.setKeyValue (publishPortKey, &publishPort); - accountmap.setKeyValue (sameasLocalKey, &sameasLocal); - accountmap.setKeyValue (serviceRouteKey, &serviceRoute); - accountmap.setKeyValue (dtmfTypeKey, &dtmfType); - accountmap.setKeyValue (displayNameKey, &displayName); - accountmap.setKeyValue (codecsKey, &codecs); - accountmap.setKeyValue (ringtonePathKey, &ringtonePath); - accountmap.setKeyValue (ringtoneEnabledKey, &ringtoneEnabled); - - accountmap.setKeyValue (srtpKey, &srtpmap); - srtpmap.setKeyValue (srtpEnableKey, &srtpenabled); - srtpmap.setKeyValue (keyExchangeKey, &keyExchange); - srtpmap.setKeyValue (rtpFallbackKey, &rtpFallback); - - accountmap.setKeyValue (zrtpKey, &zrtpmap); - zrtpmap.setKeyValue (displaySasKey, &displaySas); - zrtpmap.setKeyValue (displaySasOnceKey, &displaySasOnce); - zrtpmap.setKeyValue (helloHashEnabledKey, &helloHashEnabled); - zrtpmap.setKeyValue (notSuppWarningKey, ¬SuppWarning); - - Conf::SequenceNode credentialseq (NULL); - accountmap.setKeyValue (credKey, &credentialseq); - - std::vector<std::map<std::string, std::string> >::const_iterator it; - for (it = credentials_.begin(); it != credentials_.end(); ++it) { - std::map<std::string, std::string> cred = *it; - Conf::MappingNode *map = new Conf::MappingNode(NULL); - map->setKeyValue(USERNAME, new Conf::ScalarNode(cred[USERNAME])); - map->setKeyValue(PASSWORD, new Conf::ScalarNode(cred[PASSWORD])); - map->setKeyValue(REALM, new Conf::ScalarNode(cred[REALM])); - credentialseq.addNode(map); - } - - accountmap.setKeyValue (tlsKey, &tlsmap); - tlsmap.setKeyValue (tlsPortKey, &tlsport); - tlsmap.setKeyValue (certificateKey, &certificate); - tlsmap.setKeyValue (calistKey, &calist); - tlsmap.setKeyValue (ciphersKey, &ciphers); - tlsmap.setKeyValue (tlsEnableKey, &tlsenabled); - tlsmap.setKeyValue (methodKey, &tlsmethod); - tlsmap.setKeyValue (timeoutKey, &timeout); - tlsmap.setKeyValue (tlsPasswordKey, &tlspassword); - tlsmap.setKeyValue (privateKeyKey, &privatekey); - tlsmap.setKeyValue (requireCertifKey, &requirecertif); - tlsmap.setKeyValue (serverKey, &server); - tlsmap.setKeyValue (verifyClientKey, &verifyclient); - tlsmap.setKeyValue (verifyServerKey, &verifyserver); + Conf::ScalarNode tlsport(portstr.str()); + Conf::ScalarNode certificate(tlsCertificateFile_); + Conf::ScalarNode calist(tlsCaListFile_); + Conf::ScalarNode ciphers(tlsCiphers_); + Conf::ScalarNode tlsenabled(tlsEnable_); + Conf::ScalarNode tlsmethod(tlsMethod_); + Conf::ScalarNode timeout(tlsNegotiationTimeoutSec_); + Conf::ScalarNode tlspassword(tlsPassword_); + Conf::ScalarNode privatekey(tlsPrivateKeyFile_); + Conf::ScalarNode requirecertif(tlsRequireClientCertificate_); + Conf::ScalarNode server(tlsServerName_); + Conf::ScalarNode verifyclient(tlsVerifyServer_); + Conf::ScalarNode verifyserver(tlsVerifyClient_); + + accountmap.setKeyValue(aliasKey, &alias); + accountmap.setKeyValue(typeKey, &type); + accountmap.setKeyValue(idKey, &id); + accountmap.setKeyValue(usernameKey, &username); + accountmap.setKeyValue(hostnameKey, &hostname); + accountmap.setKeyValue(accountEnableKey, &enable); + accountmap.setKeyValue(mailboxKey, &mailbox); + accountmap.setKeyValue(expireKey, &expire); + accountmap.setKeyValue(interfaceKey, &interface); + accountmap.setKeyValue(portKey, &port); + accountmap.setKeyValue(stunServerKey, &stunServer); + accountmap.setKeyValue(stunEnabledKey, &stunEnabled); + accountmap.setKeyValue(publishAddrKey, &publishAddr); + accountmap.setKeyValue(publishPortKey, &publishPort); + accountmap.setKeyValue(sameasLocalKey, &sameasLocal); + accountmap.setKeyValue(serviceRouteKey, &serviceRoute); + accountmap.setKeyValue(dtmfTypeKey, &dtmfType); + accountmap.setKeyValue(displayNameKey, &displayName); + accountmap.setKeyValue(codecsKey, &codecs); + accountmap.setKeyValue(ringtonePathKey, &ringtonePath); + accountmap.setKeyValue(ringtoneEnabledKey, &ringtoneEnabled); + + accountmap.setKeyValue(srtpKey, &srtpmap); + srtpmap.setKeyValue(srtpEnableKey, &srtpenabled); + srtpmap.setKeyValue(keyExchangeKey, &keyExchange); + srtpmap.setKeyValue(rtpFallbackKey, &rtpFallback); + + accountmap.setKeyValue(zrtpKey, &zrtpmap); + zrtpmap.setKeyValue(displaySasKey, &displaySas); + zrtpmap.setKeyValue(displaySasOnceKey, &displaySasOnce); + zrtpmap.setKeyValue(helloHashEnabledKey, &helloHashEnabled); + zrtpmap.setKeyValue(notSuppWarningKey, ¬SuppWarning); + + Conf::SequenceNode credentialseq(NULL); + accountmap.setKeyValue(credKey, &credentialseq); + + std::vector<std::map<std::string, std::string> >::const_iterator it; + + for (it = credentials_.begin(); it != credentials_.end(); ++it) { + std::map<std::string, std::string> cred = *it; + Conf::MappingNode *map = new Conf::MappingNode(NULL); + map->setKeyValue(USERNAME, new Conf::ScalarNode(cred[USERNAME])); + map->setKeyValue(PASSWORD, new Conf::ScalarNode(cred[PASSWORD])); + map->setKeyValue(REALM, new Conf::ScalarNode(cred[REALM])); + credentialseq.addNode(map); + } + + accountmap.setKeyValue(tlsKey, &tlsmap); + tlsmap.setKeyValue(tlsPortKey, &tlsport); + tlsmap.setKeyValue(certificateKey, &certificate); + tlsmap.setKeyValue(calistKey, &calist); + tlsmap.setKeyValue(ciphersKey, &ciphers); + tlsmap.setKeyValue(tlsEnableKey, &tlsenabled); + tlsmap.setKeyValue(methodKey, &tlsmethod); + tlsmap.setKeyValue(timeoutKey, &timeout); + tlsmap.setKeyValue(tlsPasswordKey, &tlspassword); + tlsmap.setKeyValue(privateKeyKey, &privatekey); + tlsmap.setKeyValue(requireCertifKey, &requirecertif); + tlsmap.setKeyValue(serverKey, &server); + tlsmap.setKeyValue(verifyClientKey, &verifyclient); + tlsmap.setKeyValue(verifyServerKey, &verifyserver); try { - emitter->serializeAccount (&accountmap); + emitter->serializeAccount(&accountmap); } catch (const Conf::YamlEmitterException &e) { - _error ("ConfigTree: %s", e.what()); + ERROR("ConfigTree: %s", e.what()); } Conf::Sequence *seq = credentialseq.getSequence(); Conf::Sequence::iterator seqit; + for (seqit = seq->begin(); seqit != seq->end(); ++seqit) { - Conf::MappingNode *node = (Conf::MappingNode*)*seqit; - delete node->getValue(USERNAME); - delete node->getValue(PASSWORD); - delete node->getValue(REALM); - delete node; + Conf::MappingNode *node = (Conf::MappingNode*)*seqit; + delete node->getValue(USERNAME); + delete node->getValue(PASSWORD); + delete node->getValue(REALM); + delete node; } } -void SIPAccount::unserialize (Conf::MappingNode *map) +void SIPAccount::unserialize(Conf::MappingNode *map) { Conf::MappingNode *srtpMap; Conf::MappingNode *tlsMap; @@ -250,7 +254,7 @@ void SIPAccount::unserialize (Conf::MappingNode *map) map->getValue(mailboxKey, &mailBox_); map->getValue(codecsKey, &codecStr_); // Update codec list which one is used for SDP offer - setActiveCodecs (ManagerImpl::unserialize (codecStr_)); + setActiveCodecs(ManagerImpl::unserialize(codecStr_)); map->getValue(ringtonePathKey, &ringtonePath_); map->getValue(ringtoneEnabledKey, &ringtoneEnabled_); @@ -274,52 +278,56 @@ void SIPAccount::unserialize (Conf::MappingNode *map) map->getValue(stunServerKey, &stunServer_); // Init stun server name with default server name - stunServerName_ = pj_str ( (char*) stunServer_.data()); + stunServerName_ = pj_str((char*) stunServer_.data()); map->getValue(displayNameKey, &displayName_); - std::vector<std::map<std::string, std::string> > creds; - - Conf::YamlNode *credNode = map->getValue (credKey); - - /* We check if the credential key is a sequence - * because it was a mapping in a previous version of - * the configuration file. - */ - if (credNode && credNode->getType() == Conf::SEQUENCE) { - Conf::SequenceNode *credSeq = (Conf::SequenceNode *) credNode; - Conf::Sequence::iterator it; - Conf::Sequence *seq = credSeq->getSequence(); - for(it = seq->begin(); it != seq->end(); ++it) { - Conf::MappingNode *cred = (Conf::MappingNode *) (*it); - std::string user; - std::string pass; - std::string realm; - cred->getValue(USERNAME, &user); - cred->getValue(PASSWORD, &pass); - cred->getValue(REALM, &realm); - std::map<std::string, std::string> map; - map[USERNAME] = user; - map[PASSWORD] = pass; - map[REALM] = realm; - creds.push_back(map); - } - } + std::vector<std::map<std::string, std::string> > creds; + + Conf::YamlNode *credNode = map->getValue(credKey); + + /* We check if the credential key is a sequence + * because it was a mapping in a previous version of + * the configuration file. + */ + if (credNode && credNode->getType() == Conf::SEQUENCE) { + Conf::SequenceNode *credSeq = (Conf::SequenceNode *) credNode; + Conf::Sequence::iterator it; + Conf::Sequence *seq = credSeq->getSequence(); + + for (it = seq->begin(); it != seq->end(); ++it) { + Conf::MappingNode *cred = (Conf::MappingNode *)(*it); + std::string user; + std::string pass; + std::string realm; + cred->getValue(USERNAME, &user); + cred->getValue(PASSWORD, &pass); + cred->getValue(REALM, &realm); + std::map<std::string, std::string> credentialMap; + credentialMap[USERNAME] = user; + credentialMap[PASSWORD] = pass; + credentialMap[REALM] = realm; + creds.push_back(credentialMap); + } + } + if (creds.empty()) { - // migration from old file format - std::map<std::string, std::string> credmap; - std::string password; - map->getValue(passwordKey, &password); - - credmap[USERNAME] = username_; - credmap[PASSWORD] = password; - credmap[REALM] = "*"; - creds.push_back(credmap); + // migration from old file format + std::map<std::string, std::string> credmap; + std::string password; + map->getValue(passwordKey, &password); + + credmap[USERNAME] = username_; + credmap[PASSWORD] = password; + credmap[REALM] = "*"; + creds.push_back(credmap); } - setCredentials (creds); + + setCredentials(creds); // get srtp submap - srtpMap = (Conf::MappingNode *) (map->getValue (srtpKey)); + srtpMap = (Conf::MappingNode *)(map->getValue(srtpKey)); + if (srtpMap) { srtpMap->getValue(srtpEnableKey, &srtpEnabled_); srtpMap->getValue(keyExchangeKey, &srtpKeyExchange_); @@ -327,7 +335,8 @@ void SIPAccount::unserialize (Conf::MappingNode *map) } // get zrtp submap - zrtpMap = (Conf::MappingNode *) (map->getValue (zrtpKey)); + zrtpMap = (Conf::MappingNode *)(map->getValue(zrtpKey)); + if (zrtpMap) { zrtpMap->getValue(displaySasKey, &zrtpDisplaySas_); zrtpMap->getValue(displaySasOnceKey, &zrtpDisplaySasOnce_); @@ -336,7 +345,8 @@ void SIPAccount::unserialize (Conf::MappingNode *map) } // get tls submap - tlsMap = (Conf::MappingNode *) (map->getValue (tlsKey)); + tlsMap = (Conf::MappingNode *)(map->getValue(tlsKey)); + if (tlsMap) { tlsMap->getValue(tlsEnableKey, &tlsEnable_); tlsMap->getValue(tlsPortKey, &tlsPort_); @@ -357,7 +367,7 @@ void SIPAccount::unserialize (Conf::MappingNode *map) } -void SIPAccount::setAccountDetails (std::map<std::string, std::string> details) +void SIPAccount::setAccountDetails(std::map<std::string, std::string> details) { // Account setting common to SIP and IAX alias_ = details[CONFIG_ACCOUNT_ALIAS]; @@ -377,8 +387,8 @@ void SIPAccount::setAccountDetails (std::map<std::string, std::string> details) interface_ = details[LOCAL_INTERFACE]; publishedSameasLocal_ = details[PUBLISHED_SAMEAS_LOCAL] == "true"; publishedIpAddress_ = details[PUBLISHED_ADDRESS]; - localPort_ = atoi (details[LOCAL_PORT].c_str()); - publishedPort_ = atoi (details[PUBLISHED_PORT].c_str()); + localPort_ = atoi(details[LOCAL_PORT].c_str()); + publishedPort_ = atoi(details[PUBLISHED_PORT].c_str()); stunServer_ = details[STUN_SERVER]; stunEnabled_ = details[STUN_ENABLE] == "true"; dtmfType_ = details[ACCOUNT_DTMF_TYPE] == "overrtp" ? OVERRTP : SIPINFO; @@ -399,7 +409,7 @@ void SIPAccount::setAccountDetails (std::map<std::string, std::string> details) // TLS settings // The TLS listener is unique and globally defined through IP2IP_PROFILE if (accountID_ == IP2IP_PROFILE) - tlsListenerPort_ = atoi (details[TLS_LISTENER_PORT].c_str()); + tlsListenerPort_ = atoi(details[TLS_LISTENER_PORT].c_str()); tlsEnable_ = details[TLS_ENABLE]; tlsCaListFile_ = details[TLS_CA_LIST_FILE]; @@ -458,7 +468,7 @@ std::map<std::string, std::string> SIPAccount::getAccountDetails() const registrationStateDescription = registrationStateDetailed_.second; } - a[REGISTRATION_STATUS] = (accountID_ == IP2IP_PROFILE) ? "READY": mapStateNumberToString (state); + a[REGISTRATION_STATUS] = (accountID_ == IP2IP_PROFILE) ? "READY": mapStateNumberToString(state); a[REGISTRATION_STATE_CODE] = registrationStateCode; a[REGISTRATION_STATE_DESCRIPTION] = registrationStateDescription; @@ -520,7 +530,7 @@ void SIPAccount::registerVoIPLink() // Init TLS settings if the user wants to use TLS if (tlsEnable_ == "true") { - _debug ("SIPAccount: TLS is enabled for account %s", accountID_.c_str()); + DEBUG("SIPAccount: TLS is enabled for account %s", accountID_.c_str()); transportType_ = PJSIP_TRANSPORT_TLS; initTlsConfiguration(); } @@ -528,38 +538,36 @@ void SIPAccount::registerVoIPLink() // Init STUN settings for this account if the user selected it if (stunEnabled_) { transportType_ = PJSIP_TRANSPORT_START_OTHER; - initStunConfiguration (); + initStunConfiguration(); } else { - stunServerName_ = pj_str ( (char*) stunServer_.c_str()); + stunServerName_ = pj_str((char*) stunServer_.c_str()); } // In our definition of the ip2ip profile (aka Direct IP Calls), // no registration should be performed if (accountID_ == IP2IP_PROFILE) - return; + return; try { link_->sendRegister(this); - } - catch (const VoipLinkException &e) { - _error("SIPAccount: %s", e.what()); + } catch (const VoipLinkException &e) { + ERROR("SIPAccount: %s", e.what()); } } void SIPAccount::unregisterVoIPLink() { - if (accountID_ == IP2IP_PROFILE) - return; + if (accountID_ == IP2IP_PROFILE) + return; try { - link_->sendUnregister (this); - } - catch (const VoipLinkException &e) { - _error("SIPAccount: %s", e.what()); + link_->sendUnregister(this); + } catch (const VoipLinkException &e) { + ERROR("SIPAccount: %s", e.what()); } } -pjsip_ssl_method SIPAccount::sslMethodStringToPjEnum (const std::string& method) +pjsip_ssl_method SIPAccount::sslMethodStringToPjEnum(const std::string& method) { if (method == "Default") return PJSIP_SSL_UNSPECIFIED_METHOD; @@ -576,47 +584,47 @@ pjsip_ssl_method SIPAccount::sslMethodStringToPjEnum (const std::string& method) return PJSIP_SSL_UNSPECIFIED_METHOD; } -void SIPAccount::initTlsConfiguration (void) +void SIPAccount::initTlsConfiguration() { // TLS listener is unique and should be only modified through IP2IP_PROFILE tlsListenerPort_ = tlsPort_; - pjsip_tls_setting_default (&tlsSetting_); + pjsip_tls_setting_default(&tlsSetting_); - pj_cstr (&tlsSetting_.ca_list_file, tlsCaListFile_.c_str()); - pj_cstr (&tlsSetting_.cert_file, tlsCertificateFile_.c_str()); - pj_cstr (&tlsSetting_.privkey_file, tlsPrivateKeyFile_.c_str()); - pj_cstr (&tlsSetting_.password, tlsPassword_.c_str()); - tlsSetting_.method = sslMethodStringToPjEnum (tlsMethod_); - pj_cstr (&tlsSetting_.ciphers, tlsCiphers_.c_str()); - pj_cstr (&tlsSetting_.server_name, tlsServerName_.c_str()); + pj_cstr(&tlsSetting_.ca_list_file, tlsCaListFile_.c_str()); + pj_cstr(&tlsSetting_.cert_file, tlsCertificateFile_.c_str()); + pj_cstr(&tlsSetting_.privkey_file, tlsPrivateKeyFile_.c_str()); + pj_cstr(&tlsSetting_.password, tlsPassword_.c_str()); + tlsSetting_.method = sslMethodStringToPjEnum(tlsMethod_); + pj_cstr(&tlsSetting_.ciphers, tlsCiphers_.c_str()); + pj_cstr(&tlsSetting_.server_name, tlsServerName_.c_str()); tlsSetting_.verify_server = tlsVerifyServer_ ? PJ_TRUE: PJ_FALSE; tlsSetting_.verify_client = tlsVerifyClient_ ? PJ_TRUE: PJ_FALSE; tlsSetting_.require_client_cert = tlsRequireClientCertificate_ ? PJ_TRUE: PJ_FALSE; - tlsSetting_.timeout.sec = atol (tlsNegotiationTimeoutSec_.c_str()); - tlsSetting_.timeout.msec = atol (tlsNegotiationTimeoutMsec_.c_str()); + tlsSetting_.timeout.sec = atol(tlsNegotiationTimeoutSec_.c_str()); + tlsSetting_.timeout.msec = atol(tlsNegotiationTimeoutMsec_.c_str()); } -void SIPAccount::initStunConfiguration (void) +void SIPAccount::initStunConfiguration() { size_t pos; std::string stunServer, serverName, serverPort; stunServer = stunServer_; // Init STUN socket - pos = stunServer.find (':'); + pos = stunServer.find(':'); if (pos == std::string::npos) { - stunServerName_ = pj_str ( (char*) stunServer.data()); + stunServerName_ = pj_str((char*) stunServer.data()); stunPort_ = PJ_STUN_PORT; //stun_status = pj_sockaddr_in_init (&stun_srv.ipv4, &stun_adr, (pj_uint16_t) 3478); } else { - serverName = stunServer.substr (0, pos); - serverPort = stunServer.substr (pos + 1); - stunPort_ = atoi (serverPort.data()); - stunServerName_ = pj_str ( (char*) serverName.data()); + serverName = stunServer.substr(0, pos); + serverPort = stunServer.substr(pos + 1); + stunPort_ = atoi(serverPort.data()); + stunServerName_ = pj_str((char*) serverName.data()); //stun_status = pj_sockaddr_in_init (&stun_srv.ipv4, &stun_adr, (pj_uint16_t) nPort); } } @@ -633,33 +641,33 @@ void SIPAccount::loadConfig() transportType_ = PJSIP_TRANSPORT_UDP; } -bool SIPAccount::fullMatch (const std::string& username, const std::string& hostname) const +bool SIPAccount::fullMatch(const std::string& username, const std::string& hostname) const { - return userMatch (username) and hostnameMatch (hostname); + return userMatch(username) and hostnameMatch(hostname); } -bool SIPAccount::userMatch (const std::string& username) const +bool SIPAccount::userMatch(const std::string& username) const { return !username.empty() and username == username_; } -bool SIPAccount::hostnameMatch (const std::string& hostname) const +bool SIPAccount::hostnameMatch(const std::string& hostname) const { return hostname == hostname_; } -std::string SIPAccount::getLoginName (void) +std::string SIPAccount::getLoginName() { - struct passwd * user_info = getpwuid (getuid()); + struct passwd * user_info = getpwuid(getuid()); return user_info ? user_info->pw_name : ""; } -std::string SIPAccount::getFromUri (void) const +std::string SIPAccount::getFromUri() const { - std::string scheme(""); - std::string transport(""); - std::string username = username_; - std::string hostname = hostname_; + std::string scheme; + std::string transport; + std::string username(username_); + std::string hostname(hostname_); // UDP does not require the transport specification if (transportType_ == PJSIP_TRANSPORT_TLS) { @@ -679,7 +687,7 @@ std::string SIPAccount::getFromUri (void) const return "<" + scheme + username + "@" + hostname + transport + ">"; } -std::string SIPAccount::getToUri (const std::string& username) const +std::string SIPAccount::getToUri(const std::string& username) const { std::string scheme; std::string transport; @@ -693,17 +701,17 @@ std::string SIPAccount::getToUri (const std::string& username) const scheme = "sip:"; // Check if scheme is already specified - if (username.find ("sip") == 0) + if (username.find("sip") == 0) scheme = ""; // Check if hostname is already specified - if (username.find ("@") == std::string::npos) + if (username.find("@") == std::string::npos) hostname = hostname_; return "<" + scheme + username + (hostname.empty() ? "" : "@") + hostname + transport + ">"; } -std::string SIPAccount::getServerUri (void) const +std::string SIPAccount::getServerUri() const { std::string scheme; std::string transport; @@ -711,7 +719,7 @@ std::string SIPAccount::getServerUri (void) const // UDP does not require the transport specification if (transportType_ == PJSIP_TRANSPORT_TLS) { scheme = "sips:"; - transport = ";transport=" + std::string (pjsip_transport_get_type_name (transportType_)); + transport = ";transport=" + std::string(pjsip_transport_get_type_name(transportType_)); } else { scheme = "sip:"; transport = ""; @@ -720,7 +728,7 @@ std::string SIPAccount::getServerUri (void) const return "<" + scheme + hostname_ + transport + ">"; } -std::string SIPAccount::getContactHeader (const std::string& address, const std::string& port) const +std::string SIPAccount::getContactHeader(const std::string& address, const std::string& port) const { std::string scheme; std::string transport; @@ -728,18 +736,18 @@ std::string SIPAccount::getContactHeader (const std::string& address, const std: // UDP does not require the transport specification if (transportType_ == PJSIP_TRANSPORT_TLS) { scheme = "sips:"; - transport = ";transport=" + std::string (pjsip_transport_get_type_name (transportType_)); + transport = ";transport=" + std::string(pjsip_transport_get_type_name(transportType_)); } else scheme = "sip:"; return displayName_ + (displayName_.empty() ? "" : " ") + "<" + - scheme + username_ + (username_.empty() ? "":"@") + - address + ":" + port + transport + ">"; + scheme + username_ + (username_.empty() ? "":"@") + + address + ":" + port + transport + ">"; } namespace { -std::string computeMd5HashFromCredential ( +std::string computeMd5HashFromCredential( const std::string& username, const std::string& password, const std::string& realm) { @@ -748,19 +756,20 @@ std::string computeMd5HashFromCredential ( pj_md5_context pms; /* Compute md5 hash = MD5(username ":" realm ":" password) */ - pj_md5_init (&pms); - MD5_APPEND (&pms, username.data(), username.length()); - MD5_APPEND (&pms, ":", 1); - MD5_APPEND (&pms, realm.data(), realm.length()); - MD5_APPEND (&pms, ":", 1); - MD5_APPEND (&pms, password.data(), password.length()); + pj_md5_init(&pms); + MD5_APPEND(&pms, username.data(), username.length()); + MD5_APPEND(&pms, ":", 1); + MD5_APPEND(&pms, realm.data(), realm.length()); + MD5_APPEND(&pms, ":", 1); + MD5_APPEND(&pms, password.data(), password.length()); unsigned char digest[16]; - pj_md5_final (&pms, digest); + pj_md5_final(&pms, digest); char hash[32]; + for (int i = 0; i < 16; ++i) - pj_val_to_hex_digit (digest[i], &hash[2*i]); + pj_val_to_hex_digit(digest[i], &hash[2*i]); return std::string(hash, 32); } @@ -768,7 +777,7 @@ std::string computeMd5HashFromCredential ( } // anon namespace -void SIPAccount::setCredentials (const std::vector<std::map<std::string, std::string> >& creds) +void SIPAccount::setCredentials(const std::vector<std::map<std::string, std::string> >& creds) { using std::vector; using std::string; @@ -776,18 +785,18 @@ void SIPAccount::setCredentials (const std::vector<std::map<std::string, std::st bool md5HashingEnabled = Manager::instance().preferences.getMd5Hash(); - assert(creds.size() > 0); // we can not authenticate without credentials + assert(creds.size() > 0); // we can not authenticate without credentials - credentials_ = creds; + credentials_ = creds; /* md5 hashing */ for (vector<map<string, string> >::iterator it = credentials_.begin(); it != credentials_.end(); ++it) { map<string, string>::const_iterator val = (*it).find(USERNAME); const std::string username = val != (*it).end() ? val->second : ""; val = (*it).find(REALM); - const std::string realm (val != (*it).end() ? val->second : ""); + const std::string realm(val != (*it).end() ? val->second : ""); val = (*it).find(PASSWORD); - const std::string password (val != (*it).end() ? val->second : ""); + const std::string password(val != (*it).end() ? val->second : ""); if (md5HashingEnabled) { // TODO: Fix this. @@ -809,30 +818,34 @@ void SIPAccount::setCredentials (const std::vector<std::map<std::string, std::st cred_ = new pjsip_cred_info[credentials_.size()]; size_t i = 0; + for (vector<map<string, string > >::const_iterator iter = credentials_.begin(); iter != credentials_.end(); ++iter) { map<string, string>::const_iterator val = (*iter).find(PASSWORD); - const std::string password = val != (*iter).end() ? val->second : ""; - int dataType = (md5HashingEnabled and password.length() == 32) - ? PJSIP_CRED_DATA_DIGEST - : PJSIP_CRED_DATA_PLAIN_PASSWD; + const std::string password = val != (*iter).end() ? val->second : ""; + int dataType = (md5HashingEnabled and password.length() == 32) + ? PJSIP_CRED_DATA_DIGEST + : PJSIP_CRED_DATA_PLAIN_PASSWD; val = (*iter).find(USERNAME); + if (val != (*iter).end()) - cred_[i].username = pj_str ((char*) val->second.c_str()); - cred_[i].data = pj_str ((char*) password.c_str()); + cred_[i].username = pj_str((char*) val->second.c_str()); + + cred_[i].data = pj_str((char*) password.c_str()); val = (*iter).find(REALM); + if (val != (*iter).end()) - cred_[i].realm = pj_str ((char*) val->second.c_str()); + cred_[i].realm = pj_str((char*) val->second.c_str()); cred_[i].data_type = dataType; - cred_[i].scheme = pj_str ( (char*) "digest"); + cred_[i].scheme = pj_str((char*) "digest"); ++i; } } -const std::vector<std::map<std::string, std::string> > &SIPAccount::getCredentials (void) +const std::vector<std::map<std::string, std::string> > &SIPAccount::getCredentials() { return credentials_; } @@ -847,7 +860,7 @@ std::string SIPAccount::getUserAgentName() const return result; } -std::map<std::string, std::string> SIPAccount::getIp2IpDetails (void) const +std::map<std::string, std::string> SIPAccount::getIp2IpDetails() const { assert(accountID_ == IP2IP_PROFILE); std::map<std::string, std::string> ip2ipAccountDetails; @@ -866,8 +879,8 @@ std::map<std::string, std::string> SIPAccount::getIp2IpDetails (void) const std::map<std::string, std::string> tlsSettings; tlsSettings = getTlsSettings(); - std::copy (tlsSettings.begin(), tlsSettings.end(), std::inserter ( - ip2ipAccountDetails, ip2ipAccountDetails.end())); + std::copy(tlsSettings.begin(), tlsSettings.end(), std::inserter( + ip2ipAccountDetails, ip2ipAccountDetails.end())); return ip2ipAccountDetails; } @@ -898,29 +911,32 @@ std::map<std::string, std::string> SIPAccount::getTlsSettings() const } namespace { -void set_opt(const std::map<std::string, std::string> &details, const char *key, std::string &val) { +void set_opt(const std::map<std::string, std::string> &details, const char *key, std::string &val) +{ std::map<std::string, std::string>::const_iterator it = details.find(key); - if (it != details.end()) - val = it->second; + if (it != details.end()) + val = it->second; } -void set_opt(const std::map<std::string, std::string> &details, const char *key, bool &val) { +void set_opt(const std::map<std::string, std::string> &details, const char *key, bool &val) +{ std::map<std::string, std::string>::const_iterator it = details.find(key); - if (it != details.end()) - val = it->second == "true"; + if (it != details.end()) + val = it->second == "true"; } -void set_opt(const std::map<std::string, std::string> &details, const char *key, pj_uint16_t &val) { +void set_opt(const std::map<std::string, std::string> &details, const char *key, pj_uint16_t &val) +{ std::map<std::string, std::string>::const_iterator it = details.find(key); - if (it != details.end()) - val = atoi(it->second.c_str()); + if (it != details.end()) + val = atoi(it->second.c_str()); } } //anon namespace -void SIPAccount::setTlsSettings (const std::map<std::string, std::string>& details) +void SIPAccount::setTlsSettings(const std::map<std::string, std::string>& details) { assert(accountID_ == IP2IP_PROFILE); set_opt(details, TLS_LISTENER_PORT, tlsListenerPort_); diff --git a/daemon/src/sip/sipaccount.h b/daemon/src/sip/sipaccount.h index 4e59042f7e900fe70c0c29769a2782c99dc0e479..076fe6076c967e381219594d24a8eea01cd103eb 100644 --- a/daemon/src/sip/sipaccount.h +++ b/daemon/src/sip/sipaccount.h @@ -35,18 +35,17 @@ #ifndef SIPACCOUNT_H #define SIPACCOUNT_H -#include <sstream> - +#include <vector> +#include <map> #include "account.h" #include "pjsip/sip_transport_tls.h" #include "pjsip/sip_types.h" #include "pjsip-ua/sip_regc.h" -#include <vector> -#include <map> +#include "noncopyable.h" namespace Conf { - class YamlEmitter; - class MappingNode; +class YamlEmitter; +class MappingNode; } enum DtmfType { OVERRTP, SIPINFO}; @@ -101,32 +100,33 @@ class SIPVoIPLink; * @brief A SIP Account specify SIP specific functions and object = SIPCall/SIPVoIPLink) */ -class SIPAccount : public Account -{ +class SIPAccount : public Account { public: /** * Constructor * @param accountID The account identifier */ - SIPAccount (const std::string& accountID); + SIPAccount(const std::string& accountID); /** * Virtual destructor */ virtual ~SIPAccount(); std::string getUserAgentName() const; - void setRegistrationStateDetailed (const std::pair<int, std::string> &details) { registrationStateDetailed_ = details; } + void setRegistrationStateDetailed(const std::pair<int, std::string> &details) { + registrationStateDetailed_ = details; + } - virtual void serialize (Conf::YamlEmitter *emitter); + virtual void serialize(Conf::YamlEmitter *emitter); - virtual void unserialize (Conf::MappingNode *map); + virtual void unserialize(Conf::MappingNode *map); - virtual void setAccountDetails (std::map<std::string, std::string> details); + virtual void setAccountDetails(std::map<std::string, std::string> details); virtual std::map<std::string, std::string> getAccountDetails() const; - std::map<std::string, std::string> getIp2IpDetails (void) const; - std::map<std::string, std::string> getTlsSettings (void) const; - void setTlsSettings (const std::map<std::string, std::string>& details); + std::map<std::string, std::string> getIp2IpDetails() const; + std::map<std::string, std::string> getTlsSettings() const; + void setTlsSettings(const std::map<std::string, std::string>& details); /** * Actually useless, since config loading is done in init() @@ -153,12 +153,12 @@ class SIPAccount : public Account * @param none * @return int The number of credentials set for this account. */ - unsigned getCredentialCount (void) const { + unsigned getCredentialCount() const { return credentials_.size(); } - void setCredentials (const std::vector<std::map<std::string, std::string> >& details); - const std::vector<std::map<std::string, std::string> > &getCredentials (void); + void setCredentials(const std::vector<std::map<std::string, std::string> >& details); + const std::vector<std::map<std::string, std::string> > &getCredentials(); /** * A client sendings a REGISTER request MAY suggest an expiration @@ -167,30 +167,32 @@ class SIPAccount : public Account * * @return the expiration value. */ - unsigned getRegistrationExpire (void) const { - if (registrationExpire_ == 0) - return PJSIP_REGC_EXPIRATION_NOT_SPECIFIED; - return registrationExpire_; + unsigned getRegistrationExpire() const { + if (registrationExpire_ == 0) + return PJSIP_REGC_EXPIRATION_NOT_SPECIFIED; + + return registrationExpire_; } /** * Doubles the Expiration Interval of Contact Addresses. */ - void doubleRegistrationExpire (void) { - registrationExpire_ *= 2; - if (registrationExpire_ < 0) - registrationExpire_ = 0; + void doubleRegistrationExpire() { + registrationExpire_ *= 2; + + if (registrationExpire_ < 0) + registrationExpire_ = 0; } - bool fullMatch (const std::string& username, const std::string& hostname) const; - bool userMatch (const std::string& username) const; - bool hostnameMatch (const std::string& hostname) const; + bool fullMatch(const std::string& username, const std::string& hostname) const; + bool userMatch(const std::string& username) const; + bool hostnameMatch(const std::string& hostname) const; /* Registration flag */ bool isRegister() const { return bRegister_; } - void setRegister (bool result) { + void setRegister(bool result) { bRegister_ = result; } @@ -201,7 +203,7 @@ class SIPAccount : public Account * @param void * @return pjsip_regc* A pointer to the registration structure */ - pjsip_regc* getRegistrationInfo (void) const { + pjsip_regc* getRegistrationInfo() { return regc_; } @@ -211,7 +213,7 @@ class SIPAccount : public Account * @pram A pointer to the new registration structure * @return void */ - void setRegistrationInfo (pjsip_regc *regc) { + void setRegistrationInfo(pjsip_regc *regc) { regc_ = regc; } @@ -220,7 +222,7 @@ class SIPAccount : public Account * file, that can be used directly by PJSIP to initialize * TLS transport. */ - const pjsip_tls_setting * getTlsSetting (void) const { + pjsip_tls_setting * getTlsSetting() { return &tlsSetting_; } @@ -229,14 +231,14 @@ class SIPAccount : public Account * file, that can be used directly by PJSIP to initialize * an alternate UDP transport. */ - std::string getStunServer (void) const { + std::string getStunServer() const { return stunServer_; } - void setStunServer (const std::string &srv) { + void setStunServer(const std::string &srv) { stunServer_ = srv; } - pj_str_t getStunServerName (void) const { + pj_str_t getStunServerName() const { return stunServerName_; } @@ -245,10 +247,10 @@ class SIPAccount : public Account * file, that can be used directly by PJSIP to initialize * an alternate UDP transport. */ - pj_uint16_t getStunPort (void) const { + pj_uint16_t getStunPort() const { return stunPort_; } - void setStunPort (pj_uint16_t port) { + void setStunPort(pj_uint16_t port) { stunPort_ = port; } @@ -256,7 +258,7 @@ class SIPAccount : public Account * @return bool Tells if current transport for that * account is set to TLS. */ - bool isTlsEnabled (void) const { + bool isTlsEnabled() const { return transportType_ == PJSIP_TRANSPORT_TLS; } @@ -264,7 +266,7 @@ class SIPAccount : public Account * @return bool Tells if current transport for that * account is set to OTHER. */ - bool isStunEnabled (void) const { + bool isStunEnabled() const { return stunEnabled_; } @@ -277,7 +279,7 @@ class SIPAccount : public Account * of the host on which the UA is running, since these are not logical * names." */ - std::string getFromUri (void) const; + std::string getFromUri() const; /* * This method adds the correct scheme, hostname and append @@ -287,7 +289,7 @@ class SIPAccount : public Account * @return pj_str_t "To" uri based on @param username * @param username A string formatted as : "username" */ - std::string getToUri (const std::string& username) const; + std::string getToUri(const std::string& username) const; /* * In the current version of SFLPhone, "srv" uri is obtained in the preformated @@ -297,19 +299,19 @@ class SIPAccount : public Account * @return pj_str_t "server" uri based on @param hostPort * @param hostPort A string formatted as : "hostname:port" */ - std::string getServerUri (void) const; + std::string getServerUri() const; /** * @param port Optional port. Otherwise set to the port defined for that account. * @param hostname Optional local address. Otherwise set to the hostname defined for that account. * @return pj_str_t The contact header based on account information */ - std::string getContactHeader (const std::string& address, const std::string& port) const; + std::string getContactHeader(const std::string& address, const std::string& port) const; /** * Get the local interface name on which this account is bound. */ - std::string getLocalInterface (void) const { + std::string getLocalInterface() const { return interface_; } @@ -327,7 +329,7 @@ class SIPAccount : public Account * actually using. * @return pj_uint16 The port used for that account */ - pj_uint16_t getLocalPort (void) const { + pj_uint16_t getLocalPort() const { return (pj_uint16_t) localPort_; } @@ -335,7 +337,7 @@ class SIPAccount : public Account * Set the new port on which this account is running over. * @pram port The port used by this account. */ - void setLocalPort (pj_uint16_t port) { + void setLocalPort(pj_uint16_t port) { localPort_ = port; } @@ -344,7 +346,7 @@ class SIPAccount : public Account * for the chosen SIP transport. * @return pj_uint16 The port used for that account */ - pj_uint16_t getPublishedPort (void) const { + pj_uint16_t getPublishedPort() const { return (pj_uint16_t) publishedPort_; } @@ -353,7 +355,7 @@ class SIPAccount : public Account * for the chosen SIP transport. * @pram port The port used by this account. */ - void setPublishedPort (pj_uint16_t port) { + void setPublishedPort(pj_uint16_t port) { publishedPort_ = port; } @@ -361,8 +363,8 @@ class SIPAccount : public Account * Get the local port for TLS listener. * @return pj_uint16 The port used for that account */ - pj_uint16_t getTlsListenerPort (void) const { - return tlsListenerPort_; + pj_uint16_t getTlsListenerPort() const { + return tlsListenerPort_; } /** @@ -371,7 +373,7 @@ class SIPAccount : public Account * will be used. * @return std::string The public IPV4 address formatted in the standard dot notation. */ - std::string getPublishedAddress (void) const { + std::string getPublishedAddress() const { return publishedIpAddress_; } @@ -380,37 +382,37 @@ class SIPAccount : public Account * @param The public IPV4 address in the standard dot notation. * @return void */ - void setPublishedAddress (const std::string& publishedIpAddress) { + void setPublishedAddress(const std::string& publishedIpAddress) { publishedIpAddress_ = publishedIpAddress; } - std::string getServiceRoute (void) const { + std::string getServiceRoute() const { return serviceRoute_; } - DtmfType getDtmfType (void) const { + DtmfType getDtmfType() const { return dtmfType_; } - bool getSrtpEnabled (void) const { + bool getSrtpEnabled() const { return srtpEnabled_; } - std::string getSrtpKeyExchange (void) const { + std::string getSrtpKeyExchange() const { return srtpKeyExchange_; } - bool getSrtpFallback (void) const { + bool getSrtpFallback() const { return srtpFallback_; } - bool getZrtpHelloHash (void) const { + bool getZrtpHelloHash() const { return zrtpHelloHash_; } - pjsip_transport* transport; - + pjsip_transport* transport_; private: + NON_COPYABLE(SIPAccount); std::vector< std::map<std::string, std::string > > credentials_; @@ -419,18 +421,18 @@ class SIPAccount : public Account * @param method The string representation * @return pjsip_ssl_method The corresponding value in the enum */ - static pjsip_ssl_method sslMethodStringToPjEnum (const std::string& method); + static pjsip_ssl_method sslMethodStringToPjEnum(const std::string& method); /* * Initializes tls settings from configuration file. * */ - void initTlsConfiguration (void); + void initTlsConfiguration(); /* * Initializes STUN config from the config file */ - void initStunConfiguration (void); + void initStunConfiguration(); /** * If username is not provided, as it happens for Direct ip calls, @@ -438,7 +440,7 @@ class SIPAccount : public Account * running this program. * @return std::string The login name under which SFLPhone is running. */ - static std::string getLoginName (void); + static std::string getLoginName(); // The pjsip client registration information pjsip_regc *regc_; diff --git a/daemon/src/sip/sipcall.cpp b/daemon/src/sip/sipcall.cpp index 6d7c4e11a91e9a3b4a8697881bfb7c2e0baf4331..dd31f3bdc387e2db9490d1602a5fc0defc73a56e 100644 --- a/daemon/src/sip/sipcall.cpp +++ b/daemon/src/sip/sipcall.cpp @@ -32,14 +32,18 @@ */ #include "sipcall.h" -#include "logger.h" // for _debug -#include "audio/audiortp/AudioRtpFactory.h" +#include "audio/audiortp/audio_rtp_factory.h" #include "sdp.h" -SIPCall::SIPCall (const std::string& id, Call::CallType type, pj_caching_pool *caching_pool) : Call (id, type) - , inv(NULL) - , _audiortp(this) - , pool_(pj_pool_create(&caching_pool->factory, id.c_str(), 16384, 16384, NULL)) +namespace { + static const int INITIAL_SIZE = 16384; + static const int INCREMENT_SIZE = INITIAL_SIZE; +} + +SIPCall::SIPCall(const std::string& id, Call::CallType type, pj_caching_pool *caching_pool) : Call(id, type) + , inv(NULL) + , audiortp_(this) + , pool_(pj_pool_create(&caching_pool->factory, id.c_str(), INITIAL_SIZE, INCREMENT_SIZE, NULL)) , local_sdp_(new Sdp(pool_)) { } @@ -47,5 +51,5 @@ SIPCall::SIPCall (const std::string& id, Call::CallType type, pj_caching_pool *c SIPCall::~SIPCall() { delete local_sdp_; - pj_pool_release (pool_); + pj_pool_release(pool_); } diff --git a/daemon/src/sip/sipcall.h b/daemon/src/sip/sipcall.h index 24c54ce23bcf42e69e93db6cfdc5aea6c1f211df..dab99795a77a66809277723be08e990e28b25248 100644 --- a/daemon/src/sip/sipcall.h +++ b/daemon/src/sip/sipcall.h @@ -33,8 +33,8 @@ #define SIPCALL_H #include "call.h" -#include <cassert> -#include "audio/audiortp/AudioRtpFactory.h" +#include "audio/audiortp/audio_rtp_factory.h" +#include "noncopyable.h" class pjsip_evsub; class pj_caching_pool; @@ -46,8 +46,7 @@ class Sdp; * @file sipcall.h * @brief SIPCall are SIP implementation of a normal Call */ -class SIPCall : public Call -{ +class SIPCall : public Call { public: /** @@ -56,31 +55,31 @@ class SIPCall : public Call * @param type The type of the call. Could be Incoming * Outgoing */ - SIPCall (const std::string& id, Call::CallType type, pj_caching_pool *caching_pool); + SIPCall(const std::string& id, Call::CallType type, pj_caching_pool *caching_pool); /** * Destructor */ - ~SIPCall (); + ~SIPCall(); /** * Return the local SDP session */ - Sdp* getLocalSDP (void) { + Sdp* getLocalSDP() { return local_sdp_; } /** * Returns a pointer to the AudioRtp object */ - sfl::AudioRtpFactory * getAudioRtp (void) { - return &_audiortp; + sfl::AudioRtpFactory & getAudioRtp() { + return audiortp_; } /** * Return the local memory pool for this call */ - pj_pool_t *getMemoryPool(void) { + pj_pool_t *getMemoryPool() { return pool_; } @@ -91,16 +90,12 @@ class SIPCall : public Call private: - // Copy Constructor - SIPCall (const SIPCall& rh); - - // Assignment Operator - SIPCall& operator= (const SIPCall& rh); + NON_COPYABLE(SIPCall); /** * Audio Rtp Session factory */ - sfl::AudioRtpFactory _audiortp; + sfl::AudioRtpFactory audiortp_; /** * The pool to allocate memory, released once call hang up diff --git a/daemon/src/sip/sipvoiplink.cpp b/daemon/src/sip/sipvoiplink.cpp index decbbf4474160f9864ba3c246f4b9fc404b9fa66..45ba05ec467259ac26c21ec10c9af368db60756e 100644 --- a/daemon/src/sip/sipvoiplink.cpp +++ b/daemon/src/sip/sipvoiplink.cpp @@ -44,13 +44,13 @@ #include "sipcall.h" #include "sipaccount.h" #include "eventthread.h" -#include "SdesNegotiator.h" +#include "sdes_negotiator.h" #include "dbus/dbusmanager.h" #include "dbus/callmanager.h" #include "hooks/urlhook.h" -#include "im/InstantMessaging.h" +#include "im/instant_messaging.h" #include "audio/audiolayer.h" @@ -76,7 +76,7 @@ using namespace sfl; namespace { -static pjsip_transport *_localUDPTransport = NULL; /** The default transport (5060) */ +static pjsip_transport *localUDPTransport_ = NULL; /** The default transport (5060) */ /** A map to retreive SFLphone internal call id * Given a SIP call ID (usefull for transaction sucha as transfer)*/ @@ -89,30 +89,30 @@ static std::map<std::string, std::string> transferCallID; * localport, localip, localexternalport * @param call a SIPCall valid pointer */ -void setCallMediaLocal (SIPCall* call, const std::string &localIP); +void setCallMediaLocal(SIPCall* call, const std::string &localIP); /** * Helper function to parser header from incoming sip messages */ -std::string fetchHeaderValue (pjsip_msg *msg, std::string field); +std::string fetchHeaderValue(pjsip_msg *msg, std::string field); -static pj_caching_pool pool_cache, *_cp = &pool_cache; -static pj_pool_t *_pool; -static pjsip_endpoint *_endpt; -static pjsip_module _mod_ua; +static pj_caching_pool pool_cache, *cp_ = &pool_cache; +static pj_pool_t *pool_; +static pjsip_endpoint *endpt_; +static pjsip_module mod_ua_; static pj_thread_t *thread; -static void sdp_media_update_cb (pjsip_inv_session *inv, pj_status_t status UNUSED); -static void sdp_request_offer_cb (pjsip_inv_session *inv, const pjmedia_sdp_session *offer); -static void sdp_create_offer_cb (pjsip_inv_session *inv, pjmedia_sdp_session **p_offer); -static void invite_session_state_changed_cb (pjsip_inv_session *inv, pjsip_event *e); -static void outgoing_request_forked_cb (pjsip_inv_session *inv, pjsip_event *e); -static void transaction_state_changed_cb (pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e); -static void registration_cb (struct pjsip_regc_cbparam *param); -static pj_bool_t transaction_request_cb (pjsip_rx_data *rdata); -static pj_bool_t transaction_response_cb (pjsip_rx_data *rdata UNUSED) ; +static void sdp_media_update_cb(pjsip_inv_session *inv, pj_status_t status UNUSED); +static void sdp_request_offer_cb(pjsip_inv_session *inv, const pjmedia_sdp_session *offer); +static void sdp_create_offer_cb(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer); +static void invite_session_state_changed_cb(pjsip_inv_session *inv, pjsip_event *e); +static void outgoing_request_forked_cb(pjsip_inv_session *inv, pjsip_event *e); +static void transaction_state_changed_cb(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e); +static void registration_cb(pjsip_regc_cbparam *param); +static pj_bool_t transaction_request_cb(pjsip_rx_data *rdata); +static pj_bool_t transaction_response_cb(pjsip_rx_data *rdata UNUSED) ; -static void transfer_client_cb (pjsip_evsub *sub, pjsip_event *event); +static void transfer_client_cb(pjsip_evsub *sub, pjsip_event *event); /** * Send a reINVITE inside an active dialog to modify its state @@ -124,38 +124,41 @@ int SIPSessionReinvite(SIPCall *); /** * Helper function to process refer function on call transfer */ -void onCallTransfered (pjsip_inv_session *inv, pjsip_rx_data *rdata); +void onCallTransfered(pjsip_inv_session *inv, pjsip_rx_data *rdata); -std::string loadSIPLocalIP() +std::string getSIPLocalIP() { pj_sockaddr ip_addr; - if (pj_gethostip (pj_AF_INET(), &ip_addr) == PJ_SUCCESS) - return pj_inet_ntoa (ip_addr.ipv4.sin_addr); - return ""; + + if (pj_gethostip(pj_AF_INET(), &ip_addr) == PJ_SUCCESS) + return pj_inet_ntoa(ip_addr.ipv4.sin_addr); + else { + ERROR("SIPVoIPLink: Could not get local IP"); + return ""; + } } pjsip_route_hdr *createRouteSet(const std::string &route, pj_pool_t *hdr_pool) { - int port = 0; - std::string host; + int port = 0; + std::string host; size_t found = route.find(":"); + if (found != std::string::npos) { - host = route.substr(0, found); - port = atoi(route.substr(found + 1, route.length()).c_str()); - } - else { - host = route; - } - - pjsip_route_hdr *route_set = pjsip_route_hdr_create (hdr_pool); - pjsip_route_hdr *routing = pjsip_route_hdr_create (hdr_pool); - pjsip_sip_uri *url = pjsip_sip_uri_create (hdr_pool, 0); + host = route.substr(0, found); + port = atoi(route.substr(found + 1, route.length()).c_str()); + } else + host = route; + + pjsip_route_hdr *route_set = pjsip_route_hdr_create(hdr_pool); + pjsip_route_hdr *routing = pjsip_route_hdr_create(hdr_pool); + pjsip_sip_uri *url = pjsip_sip_uri_create(hdr_pool, 0); routing->name_addr.uri = (pjsip_uri*) url; pj_strdup2(hdr_pool, &url->host, host.c_str()); url->port = port; - pj_list_push_back(route_set, pjsip_hdr_clone (hdr_pool, routing)); + pj_list_push_back(route_set, pjsip_hdr_clone(hdr_pool, routing)); return route_set; } @@ -164,7 +167,7 @@ pjsip_route_hdr *createRouteSet(const std::string &route, pj_pool_t *hdr_pool) /*************************************************************************************************/ -SIPVoIPLink::SIPVoIPLink() : evThread_(new EventThread(this)) +SIPVoIPLink::SIPVoIPLink() : transportMap_(), evThread_(new EventThread(this)) { #define TRY(ret) do { \ if (ret != PJ_SUCCESS) \ @@ -178,78 +181,82 @@ SIPVoIPLink::SIPVoIPLink() : evThread_(new EventThread(this)) pj_log_set_level(6); // From 0 (min) to 6 (max) TRY(pjnath_init()); - pj_caching_pool_init (_cp, &pj_pool_factory_default_policy, 0); - _pool = pj_pool_create (&_cp->factory, "sflphone", 4000, 4000, NULL); - if (!_pool) + pj_caching_pool_init(cp_, &pj_pool_factory_default_policy, 0); + pool_ = pj_pool_create(&cp_->factory, "sflphone", 4000, 4000, NULL); + + if (!pool_) throw VoipLinkException("UserAgent: Could not initialize memory pool"); - TRY(pjsip_endpt_create (&_cp->factory, pj_gethostname()->ptr, &_endpt)); - if (loadSIPLocalIP().empty()) + TRY(pjsip_endpt_create(&cp_->factory, pj_gethostname()->ptr, &endpt_)); + + if (getSIPLocalIP().empty()) throw VoipLinkException("UserAgent: Unable to determine network capabilities"); - TRY(pjsip_tsx_layer_init_module(_endpt)); - TRY(pjsip_ua_init_module(_endpt, NULL)); - TRY(pjsip_replaces_init_module(_endpt)); // See the Replaces specification in RFC 3891 - TRY(pjsip_100rel_init_module(_endpt)); + TRY(pjsip_tsx_layer_init_module(endpt_)); + TRY(pjsip_ua_init_module(endpt_, NULL)); + TRY(pjsip_replaces_init_module(endpt_)); // See the Replaces specification in RFC 3891 + TRY(pjsip_100rel_init_module(endpt_)); // Initialize and register sflphone module - _mod_ua.name = pj_str ( (char*) PACKAGE); - _mod_ua.id = -1; - _mod_ua.priority = PJSIP_MOD_PRIORITY_APPLICATION; - _mod_ua.on_rx_request = &transaction_request_cb; - _mod_ua.on_rx_response = &transaction_response_cb; - TRY(pjsip_endpt_register_module(_endpt, &_mod_ua)); + mod_ua_.name = pj_str((char*) PACKAGE); + mod_ua_.id = -1; + mod_ua_.priority = PJSIP_MOD_PRIORITY_APPLICATION; + mod_ua_.on_rx_request = &transaction_request_cb; + mod_ua_.on_rx_response = &transaction_response_cb; + TRY(pjsip_endpt_register_module(endpt_, &mod_ua_)); - TRY(pjsip_evsub_init_module(_endpt)); - TRY(pjsip_xfer_init_module(_endpt)); + TRY(pjsip_evsub_init_module(endpt_)); + TRY(pjsip_xfer_init_module(endpt_)); static const pjsip_inv_callback inv_cb = { - invite_session_state_changed_cb, - outgoing_request_forked_cb, - transaction_state_changed_cb, - sdp_request_offer_cb, - sdp_create_offer_cb, - sdp_media_update_cb, - NULL, - NULL, + invite_session_state_changed_cb, + outgoing_request_forked_cb, + transaction_state_changed_cb, + sdp_request_offer_cb, + sdp_create_offer_cb, + sdp_media_update_cb, + NULL, + NULL, }; - TRY(pjsip_inv_usage_init(_endpt, &inv_cb)); + TRY(pjsip_inv_usage_init(endpt_, &inv_cb)); static const pj_str_t allowed[] = { { (char*) "INFO", 4}, { (char*) "REGISTER", 8}, { (char*) "OPTIONS", 7}, { (char*) "MESSAGE", 7 } }; // //{"INVITE", 6}, {"ACK",3}, {"BYE",3}, {"CANCEL",6} - pjsip_endpt_add_capability (_endpt, &_mod_ua, PJSIP_H_ALLOW, NULL, PJ_ARRAY_SIZE (allowed), allowed); + pjsip_endpt_add_capability(endpt_, &mod_ua_, PJSIP_H_ALLOW, NULL, PJ_ARRAY_SIZE(allowed), allowed); static const pj_str_t text_plain = { (char*) "text/plain", 10 }; - pjsip_endpt_add_capability (_endpt, &_mod_ua, PJSIP_H_ACCEPT, NULL, 1, &text_plain); + pjsip_endpt_add_capability(endpt_, &mod_ua_, PJSIP_H_ACCEPT, NULL, 1, &text_plain); static const pj_str_t accepted = { (char*) "application/sdp", 15 }; - pjsip_endpt_add_capability (_endpt, &_mod_ua, PJSIP_H_ACCEPT, NULL, 1, &accepted); + pjsip_endpt_add_capability(endpt_, &mod_ua_, PJSIP_H_ACCEPT, NULL, 1, &accepted); - _debug ("UserAgent: pjsip version %s for %s initialized", pj_get_version(), PJ_OS_NAME); + DEBUG("UserAgent: pjsip version %s for %s initialized", pj_get_version(), PJ_OS_NAME); - TRY(pjsip_replaces_init_module(_endpt)); + TRY(pjsip_replaces_init_module(endpt_)); +#undef TRY evThread_->start(); } SIPVoIPLink::~SIPVoIPLink() { - delete evThread_; - pj_thread_join (thread); - pj_thread_destroy (thread); + delete evThread_; + pj_thread_join(thread); + pj_thread_destroy(thread); const pj_time_val tv = {0, 10}; - pjsip_endpt_handle_events(_endpt, &tv); - pjsip_endpt_destroy (_endpt); + pjsip_endpt_handle_events(endpt_, &tv); + pjsip_endpt_destroy(endpt_); - pj_pool_release (_pool); - pj_caching_pool_destroy (_cp); + pj_pool_release(pool_); + pj_caching_pool_destroy(cp_); pj_shutdown(); } SIPVoIPLink* SIPVoIPLink::instance() { - static SIPVoIPLink* instance = NULL; + static SIPVoIPLink* instance = NULL; + if (!instance) instance = new SIPVoIPLink; @@ -263,294 +270,308 @@ void SIPVoIPLink::terminate() {} void SIPVoIPLink::getEvent() { - static pj_thread_desc desc; + static pj_thread_desc desc; // We have to register the external thread so it could access the pjsip frameworks if (!pj_thread_is_registered()) pj_thread_register(NULL, desc, &thread); static const pj_time_val timeout = {0, 10}; - pjsip_endpt_handle_events(_endpt, &timeout); + pjsip_endpt_handle_events(endpt_, &timeout); } -void SIPVoIPLink::sendRegister (Account *a) +void SIPVoIPLink::sendRegister(Account *a) { - SIPAccount *account = static_cast<SIPAccount*>(a); + SIPAccount *account = dynamic_cast<SIPAccount*>(a); createSipTransport(account); - account->setRegister(true); - account->setRegistrationState (Trying); + account->setRegister(true); + account->setRegistrationState(Trying); pjsip_regc *regc = account->getRegistrationInfo(); - if (pjsip_regc_create(_endpt, (void *) account, ®istration_cb, ®c) != PJ_SUCCESS) - throw VoipLinkException("UserAgent: Unable to create regc structure."); - std::string srvUri(account->getServerUri()); + if (pjsip_regc_create(endpt_, (void *) account, ®istration_cb, ®c) != PJ_SUCCESS) + throw VoipLinkException("UserAgent: Unable to create regc structure."); - std::string address, port; - findLocalAddressFromUri(srvUri, account->transport, address, port); + std::string srvUri(account->getServerUri()); - std::string from(account->getFromUri()); - pj_str_t pjFrom = pj_str((char*)from.c_str()); - std::string contact(account->getContactHeader(address, port)); - pj_str_t pjContact = pj_str((char*)contact.c_str()); - pj_str_t pjSrv = pj_str((char*)srvUri.c_str()); + std::string address, port; + findLocalAddressFromUri(srvUri, account->transport_, address, port); + + std::string from(account->getFromUri()); + pj_str_t pjFrom = pj_str((char*) from.c_str()); + std::string contact(account->getContactHeader(address, port)); + pj_str_t pjContact = pj_str((char*) contact.c_str()); + pj_str_t pjSrv = pj_str((char*) srvUri.c_str()); - if (pjsip_regc_init (regc, &pjSrv, &pjFrom, &pjFrom, 1, &pjContact, account->getRegistrationExpire()) != PJ_SUCCESS) - throw VoipLinkException("Unable to initialize account registration structure"); + if (pjsip_regc_init(regc, &pjSrv, &pjFrom, &pjFrom, 1, &pjContact, account->getRegistrationExpire()) != PJ_SUCCESS) + throw VoipLinkException("Unable to initialize account registration structure"); - if (!account->getServiceRoute().empty()) - pjsip_regc_set_route_set (regc, createRouteSet(account->getServiceRoute(), _pool)); + if (!account->getServiceRoute().empty()) + pjsip_regc_set_route_set(regc, createRouteSet(account->getServiceRoute(), pool_)); - pjsip_regc_set_credentials (regc, account->getCredentialCount(), account->getCredInfo()); + pjsip_regc_set_credentials(regc, account->getCredentialCount(), account->getCredInfo()); pjsip_hdr hdr_list; - pj_list_init (&hdr_list); - std::string useragent(account->getUserAgentName()); - pj_str_t pJuseragent = pj_str ((char*)useragent.c_str()); - const pj_str_t STR_USER_AGENT = { (char*) "User-Agent", 10 }; + pj_list_init(&hdr_list); + std::string useragent(account->getUserAgentName()); + pj_str_t pJuseragent = pj_str((char*) useragent.c_str()); + const pj_str_t STR_USER_AGENT = { (char*) "User-Agent", 10 }; - pjsip_generic_string_hdr *h = pjsip_generic_string_hdr_create(_pool, &STR_USER_AGENT, &pJuseragent); - pj_list_push_back (&hdr_list, (pjsip_hdr*) h); - pjsip_regc_add_headers (regc, &hdr_list); + pjsip_generic_string_hdr *h = pjsip_generic_string_hdr_create(pool_, &STR_USER_AGENT, &pJuseragent); + pj_list_push_back(&hdr_list, (pjsip_hdr*) h); + pjsip_regc_add_headers(regc, &hdr_list); pjsip_tx_data *tdata; - if (pjsip_regc_register (regc, PJ_TRUE, &tdata) != PJ_SUCCESS) - throw VoipLinkException("Unable to initialize transaction data for account registration"); - if (pjsip_regc_set_transport (regc, initTransportSelector (account->transport, _pool)) != PJ_SUCCESS) - throw VoipLinkException("Unable to set transport"); + if (pjsip_regc_register(regc, PJ_TRUE, &tdata) != PJ_SUCCESS) + throw VoipLinkException("Unable to initialize transaction data for account registration"); - // decrease transport's ref count, counter incrementation is managed when acquiring transport - pjsip_transport_dec_ref(account->transport); + if (pjsip_regc_set_transport(regc, initTransportSelector(account->transport_, pool_)) != PJ_SUCCESS) + throw VoipLinkException("Unable to set transport"); - // pjsip_regc_send increment the transport ref count by one, - if (pjsip_regc_send(regc, tdata) != PJ_SUCCESS) - throw VoipLinkException("Unable to send account registration request"); + // decrease transport's ref count, counter incrementation is managed when acquiring transport + pjsip_transport_dec_ref(account->transport_); - // Decrease transport's ref count, since coresponding reference counter decrementation - // is performed in pjsip_regc_destroy. This function is never called in SFLphone as the - // regc data structure is permanently associated to the account at first registration. - pjsip_transport_dec_ref (account->transport); + // pjsip_regc_send increment the transport ref count by one, + if (pjsip_regc_send(regc, tdata) != PJ_SUCCESS) + throw VoipLinkException("Unable to send account registration request"); - account->setRegistrationInfo (regc); + // Decrease transport's ref count, since coresponding reference counter decrementation + // is performed in pjsip_regc_destroy. This function is never called in SFLphone as the + // regc data structure is permanently associated to the account at first registration. + pjsip_transport_dec_ref(account->transport_); + + account->setRegistrationInfo(regc); } -void SIPVoIPLink::sendUnregister (Account *a) +void SIPVoIPLink::sendUnregister(Account *a) { SIPAccount *account = dynamic_cast<SIPAccount *>(a); // This may occurs if account failed to register and is in state INVALID if (!account->isRegister()) { - account->setRegistrationState (Unregistered); + account->setRegistrationState(Unregistered); return; } pjsip_regc *regc = account->getRegistrationInfo(); + if (!regc) throw VoipLinkException("Registration structure is NULL"); pjsip_tx_data *tdata = NULL; - if (pjsip_regc_unregister (regc, &tdata) != PJ_SUCCESS) + + if (pjsip_regc_unregister(regc, &tdata) != PJ_SUCCESS) throw VoipLinkException("Unable to unregister sip account"); - if (pjsip_regc_send (regc, tdata) != PJ_SUCCESS) + if (pjsip_regc_send(regc, tdata) != PJ_SUCCESS) throw VoipLinkException("Unable to send request to unregister sip account"); - account->setRegister (false); + account->setRegister(false); } -Call *SIPVoIPLink::newOutgoingCall (const std::string& id, const std::string& toUrl) +Call *SIPVoIPLink::newOutgoingCall(const std::string& id, const std::string& toUrl) { - SIPAccount *account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (Manager::instance().getAccountFromCall (id))); + SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(Manager::instance().getAccountFromCall(id))); + if (account == NULL) // TODO: We should investigate how we could get rid of this error and create a IP2IP call instead - throw VoipLinkException("Could not get account for this call"); + throw VoipLinkException("Could not get account for this call"); - SIPCall* call = new SIPCall (id, Call::Outgoing, _cp); + SIPCall* call = new SIPCall(id, Call::Outgoing, cp_); // If toUri is not a well formated sip URI, use account information to process it std::string toUri; - if((toUrl.find("sip:") != std::string::npos) or - toUrl.find("sips:") != std::string::npos) - toUri = toUrl; + + if (toUrl.find("sip:") != std::string::npos or + toUrl.find("sips:") != std::string::npos) + toUri = toUrl; else toUri = account->getToUri(toUrl); - call->setPeerNumber (toUri); - std::string localAddr(getInterfaceAddrFromName (account->getLocalInterface ())); + call->setPeerNumber(toUri); + std::string localAddr(getInterfaceAddrFromName(account->getLocalInterface())); if (localAddr == "0.0.0.0") - localAddr = loadSIPLocalIP(); + localAddr = getSIPLocalIP(); - setCallMediaLocal (call, localAddr); + setCallMediaLocal(call, localAddr); // May use the published address as well std::string addrSdp = account->isStunEnabled() ? - account->getPublishedAddress() : - getInterfaceAddrFromName(account->getLocalInterface()); + account->getPublishedAddress() : + getInterfaceAddrFromName(account->getLocalInterface()); if (addrSdp == "0.0.0.0") - addrSdp = loadSIPLocalIP(); + addrSdp = getSIPLocalIP(); // Initialize the session using ULAW as default codec in case of early media // The session should be ready to receive media once the first INVITE is sent, before // the session initialization is completed - sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec (PAYLOAD_CODEC_ULAW); + sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec(PAYLOAD_CODEC_ULAW); + if (audiocodec == NULL) { - delete call; - throw VoipLinkException ("Could not instantiate codec for early media"); + delete call; + throw VoipLinkException("Could not instantiate codec for early media"); } - try { - call->getAudioRtp()->initAudioRtpConfig (); - call->getAudioRtp()->initAudioSymmetricRtpSession (); - call->getAudioRtp()->initLocalCryptoInfo (); - call->getAudioRtp()->start (static_cast<sfl::AudioCodec *>(audiocodec)); - } catch (...) { + try { + call->getAudioRtp().initAudioRtpConfig(); + call->getAudioRtp().initAudioSymmetricRtpSession(); + call->getAudioRtp().initLocalCryptoInfo(); + call->getAudioRtp().start(static_cast<sfl::AudioCodec *>(audiocodec)); + } catch (...) { delete call; - throw VoipLinkException ("Could not start rtp session for early media"); - } + throw VoipLinkException("Could not start rtp session for early media"); + } - call->initRecFileName(toUrl); + call->initRecFileName(toUrl); - call->getLocalSDP()->setLocalIP (addrSdp); - call->getLocalSDP()->createOffer(account->getActiveCodecs()); + call->getLocalSDP()->setLocalIP(addrSdp); + call->getLocalSDP()->createOffer(account->getActiveCodecs()); - if (!SIPStartCall(call)) { - delete call; - throw VoipLinkException("Could not send outgoing INVITE request for new call"); - } + if (!SIPStartCall(call)) { + delete call; + throw VoipLinkException("Could not send outgoing INVITE request for new call"); + } - return call; + return call; } void -SIPVoIPLink::answer (Call *c) +SIPVoIPLink::answer(Call *c) { SIPCall *call = dynamic_cast<SIPCall*>(c); + if (!call) - return; + return; pjsip_tx_data *tdata; - if (pjsip_inv_answer (call->inv, PJSIP_SC_OK, NULL, NULL, &tdata) != PJ_SUCCESS) - throw VoipLinkException("Could not init invite request answer (200 OK)"); - if (pjsip_inv_send_msg (call->inv, tdata) != PJ_SUCCESS) - throw VoipLinkException("Could not send invite request answer (200 OK)"); + if (pjsip_inv_answer(call->inv, PJSIP_SC_OK, NULL, NULL, &tdata) != PJ_SUCCESS) + throw VoipLinkException("Could not init invite request answer (200 OK)"); + + if (pjsip_inv_send_msg(call->inv, tdata) != PJ_SUCCESS) + throw VoipLinkException("Could not send invite request answer (200 OK)"); - call->setConnectionState (Call::Connected); - call->setState (Call::Active); + call->setConnectionState(Call::Connected); + call->setState(Call::Active); } void -SIPVoIPLink::hangup (const std::string& id) +SIPVoIPLink::hangup(const std::string& id) { SIPCall* call = getSIPCall(id); std::string account_id(Manager::instance().getAccountFromCall(id)); - SIPAccount *account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (account_id)); + SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(account_id)); + if (account == NULL) - throw VoipLinkException("Could not find account for this call"); + throw VoipLinkException("Could not find account for this call"); pjsip_inv_session *inv = call->inv; + if (inv == NULL) throw VoipLinkException("No invite session for this call"); // Looks for sip routes - if (not (account->getServiceRoute().empty())) { + if (not account->getServiceRoute().empty()) { pjsip_route_hdr *route_set = createRouteSet(account->getServiceRoute(), inv->pool); - pjsip_dlg_set_route_set (inv->dlg, route_set); + pjsip_dlg_set_route_set(inv->dlg, route_set); } pjsip_tx_data *tdata = NULL; + // User hangup current call. Notify peer - if (pjsip_inv_end_session (inv, 404, NULL, &tdata) != PJ_SUCCESS || !tdata) + if (pjsip_inv_end_session(inv, 404, NULL, &tdata) != PJ_SUCCESS || !tdata) return; - if (pjsip_inv_send_msg (inv, tdata) != PJ_SUCCESS) + if (pjsip_inv_send_msg(inv, tdata) != PJ_SUCCESS) return; // Make sure user data is NULL in callbacks - inv->mod_data[_mod_ua.id] = NULL; + inv->mod_data[mod_ua_.id] = NULL; - if (Manager::instance().isCurrentCall (id)) - call->getAudioRtp()->stop(); + if (Manager::instance().isCurrentCall(id)) + call->getAudioRtp().stop(); - removeCall (id); + removeCall(id); } void -SIPVoIPLink::peerHungup (const std::string& id) +SIPVoIPLink::peerHungup(const std::string& id) { SIPCall* call = getSIPCall(id); // User hangup current call. Notify peer pjsip_tx_data *tdata = NULL; - if (pjsip_inv_end_session (call->inv, 404, NULL, &tdata) != PJ_SUCCESS || !tdata) + + if (pjsip_inv_end_session(call->inv, 404, NULL, &tdata) != PJ_SUCCESS || !tdata) return; - if (pjsip_inv_send_msg (call->inv, tdata) != PJ_SUCCESS) + if (pjsip_inv_send_msg(call->inv, tdata) != PJ_SUCCESS) return; // Make sure user data is NULL in callbacks - call->inv->mod_data[_mod_ua.id ] = NULL; + call->inv->mod_data[mod_ua_.id ] = NULL; - if (Manager::instance().isCurrentCall (id)) - call->getAudioRtp()->stop(); + if (Manager::instance().isCurrentCall(id)) + call->getAudioRtp().stop(); - removeCall (id); + removeCall(id); } void -SIPVoIPLink::onhold (const std::string& id) +SIPVoIPLink::onhold(const std::string& id) { SIPCall *call = getSIPCall(id); - call->setState (Call::Hold); - call->getAudioRtp()->stop(); + call->setState(Call::Hold); + call->getAudioRtp().stop(); + + Sdp *sdpSession = call->getLocalSDP(); - Sdp *sdpSession = call->getLocalSDP(); if (!sdpSession) - throw VoipLinkException("Could not find sdp session"); + throw VoipLinkException("Could not find sdp session"); sdpSession->removeAttributeFromLocalAudioMedia("sendrecv"); sdpSession->removeAttributeFromLocalAudioMedia("sendonly"); sdpSession->addAttributeToLocalAudioMedia("sendonly"); - SIPSessionReinvite (call); + SIPSessionReinvite(call); } void -SIPVoIPLink::offhold (const std::string& id) +SIPVoIPLink::offhold(const std::string& id) { - SIPCall *call = getSIPCall (id); + SIPCall *call = getSIPCall(id); + + Sdp *sdpSession = call->getLocalSDP(); - Sdp *sdpSession = call->getLocalSDP(); if (sdpSession == NULL) - throw VoipLinkException("Could not find sdp session"); + throw VoipLinkException("Could not find sdp session"); try { int pl = PAYLOAD_CODEC_ULAW; sfl::Codec *sessionMedia = sdpSession->getSessionMedia(); + if (sessionMedia) - pl = sessionMedia->getPayloadType(); + pl = sessionMedia->getPayloadType(); // Create a new instance for this codec - sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec (pl); - if (audiocodec == NULL) - throw VoipLinkException("Could not instantiate codec"); - - call->getAudioRtp()->initAudioRtpConfig (); - call->getAudioRtp()->initAudioSymmetricRtpSession (); - call->getAudioRtp()->start (static_cast<sfl::AudioCodec *>(audiocodec)); + sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec(pl); - } - catch (const SdpException &e) { - _error("UserAgent: Exception: %s", e.what()); - } - catch (...) { - throw VoipLinkException("Could not create audio rtp session"); + if (audiocodec == NULL) + throw VoipLinkException("Could not instantiate codec"); + + call->getAudioRtp().initAudioRtpConfig(); + call->getAudioRtp().initAudioSymmetricRtpSession(); + call->getAudioRtp().start(static_cast<sfl::AudioCodec *>(audiocodec)); + } catch (const SdpException &e) { + ERROR("UserAgent: Exception: %s", e.what()); + } catch (...) { + throw VoipLinkException("Could not create audio rtp session"); } sdpSession->removeAttributeFromLocalAudioMedia("sendrecv"); @@ -558,135 +579,139 @@ SIPVoIPLink::offhold (const std::string& id) sdpSession->addAttributeToLocalAudioMedia("sendrecv"); if (SIPSessionReinvite(call) == PJ_SUCCESS) - call->setState (Call::Active); + call->setState(Call::Active); } void -SIPVoIPLink::sendTextMessage (sfl::InstantMessaging *module, const std::string& callID, const std::string& message, const std::string& from) +SIPVoIPLink::sendTextMessage(sfl::InstantMessaging *module, const std::string& callID, const std::string& message, const std::string& from) { SIPCall *call; + try { - call = getSIPCall (callID); - } - catch (const VoipLinkException &e) { + call = getSIPCall(callID); + } catch (const VoipLinkException &e) { return; } - /* Send IM message */ - sfl::InstantMessaging::UriList list; - sfl::InstantMessaging::UriEntry entry; - entry[sfl::IM_XML_URI] = std::string ("\"" + from + "\""); // add double quotes for xml formating + /* Send IM message */ + sfl::InstantMessaging::UriList list; + sfl::InstantMessaging::UriEntry entry; + entry[sfl::IM_XML_URI] = std::string("\"" + from + "\""); // add double quotes for xml formating - list.push_front (entry); + list.push_front(entry); - module->send_sip_message (call->inv, callID, module->appendUriList (message, list)); + module->send_sip_message(call->inv, callID, module->appendUriList(message, list)); } bool SIPVoIPLink::transferCommon(SIPCall *call, pj_str_t *dst) { pjsip_evsub_user xfer_cb; - pj_bzero (&xfer_cb, sizeof (xfer_cb)); + pj_bzero(&xfer_cb, sizeof(xfer_cb)); xfer_cb.on_evsub_state = &transfer_client_cb; pjsip_evsub *sub; - if (pjsip_xfer_create_uac (call->inv->dlg, &xfer_cb, &sub) != PJ_SUCCESS) - return false; + + if (pjsip_xfer_create_uac(call->inv->dlg, &xfer_cb, &sub) != PJ_SUCCESS) + return false; /* Associate this voiplink of call with the client subscription * We can not just associate call with the client subscription * because after this function, we can no find the cooresponding * voiplink from the call any more. But the voiplink is useful! */ - pjsip_evsub_set_mod_data (sub, _mod_ua.id, this); + pjsip_evsub_set_mod_data(sub, mod_ua_.id, this); /* * Create REFER request. */ pjsip_tx_data *tdata; - if (pjsip_xfer_initiate (sub, dst, &tdata) != PJ_SUCCESS) - return false; + if (pjsip_xfer_initiate(sub, dst, &tdata) != PJ_SUCCESS) + return false; // Put SIP call id in map in order to retrieve call during transfer callback std::string callidtransfer(call->inv->dlg->call_id->id.ptr, call->inv->dlg->call_id->id.slen); transferCallID[callidtransfer] = call->getCallId(); /* Send. */ - if (pjsip_xfer_send_request (sub, tdata) != PJ_SUCCESS) - return false; + if (pjsip_xfer_send_request(sub, tdata) != PJ_SUCCESS) + return false; return true; } void -SIPVoIPLink::transfer (const std::string& id, const std::string& to) +SIPVoIPLink::transfer(const std::string& id, const std::string& to) { SIPCall *call = getSIPCall(id); call->stopRecording(); std::string account_id(Manager::instance().getAccountFromCall(id)); - SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount (account_id)); + SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(account_id)); + if (account == NULL) - throw VoipLinkException("Could not find account"); + throw VoipLinkException("Could not find account"); std::string toUri; - pj_str_t dst = { NULL, 0 }; + pj_str_t dst = { 0, 0 }; - if (to.find ("@") == std::string::npos) { + if (to.find("@") == std::string::npos) { toUri = account->getToUri(to); - pj_cstr (&dst, toUri.c_str()); + pj_cstr(&dst, toUri.c_str()); } if (!transferCommon(getSIPCall(id), &dst)) - throw VoipLinkException("Couldn't transfer"); + throw VoipLinkException("Couldn't transfer"); } bool SIPVoIPLink::attendedTransfer(const std::string& id, const std::string& to) { - pjsip_dialog *target_dlg = getSIPCall(to)->inv->dlg; - pjsip_uri *uri = (pjsip_uri*) pjsip_uri_get_uri(target_dlg->remote.info->uri); + pjsip_dialog *target_dlg = getSIPCall(to)->inv->dlg; + pjsip_uri *uri = (pjsip_uri*) pjsip_uri_get_uri(target_dlg->remote.info->uri); - char str_dest_buf[PJSIP_MAX_URL_SIZE*2] = { '<' }; - pj_str_t dst = { str_dest_buf, 1 }; + char str_dest_buf[PJSIP_MAX_URL_SIZE*2] = { '<' }; + pj_str_t dst = { str_dest_buf, 1 }; dst.slen += pjsip_uri_print(PJSIP_URI_IN_REQ_URI, uri, str_dest_buf+1, sizeof(str_dest_buf)-1); dst.slen += pj_ansi_snprintf(str_dest_buf + dst.slen, - sizeof(str_dest_buf) - dst.slen, - "?" - "Replaces=%.*s" - "%%3Bto-tag%%3D%.*s" - "%%3Bfrom-tag%%3D%.*s>", - (int)target_dlg->call_id->id.slen, - target_dlg->call_id->id.ptr, - (int)target_dlg->remote.info->tag.slen, - target_dlg->remote.info->tag.ptr, - (int)target_dlg->local.info->tag.slen, - target_dlg->local.info->tag.ptr); + sizeof(str_dest_buf) - dst.slen, + "?" + "Replaces=%.*s" + "%%3Bto-tag%%3D%.*s" + "%%3Bfrom-tag%%3D%.*s>", + (int)target_dlg->call_id->id.slen, + target_dlg->call_id->id.ptr, + (int)target_dlg->remote.info->tag.slen, + target_dlg->remote.info->tag.ptr, + (int)target_dlg->local.info->tag.slen, + target_dlg->local.info->tag.ptr); return transferCommon(getSIPCall(id), &dst); } void -SIPVoIPLink::refuse (const std::string& id) +SIPVoIPLink::refuse(const std::string& id) { - SIPCall *call = getSIPCall (id); + SIPCall *call = getSIPCall(id); + if (!call->isIncoming() or call->getConnectionState() == Call::Connected) return; - call->getAudioRtp()->stop(); + call->getAudioRtp().stop(); pjsip_tx_data *tdata; - if (pjsip_inv_end_session (call->inv, PJSIP_SC_DECLINE, NULL, &tdata) != PJ_SUCCESS) + + if (pjsip_inv_end_session(call->inv, PJSIP_SC_DECLINE, NULL, &tdata) != PJ_SUCCESS) return; - if (pjsip_inv_send_msg (call->inv, tdata) != PJ_SUCCESS) + if (pjsip_inv_send_msg(call->inv, tdata) != PJ_SUCCESS) return; // Make sure the pointer is NULL in callbacks - call->inv->mod_data[_mod_ua.id] = NULL; + call->inv->mod_data[mod_ua_.id] = NULL; - removeCall (id); + removeCall(id); } std::string @@ -696,34 +721,36 @@ SIPVoIPLink::getCurrentCodecName(Call *call) const } void -SIPVoIPLink::carryingDTMFdigits (const std::string& id, char code) +SIPVoIPLink::carryingDTMFdigits(const std::string& id, char code) { std::string accountID(Manager::instance().getAccountFromCall(id)); SIPAccount *account = static_cast<SIPAccount*>(Manager::instance().getAccount(accountID)); + if (account) try { - dtmfSend(getSIPCall(id), code, account->getDtmfType()); - } catch (VoipLinkException) { - // don't do anything if call doesn't exist - } + dtmfSend(getSIPCall(id), code, account->getDtmfType()); + } catch (VoipLinkException) { + // don't do anything if call doesn't exist + } } void -SIPVoIPLink::dtmfSend (SIPCall *call, char code, DtmfType dtmf) +SIPVoIPLink::dtmfSend(SIPCall *call, char code, DtmfType dtmf) { - if (dtmf == OVERRTP) { - call->getAudioRtp()->sendDtmfDigit(code - '0'); - return; - } + if (dtmf == OVERRTP) { + call->getAudioRtp().sendDtmfDigit(code - '0'); + return; + } - // else : dtmf == SIPINFO + // else : dtmf == SIPINFO pj_str_t methodName = pj_str((char*)"INFO"); pjsip_method method; - pjsip_method_init_np (&method, &methodName); + pjsip_method_init_np(&method, &methodName); /* Create request message. */ pjsip_tx_data *tdata; - if (pjsip_dlg_create_request (call->inv->dlg, &method, -1, &tdata) != PJ_SUCCESS) + + if (pjsip_dlg_create_request(call->inv->dlg, &method, -1, &tdata) != PJ_SUCCESS) return; int duration = Manager::instance().voipPreferences.getPulseLength(); @@ -734,12 +761,12 @@ SIPVoIPLink::dtmfSend (SIPCall *call, char code, DtmfType dtmf) pj_str_t content = pj_str(dtmf_body); pj_str_t type = pj_str((char*)"application"); pj_str_t subtype = pj_str((char*)"dtmf-relay"); - tdata->msg->body = pjsip_msg_body_create (tdata->pool, &type, &subtype, &content); + tdata->msg->body = pjsip_msg_body_create(tdata->pool, &type, &subtype, &content); if (tdata->msg->body == NULL) - pjsip_tx_data_dec_ref (tdata); + pjsip_tx_data_dec_ref(tdata); else - pjsip_dlg_send_request (call->inv->dlg, tdata, _mod_ua.id, NULL); + pjsip_dlg_send_request(call->inv->dlg, tdata, mod_ua_.id, NULL); } bool @@ -747,57 +774,58 @@ SIPVoIPLink::SIPStartCall(SIPCall *call) { std::string id(Manager::instance().getAccountFromCall(call->getCallId())); SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(id)); + if (account == NULL) - return false; + return false; std::string toUri(call->getPeerNumber()); // expecting a fully well formed sip uri std::string address, port; - findLocalAddressFromUri(toUri, account->transport, address, port); + findLocalAddressFromUri(toUri, account->transport_, address, port); std::string from(account->getFromUri()); - pj_str_t pjFrom = pj_str((char*)from.c_str()); + pj_str_t pjFrom = pj_str((char*) from.c_str()); std::string contact(account->getContactHeader(address, port)); - pj_str_t pjContact = pj_str((char*)contact.c_str()); - pj_str_t pjTo = pj_str((char*)toUri.c_str()); - - - + pj_str_t pjContact = pj_str((char*) contact.c_str()); + pj_str_t pjTo = pj_str((char*) toUri.c_str()); pjsip_dialog *dialog; - if (pjsip_dlg_create_uac (pjsip_ua_instance(), &pjFrom, &pjContact, &pjTo, NULL, &dialog) != PJ_SUCCESS) - return false; + + if (pjsip_dlg_create_uac(pjsip_ua_instance(), &pjFrom, &pjContact, &pjTo, NULL, &dialog) != PJ_SUCCESS) + return false; if (pjsip_inv_create_uac(dialog, call->getLocalSDP()->getLocalSdpSession(), 0, &call->inv) != PJ_SUCCESS) - return false; + return false; if (not account->getServiceRoute().empty()) pjsip_dlg_set_route_set(dialog, createRouteSet(account->getServiceRoute(), call->inv->pool)); - pjsip_auth_clt_set_credentials (&dialog->auth_sess, account->getCredentialCount(), account->getCredInfo()); + pjsip_auth_clt_set_credentials(&dialog->auth_sess, account->getCredentialCount(), account->getCredInfo()); - call->inv->mod_data[_mod_ua.id] = call; + call->inv->mod_data[mod_ua_.id] = call; pjsip_tx_data *tdata; + if (pjsip_inv_invite(call->inv, &tdata) != PJ_SUCCESS) - return false; + return false; - pjsip_tpselector *tp = initTransportSelector(account->transport, call->inv->pool); - if (pjsip_dlg_set_transport (dialog, tp) != PJ_SUCCESS) - return false; + pjsip_tpselector *tp = initTransportSelector(account->transport_, call->inv->pool); + + if (pjsip_dlg_set_transport(dialog, tp) != PJ_SUCCESS) + return false; if (pjsip_inv_send_msg(call->inv, tdata) != PJ_SUCCESS) - return false; + return false; - call->setConnectionState(Call::Progressing); - call->setState(Call::Active); - addCall(call); + call->setConnectionState(Call::Progressing); + call->setState(Call::Active); + addCall(call); return true; } void -SIPVoIPLink::SIPCallServerFailure (SIPCall *call) +SIPVoIPLink::SIPCallServerFailure(SIPCall *call) { std::string id(call->getCallId()); Manager::instance().callFailure(id); @@ -805,93 +833,104 @@ SIPVoIPLink::SIPCallServerFailure (SIPCall *call) } void -SIPVoIPLink::SIPCallClosed (SIPCall *call) +SIPVoIPLink::SIPCallClosed(SIPCall *call) { std::string id(call->getCallId()); if (Manager::instance().isCurrentCall(id)) - call->getAudioRtp()->stop(); + call->getAudioRtp().stop(); Manager::instance().peerHungupCall(id); removeCall(id); } void -SIPVoIPLink::SIPCallAnswered (SIPCall *call, pjsip_rx_data *rdata UNUSED) +SIPVoIPLink::SIPCallAnswered(SIPCall *call, pjsip_rx_data *rdata UNUSED) { if (call->getConnectionState() != Call::Connected) { - call->setConnectionState (Call::Connected); - call->setState (Call::Active); - Manager::instance().peerAnsweredCall (call->getCallId()); + call->setConnectionState(Call::Connected); + call->setState(Call::Active); + Manager::instance().peerAnsweredCall(call->getCallId()); } } SIPCall* -SIPVoIPLink::getSIPCall (const std::string& id) +SIPVoIPLink::getSIPCall(const std::string& id) { - SIPCall *result = dynamic_cast<SIPCall*> (getCall (id)); + SIPCall *result = dynamic_cast<SIPCall*>(getCall(id)); + if (result == NULL) throw VoipLinkException("Could not find SIPCall " + id); + return result; } -bool SIPVoIPLink::SIPNewIpToIpCall (const std::string& id, const std::string& to) +bool SIPVoIPLink::SIPNewIpToIpCall(const std::string& id, const std::string& to) { SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(IP2IP_PROFILE)); + if (!account) - return false; + return false; - SIPCall *call = new SIPCall(id, Call::Outgoing, _cp); + SIPCall *call = new SIPCall(id, Call::Outgoing, cp_); call->setCallConfiguration(Call::IPtoIP); call->initRecFileName(to); - std::string localAddress(getInterfaceAddrFromName (account->getLocalInterface ())); + std::string localAddress(getInterfaceAddrFromName(account->getLocalInterface())); + if (localAddress == "0.0.0.0") - localAddress = loadSIPLocalIP(); + localAddress = getSIPLocalIP(); - setCallMediaLocal (call, localAddress); + setCallMediaLocal(call, localAddress); - std::string toUri = account->getToUri (to); - call->setPeerNumber (toUri); + std::string toUri = account->getToUri(to); + call->setPeerNumber(toUri); - sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec (PAYLOAD_CODEC_ULAW); + sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec(PAYLOAD_CODEC_ULAW); // Audio Rtp Session must be initialized before creating initial offer in SDP session // since SDES require crypto attribute. - call->getAudioRtp()->initAudioRtpConfig (); - call->getAudioRtp()->initAudioSymmetricRtpSession (); - call->getAudioRtp()->initLocalCryptoInfo (); - call->getAudioRtp()->start (static_cast<sfl::AudioCodec *>(audiocodec)); + call->getAudioRtp().initAudioRtpConfig(); + call->getAudioRtp().initAudioSymmetricRtpSession(); + call->getAudioRtp().initLocalCryptoInfo(); + call->getAudioRtp().start(static_cast<sfl::AudioCodec *>(audiocodec)); // Building the local SDP offer - call->getLocalSDP()->setLocalIP (localAddress); - call->getLocalSDP()->createOffer (account->getActiveCodecs ()); + call->getLocalSDP()->setLocalIP(localAddress); + call->getLocalSDP()->createOffer(account->getActiveCodecs()); // Init TLS transport if enabled if (account->isTlsEnabled()) { - int at = toUri.find ("@"); - int trns = toUri.find (";transport"); - std::string remoteAddr = toUri.substr (at+1, trns-at-1); + size_t at = toUri.find("@"); + size_t trns = toUri.find(";transport"); + if (at == std::string::npos or trns == std::string::npos) { + ERROR("UserAgent: Error \"@\" or \";transport\" not in URI %s", toUri.c_str()); + delete call; + return false; + } + + std::string remoteAddr(toUri.substr(at + 1, trns - at - 1)); - if (toUri.find ("sips:") != 1) { - _debug ("UserAgent: Error \"sips\" scheme required for TLS call"); + if (toUri.find("sips:") != 1) { + DEBUG("UserAgent: Error \"sips\" scheme required for TLS call"); delete call; return false; } shutdownSipTransport(account); createTlsTransport(account, remoteAddr); - if (!account->transport) { + + if (!account->transport_) { delete call; return false; } } - if (!SIPStartCall(call)) { - delete call; - return false; - } + if (!SIPStartCall(call)) { + delete call; + return false; + } return true; } @@ -901,46 +940,47 @@ bool SIPVoIPLink::SIPNewIpToIpCall (const std::string& id, const std::string& to // Private functions /////////////////////////////////////////////////////////////////////////////// -static pj_bool_t stun_sock_on_status_cb (pj_stun_sock *stun_sock UNUSED, pj_stun_sock_op op UNUSED, pj_status_t status) +static pj_bool_t stun_sock_on_status_cb(pj_stun_sock *stun_sock UNUSED, pj_stun_sock_op op UNUSED, pj_status_t status) { return status == PJ_SUCCESS; } -static pj_bool_t stun_sock_on_rx_data_cb (pj_stun_sock *stun_sock UNUSED, void *pkt UNUSED, unsigned pkt_len UNUSED, const pj_sockaddr_t *src_addr UNUSED, unsigned addr_len UNUSED) +static pj_bool_t stun_sock_on_rx_data_cb(pj_stun_sock *stun_sock UNUSED, void *pkt UNUSED, unsigned pkt_len UNUSED, const pj_sockaddr_t *src_addr UNUSED, unsigned addr_len UNUSED) { return PJ_TRUE; } -pj_status_t SIPVoIPLink::stunServerResolve (SIPAccount *account) +pj_status_t SIPVoIPLink::stunServerResolve(SIPAccount *account) { pj_stun_config stunCfg; - pj_stun_config_init (&stunCfg, &_cp->factory, 0, pjsip_endpt_get_ioqueue (_endpt), pjsip_endpt_get_timer_heap (_endpt)); + pj_stun_config_init(&stunCfg, &cp_->factory, 0, pjsip_endpt_get_ioqueue(endpt_), pjsip_endpt_get_timer_heap(endpt_)); static const pj_stun_sock_cb stun_sock_cb = { - stun_sock_on_rx_data_cb, - NULL, - stun_sock_on_status_cb + stun_sock_on_rx_data_cb, + NULL, + stun_sock_on_status_cb }; pj_stun_sock *stun_sock; - pj_status_t status = pj_stun_sock_create (&stunCfg, "stunresolve", pj_AF_INET(), &stun_sock_cb, NULL, NULL, &stun_sock); - + pj_status_t status = pj_stun_sock_create(&stunCfg, "stunresolve", pj_AF_INET(), &stun_sock_cb, NULL, NULL, &stun_sock); + pj_str_t stunServer = account->getStunServerName(); + if (status != PJ_SUCCESS) { char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror (status, errmsg, sizeof (errmsg)); - _debug ("Error creating STUN socket for %.*s: %s", (int) stunServer.slen, stunServer.ptr, errmsg); + pj_strerror(status, errmsg, sizeof(errmsg)); + DEBUG("Error creating STUN socket for %.*s: %s", (int) stunServer.slen, stunServer.ptr, errmsg); return status; } - status = pj_stun_sock_start (stun_sock, &stunServer, account->getStunPort (), NULL); + status = pj_stun_sock_start(stun_sock, &stunServer, account->getStunPort(), NULL); if (status != PJ_SUCCESS) { char errmsg[PJ_ERR_MSG_SIZE]; - pj_strerror (status, errmsg, sizeof (errmsg)); - _debug ("Error starting STUN socket for %.*s: %s", (int) stunServer.slen, stunServer.ptr, errmsg); - pj_stun_sock_destroy (stun_sock); + pj_strerror(status, errmsg, sizeof(errmsg)); + DEBUG("Error starting STUN socket for %.*s: %s", (int) stunServer.slen, stunServer.ptr, errmsg); + pj_stun_sock_destroy(stun_sock); } return status; @@ -951,89 +991,94 @@ void SIPVoIPLink::createDefaultSipUdpTransport() { SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(IP2IP_PROFILE)); createUdpTransport(account); - assert(account->transport); + assert(account->transport_); - _localUDPTransport = account->transport; + localUDPTransport_ = account->transport_; } -void SIPVoIPLink::createTlsListener (SIPAccount *account, pjsip_tpfactory **listener) +void SIPVoIPLink::createTlsListener(SIPAccount *account, pjsip_tpfactory **listener) { pj_sockaddr_in local_addr; - pj_sockaddr_in_init (&local_addr, 0, 0); + pj_sockaddr_in_init(&local_addr, 0, 0); local_addr.sin_port = pj_htons(account->getTlsListenerPort()); pj_str_t pjAddress; - pj_cstr (&pjAddress, PJ_INADDR_ANY); - pj_sockaddr_in_set_str_addr (&local_addr, &pjAddress); + pj_cstr(&pjAddress, PJ_INADDR_ANY); + pj_sockaddr_in_set_str_addr(&local_addr, &pjAddress); + std::string localIP(getSIPLocalIP()); pjsip_host_port a_name = { - pj_str((char*)loadSIPLocalIP().c_str()), - local_addr.sin_port + pj_str((char*) localIP.c_str()), + local_addr.sin_port }; - pjsip_tls_transport_start(_endpt, account->getTlsSetting(), &local_addr, &a_name, 1, listener); + pjsip_tls_transport_start(endpt_, account->getTlsSetting(), &local_addr, &a_name, 1, listener); } -void SIPVoIPLink::createTlsTransport (SIPAccount *account, std::string remoteAddr) +void SIPVoIPLink::createTlsTransport(SIPAccount *account, std::string remoteAddr) { pj_str_t remote; - pj_cstr (&remote, remoteAddr.c_str()); + pj_cstr(&remote, remoteAddr.c_str()); pj_sockaddr_in rem_addr; - pj_sockaddr_in_init (&rem_addr, &remote, (pj_uint16_t) 5061); + pj_sockaddr_in_init(&rem_addr, &remote, (pj_uint16_t) DEFAULT_SIP_TLS_PORT); static pjsip_tpfactory *localTlsListener = NULL; /** The local tls listener */ + if (localTlsListener == NULL) createTlsListener(account, &localTlsListener); - pjsip_endpt_acquire_transport(_endpt, PJSIP_TRANSPORT_TLS, &rem_addr, sizeof (rem_addr), NULL, &account->transport); + pjsip_endpt_acquire_transport(endpt_, PJSIP_TRANSPORT_TLS, &rem_addr, + sizeof rem_addr, NULL, &account->transport_); } -void SIPVoIPLink::createSipTransport (SIPAccount *account) +void SIPVoIPLink::createSipTransport(SIPAccount *account) { - shutdownSipTransport(account); + shutdownSipTransport(account); if (account->isTlsEnabled()) { std::string remoteSipUri(account->getServerUri()); - size_t sips = remoteSipUri.find ("<sips:") + 6; - size_t trns = remoteSipUri.find (";transport"); - std::string remoteAddr(remoteSipUri.substr (sips, trns-sips)); + static const char SIPS_PREFIX[] = "<sips:"; + size_t sips = remoteSipUri.find(SIPS_PREFIX) + (sizeof SIPS_PREFIX) - 1; + size_t trns = remoteSipUri.find(";transport"); + std::string remoteAddr(remoteSipUri.substr(sips, trns-sips)); createTlsTransport(account, remoteAddr); - } else if (account->isStunEnabled ()) - createStunTransport(account); + } else if (account->isStunEnabled()) + createStunTransport(account); else - createUdpTransport(account); - - if (!account->transport) { - // Could not create new transport, this transport may already exists - account->transport = transportMap_[account->getLocalPort()]; - if (account->transport) { - pjsip_transport_add_ref(account->transport); - } else { - account->transport = _localUDPTransport; - account->setLocalPort(_localUDPTransport->local_name.port); - } - } + createUdpTransport(account); + + if (!account->transport_) { + // Could not create new transport, this transport may already exists + account->transport_ = transportMap_[account->getLocalPort()]; + + if (account->transport_) + pjsip_transport_add_ref(account->transport_); + else { + account->transport_ = localUDPTransport_; + account->setLocalPort(localUDPTransport_->local_name.port); + } + } } -void SIPVoIPLink::createUdpTransport (SIPAccount *account) +void SIPVoIPLink::createUdpTransport(SIPAccount *account) { std::string listeningAddress; pj_uint16_t listeningPort = account->getLocalPort(); pj_sockaddr_in bound_addr; - pj_bzero(&bound_addr, sizeof (bound_addr)); + pj_bzero(&bound_addr, sizeof(bound_addr)); bound_addr.sin_port = pj_htons(listeningPort); bound_addr.sin_family = PJ_AF_INET; - if (account->getLocalInterface () == "default") { - listeningAddress = loadSIPLocalIP (); - bound_addr.sin_addr.s_addr = pj_htonl (PJ_INADDR_ANY); + if (account->getLocalInterface() == "default") { + listeningAddress = getSIPLocalIP(); + bound_addr.sin_addr.s_addr = pj_htonl(PJ_INADDR_ANY); } else { - listeningAddress = getInterfaceAddrFromName(account->getLocalInterface()); + listeningAddress = getInterfaceAddrFromName(account->getLocalInterface()); bound_addr.sin_addr = pj_inet_addr2(listeningAddress.c_str()); } @@ -1042,140 +1087,149 @@ void SIPVoIPLink::createUdpTransport (SIPAccount *account) listeningPort = account->getPublishedPort(); } - // We must specify this here to avoid the IP2IP_PROFILE to create a transport with name 0.0.0.0 to appear in the via header + // We must specify this here to avoid the IP2IP_PROFILE creating a + // transport with the name 0.0.0.0 appearing in the via header if (account->getAccountID() == IP2IP_PROFILE) - listeningAddress = loadSIPLocalIP(); + listeningAddress = getSIPLocalIP(); - if (listeningAddress.empty() || listeningPort == 0) + if (listeningAddress.empty() or listeningPort == 0) return; const pjsip_host_port a_name = { - pj_str((char*)listeningAddress.c_str()), - listeningPort + pj_str((char*) listeningAddress.c_str()), + listeningPort }; - pjsip_udp_transport_start(_endpt, &bound_addr, &a_name, 1, &account->transport); - pjsip_tpmgr_dump_transports(pjsip_endpt_get_tpmgr(_endpt)); // dump debug information to stdout + pjsip_udp_transport_start(endpt_, &bound_addr, &a_name, 1, &account->transport_); + pjsip_tpmgr_dump_transports(pjsip_endpt_get_tpmgr(endpt_)); // dump debug information to stdout - if (account->transport) - transportMap_[account->getLocalPort()] = account->transport; + if (account->transport_) + transportMap_[account->getLocalPort()] = account->transport_; } -pjsip_tpselector *SIPVoIPLink::initTransportSelector (pjsip_transport *transport, pj_pool_t *tp_pool) +pjsip_tpselector *SIPVoIPLink::initTransportSelector(pjsip_transport *transport, pj_pool_t *tp_pool) { - assert(transport); - pjsip_tpselector *tp = (pjsip_tpselector *) pj_pool_zalloc (tp_pool, sizeof (pjsip_tpselector)); - tp->type = PJSIP_TPSELECTOR_TRANSPORT; - tp->u.transport = transport; - return tp; + assert(transport); + pjsip_tpselector *tp = (pjsip_tpselector *) pj_pool_zalloc(tp_pool, sizeof(pjsip_tpselector)); + tp->type = PJSIP_TPSELECTOR_TRANSPORT; + tp->u.transport = transport; + return tp; } -void SIPVoIPLink::createStunTransport (SIPAccount *account) +void SIPVoIPLink::createStunTransport(SIPAccount *account) { - pj_str_t stunServer = account->getStunServerName (); - pj_uint16_t stunPort = account->getStunPort (); + pj_str_t stunServer = account->getStunServerName(); + pj_uint16_t stunPort = account->getStunPort(); if (stunServerResolve(account) != PJ_SUCCESS) { - _error("Can't resolve STUN server"); + ERROR("Can't resolve STUN server"); return; } pj_sock_t sock = PJ_INVALID_SOCKET; pj_sockaddr_in boundAddr; - if (pj_sockaddr_in_init (&boundAddr, &stunServer, 0) != PJ_SUCCESS) { - _error("Can't initialize IPv4 socket on %*s:%i", stunServer.slen, stunServer.ptr, stunPort); + + if (pj_sockaddr_in_init(&boundAddr, &stunServer, 0) != PJ_SUCCESS) { + ERROR("Can't initialize IPv4 socket on %*s:%i", stunServer.slen, stunServer.ptr, stunPort); return; } - if (pj_sock_socket (pj_AF_INET(), pj_SOCK_DGRAM(), 0, &sock) != PJ_SUCCESS) { - _error("Can't create or bind socket"); + if (pj_sock_socket(pj_AF_INET(), pj_SOCK_DGRAM(), 0, &sock) != PJ_SUCCESS) { + ERROR("Can't create or bind socket"); return; } // Query the mapped IP address and port on the 'outside' of the NAT pj_sockaddr_in pub_addr; - if (pjstun_get_mapped_addr (&_cp->factory, 1, &sock, &stunServer, stunPort, &stunServer, stunPort, &pub_addr) != PJ_SUCCESS) { - _error("Can't contact STUN server"); - pj_sock_close (sock); + + if (pjstun_get_mapped_addr(&cp_->factory, 1, &sock, &stunServer, stunPort, &stunServer, stunPort, &pub_addr) != PJ_SUCCESS) { + ERROR("Can't contact STUN server"); + pj_sock_close(sock); return; } pjsip_host_port a_name = { - pj_str (pj_inet_ntoa (pub_addr.sin_addr)), - pj_ntohs (pub_addr.sin_port) + pj_str(pj_inet_ntoa(pub_addr.sin_addr)), + pj_ntohs(pub_addr.sin_port) }; - std::string listeningAddress = std::string (a_name.host.ptr, a_name.host.slen); + std::string listeningAddress = std::string(a_name.host.ptr, a_name.host.slen); - account->setPublishedAddress (listeningAddress); - account->setPublishedPort (a_name.port); + account->setPublishedAddress(listeningAddress); + account->setPublishedPort(a_name.port); - pjsip_udp_transport_attach2 (_endpt, PJSIP_TRANSPORT_UDP, sock, &a_name, 1, &account->transport); + pjsip_udp_transport_attach2(endpt_, PJSIP_TRANSPORT_UDP, sock, &a_name, 1, + &account->transport_); - pjsip_tpmgr_dump_transports (pjsip_endpt_get_tpmgr (_endpt)); + pjsip_tpmgr_dump_transports(pjsip_endpt_get_tpmgr(endpt_)); } -void SIPVoIPLink::shutdownSipTransport (SIPAccount *account) +void SIPVoIPLink::shutdownSipTransport(SIPAccount *account) { - if (account->transport) { - pjsip_transport_dec_ref(account->transport); - account->transport = NULL; + if (account->transport_) { + pjsip_transport_dec_ref(account->transport_); + account->transport_ = NULL; } } -void SIPVoIPLink::findLocalAddressFromUri (const std::string& uri, pjsip_transport *transport, std::string& addr, std::string &port) +void SIPVoIPLink::findLocalAddressFromUri(const std::string& uri, pjsip_transport *transport, std::string& addr, std::string &port) { - std::stringstream ss; - ss << DEFAULT_SIP_PORT; - port = ss.str(); + std::stringstream ss; + ss << DEFAULT_SIP_PORT; + port = ss.str(); - pjsip_uri *genericUri = pjsip_parse_uri(_pool, (char*)uri.data(), uri.size(), 0); + pjsip_uri *genericUri = pjsip_parse_uri(pool_, (char*)uri.data(), uri.size(), 0); const pj_str_t *pjMachineName = pj_gethostname(); addr = std::string(pjMachineName->ptr, pjMachineName->slen); if (genericUri == NULL) - return; + return; + + pjsip_sip_uri *sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(genericUri); - pjsip_sip_uri *sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri (genericUri); if (sip_uri == NULL) - return; + return; pjsip_transport_type_e transportType; - if (PJSIP_URI_SCHEME_IS_SIPS (sip_uri)) { + + if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri)) { transportType = PJSIP_TRANSPORT_TLS; ss.str(""); ss << DEFAULT_SIP_TLS_PORT; port = ss.str(); } else { if (transport == NULL) - transport = _localUDPTransport; + transport = localUDPTransport_; transportType = PJSIP_TRANSPORT_UDP; } - pjsip_tpmgr *tpmgr = pjsip_endpt_get_tpmgr(_endpt); + pjsip_tpmgr *tpmgr = pjsip_endpt_get_tpmgr(endpt_); + if (!tpmgr) - return; + return; pjsip_tpselector *tp_sel = NULL; - if (transportType == PJSIP_TRANSPORT_UDP && transport) - tp_sel = initTransportSelector (transport, _pool); - pj_str_t localAddress; - int i_port; - if (pjsip_tpmgr_find_local_addr(tpmgr, _pool, transportType, tp_sel, &localAddress, &i_port) != PJ_SUCCESS) - return; + if (transportType == PJSIP_TRANSPORT_UDP and transport) + tp_sel = initTransportSelector(transport, pool_); + + pj_str_t localAddress = {0,0}; + int i_port = 0; + + if (pjsip_tpmgr_find_local_addr(tpmgr, pool_, transportType, tp_sel, &localAddress, &i_port) != PJ_SUCCESS) + return; addr = std::string(localAddress.ptr, localAddress.slen); if (addr == "0.0.0.0") - addr = loadSIPLocalIP(); + addr = getSIPLocalIP(); ss.str(""); ss << i_port; @@ -1187,48 +1241,54 @@ namespace { std::string parseDisplayName(const char * buffer) { // Parse the display name from "From" header - const char* from_header = strstr (buffer, "From: "); + const char* from_header = strstr(buffer, "From: "); + if (!from_header) - return ""; + return ""; - std::string temp(from_header); - size_t begin_displayName = temp.find ("\"") + 1; - size_t end_displayName = temp.rfind ("\""); - std::string displayName(temp.substr(begin_displayName, end_displayName - begin_displayName)); + std::string temp(from_header); + size_t begin_displayName = temp.find("\"") + 1; + size_t end_displayName = temp.rfind("\""); + std::string displayName(temp.substr(begin_displayName, end_displayName - begin_displayName)); - if (displayName.size() > 25) - return ""; - return displayName; + static const size_t MAX_DISPLAY_NAME_SIZE = 25; + if (displayName.size() > MAX_DISPLAY_NAME_SIZE) + return ""; + + return displayName; } void stripSipUriPrefix(std::string& sipUri) { - //Remove sip: prefix - size_t found = sipUri.find("sip:"); + // Remove sip: prefix + static const char SIP_PREFIX[] = "sip:"; + size_t found = sipUri.find(SIP_PREFIX); if (found != std::string::npos) - sipUri.erase (found, found + 4); + sipUri.erase(found, found + (sizeof SIP_PREFIX) - 1); - found = sipUri.find ("@"); + found = sipUri.find("@"); if (found != std::string::npos) - sipUri.erase(found); + sipUri.erase(found); } -int SIPSessionReinvite (SIPCall *call) +int SIPSessionReinvite(SIPCall *call) { pjsip_tx_data *tdata; pjmedia_sdp_session *local_sdp = call->getLocalSDP()->getLocalSdpSession(); + if (local_sdp && pjsip_inv_reinvite(call->inv, NULL, local_sdp, &tdata) == PJ_SUCCESS) - return pjsip_inv_send_msg (call->inv, tdata); + return pjsip_inv_send_msg(call->inv, tdata); return !PJ_SUCCESS; } -void invite_session_state_changed_cb (pjsip_inv_session *inv, pjsip_event *e) +void invite_session_state_changed_cb(pjsip_inv_session *inv, pjsip_event *e) { - SIPCall *call = reinterpret_cast<SIPCall*> (inv->mod_data[_mod_ua.id]); + SIPCall *call = reinterpret_cast<SIPCall*>(inv->mod_data[mod_ua_.id]); + if (call == NULL) return; @@ -1238,30 +1298,33 @@ void invite_session_state_changed_cb (pjsip_inv_session *inv, pjsip_event *e) // Update UI with the current status code and description pjsip_transaction * tsx = e->body.tsx_state.tsx; int statusCode = tsx ? tsx->status_code : 404; + if (statusCode) { - const pj_str_t * description = pjsip_get_status_text (statusCode); - Manager::instance().getDbusManager()->getCallManager()->sipCallStateChanged (call->getCallId(), std::string (description->ptr, description->slen), statusCode); + const pj_str_t * description = pjsip_get_status_text(statusCode); + Manager::instance().getDbusManager()->getCallManager()->sipCallStateChanged(call->getCallId(), std::string(description->ptr, description->slen), statusCode); } } if (inv->state == PJSIP_INV_STATE_EARLY and e->body.tsx_state.tsx->role == PJSIP_ROLE_UAC) { - call->setConnectionState (Call::Ringing); - Manager::instance().peerRingingCall (call->getCallId()); + call->setConnectionState(Call::Ringing); + Manager::instance().peerRingingCall(call->getCallId()); } else if (inv->state == PJSIP_INV_STATE_CONFIRMED) { - // After we sent or received a ACK - The connection is established - link->SIPCallAnswered (call, e->body.tsx_state.src.rdata); + // After we sent or received a ACK - The connection is established + link->SIPCallAnswered(call, e->body.tsx_state.src.rdata); } else if (inv->state == PJSIP_INV_STATE_DISCONNECTED) { - std::string accId(Manager::instance().getAccountFromCall (call->getCallId())); + std::string accId(Manager::instance().getAccountFromCall(call->getCallId())); switch (inv->cause) { - // The call terminates normally - BYE / CANCEL + // The call terminates normally - BYE / CANCEL case PJSIP_SC_OK: case PJSIP_SC_REQUEST_TERMINATED: - link->SIPCallClosed (call); + link->SIPCallClosed(call); break; case PJSIP_SC_DECLINE: + if (inv->role != PJSIP_ROLE_UAC) - break; + break; + case PJSIP_SC_NOT_FOUND: case PJSIP_SC_REQUEST_TIMEOUT: case PJSIP_SC_NOT_ACCEPTABLE_HERE: /* no compatible codecs */ @@ -1272,44 +1335,45 @@ void invite_session_state_changed_cb (pjsip_inv_session *inv, pjsip_event *e) case PJSIP_SC_REQUEST_PENDING: case PJSIP_SC_ADDRESS_INCOMPLETE: default: - link->SIPCallServerFailure (call); + link->SIPCallServerFailure(call); break; } } } -void sdp_request_offer_cb (pjsip_inv_session *inv, const pjmedia_sdp_session *offer) +void sdp_request_offer_cb(pjsip_inv_session *inv, const pjmedia_sdp_session *offer) { - SIPCall *call = (SIPCall*) inv->mod_data[_mod_ua.id ]; + SIPCall *call = (SIPCall*) inv->mod_data[mod_ua_.id ]; + if (!call) return; std::string accId(Manager::instance().getAccountFromCall(call->getCallId())); SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(accId)); - call->getLocalSDP()->receiveOffer (offer, account->getActiveCodecs()); + call->getLocalSDP()->receiveOffer(offer, account->getActiveCodecs()); call->getLocalSDP()->startNegotiation(); - pjsip_inv_set_sdp_answer (call->inv, call->getLocalSDP()->getLocalSdpSession()); + pjsip_inv_set_sdp_answer(call->inv, call->getLocalSDP()->getLocalSdpSession()); } -static void sdp_create_offer_cb (pjsip_inv_session *inv, pjmedia_sdp_session **p_offer) +static void sdp_create_offer_cb(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer) { - SIPCall *call = reinterpret_cast<SIPCall*>(inv->mod_data[_mod_ua.id]); + SIPCall *call = reinterpret_cast<SIPCall*>(inv->mod_data[mod_ua_.id]); std::string accountid(Manager::instance().getAccountFromCall(call->getCallId())); SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(accountid)); - std::string localAddress(SIPVoIPLink::instance()->getInterfaceAddrFromName(account->getLocalInterface ())); + std::string localAddress(SIPVoIPLink::instance()->getInterfaceAddrFromName(account->getLocalInterface())); std::string addrSdp(localAddress); if (localAddress == "0.0.0.0") - localAddress = loadSIPLocalIP(); + localAddress = getSIPLocalIP(); if (addrSdp == "0.0.0.0") addrSdp = localAddress; - setCallMediaLocal (call, localAddress); + setCallMediaLocal(call, localAddress); call->getLocalSDP()->setLocalIP(addrSdp); call->getLocalSDP()->createOffer(account->getActiveCodecs()); @@ -1318,26 +1382,27 @@ static void sdp_create_offer_cb (pjsip_inv_session *inv, pjmedia_sdp_session **p } // This callback is called after SDP offer/answer session has completed. -void sdp_media_update_cb (pjsip_inv_session *inv, pj_status_t status) +void sdp_media_update_cb(pjsip_inv_session *inv, pj_status_t status) { const pjmedia_sdp_session *remote_sdp; const pjmedia_sdp_session *local_sdp; - SIPCall *call = reinterpret_cast<SIPCall *> (inv->mod_data[_mod_ua.id]); + SIPCall *call = reinterpret_cast<SIPCall *>(inv->mod_data[mod_ua_.id]); + if (call == NULL) { - _debug ("UserAgent: Call declined by peer, SDP negotiation stopped"); + DEBUG("UserAgent: Call declined by peer, SDP negotiation stopped"); return; } if (status != PJ_SUCCESS) { - _warn ("UserAgent: Error: while negotiating the offer"); - SIPVoIPLink::instance()->hangup (call->getCallId()); - Manager::instance().callFailure (call->getCallId()); + WARN("UserAgent: Error: while negotiating the offer"); + SIPVoIPLink::instance()->hangup(call->getCallId()); + Manager::instance().callFailure(call->getCallId()); return; } if (!inv->neg) { - _warn ("UserAgent: Error: no negotiator for this session"); + WARN("UserAgent: Error: no negotiator for this session"); return; } @@ -1345,32 +1410,32 @@ void sdp_media_update_cb (pjsip_inv_session *inv, pj_status_t status) Sdp *sdpSession = call->getLocalSDP(); // Get active session sessions - pjmedia_sdp_neg_get_active_remote (inv->neg, &remote_sdp); - pjmedia_sdp_neg_get_active_local (inv->neg, &local_sdp); + pjmedia_sdp_neg_get_active_remote(inv->neg, &remote_sdp); + pjmedia_sdp_neg_get_active_local(inv->neg, &local_sdp); // Print SDP session char buffer[1000]; - memset(buffer, 0, sizeof buffer); - pjmedia_sdp_print(remote_sdp, buffer, 1000); - _debug("SDP: Remote active SDP Session:\n%s", buffer); + memset(buffer, 0, sizeof buffer); + pjmedia_sdp_print(remote_sdp, buffer, 1000); + DEBUG("SDP: Remote active SDP Session:\n%s", buffer); - memset(buffer, 0, 1000); - pjmedia_sdp_print(local_sdp, buffer, 1000); - _debug("SDP: Local active SDP Session:\n%s", buffer); + memset(buffer, 0, 1000); + pjmedia_sdp_print(local_sdp, buffer, 1000); + DEBUG("SDP: Local active SDP Session:\n%s", buffer); - // Set active SDP sessions + // Set active SDP sessions sdpSession->setActiveRemoteSdpSession(remote_sdp); sdpSession->setActiveLocalSdpSession(local_sdp); // Update internal field for sdpSession->setMediaTransportInfoFromRemoteSdp(); - call->getAudioRtp()->updateDestinationIpAddress(); - call->getAudioRtp()->setDtmfPayloadType(sdpSession->getTelephoneEventType()); + call->getAudioRtp().updateDestinationIpAddress(); + call->getAudioRtp().setDtmfPayloadType(sdpSession->getTelephoneEventType()); // Get the crypto attribute containing srtp's cryptographic context (keys, cipher) CryptoOffer crypto_offer; - call->getLocalSDP()->getRemoteSdpCryptoFromOffer (remote_sdp, crypto_offer); + call->getLocalSDP()->getRemoteSdpCryptoFromOffer(remote_sdp, crypto_offer); bool nego_success = false; @@ -1378,32 +1443,34 @@ void sdp_media_update_cb (pjsip_inv_session *inv, pj_status_t status) std::vector<sfl::CryptoSuiteDefinition>localCapabilities; for (int i = 0; i < 3; i++) - localCapabilities.push_back (sfl::CryptoSuites[i]); + localCapabilities.push_back(sfl::CryptoSuites[i]); sfl::SdesNegotiator sdesnego(localCapabilities, crypto_offer); + if (sdesnego.negotiate()) { - _debug ("UserAgent: SDES negotiation successfull"); + DEBUG("UserAgent: SDES negotiation successfull"); nego_success = true; try { - call->getAudioRtp()->setRemoteCryptoInfo (sdesnego); + call->getAudioRtp().setRemoteCryptoInfo(sdesnego); } catch (...) {} - Manager::instance().getDbusManager()->getCallManager()->secureSdesOn (call->getCallId()); + Manager::instance().getDbusManager()->getCallManager()->secureSdesOn(call->getCallId()); } else { - Manager::instance().getDbusManager()->getCallManager()->secureSdesOff (call->getCallId()); + Manager::instance().getDbusManager()->getCallManager()->secureSdesOff(call->getCallId()); } } // We did not found any crypto context for this media, RTP fallback - if (!nego_success && call->getAudioRtp()->isSdesEnabled()) { - call->getAudioRtp()->stop(); - call->getAudioRtp()->setSrtpEnabled (false); + if (!nego_success && call->getAudioRtp().isSdesEnabled()) { + call->getAudioRtp().stop(); + call->getAudioRtp().setSrtpEnabled(false); std::string accountID = Manager::instance().getAccountFromCall(call->getCallId()); + if (((SIPAccount *) Manager::instance().getAccount(accountID))->getSrtpFallback()) - call->getAudioRtp()->initAudioSymmetricRtpSession (); + call->getAudioRtp().initAudioSymmetricRtpSession(); } if (!sdpSession) @@ -1420,34 +1487,33 @@ void sdp_media_update_cb (pjsip_inv_session *inv, pj_status_t status) Manager::instance().audioLayerMutexUnlock(); int pl = sessionMedia->getPayloadType(); - if (pl != call->getAudioRtp()->getSessionMedia()) { + + if (pl != call->getAudioRtp().getSessionMedia()) { sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec(pl); - call->getAudioRtp()->updateSessionMedia(static_cast<sfl::AudioCodec *>(audiocodec)); + call->getAudioRtp().updateSessionMedia(static_cast<sfl::AudioCodec *>(audiocodec)); } + } catch (const SdpException &e) { + ERROR("UserAgent: Exception: %s", e.what()); + } catch (const std::exception& rtpException) { + ERROR("UserAgent: Exception: %s", rtpException.what()); } - catch (const SdpException &e) { - _error("UserAgent: Exception: %s", e.what()); - } - catch (const std::exception& rtpException) { - _error ("UserAgent: Exception: %s", rtpException.what()); - } } -void outgoing_request_forked_cb (pjsip_inv_session *inv UNUSED, pjsip_event *e UNUSED) +void outgoing_request_forked_cb(pjsip_inv_session *inv UNUSED, pjsip_event *e UNUSED) { } -void transaction_state_changed_cb (pjsip_inv_session *inv UNUSED, pjsip_transaction *tsx, pjsip_event *e) +void transaction_state_changed_cb(pjsip_inv_session *inv UNUSED, pjsip_transaction *tsx, pjsip_event *e) { - assert (tsx); + assert(tsx); assert(e); if (tsx->role != PJSIP_ROLE_UAS || tsx->state != PJSIP_TSX_STATE_TRYING) - return; + return; - if (pjsip_method_cmp (&tsx->method, &pjsip_refer_method) ==0) { - onCallTransfered (inv, e->body.tsx_state.src.rdata); /** Handle the refer method **/ + if (pjsip_method_cmp(&tsx->method, &pjsip_refer_method) ==0) { + onCallTransfered(inv, e->body.tsx_state.src.rdata); /** Handle the refer method **/ return; } @@ -1455,135 +1521,141 @@ void transaction_state_changed_cb (pjsip_inv_session *inv UNUSED, pjsip_transact if (e->body.rx_msg.rdata) { pjsip_rx_data *r_data = e->body.rx_msg.rdata; - if (r_data && r_data->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD) { - std::string request = pjsip_rx_data_get_info (r_data); - _debug ("UserAgent: %s", request.c_str()); - - if (request.find ("NOTIFY") == std::string::npos && request.find ("INFO") != std::string::npos) { - pjsip_dlg_create_response (inv->dlg, r_data, PJSIP_SC_OK, NULL, &t_data); - pjsip_dlg_send_response (inv->dlg, tsx, t_data); - return; - } - } - } - - if (!e->body.tsx_state.src.rdata) - return; - - // Incoming TEXT message - - // Get the message inside the transaction - pjsip_rx_data *r_data = e->body.tsx_state.src.rdata; - std::string formatedMessage = (char*) r_data->msg_info.msg->body->data; - - // Try to determine who is the recipient of the message - SIPCall *call = reinterpret_cast<SIPCall *> (inv->mod_data[_mod_ua.id]); - if (!call) - return; - - // Respond with a 200/OK - pjsip_dlg_create_response (inv->dlg, r_data, PJSIP_SC_OK, NULL, &t_data); - pjsip_dlg_send_response (inv->dlg, tsx, t_data); - - sfl::InstantMessaging *module = Manager::instance().getInstantMessageModule(); - - try { - // retreive the recipient-list of this message - std::string urilist = module->findTextUriList (formatedMessage); - sfl::InstantMessaging::UriList list = module->parseXmlUriList (urilist); - - // If no item present in the list, peer is considered as the sender - std::string from; - if (list.empty()) { - from = call->getPeerNumber (); - } else { - from = list.front()[IM_XML_URI]; - if (from == "Me") - from = call->getPeerNumber (); - } - - // strip < and > characters in case of an IP address - if (from[0] == '<' && from[from.size()-1] == '>') - from = from.substr (1, from.size()-2); - - Manager::instance().incomingMessage(call->getCallId(), from, module->findTextMessage (formatedMessage)); - - } catch (sfl::InstantMessageException &e) { - _error ("SipVoipLink: %s", e.what()); - } + + if (r_data && r_data->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD) { + std::string request = pjsip_rx_data_get_info(r_data); + DEBUG("UserAgent: %s", request.c_str()); + + if (request.find("NOTIFY") == std::string::npos && request.find("INFO") != std::string::npos) { + pjsip_dlg_create_response(inv->dlg, r_data, PJSIP_SC_OK, NULL, &t_data); + pjsip_dlg_send_response(inv->dlg, tsx, t_data); + return; + } + } + } + + if (!e->body.tsx_state.src.rdata) + return; + + // Incoming TEXT message + + // Get the message inside the transaction + pjsip_rx_data *r_data = e->body.tsx_state.src.rdata; + std::string formatedMessage = (char*) r_data->msg_info.msg->body->data; + + // Try to determine who is the recipient of the message + SIPCall *call = reinterpret_cast<SIPCall *>(inv->mod_data[mod_ua_.id]); + + if (!call) + return; + + // Respond with a 200/OK + pjsip_dlg_create_response(inv->dlg, r_data, PJSIP_SC_OK, NULL, &t_data); + pjsip_dlg_send_response(inv->dlg, tsx, t_data); + + sfl::InstantMessaging *module = Manager::instance().getInstantMessageModule(); + + try { + // retreive the recipient-list of this message + std::string urilist = module->findTextUriList(formatedMessage); + sfl::InstantMessaging::UriList list = module->parseXmlUriList(urilist); + + // If no item present in the list, peer is considered as the sender + std::string from; + + if (list.empty()) { + from = call->getPeerNumber(); + } else { + from = list.front()[IM_XML_URI]; + + if (from == "Me") + from = call->getPeerNumber(); + } + + // strip < and > characters in case of an IP address + if (from[0] == '<' && from[from.size()-1] == '>') + from = from.substr(1, from.size()-2); + + Manager::instance().incomingMessage(call->getCallId(), from, module->findTextMessage(formatedMessage)); + + } catch (const sfl::InstantMessageException &except) { + ERROR("SipVoipLink: %s", except.what()); + } } -void registration_cb (struct pjsip_regc_cbparam *param) +void registration_cb(struct pjsip_regc_cbparam *param) { - SIPAccount *account = static_cast<SIPAccount *>(param->token); + SIPAccount *account = static_cast<SIPAccount *>(param->token); + if (account == NULL) return; - const pj_str_t *description = pjsip_get_status_text (param->code); + const pj_str_t *description = pjsip_get_status_text(param->code); if (param->code && description) { std::string state(description->ptr, description->slen); - Manager::instance().getDbusManager()->getCallManager()->registrationStateChanged (account->getAccountID(), state, param->code); - std::pair<int, std::string> details (param->code, state); + Manager::instance().getDbusManager()->getCallManager()->registrationStateChanged(account->getAccountID(), state, param->code); + std::pair<int, std::string> details(param->code, state); // TODO: there id a race condition for this ressource when closing the application - account->setRegistrationStateDetailed (details); + account->setRegistrationStateDetailed(details); } if (param->status != PJ_SUCCESS) { - account->setRegistrationState (ErrorAuth); - account->setRegister (false); + account->setRegistrationState(ErrorAuth); + account->setRegister(false); - SIPVoIPLink::instance()->shutdownSipTransport (account); + SIPVoIPLink::instance()->shutdownSipTransport(account); return; } - if (param->code < 0 || param->code >= 300) { - switch (param->code) { - case 606: - account->setRegistrationState (ErrorConfStun); - break; - - case 503: - case 408: - account->setRegistrationState (ErrorHost); - break; - - case 401: - case 403: - case 404: - account->setRegistrationState (ErrorAuth); - break; - - case 423: { // Expiration Interval Too Brief - account->doubleRegistrationExpire(); - account->registerVoIPLink(); - } - break; - - default: - account->setRegistrationState (Error); - break; - } - - account->setRegister (false); - - SIPVoIPLink::instance ()->shutdownSipTransport (account); - - } else { - if (account->isRegister()) - account->setRegistrationState (Registered); - else { - account->setRegistrationState (Unregistered); - SIPVoIPLink::instance ()->shutdownSipTransport (account); - } - } + if (param->code < 0 || param->code >= 300) { + switch (param->code) { + case 606: + account->setRegistrationState(ErrorConfStun); + break; + + case 503: + case 408: + account->setRegistrationState(ErrorHost); + break; + + case 401: + case 403: + case 404: + account->setRegistrationState(ErrorAuth); + break; + + case 423: { // Expiration Interval Too Brief + account->doubleRegistrationExpire(); + account->registerVoIPLink(); + } + break; + + default: + account->setRegistrationState(Error); + break; + } + + account->setRegister(false); + + SIPVoIPLink::instance()->shutdownSipTransport(account); + + } else { + if (account->isRegister()) + account->setRegistrationState(Registered); + else { + account->setRegistrationState(Unregistered); + SIPVoIPLink::instance()->shutdownSipTransport(account); + } + } } -static void handleIncomingOptions (pjsip_rx_data *rdata) +static void handleIncomingOptions(pjsip_rx_data *rdata) { pjsip_tx_data *tdata; - if (pjsip_endpt_create_response (_endpt, rdata, PJSIP_SC_OK, NULL, &tdata) != PJ_SUCCESS) + + if (pjsip_endpt_create_response(endpt_, rdata, PJSIP_SC_OK, NULL, &tdata) != PJ_SUCCESS) return; #define ADD_HDR(hdr) do { \ @@ -1591,7 +1663,7 @@ static void handleIncomingOptions (pjsip_rx_data *rdata) if (cap_hdr) \ pjsip_msg_add_hdr (tdata->msg, (pjsip_hdr*) pjsip_hdr_clone (tdata->pool, cap_hdr)); \ } while(0) -#define ADD_CAP(cap) ADD_HDR(pjsip_endpt_get_capability(_endpt, cap, NULL)); +#define ADD_CAP(cap) ADD_HDR(pjsip_endpt_get_capability(endpt_, cap, NULL)); ADD_CAP(PJSIP_H_ALLOW); ADD_CAP(PJSIP_H_ACCEPT); @@ -1599,84 +1671,91 @@ static void handleIncomingOptions (pjsip_rx_data *rdata) ADD_HDR(pjsip_evsub_get_allow_events_hdr(NULL)); pjsip_response_addr res_addr; - pjsip_get_response_addr (tdata->pool, rdata, &res_addr); + pjsip_get_response_addr(tdata->pool, rdata, &res_addr); - if (pjsip_endpt_send_response (_endpt, &res_addr, tdata, NULL, NULL) != PJ_SUCCESS) - pjsip_tx_data_dec_ref (tdata); + if (pjsip_endpt_send_response(endpt_, &res_addr, tdata, NULL, NULL) != PJ_SUCCESS) + pjsip_tx_data_dec_ref(tdata); } -static pj_bool_t transaction_request_cb (pjsip_rx_data *rdata) +static pj_bool_t transaction_request_cb(pjsip_rx_data *rdata) { - pjsip_method *method = &rdata->msg_info.msg->line.req.method; - if (method->id == PJSIP_ACK_METHOD && pjsip_rdata_get_dlg (rdata)) + pjsip_method *method = &rdata->msg_info.msg->line.req.method; + + if (method->id == PJSIP_ACK_METHOD && pjsip_rdata_get_dlg(rdata)) return true; - pjsip_sip_uri *sip_to_uri = (pjsip_sip_uri *) pjsip_uri_get_uri (rdata->msg_info.to->uri); - pjsip_sip_uri *sip_from_uri = (pjsip_sip_uri *) pjsip_uri_get_uri (rdata->msg_info.from->uri); + pjsip_sip_uri *sip_to_uri = (pjsip_sip_uri *) pjsip_uri_get_uri(rdata->msg_info.to->uri); + pjsip_sip_uri *sip_from_uri = (pjsip_sip_uri *) pjsip_uri_get_uri(rdata->msg_info.from->uri); std::string userName(sip_to_uri->user.ptr, sip_to_uri->user.slen); std::string server(sip_from_uri->host.ptr, sip_from_uri->host.slen); - std::string account_id(Manager::instance().getAccountIdFromNameAndServer (userName, server)); + std::string account_id(Manager::instance().getAccountIdFromNameAndServer(userName, server)); std::string displayName(parseDisplayName(rdata->msg_info.msg_buf)); if (method->id == PJSIP_OTHER_METHOD) { - pj_str_t *str = &method->name; + pj_str_t *str = &method->name; std::string request(str->ptr, str->slen); - if (request.find ("NOTIFY") != (size_t)-1) { - int voicemail; - if (sscanf((const char*)rdata->msg_info.msg->body->data, "Voice-Message: %d/", &voicemail) == 1 && voicemail != 0) - Manager::instance().startVoiceMessageNotification (account_id, voicemail); + + if (request.find("NOTIFY") != (size_t)-1) { + int voicemail; + + if (sscanf((const char*)rdata->msg_info.msg->body->data, "Voice-Message: %d/", &voicemail) == 1 && voicemail != 0) + Manager::instance().startVoiceMessageNotification(account_id, voicemail); } - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_OK, NULL, NULL, NULL); + pjsip_endpt_respond_stateless(endpt_, rdata, PJSIP_SC_OK, NULL, NULL, NULL); return true; } else if (method->id == PJSIP_OPTIONS_METHOD) { - handleIncomingOptions (rdata); + handleIncomingOptions(rdata); return true; } else if (method->id != PJSIP_INVITE_METHOD && method->id != PJSIP_ACK_METHOD) { - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, NULL, NULL, NULL); - return true; + pjsip_endpt_respond_stateless(endpt_, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, NULL, NULL, NULL); + return true; } SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(account_id)); pjmedia_sdp_session *r_sdp; pjsip_msg_body *body = rdata->msg_info.msg->body; - if (!body || pjmedia_sdp_parse (rdata->tp_info.pool, (char*) body->data, body->len, &r_sdp) != PJ_SUCCESS) - r_sdp = NULL; + + if (!body || pjmedia_sdp_parse(rdata->tp_info.pool, (char*) body->data, body->len, &r_sdp) != PJ_SUCCESS) + r_sdp = NULL; if (account->getActiveCodecs().empty()) { - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_NOT_ACCEPTABLE_HERE, NULL, NULL, NULL); + pjsip_endpt_respond_stateless(endpt_, rdata, + PJSIP_SC_NOT_ACCEPTABLE_HERE, NULL, NULL, + NULL); return false; } // Verify that we can handle the request unsigned options = 0; - if (pjsip_inv_verify_request (rdata, &options, NULL, NULL, _endpt, NULL) != PJ_SUCCESS) { - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, NULL, NULL, NULL); + + if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, endpt_, NULL) != PJ_SUCCESS) { + pjsip_endpt_respond_stateless(endpt_, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, NULL, NULL, NULL); return true; } if (Manager::instance().hookPreference.getSipEnabled()) { - std::string header_value(fetchHeaderValue (rdata->msg_info.msg, Manager::instance().hookPreference.getUrlSipField())); - UrlHook::runAction (Manager::instance().hookPreference.getUrlCommand(), header_value); + std::string header_value(fetchHeaderValue(rdata->msg_info.msg, Manager::instance().hookPreference.getUrlSipField())); + UrlHook::runAction(Manager::instance().hookPreference.getUrlCommand(), header_value); } - SIPCall* call = new SIPCall(Manager::instance().getNewCallID(), Call::Incoming, _cp); + SIPCall* call = new SIPCall(Manager::instance().getNewCallID(), Call::Incoming, cp_); Manager::instance().associateCallToAccount(call->getCallId(), account_id); - // May use the published address as well + // May use the published address as well std::string addrToUse = SIPVoIPLink::instance()->getInterfaceAddrFromName(account->getLocalInterface()); - std::string addrSdp = account->isStunEnabled() - ? account->getPublishedAddress() - : addrToUse; + std::string addrSdp = account->isStunEnabled() + ? account->getPublishedAddress() + : addrToUse; - pjsip_tpselector *tp = SIPVoIPLink::instance()->initTransportSelector (account->transport, call->getMemoryPool()); + pjsip_tpselector *tp = SIPVoIPLink::instance()->initTransportSelector(account->transport_, call->getMemoryPool()); if (addrToUse == "0.0.0.0") - addrToUse = loadSIPLocalIP(); + addrToUse = getSIPLocalIP(); if (addrSdp == "0.0.0.0") addrSdp = addrToUse; @@ -1686,130 +1765,141 @@ static pj_bool_t transaction_request_cb (pjsip_rx_data *rdata) std::string peerNumber(tmp, length); stripSipUriPrefix(peerNumber); - call->setConnectionState (Call::Progressing); - call->setPeerNumber (peerNumber); - call->setDisplayName (displayName); - call->initRecFileName (peerNumber); + call->setConnectionState(Call::Progressing); + call->setPeerNumber(peerNumber); + call->setDisplayName(displayName); + call->initRecFileName(peerNumber); - setCallMediaLocal (call, addrToUse); + setCallMediaLocal(call, addrToUse); - call->getLocalSDP()->setLocalIP (addrSdp); + call->getLocalSDP()->setLocalIP(addrSdp); - call->getAudioRtp()->initAudioRtpConfig (); - call->getAudioRtp()->initAudioSymmetricRtpSession (); + call->getAudioRtp().initAudioRtpConfig(); + call->getAudioRtp().initAudioSymmetricRtpSession(); if (rdata->msg_info.msg->body) { char sdpbuffer[1000]; - int len = rdata->msg_info.msg->body->print_body (rdata->msg_info.msg->body, sdpbuffer, sizeof sdpbuffer); + int len = rdata->msg_info.msg->body->print_body(rdata->msg_info.msg->body, sdpbuffer, sizeof sdpbuffer); + if (len == -1) // error - len = 0; + len = 0; + std::string sdpoffer(sdpbuffer, len); - size_t start = sdpoffer.find ("a=crypto:"); + size_t start = sdpoffer.find("a=crypto:"); // Found crypto header in SDP if (start != std::string::npos) { CryptoOffer crypto_offer; - crypto_offer.push_back (std::string(sdpoffer.substr (start, (sdpoffer.size() - start) - 1))); - - std::vector<sfl::CryptoSuiteDefinition>localCapabilities; - for (int i = 0; i < 3; i++) - localCapabilities.push_back (sfl::CryptoSuites[i]); - sfl::SdesNegotiator sdesnego (localCapabilities, crypto_offer); - if (sdesnego.negotiate()) { - call->getAudioRtp()->setRemoteCryptoInfo (sdesnego); - call->getAudioRtp()->initLocalCryptoInfo (); - } + crypto_offer.push_back(std::string(sdpoffer.substr(start, (sdpoffer.size() - start) - 1))); + + std::vector<sfl::CryptoSuiteDefinition>localCapabilities; + + for (int i = 0; i < 3; i++) + localCapabilities.push_back(sfl::CryptoSuites[i]); + + sfl::SdesNegotiator sdesnego(localCapabilities, crypto_offer); + + if (sdesnego.negotiate()) { + call->getAudioRtp().setRemoteCryptoInfo(sdesnego); + call->getAudioRtp().initLocalCryptoInfo(); + } } } - call->getLocalSDP()->receiveOffer (r_sdp, account->getActiveCodecs ()); + call->getLocalSDP()->receiveOffer(r_sdp, account->getActiveCodecs()); - sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec (PAYLOAD_CODEC_ULAW); - call->getAudioRtp()->start (static_cast<sfl::AudioCodec *>(audiocodec)); + sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec(PAYLOAD_CODEC_ULAW); + call->getAudioRtp().start(static_cast<sfl::AudioCodec *>(audiocodec)); pjsip_dialog* dialog; - if (pjsip_dlg_create_uas (pjsip_ua_instance(), rdata, NULL, &dialog) != PJ_SUCCESS) { - delete call; - pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, NULL, NULL); - return false; + if (pjsip_dlg_create_uas(pjsip_ua_instance(), rdata, NULL, &dialog) != PJ_SUCCESS) { + delete call; + pjsip_endpt_respond_stateless(endpt_, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, NULL, NULL); + return false; } - pjsip_inv_create_uas (dialog, rdata, call->getLocalSDP()->getLocalSdpSession(), 0, &call->inv); + pjsip_inv_create_uas(dialog, rdata, call->getLocalSDP()->getLocalSdpSession(), 0, &call->inv); - PJ_ASSERT_RETURN (pjsip_dlg_set_transport (dialog, tp) == PJ_SUCCESS, 1); + PJ_ASSERT_RETURN(pjsip_dlg_set_transport(dialog, tp) == PJ_SUCCESS, 1); - call->inv->mod_data[_mod_ua.id] = call; + call->inv->mod_data[mod_ua_.id] = call; // Check whether Replaces header is present in the request and process accordingly. pjsip_dialog *replaced_dlg; pjsip_tx_data *response; + if (pjsip_replaces_verify_request(rdata, &replaced_dlg, PJ_FALSE, &response) != PJ_SUCCESS) { - _error("Something wrong with Replaces request."); - pjsip_endpt_respond_stateless(_endpt, rdata, 500 /* internal server error */, NULL, NULL, NULL); + ERROR("Something wrong with Replaces request."); + pjsip_endpt_respond_stateless(endpt_, rdata, 500 /* internal server error */, NULL, NULL, NULL); } // Check if call has been transfered pjsip_tx_data *tdata; + if (replaced_dlg) { // If Replace header present - // Always answer the new INVITE with 200, regardless whether - // the replaced call is in early or confirmed state. - if (pjsip_inv_answer(call->inv, 200, NULL, NULL, &response) == PJ_SUCCESS) - pjsip_inv_send_msg(call->inv, response); + // Always answer the new INVITE with 200, regardless whether + // the replaced call is in early or confirmed state. + if (pjsip_inv_answer(call->inv, 200, NULL, NULL, &response) == PJ_SUCCESS) + pjsip_inv_send_msg(call->inv, response); - // Get the INVITE session associated with the replaced dialog. - pjsip_inv_session *replaced_inv = pjsip_dlg_get_inv_session(replaced_dlg); + // Get the INVITE session associated with the replaced dialog. + pjsip_inv_session *replaced_inv = pjsip_dlg_get_inv_session(replaced_dlg); - // Disconnect the "replaced" INVITE session. - if (pjsip_inv_end_session(replaced_inv, PJSIP_SC_GONE, NULL, &tdata) == PJ_SUCCESS && tdata) - pjsip_inv_send_msg(replaced_inv, tdata); + // Disconnect the "replaced" INVITE session. + if (pjsip_inv_end_session(replaced_inv, PJSIP_SC_GONE, NULL, &tdata) == PJ_SUCCESS && tdata) + pjsip_inv_send_msg(replaced_inv, tdata); } else { // Prooceed with normal call flow - PJ_ASSERT_RETURN (pjsip_inv_initial_answer (call->inv, rdata, PJSIP_SC_RINGING, NULL, NULL, &tdata) == PJ_SUCCESS, 1); - PJ_ASSERT_RETURN (pjsip_inv_send_msg (call->inv, tdata) == PJ_SUCCESS, 1); + PJ_ASSERT_RETURN(pjsip_inv_initial_answer(call->inv, rdata, PJSIP_SC_RINGING, NULL, NULL, &tdata) == PJ_SUCCESS, 1); + PJ_ASSERT_RETURN(pjsip_inv_send_msg(call->inv, tdata) == PJ_SUCCESS, 1); - call->setConnectionState (Call::Ringing); + call->setConnectionState(Call::Ringing); - Manager::instance().incomingCall (call, account_id); - Manager::instance().getAccountLink (account_id)->addCall (call); + Manager::instance().incomingCall(call, account_id); + Manager::instance().getAccountLink(account_id)->addCall(call); } return true; } -static pj_bool_t transaction_response_cb (pjsip_rx_data *rdata) +static pj_bool_t transaction_response_cb(pjsip_rx_data *rdata) { - pjsip_dialog *dlg = pjsip_rdata_get_dlg (rdata); + pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata); + if (!dlg) return PJ_SUCCESS; - pjsip_transaction *tsx = pjsip_rdata_get_tsx (rdata); - if (!tsx || tsx->method.id != PJSIP_INVITE_METHOD) + pjsip_transaction *tsx = pjsip_rdata_get_tsx(rdata); + + if (!tsx or tsx->method.id != PJSIP_INVITE_METHOD) return PJ_SUCCESS; - if (tsx->status_code / 100 == 2) { - /** - * Send an ACK message inside a transaction. PJSIP send automatically, non-2xx ACK response. - * ACK for a 2xx response must be send using this method. - */ - pjsip_tx_data *tdata; - pjsip_dlg_create_request(dlg, &pjsip_ack_method, rdata->msg_info.cseq->cseq, &tdata); - pjsip_dlg_send_request(dlg, tdata, -1, NULL); - } + if (tsx->status_code / 100 == 2) { + /** + * Send an ACK message inside a transaction. PJSIP send automatically, non-2xx ACK response. + * ACK for a 2xx response must be send using this method. + */ + pjsip_tx_data *tdata; + pjsip_dlg_create_request(dlg, &pjsip_ack_method, rdata->msg_info.cseq->cseq, &tdata); + pjsip_dlg_send_request(dlg, tdata, -1, NULL); + } return PJ_SUCCESS; } -void onCallTransfered (pjsip_inv_session *inv, pjsip_rx_data *rdata) +void onCallTransfered(pjsip_inv_session *inv, pjsip_rx_data *rdata) { - SIPCall *currentCall = reinterpret_cast<SIPCall *>(inv->mod_data[_mod_ua.id]); + SIPCall *currentCall = reinterpret_cast<SIPCall *>(inv->mod_data[mod_ua_.id]); + if (currentCall == NULL) return; static const pj_str_t str_refer_to = { (char*) "Refer-To", 8}; pjsip_generic_string_hdr *refer_to = static_cast<pjsip_generic_string_hdr*> - (pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_refer_to, NULL)); + (pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_refer_to, NULL)); + if (!refer_to) { - pjsip_dlg_respond (inv->dlg, rdata, 400, NULL, NULL, NULL); + pjsip_dlg_respond(inv->dlg, rdata, 400, NULL, NULL, NULL); return; } @@ -1817,126 +1907,138 @@ void onCallTransfered (pjsip_inv_session *inv, pjsip_rx_data *rdata) Manager::instance().hangupCall(currentCall->getCallId()); } -void transfer_client_cb (pjsip_evsub *sub, pjsip_event *event) +void transfer_client_cb(pjsip_evsub *sub, pjsip_event *event) { - switch(pjsip_evsub_get_state(sub)) { - case PJSIP_EVSUB_STATE_ACCEPTED: - pj_assert(event->type == PJSIP_EVENT_TSX_STATE && event->body.tsx_state.type == PJSIP_EVENT_RX_MSG); - break; - - case PJSIP_EVSUB_STATE_TERMINATED: - pjsip_evsub_set_mod_data (sub, _mod_ua.id, NULL); - break; - - case PJSIP_EVSUB_STATE_ACTIVE: { - - SIPVoIPLink *link = reinterpret_cast<SIPVoIPLink *>(pjsip_evsub_get_mod_data(sub, _mod_ua.id)); - if (!link or !event) - return; - - pjsip_rx_data* r_data = event->body.rx_msg.rdata; - if (!r_data) - return; - std::string request(pjsip_rx_data_get_info (r_data)); - - pjsip_status_line status_line = { 500, *pjsip_get_status_text (500) }; - if (r_data->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD and - request.find ("NOTIFY") != std::string::npos) { - pjsip_msg_body *body = r_data->msg_info.msg->body; - if (!body) - return; - - if (pj_stricmp2 (&body->content_type.type, "message") or - pj_stricmp2 (&body->content_type.subtype, "sipfrag")) - return; - - if (pjsip_parse_status_line ( (char*) body->data, body->len, &status_line) != PJ_SUCCESS) - return; - } - - std::string transferID(r_data->msg_info.cid->id.ptr, r_data->msg_info.cid->id.slen); - SIPCall *call = dynamic_cast<SIPCall *> (link->getCall(transferCallID[transferID])); - if (!call) - return; - - if (status_line.code/100 == 2) { - pjsip_tx_data *tdata; - - if (pjsip_inv_end_session (call->inv, PJSIP_SC_GONE, NULL, &tdata) == PJ_SUCCESS) - pjsip_inv_send_msg (call->inv, tdata); - - Manager::instance().hangupCall(call->getCallId()); - pjsip_evsub_set_mod_data (sub, _mod_ua.id, NULL); - } - break; - } - default: - break; - } + switch (pjsip_evsub_get_state(sub)) { + case PJSIP_EVSUB_STATE_ACCEPTED: + pj_assert(event->type == PJSIP_EVENT_TSX_STATE && event->body.tsx_state.type == PJSIP_EVENT_RX_MSG); + break; + + case PJSIP_EVSUB_STATE_TERMINATED: + pjsip_evsub_set_mod_data(sub, mod_ua_.id, NULL); + break; + + case PJSIP_EVSUB_STATE_ACTIVE: { + + SIPVoIPLink *link = reinterpret_cast<SIPVoIPLink *>(pjsip_evsub_get_mod_data(sub, mod_ua_.id)); + + if (!link or !event) + return; + + pjsip_rx_data* r_data = event->body.rx_msg.rdata; + + if (!r_data) + return; + + std::string request(pjsip_rx_data_get_info(r_data)); + + pjsip_status_line status_line = { 500, *pjsip_get_status_text(500) }; + + if (r_data->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD and + request.find("NOTIFY") != std::string::npos) { + pjsip_msg_body *body = r_data->msg_info.msg->body; + + if (!body) + return; + + if (pj_stricmp2(&body->content_type.type, "message") or + pj_stricmp2(&body->content_type.subtype, "sipfrag")) + return; + + if (pjsip_parse_status_line((char*) body->data, body->len, &status_line) != PJ_SUCCESS) + return; + } + + std::string transferID(r_data->msg_info.cid->id.ptr, r_data->msg_info.cid->id.slen); + SIPCall *call = dynamic_cast<SIPCall *>(link->getCall(transferCallID[transferID])); + + if (!call) + return; + + if (status_line.code/100 == 2) { + pjsip_tx_data *tdata; + + if (pjsip_inv_end_session(call->inv, PJSIP_SC_GONE, NULL, &tdata) == PJ_SUCCESS) + pjsip_inv_send_msg(call->inv, tdata); + + Manager::instance().hangupCall(call->getCallId()); + pjsip_evsub_set_mod_data(sub, mod_ua_.id, NULL); + } + + break; + } + default: + break; + } } -void setCallMediaLocal (SIPCall* call, const std::string &localIP) +void setCallMediaLocal(SIPCall* call, const std::string &localIP) { - std::string account_id(Manager::instance().getAccountFromCall (call->getCallId ())); - SIPAccount *account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (account_id)); + std::string account_id(Manager::instance().getAccountFromCall(call->getCallId())); + SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(account_id)); - unsigned int callLocalAudioPort = ((rand() % 27250) + 5250) * 2; + unsigned int callLocalAudioPort = ((rand() % 27250) + 5250) * 2; - unsigned int callLocalExternAudioPort = account->isStunEnabled() - ? account->getStunPort() - : callLocalAudioPort; + unsigned int callLocalExternAudioPort = account->isStunEnabled() + ? account->getStunPort() + : callLocalAudioPort; - call->setLocalIp (localIP); - call->setLocalAudioPort(callLocalAudioPort); - call->getLocalSDP()->setLocalPublishedAudioPort(callLocalExternAudioPort); + call->setLocalIp(localIP); + call->setLocalAudioPort(callLocalAudioPort); + call->getLocalSDP()->setLocalPublishedAudioPort(callLocalExternAudioPort); } -std::string fetchHeaderValue (pjsip_msg *msg, std::string field) +std::string fetchHeaderValue(pjsip_msg *msg, std::string field) { - pj_str_t name = pj_str ( (char*) field.c_str()); + pj_str_t name = pj_str((char*) field.c_str()); + + pjsip_generic_string_hdr *hdr = (pjsip_generic_string_hdr*) pjsip_msg_find_hdr_by_name(msg, &name, NULL); - pjsip_generic_string_hdr *hdr = (pjsip_generic_string_hdr*) pjsip_msg_find_hdr_by_name (msg, &name, NULL); if (!hdr) return ""; std::string value(std::string(hdr->hvalue.ptr, hdr->hvalue.slen)); - size_t pos = value.find ("\n"); + size_t pos = value.find("\n"); + if (pos == std::string::npos) return ""; - return value.substr (0, pos); + return value.substr(0, pos); } } // end anonymous namespace -std::vector<std::string> SIPVoIPLink::getAllIpInterfaceByName (void) +std::vector<std::string> SIPVoIPLink::getAllIpInterfaceByName() { static ifreq ifreqs[20]; ifconf ifconf; std::vector<std::string> ifaceList; - ifaceList.push_back ("default"); + ifaceList.push_back("default"); - ifconf.ifc_buf = (char*) (ifreqs); - ifconf.ifc_len = sizeof (ifreqs); + ifconf.ifc_buf = (char*)(ifreqs); + ifconf.ifc_len = sizeof(ifreqs); int sock = socket(AF_INET,SOCK_STREAM,0); + if (sock >= 0) { - if (ioctl (sock, SIOCGIFCONF, &ifconf) >= 0) - for (unsigned i = 0; i < ifconf.ifc_len/sizeof (struct ifreq); i++) - ifaceList.push_back (std::string (ifreqs[i].ifr_name)); - close (sock); + if (ioctl(sock, SIOCGIFCONF, &ifconf) >= 0) + for (unsigned i = 0; i < ifconf.ifc_len/sizeof(struct ifreq); i++) + ifaceList.push_back(std::string(ifreqs[i].ifr_name)); + + close(sock); } return ifaceList; } -std::string SIPVoIPLink::getInterfaceAddrFromName (const std::string &ifaceName) +std::string SIPVoIPLink::getInterfaceAddrFromName(const std::string &ifaceName) { - int fd = socket (AF_INET, SOCK_DGRAM,0); + int fd = socket(AF_INET, SOCK_DGRAM,0); + if (fd < 0) { - _error ("UserAgent: Error: could not open socket: %m"); + ERROR("UserAgent: Error: could not open socket: %m"); return ""; } @@ -1945,26 +2047,26 @@ std::string SIPVoIPLink::getInterfaceAddrFromName (const std::string &ifaceName) memset(&ifr.ifr_addr, 0, sizeof(ifr.ifr_addr)); ifr.ifr_addr.sa_family = AF_INET; - ioctl (fd, SIOCGIFADDR, &ifr); - close (fd); + ioctl(fd, SIOCGIFADDR, &ifr); + close(fd); sockaddr_in *saddr_in = (struct sockaddr_in *) &ifr.ifr_addr; return inet_ntoa(saddr_in->sin_addr); } -std::vector<std::string> SIPVoIPLink::getAllIpInterface (void) +std::vector<std::string> SIPVoIPLink::getAllIpInterface() { pj_sockaddr addrList[16]; - unsigned addrCnt = PJ_ARRAY_SIZE (addrList); + unsigned addrCnt = PJ_ARRAY_SIZE(addrList); std::vector<std::string> ifaceList; - if (pj_enum_ip_interface (pj_AF_INET(), &addrCnt, addrList) == PJ_SUCCESS) - for (unsigned i = 0; i < addrCnt; i++) { - char addr[PJ_INET_ADDRSTRLEN]; - pj_sockaddr_print (&addrList[i], addr, sizeof (addr), 0); - ifaceList.push_back (std::string (addr)); - } + if (pj_enum_ip_interface(pj_AF_INET(), &addrCnt, addrList) == PJ_SUCCESS) + for (unsigned i = 0; i < addrCnt; i++) { + char addr[PJ_INET_ADDRSTRLEN]; + pj_sockaddr_print(&addrList[i], addr, sizeof(addr), 0); + ifaceList.push_back(std::string(addr)); + } return ifaceList; } diff --git a/daemon/src/sip/sipvoiplink.h b/daemon/src/sip/sipvoiplink.h index edaa5e2fb9fc799e2172922be89650451d83fbb4..1c2fceb9bc8fe1f63814dd1cd071e8c1d748e965 100644 --- a/daemon/src/sip/sipvoiplink.h +++ b/daemon/src/sip/sipvoiplink.h @@ -32,8 +32,8 @@ * as that of the covered work. */ -#ifndef SIPVOIPLINK_H -#define SIPVOIPLINK_H +#ifndef SIPVOIPLINK_H_ +#define SIPVOIPLINK_H_ #include <map> @@ -50,7 +50,7 @@ #include "voiplink.h" namespace sfl { - class InstantMessaging; +class InstantMessaging; } class EventThread; @@ -64,45 +64,40 @@ class SIPAccount; * One SIPVoIPLink can handle multiple SIP accounts, but all the SIP accounts have all the same SIPVoIPLink */ -class SIPVoIPLink : public VoIPLink -{ - public: - - /** - * Destructor - */ - ~SIPVoIPLink(); +class SIPVoIPLink : public VoIPLink { + public: + ~SIPVoIPLink(); /** * Singleton method. Enable to retrieve the unique static instance * @return SIPVoIPLink* A pointer on the object */ - static SIPVoIPLink* instance (); + static SIPVoIPLink* instance(); /** * Try to initiate the pjsip engine/thread and set config */ - virtual void init (void); + virtual void init(); /** * Shut the library and clean up */ - virtual void terminate (void); + virtual void terminate(); /** * Event listener. Each event send by the call manager is received and handled from here */ - virtual void getEvent (void); + virtual void getEvent(); /** * Build and send SIP registration request */ - virtual void sendRegister (Account *a); + virtual void sendRegister(Account *a); /** * Build and send SIP unregistration request */ - virtual void sendUnregister (Account *a); + virtual void sendUnregister(Account *a); /** * Place a new call @@ -110,39 +105,39 @@ class SIPVoIPLink : public VoIPLink * @param toUrl The Sip address of the recipient of the call * @return Call* The current call */ - virtual Call* newOutgoingCall (const std::string& id, const std::string& toUrl); + virtual Call* newOutgoingCall(const std::string& id, const std::string& toUrl); /** * Answer the call * @param c The call */ - virtual void answer (Call *c); + virtual void answer(Call *c); /** * Hang up the call * @param id The call identifier */ - virtual void hangup (const std::string& id); + virtual void hangup(const std::string& id); /** * Hang up the call * @param id The call identifier */ - virtual void peerHungup (const std::string& id); + virtual void peerHungup(const std::string& id); /** * Put the call on hold * @param id The call identifier * @return bool True on success */ - virtual void onhold (const std::string& id); + virtual void onhold(const std::string& id); /** * Put the call off hold * @param id The call identifier * @return bool True on success */ - virtual void offhold (const std::string& id); + virtual void offhold(const std::string& id); bool transferCommon(SIPCall *call, pj_str_t *dst); @@ -151,7 +146,7 @@ class SIPVoIPLink : public VoIPLink * @param id The call identifier * @param to The recipient of the transfer */ - virtual void transfer (const std::string& id, const std::string& to); + virtual void transfer(const std::string& id, const std::string& to); /** * Attended transfer @@ -165,39 +160,39 @@ class SIPVoIPLink : public VoIPLink * Refuse the call * @param id The call identifier */ - virtual void refuse (const std::string& id); + virtual void refuse(const std::string& id); /** * Send DTMF refering to account configuration * @param id The call identifier * @param code The char code */ - virtual void carryingDTMFdigits (const std::string& id, char code); + virtual void carryingDTMFdigits(const std::string& id, char code); /** * Start a new SIP call using the IP2IP profile * @param The call id * @param The target sip uri */ - bool SIPNewIpToIpCall (const std::string& id, const std::string& to); + bool SIPNewIpToIpCall(const std::string& id, const std::string& to); /** * Tell the user that the call was answered * @param */ - void SIPCallAnswered (SIPCall *call, pjsip_rx_data *rdata); + void SIPCallAnswered(SIPCall *call, pjsip_rx_data *rdata); /** * Handling 5XX/6XX error * @param */ - void SIPCallServerFailure (SIPCall *call); + void SIPCallServerFailure(SIPCall *call); /** * Peer close the connection * @param */ - void SIPCallClosed (SIPCall *call); + void SIPCallClosed(SIPCall *call); pj_caching_pool *getMemoryPoolFactory(); @@ -206,7 +201,7 @@ class SIPVoIPLink : public VoIPLink * @param id The call identifier * @return SIPCall* A pointer on SIPCall object */ - SIPCall* getSIPCall (const std::string& id); + SIPCall* getSIPCall(const std::string& id); /** * Return the codec protocol used for this call @@ -217,7 +212,7 @@ class SIPVoIPLink : public VoIPLink /** * Retrive useragent name from account */ - std::string getUseragentName (SIPAccount *) const; + std::string getUseragentName(SIPAccount *) const; /** * List all the interfaces on the system and return @@ -227,7 +222,7 @@ class SIPVoIPLink : public VoIPLink * of IPV4 address available on all of the interfaces on * the system. */ - static std::vector<std::string> getAllIpInterface (void); + static std::vector<std::string> getAllIpInterface(); /** * List all the interfaces on the system and return @@ -237,7 +232,7 @@ class SIPVoIPLink : public VoIPLink * of interface name available on all of the interfaces on * the system. */ - static std::vector<std::string> getAllIpInterfaceByName (void); + static std::vector<std::string> getAllIpInterfaceByName(); /** * List all the interfaces on the system and return @@ -247,7 +242,7 @@ class SIPVoIPLink : public VoIPLink * of interface name available on all of the interfaces on * the system. */ - static std::string getInterfaceAddrFromName (const std::string &ifaceName); + static std::string getInterfaceAddrFromName(const std::string &ifaceName); /** * Initialize the transport selector @@ -255,12 +250,12 @@ class SIPVoIPLink : public VoIPLink * * @return A pointer to the transport selector structure */ - pjsip_tpselector *initTransportSelector (pjsip_transport *, pj_pool_t *); + pjsip_tpselector *initTransportSelector(pjsip_transport *, pj_pool_t *); /** * This function unset the transport for a given account. */ - void shutdownSipTransport (SIPAccount *account); + void shutdownSipTransport(SIPAccount *account); /** * Send a SIP message to a call identified by its callid @@ -270,7 +265,7 @@ class SIPVoIPLink : public VoIPLink * @param The actual message to be transmitted * @param The sender of this message (could be another participant of a conference) */ - void sendTextMessage (sfl::InstantMessaging *module, const std::string& callID, const std::string& message, const std::string& from); + void sendTextMessage(sfl::InstantMessaging *module, const std::string& callID, const std::string& message, const std::string& from); /** * Create the default UDP transport according ot Ip2Ip profile settings @@ -283,52 +278,48 @@ class SIPVoIPLink : public VoIPLink * @param call The current call * @return true if all is correct */ - bool SIPStartCall (SIPCall* call); - - void dtmfSend (SIPCall *call, char code, DtmfType type); + bool SIPStartCall(SIPCall* call); - /* Assignment Operator */ - SIPVoIPLink& operator= (const SIPVoIPLink& rh); + void dtmfSend(SIPCall *call, char code, DtmfType type); - /* Copy Constructor */ - SIPVoIPLink (const SIPVoIPLink& rh); + NON_COPYABLE(SIPVoIPLink); - SIPVoIPLink (); + SIPVoIPLink(); /** * Resolve public address for this account */ - pj_status_t stunServerResolve (SIPAccount *); + pj_status_t stunServerResolve(SIPAccount *); /** * Create the default TLS listener. */ - void createTlsListener (SIPAccount*, pjsip_tpfactory **listener); + void createTlsListener(SIPAccount*, pjsip_tpfactory **listener); /** * General Sip transport creation method according to the * transport type specified in account settings * @param account The account for which a transport must be created. */ - void createSipTransport (SIPAccount *account); + void createSipTransport(SIPAccount *account); /** * Create SIP UDP transport from account's setting * @param account The account for which a transport must be created. */ - void createUdpTransport (SIPAccount *account); + void createUdpTransport(SIPAccount *account); /** * Create a TLS transport from the default TLS listener from * @param account The account for which a transport must be created. */ - void createTlsTransport (SIPAccount *, std::string remoteAddr); + void createTlsTransport(SIPAccount *, std::string remoteAddr); /** * Create a UDP transport using stun server to resove public address * @param account The account for which a transport must be created. */ - void createStunTransport (SIPAccount *account); + void createStunTransport(SIPAccount *account); /** * Get the correct address to use (ie advertised) from @@ -338,7 +329,7 @@ class SIPVoIPLink : public VoIPLink * @param uri The uri from which we want to discover the address to use * @param transport The transport to use to discover the address */ - void findLocalAddressFromUri (const std::string& uri, pjsip_transport *transport, std::string &address, std::string &port); + void findLocalAddressFromUri(const std::string& uri, pjsip_transport *transport, std::string &address, std::string &port); /** * UDP Transports are stored in this map in order to retreive them in case @@ -354,5 +345,4 @@ class SIPVoIPLink : public VoIPLink friend class SIPTest; }; - -#endif +#endif // SIPVOIPLINK_H_ diff --git a/daemon/src/voiplink.cpp b/daemon/src/voiplink.cpp index 35d1a34db2caed59b6f838497cafb0da5a9e6384..6a34ea5f4cf704ba933bfbd3f17ce70d6ca49cf2 100644 --- a/daemon/src/voiplink.cpp +++ b/daemon/src/voiplink.cpp @@ -31,44 +31,47 @@ * as that of the covered work. */ +#include "call.h" #include "voiplink.h" -#include "manager.h" -VoIPLink::~VoIPLink (void) +VoIPLink::VoIPLink() : callMap_(), callMapMutex_() {} + +VoIPLink::~VoIPLink() { - ost::MutexLock m(_callMapMutex); - for (CallMap::const_iterator iter = _callMap.begin(); - iter != _callMap.end(); ++iter) + ost::MutexLock m(callMapMutex_); + + for (CallMap::const_iterator iter = callMap_.begin(); + iter != callMap_.end(); ++iter) delete iter->second; - _callMap.clear(); + callMap_.clear(); } -void VoIPLink::addCall (Call* call) +void VoIPLink::addCall(Call* call) { - if (call and getCall (call->getCallId()) == NULL) { - ost::MutexLock m(_callMapMutex); - _callMap[call->getCallId()] = call; + if (call and getCall(call->getCallId()) == NULL) { + ost::MutexLock m(callMapMutex_); + callMap_[call->getCallId()] = call; } } -void VoIPLink::removeCall (const std::string& id) +void VoIPLink::removeCall(const std::string& id) { - ost::MutexLock m(_callMapMutex); + ost::MutexLock m(callMapMutex_); - _debug ("VoipLink: removing call %s from list", id.c_str()); + DEBUG("VoipLink: removing call %s from list", id.c_str()); - delete _callMap[id]; - _callMap.erase(id); + delete callMap_[id]; + callMap_.erase(id); } -Call* VoIPLink::getCall (const std::string& id) +Call* VoIPLink::getCall(const std::string& id) { - ost::MutexLock m(_callMapMutex); - CallMap::iterator iter = _callMap.find (id); + ost::MutexLock m(callMapMutex_); + CallMap::iterator iter = callMap_.find(id); - if (iter != _callMap.end()) + if (iter != callMap_.end()) return iter->second; else return NULL; diff --git a/daemon/src/voiplink.h b/daemon/src/voiplink.h index 0936e3c4630edf4ae044d649f3731b87ef00a57a..52257afd75300cd18bb07194652ce79382c77922 100644 --- a/daemon/src/voiplink.h +++ b/daemon/src/voiplink.h @@ -35,10 +35,12 @@ #define __VOIP_LINK_H__ #include <stdexcept> +#include <map> +#include <cc++/thread.h> // for ost::Mutex -#include "call.h" - +class Call; class Account; + namespace sfl { class InstantMessaging; }; @@ -46,49 +48,44 @@ class InstantMessaging; /** Define a map that associate a Call object to a call identifier */ typedef std::map<std::string, Call*> CallMap; -class VoipLinkException : public std::runtime_error -{ +class VoipLinkException : public std::runtime_error { public: - VoipLinkException (const std::string& str="") : - std::runtime_error("UserAgent: VoipLinkException occured: " + str) {} + VoipLinkException(const std::string& str = "") : + std::runtime_error("UserAgent: VoipLinkException occured: " + str) {} }; /** * @file voiplink.h * @brief Listener and manager interface for each VoIP protocol */ -class VoIPLink -{ +class VoIPLink { public: - /** - * Virtual destructor - */ - virtual ~VoIPLink (void); - + VoIPLink(); + virtual ~VoIPLink(); /** * Virtual method * Event listener. Each event send by the call manager is received and handled from here */ - virtual void getEvent (void) = 0; + virtual void getEvent() = 0; /** * Virtual method * Try to initiate the communication layer and set config */ - virtual void init (void) = 0; + virtual void init() = 0; /** * Virtual method * Build and send account registration request */ - virtual void sendRegister (Account *a) = 0; + virtual void sendRegister(Account *a) = 0; /** * Virtual method * Build and send account unregistration request */ - virtual void sendUnregister (Account *a) = 0; + virtual void sendUnregister(Account *a) = 0; /** * Place a new call @@ -96,46 +93,46 @@ class VoIPLink * @param toUrl The address of the recipient of the call * @return Call* The current call */ - virtual Call* newOutgoingCall (const std::string& id, const std::string& toUrl) = 0; + virtual Call* newOutgoingCall(const std::string& id, const std::string& toUrl) = 0; /** * Answer the call * @param c The call */ - virtual void answer (Call *c) = 0; + virtual void answer(Call *c) = 0; /** * Hang up a call * @param id The call identifier */ - virtual void hangup (const std::string& id) = 0; + virtual void hangup(const std::string& id) = 0; /** * Peer Hung up a call * @param id The call identifier */ - virtual void peerHungup (const std::string& id) = 0; + virtual void peerHungup(const std::string& id) = 0; /** * Put a call on hold * @param id The call identifier * @return bool True on success */ - virtual void onhold (const std::string& id) = 0; + virtual void onhold(const std::string& id) = 0; /** * Resume a call from hold state * @param id The call identifier * @return bool True on success */ - virtual void offhold (const std::string& id) = 0; + virtual void offhold(const std::string& id) = 0; /** * Transfer a call to specified URI * @param id The call identifier * @param to The recipient of the call */ - virtual void transfer (const std::string& id, const std::string& to) = 0; + virtual void transfer(const std::string& id, const std::string& to) = 0; /** * Attended transfer @@ -143,20 +140,20 @@ class VoIPLink * @param The target call id * @return True on success */ - virtual bool attendedTransfer (const std::string&, const std::string&) = 0; + virtual bool attendedTransfer(const std::string&, const std::string&) = 0; /** * Refuse incoming call * @param id The call identifier */ - virtual void refuse (const std::string& id) = 0; + virtual void refuse(const std::string& id) = 0; /** * Send DTMF * @param id The call identifier * @param code The char code */ - virtual void carryingDTMFdigits (const std::string& id, char code) = 0; + virtual void carryingDTMFdigits(const std::string& id, char code) = 0; /** * Return the codec protocol used for this call @@ -172,32 +169,32 @@ class VoIPLink * @param The actual message to be transmitted * @param The sender of this message (could be another participant of a conference) */ - virtual void sendTextMessage (sfl::InstantMessaging *module, const std::string& callID, const std::string& message, const std::string& from) = 0; + virtual void sendTextMessage(sfl::InstantMessaging *module, const std::string& callID, const std::string& message, const std::string& from) = 0; /** Add a call to the call map (protected by mutex) * @param call A call pointer with a unique pointer * @return bool True if the call was unique and added */ - void addCall (Call* call); + void addCall(Call* call); /** * Get the call pointer from the call map (protected by mutex) * @param id A Call ID * @return Call* Call pointer or 0 */ - Call* getCall (const std::string& id); + Call* getCall(const std::string& id); protected: /** Contains all the calls for this Link, protected by mutex */ - CallMap _callMap; + CallMap callMap_; /** Mutex to protect call map */ - ost::Mutex _callMapMutex; + ost::Mutex callMapMutex_; /** Remove a call from the call map (protected by mutex) * @param id A Call ID */ - void removeCall (const std::string& id); + void removeCall(const std::string& id); }; #endif // __VOIP_LINK_H__ diff --git a/daemon/test/Makefile.am b/daemon/test/Makefile.am index 28d0f9ff8943894ddfa56c0906e2205b202340d0..28c269d257e34af7e9c53d885d1deba3c7911399 100644 --- a/daemon/test/Makefile.am +++ b/daemon/test/Makefile.am @@ -1,14 +1,12 @@ include ../globals.mak -TESTS_ENVIRONMENT = CODECS_PATH="$(top_builddir)/src/audio/codecs" \ - FAKE_PLUGIN_DIR="$(top_builddir)/src/plug-in/test/" \ - FAKE_PLUGIN_NAME="$(top_builddir)/src/plug-in/test/libplugintest.so" +TESTS_ENVIRONMENT = CODECS_PATH="$(top_builddir)/src/audio/codecs" check_PROGRAMS = test TESTS = run_tests.sh test_CXXFLAGS = -I . -test_LDADD = $(top_builddir)/src/libsflphone.la @LIBCRYPTO_LIBS@ @CPPUNIT_LIBS@ +test_LDADD = $(top_builddir)/src/libsflphone.la @ZRTPCPP_LIBS@ @LIBCRYPTO_LIBS@ @CPPUNIT_LIBS@ EXTRA_DIST = $(test_SOURCES) sflphoned-sample.yml history-sample.tpl run_tests.sh test_SOURCES = \ @@ -24,14 +22,8 @@ test_SOURCES = \ configurationtest.cpp \ historytest.h \ historytest.cpp \ - hookmanagertest.h \ - hookmanagertest.cpp \ numbercleanertest.h \ numbercleanertest.cpp \ - pluginmanagertest.h \ - pluginmanagertest.cpp \ - rtptest.h \ - rtptest.cpp \ sdesnegotiatortest.h \ sdesnegotiatortest.cpp \ instantmessagingtest.h \ @@ -52,13 +44,10 @@ test_SOURCES = \ echocanceltest.h \ gaincontroltest.h \ historytest.h \ - hookmanagertest.h \ instantmessagingtest.h \ mainbuffertest.h \ numbercleanertest.h \ - pluginmanagertest.h \ ringtonetest.h \ - rtptest.h \ sdesnegotiatortest.h \ sdptest.h \ siptest.h \ diff --git a/daemon/test/accounttest.cpp b/daemon/test/accounttest.cpp index c75eeaf8a4dc19c10314d4c052742478183892fb..3df3153c230e7662d4d8fb61f853dab2eea4912d 100644 --- a/daemon/test/accounttest.cpp +++ b/daemon/test/accounttest.cpp @@ -36,19 +36,19 @@ #include "logger.h" #include "validator.h" -void AccountTest::TestAddRemove (void) +void AccountTest::TestAddRemove(void) { - _debug ("-------------------- AccountTest::TestAddRemove --------------------\n"); + DEBUG("-------------------- AccountTest::TestAddRemove --------------------\n"); std::map<std::string, std::string> details; details[CONFIG_ACCOUNT_TYPE] = "SIP"; details[CONFIG_ACCOUNT_ENABLE] = "false"; - std::string accountId = Manager::instance().addAccount (details); - CPPUNIT_ASSERT (Validator::isNotNull (accountId)); - CPPUNIT_ASSERT (Manager::instance().accountExists (accountId)); + std::string accountId = Manager::instance().addAccount(details); + CPPUNIT_ASSERT(Validator::isNotNull(accountId)); + CPPUNIT_ASSERT(Manager::instance().accountExists(accountId)); - Manager::instance().removeAccount (accountId); + Manager::instance().removeAccount(accountId); - CPPUNIT_ASSERT (!Manager::instance().accountExists (accountId)); + CPPUNIT_ASSERT(!Manager::instance().accountExists(accountId)); } diff --git a/daemon/test/accounttest.h b/daemon/test/accounttest.h index efb6df3860b03d1a564239af0320bd28f75c0537..486117fa3c384d462da3ab6cfdff18d6c79e2475 100644 --- a/daemon/test/accounttest.h +++ b/daemon/test/accounttest.h @@ -36,14 +36,14 @@ class AccountTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE( AccountTest ); - CPPUNIT_TEST( TestAddRemove ); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(AccountTest); + CPPUNIT_TEST(TestAddRemove); + CPPUNIT_TEST_SUITE_END(); - public: - void TestAddRemove(void); + public: + void TestAddRemove(void); }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(AccountTest, "AccountTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( AccountTest ); +CPPUNIT_TEST_SUITE_REGISTRATION(AccountTest); #endif /* ACCOUNTTEST_H_ */ diff --git a/daemon/test/audiolayertest.cpp b/daemon/test/audiolayertest.cpp index 8b8ca997bad02e5fee5d5126c7c99d7fe19d269b..589271f04b33ef3d5d47ad93762c031b7719b174 100644 --- a/daemon/test/audiolayertest.cpp +++ b/daemon/test/audiolayertest.cpp @@ -39,25 +39,28 @@ using std::cout; using std::endl; +AudioLayerTest::AudioLayerTest() : manager_(0), pulselayer_(0), layer_(0) +{} + void AudioLayerTest::testAudioLayerConfig() { - _debug ("-------------------- AudioLayerTest::testAudioLayerConfig --------------------\n"); + DEBUG("-------------------- AudioLayerTest::testAudioLayerConfig --------------------\n"); - CPPUNIT_ASSERT( Manager::instance().audioPreference.getSmplrate() == 44100); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getSmplrate() == 44100); // alsa preferences - CPPUNIT_ASSERT( Manager::instance().audioPreference.getCardin() == 0); - CPPUNIT_ASSERT( Manager::instance().audioPreference.getCardout() == 0); - CPPUNIT_ASSERT( Manager::instance().audioPreference.getCardring() == 0); - CPPUNIT_ASSERT( Manager::instance().audioPreference.getPlugin() == "default"); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getCardin() == 0); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getCardout() == 0); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getCardring() == 0); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getPlugin() == "default"); // pulseaudio preferences - CPPUNIT_ASSERT( Manager::instance().audioPreference.getDevicePlayback() == "alsa_output.pci-0000_00_1b.0.analog-stereo"); - CPPUNIT_ASSERT( Manager::instance().audioPreference.getDeviceRecord() == "alsa_input.pci-0000_00_1b.0.analog-stereo"); - CPPUNIT_ASSERT( Manager::instance().audioPreference.getDeviceRingtone() == "alsa_output.pci-0000_00_1b.0.analog-stereo"); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getDevicePlayback() == "alsa_output.pci-0000_00_1b.0.analog-stereo"); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getDeviceRecord() == "alsa_input.pci-0000_00_1b.0.analog-stereo"); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getDeviceRingtone() == "alsa_output.pci-0000_00_1b.0.analog-stereo"); - CPPUNIT_ASSERT( Manager::instance().audioPreference.getVolumemic() == 100); - CPPUNIT_ASSERT( Manager::instance().audioPreference.getVolumespkr() == 100); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getVolumemic() == 100); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getVolumespkr() == 100); // TODO: Fix tests //CPPUNIT_ASSERT ( (int) Manager::instance().getAudioDriver()->getSampleRate() == sampling_rate); @@ -65,34 +68,34 @@ void AudioLayerTest::testAudioLayerConfig() void AudioLayerTest::testAudioLayerSwitch() { - _debug ("-------------------- AudioLayerTest::testAudioLayerSwitch --------------------\n"); + DEBUG("-------------------- AudioLayerTest::testAudioLayerSwitch --------------------\n"); bool wasAlsa = dynamic_cast<AlsaLayer*>(Manager::instance().getAudioDriver()) != 0; for (int i = 0; i < 2; i++) { - _debug ("iter - %i", i); + DEBUG("iter - %i", i); Manager::instance().switchAudioManager(); if (wasAlsa) - CPPUNIT_ASSERT (dynamic_cast<PulseLayer*>(Manager::instance().getAudioDriver())); + CPPUNIT_ASSERT(dynamic_cast<PulseLayer*>(Manager::instance().getAudioDriver())); else - CPPUNIT_ASSERT (dynamic_cast<AlsaLayer*>(Manager::instance().getAudioDriver())); + CPPUNIT_ASSERT(dynamic_cast<AlsaLayer*>(Manager::instance().getAudioDriver())); wasAlsa = dynamic_cast<AlsaLayer*>(Manager::instance().getAudioDriver()) != 0; - usleep (100000); + usleep(100000); } } void AudioLayerTest::testPulseConnect() { - _debug ("-------------------- AudioLayerTest::testPulseConnect --------------------\n"); + DEBUG("-------------------- AudioLayerTest::testPulseConnect --------------------\n"); if (dynamic_cast<AlsaLayer*>(Manager::instance().getAudioDriver())) { Manager::instance().switchAudioManager(); - usleep (100000); + usleep(100000); } - _pulselayer = dynamic_cast<PulseLayer*>(Manager::instance().getAudioDriver()); + pulselayer_ = dynamic_cast<PulseLayer*>(Manager::instance().getAudioDriver()); - CPPUNIT_ASSERT (_pulselayer); + CPPUNIT_ASSERT(pulselayer_); } diff --git a/daemon/test/audiolayertest.h b/daemon/test/audiolayertest.h index 783548e15a1fdaa121a7d1b10afab4b9646a7d34..994cbaa62f96f567d60f8b97bf7232f9ec0c1895 100644 --- a/daemon/test/audiolayertest.h +++ b/daemon/test/audiolayertest.h @@ -42,7 +42,7 @@ #include <cppunit/TestCase.h> #include <cppunit/TestSuite.h> -#include <assert.h> +#include <cassert> // Application import #include "manager.h" @@ -52,31 +52,31 @@ #include "audio/audiolayer.h" #include "audio/alsa/alsalayer.h" #include "audio/pulseaudio/pulselayer.h" +#include "noncopyable.h" class AudioLayerTest: public CppUnit::TestFixture { -CPPUNIT_TEST_SUITE( AudioLayerTest ); - CPPUNIT_TEST( testAudioLayerConfig ); - CPPUNIT_TEST( testPulseConnect ); - //TODO: this test ends the test sequence when using on a alsa only system - //CPPUNIT_TEST(testAudioLayerSwitch); - CPPUNIT_TEST_SUITE_END(); - -public: - - void testAudioLayerConfig(); - void testPulseConnect(); - void testAudioLayerSwitch(); - -private: - - ManagerImpl* manager; - - PulseLayer* _pulselayer; - - int layer; + CPPUNIT_TEST_SUITE(AudioLayerTest); + CPPUNIT_TEST(testAudioLayerConfig); + CPPUNIT_TEST(testPulseConnect); + //TODO: this test ends the test sequence when using on a alsa only system + //CPPUNIT_TEST(testAudioLayerSwitch); + CPPUNIT_TEST_SUITE_END(); + + public: + AudioLayerTest(); + void testAudioLayerConfig(); + void testPulseConnect(); + void testAudioLayerSwitch(); + + private: + NON_COPYABLE(AudioLayerTest); + + ManagerImpl* manager_; + PulseLayer* pulselayer_; + int layer_; }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(AudioLayerTest, "AudioLayerTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( AudioLayerTest ); +CPPUNIT_TEST_SUITE_REGISTRATION(AudioLayerTest); #endif diff --git a/daemon/test/configurationtest.cpp b/daemon/test/configurationtest.cpp index b10490561da895f566eae37f6997e7fca1658781..cce25d5d5c056e85f283dcb08ffa8fb7fbcef1d9 100644 --- a/daemon/test/configurationtest.cpp +++ b/daemon/test/configurationtest.cpp @@ -41,36 +41,36 @@ using std::endl; void ConfigurationTest::testDefaultValueAudio() { - _debug ("-------------------- ConfigurationTest::testDefaultValueAudio() --------------------\n"); - - CPPUNIT_ASSERT (Manager::instance().audioPreference.getCardin() == 0); // ALSA_DFT_CARD); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getCardout() == 0); // ALSA_DFT_CARD); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getSmplrate() == 44100); // DFT_SAMPLE_RATE); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getPlugin() == PCM_DEFAULT); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumespkr() == 100); - CPPUNIT_ASSERT (Manager::instance().audioPreference.getVolumemic() == 100); + DEBUG("-------------------- ConfigurationTest::testDefaultValueAudio() --------------------\n"); + + CPPUNIT_ASSERT(Manager::instance().audioPreference.getCardin() == 0); // ALSA_DFT_CARD); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getCardout() == 0); // ALSA_DFT_CARD); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getSmplrate() == 44100); // DFT_SAMPLE_RATE); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getPlugin() == PCM_DEFAULT); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getVolumespkr() == 100); + CPPUNIT_ASSERT(Manager::instance().audioPreference.getVolumemic() == 100); } void ConfigurationTest::testDefaultValuePreferences() { - _debug ("-------------------- ConfigurationTest::testDefaultValuePreferences --------------------\n"); + DEBUG("-------------------- ConfigurationTest::testDefaultValuePreferences --------------------\n"); - CPPUNIT_ASSERT (Manager::instance().preferences.getZoneToneChoice() == Preferences::DFT_ZONE); + CPPUNIT_ASSERT(Manager::instance().preferences.getZoneToneChoice() == Preferences::DFT_ZONE); } void ConfigurationTest::testDefaultValueSignalisation() { - _debug ("-------------------- ConfigurationTest::testDefaultValueSignalisation --------------------\n"); + DEBUG("-------------------- ConfigurationTest::testDefaultValueSignalisation --------------------\n"); - CPPUNIT_ASSERT (Manager::instance().voipPreferences.getSymmetricRtp() == true); - CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPlayDtmf() == true); - CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPlayTones() == true); - CPPUNIT_ASSERT (Manager::instance().voipPreferences.getPulseLength() == 250); + CPPUNIT_ASSERT(Manager::instance().voipPreferences.getSymmetricRtp() == true); + CPPUNIT_ASSERT(Manager::instance().voipPreferences.getPlayDtmf() == true); + CPPUNIT_ASSERT(Manager::instance().voipPreferences.getPlayTones() == true); + CPPUNIT_ASSERT(Manager::instance().voipPreferences.getPulseLength() == 250); } void ConfigurationTest::testInitAudioDriver() { - _debug ("-------------------- ConfigurationTest::testInitAudioDriver --------------------\n"); + DEBUG("-------------------- ConfigurationTest::testInitAudioDriver --------------------\n"); // Load the audio driver Manager::instance().initAudioDriver(); @@ -78,117 +78,117 @@ void ConfigurationTest::testInitAudioDriver() // Check the creation if (Manager::instance().getAudioDriver() == NULL) - CPPUNIT_FAIL ("Error while loading audio layer"); + CPPUNIT_FAIL("Error while loading audio layer"); // Check if it has been created with the right type if (Manager::instance().audioPreference.getAudioApi() == "alsa") - CPPUNIT_ASSERT (!dynamic_cast<PulseLayer*>(Manager::instance().getAudioDriver())); + CPPUNIT_ASSERT(!dynamic_cast<PulseLayer*>(Manager::instance().getAudioDriver())); else if (Manager::instance().audioPreference.getAudioApi() == "pulseaudio") - CPPUNIT_ASSERT (!dynamic_cast<AlsaLayer*>(Manager::instance().getAudioDriver())); + CPPUNIT_ASSERT(!dynamic_cast<AlsaLayer*>(Manager::instance().getAudioDriver())); else - CPPUNIT_FAIL ("Wrong audio layer type"); + CPPUNIT_FAIL("Wrong audio layer type"); } void ConfigurationTest::testYamlParser() { try { - Conf::YamlParser *parser = new Conf::YamlParser ("ymlParser.yml"); + Conf::YamlParser *parser = new Conf::YamlParser("ymlParser.yml"); parser->serializeEvents(); parser->composeEvents(); parser->constructNativeData(); delete parser; } catch (Conf::YamlParserException &e) { - _error ("ConfigTree: %s", e.what()); + ERROR("ConfigTree: %s", e.what()); } } void ConfigurationTest::testYamlEmitter() { - Conf::MappingNode accountmap (NULL); - Conf::MappingNode credentialmap (NULL); - Conf::MappingNode srtpmap (NULL); - Conf::MappingNode zrtpmap (NULL); - Conf::MappingNode tlsmap (NULL); - - - Conf::ScalarNode id ("Account:1278432417"); - Conf::ScalarNode username ("181"); - Conf::ScalarNode password ("pass181"); - Conf::ScalarNode alias ("sfl-181"); - Conf::ScalarNode hostname ("192.168.50.3"); - Conf::ScalarNode enable (true); - Conf::ScalarNode type ("SIP"); - Conf::ScalarNode expire ("3600"); - Conf::ScalarNode interface ("default"); - Conf::ScalarNode port ("5060"); - Conf::ScalarNode mailbox ("97"); - Conf::ScalarNode publishAddr ("192.168.50.182"); - Conf::ScalarNode publishPort ("5060"); - Conf::ScalarNode sameasLocal (true); - Conf::ScalarNode codecs ("0/9/110/111/112/"); - Conf::ScalarNode stunServer ("stun.sflphone.org"); - Conf::ScalarNode stunEnabled (false); - Conf::ScalarNode displayName ("Alexandre Savard"); - Conf::ScalarNode dtmfType ("sipinfo"); - - Conf::ScalarNode count ("0"); - - Conf::ScalarNode srtpenabled (false); - Conf::ScalarNode keyExchange ("sdes"); - Conf::ScalarNode rtpFallback (false); - - Conf::ScalarNode displaySas (false); - Conf::ScalarNode displaySasOnce (false); - Conf::ScalarNode helloHashEnabled (false); - Conf::ScalarNode notSuppWarning (false); - - Conf::ScalarNode tlsport (""); - Conf::ScalarNode certificate (""); - Conf::ScalarNode calist (""); - Conf::ScalarNode ciphers (""); - Conf::ScalarNode tlsenabled (false); - Conf::ScalarNode tlsmethod ("TLSV1"); - Conf::ScalarNode timeout ("0"); - Conf::ScalarNode tlspassword (""); - Conf::ScalarNode privatekey (""); - Conf::ScalarNode requirecertif (true); - Conf::ScalarNode server (""); - Conf::ScalarNode verifyclient (true); - Conf::ScalarNode verifyserver (true); - - accountmap.setKeyValue (aliasKey, &alias); - accountmap.setKeyValue (typeKey, &type); - accountmap.setKeyValue (idKey, &id); - accountmap.setKeyValue (usernameKey, &username); - accountmap.setKeyValue (passwordKey, &password); - accountmap.setKeyValue (hostnameKey, &hostname); - accountmap.setKeyValue (accountEnableKey, &enable); - accountmap.setKeyValue (mailboxKey, &mailbox); - accountmap.setKeyValue (expireKey, &expire); - accountmap.setKeyValue (interfaceKey, &interface); - accountmap.setKeyValue (portKey, &port); - accountmap.setKeyValue (publishAddrKey, &publishAddr); - accountmap.setKeyValue (publishPortKey, &publishPort); - accountmap.setKeyValue (sameasLocalKey, &sameasLocal); - accountmap.setKeyValue (dtmfTypeKey, &dtmfType); - accountmap.setKeyValue (displayNameKey, &displayName); - - accountmap.setKeyValue (srtpKey, &srtpmap); - srtpmap.setKeyValue (srtpEnableKey, &srtpenabled); - srtpmap.setKeyValue (keyExchangeKey, &keyExchange); - srtpmap.setKeyValue (rtpFallbackKey, &rtpFallback); - - accountmap.setKeyValue (zrtpKey, &zrtpmap); - zrtpmap.setKeyValue (displaySasKey, &displaySas); - zrtpmap.setKeyValue (displaySasOnceKey, &displaySasOnce); - zrtpmap.setKeyValue (helloHashEnabledKey, &helloHashEnabled); - zrtpmap.setKeyValue (notSuppWarningKey, ¬SuppWarning); - - accountmap.setKeyValue (credKey, &credentialmap); - Conf::SequenceNode credentialseq (NULL); - accountmap.setKeyValue (credKey, &credentialseq); + Conf::MappingNode accountmap(NULL); + Conf::MappingNode credentialmap(NULL); + Conf::MappingNode srtpmap(NULL); + Conf::MappingNode zrtpmap(NULL); + Conf::MappingNode tlsmap(NULL); + + + Conf::ScalarNode id("Account:1278432417"); + Conf::ScalarNode username("181"); + Conf::ScalarNode password("pass181"); + Conf::ScalarNode alias("sfl-181"); + Conf::ScalarNode hostname("192.168.50.3"); + Conf::ScalarNode enable(true); + Conf::ScalarNode type("SIP"); + Conf::ScalarNode expire("3600"); + Conf::ScalarNode interface("default"); + Conf::ScalarNode port("5060"); + Conf::ScalarNode mailbox("97"); + Conf::ScalarNode publishAddr("192.168.50.182"); + Conf::ScalarNode publishPort("5060"); + Conf::ScalarNode sameasLocal(true); + Conf::ScalarNode codecs("0/9/110/111/112/"); + Conf::ScalarNode stunServer("stun.sflphone.org"); + Conf::ScalarNode stunEnabled(false); + Conf::ScalarNode displayName("Alexandre Savard"); + Conf::ScalarNode dtmfType("sipinfo"); + + Conf::ScalarNode count("0"); + + Conf::ScalarNode srtpenabled(false); + Conf::ScalarNode keyExchange("sdes"); + Conf::ScalarNode rtpFallback(false); + + Conf::ScalarNode displaySas(false); + Conf::ScalarNode displaySasOnce(false); + Conf::ScalarNode helloHashEnabled(false); + Conf::ScalarNode notSuppWarning(false); + + Conf::ScalarNode tlsport(""); + Conf::ScalarNode certificate(""); + Conf::ScalarNode calist(""); + Conf::ScalarNode ciphers(""); + Conf::ScalarNode tlsenabled(false); + Conf::ScalarNode tlsmethod("TLSV1"); + Conf::ScalarNode timeout("0"); + Conf::ScalarNode tlspassword(""); + Conf::ScalarNode privatekey(""); + Conf::ScalarNode requirecertif(true); + Conf::ScalarNode server(""); + Conf::ScalarNode verifyclient(true); + Conf::ScalarNode verifyserver(true); + + accountmap.setKeyValue(aliasKey, &alias); + accountmap.setKeyValue(typeKey, &type); + accountmap.setKeyValue(idKey, &id); + accountmap.setKeyValue(usernameKey, &username); + accountmap.setKeyValue(passwordKey, &password); + accountmap.setKeyValue(hostnameKey, &hostname); + accountmap.setKeyValue(accountEnableKey, &enable); + accountmap.setKeyValue(mailboxKey, &mailbox); + accountmap.setKeyValue(expireKey, &expire); + accountmap.setKeyValue(interfaceKey, &interface); + accountmap.setKeyValue(portKey, &port); + accountmap.setKeyValue(publishAddrKey, &publishAddr); + accountmap.setKeyValue(publishPortKey, &publishPort); + accountmap.setKeyValue(sameasLocalKey, &sameasLocal); + accountmap.setKeyValue(dtmfTypeKey, &dtmfType); + accountmap.setKeyValue(displayNameKey, &displayName); + + accountmap.setKeyValue(srtpKey, &srtpmap); + srtpmap.setKeyValue(srtpEnableKey, &srtpenabled); + srtpmap.setKeyValue(keyExchangeKey, &keyExchange); + srtpmap.setKeyValue(rtpFallbackKey, &rtpFallback); + + accountmap.setKeyValue(zrtpKey, &zrtpmap); + zrtpmap.setKeyValue(displaySasKey, &displaySas); + zrtpmap.setKeyValue(displaySasOnceKey, &displaySasOnce); + zrtpmap.setKeyValue(helloHashEnabledKey, &helloHashEnabled); + zrtpmap.setKeyValue(notSuppWarningKey, ¬SuppWarning); + + accountmap.setKeyValue(credKey, &credentialmap); + Conf::SequenceNode credentialseq(NULL); + accountmap.setKeyValue(credKey, &credentialseq); Conf::MappingNode credmap1(NULL); Conf::MappingNode credmap2(NULL); @@ -207,30 +207,30 @@ void ConfigurationTest::testYamlEmitter() credentialseq.addNode(&credmap1); credentialseq.addNode(&credmap2); - accountmap.setKeyValue (tlsKey, &tlsmap); - tlsmap.setKeyValue (tlsPortKey, &tlsport); - tlsmap.setKeyValue (certificateKey, &certificate); - tlsmap.setKeyValue (calistKey, &calist); - tlsmap.setKeyValue (ciphersKey, &ciphers); - tlsmap.setKeyValue (tlsEnableKey, &tlsenabled); - tlsmap.setKeyValue (methodKey, &tlsmethod); - tlsmap.setKeyValue (timeoutKey, &timeout); - tlsmap.setKeyValue (tlsPasswordKey, &tlspassword); - tlsmap.setKeyValue (privateKeyKey, &privatekey); - tlsmap.setKeyValue (requireCertifKey, &requirecertif); - tlsmap.setKeyValue (serverKey, &server); - tlsmap.setKeyValue (verifyClientKey, &verifyclient); - tlsmap.setKeyValue (verifyServerKey, &verifyserver); + accountmap.setKeyValue(tlsKey, &tlsmap); + tlsmap.setKeyValue(tlsPortKey, &tlsport); + tlsmap.setKeyValue(certificateKey, &certificate); + tlsmap.setKeyValue(calistKey, &calist); + tlsmap.setKeyValue(ciphersKey, &ciphers); + tlsmap.setKeyValue(tlsEnableKey, &tlsenabled); + tlsmap.setKeyValue(methodKey, &tlsmethod); + tlsmap.setKeyValue(timeoutKey, &timeout); + tlsmap.setKeyValue(tlsPasswordKey, &tlspassword); + tlsmap.setKeyValue(privateKeyKey, &privatekey); + tlsmap.setKeyValue(requireCertifKey, &requirecertif); + tlsmap.setKeyValue(serverKey, &server); + tlsmap.setKeyValue(verifyClientKey, &verifyclient); + tlsmap.setKeyValue(verifyServerKey, &verifyserver); try { - Conf::YamlEmitter *emitter = new Conf::YamlEmitter ("/tmp/ymlEmiter.txt"); + Conf::YamlEmitter *emitter = new Conf::YamlEmitter("/tmp/ymlEmiter.txt"); - emitter->serializeAccount (&accountmap); - emitter->serializeAccount (&accountmap); + emitter->serializeAccount(&accountmap); + emitter->serializeAccount(&accountmap); emitter->serializeData(); delete emitter; } catch (Conf::YamlEmitterException &e) { - _error ("ConfigTree: %s", e.what()); + ERROR("ConfigTree: %s", e.what()); } } diff --git a/daemon/test/configurationtest.h b/daemon/test/configurationtest.h old mode 100755 new mode 100644 index aea9a3cf8543a7d1d68dd276c04d92ef0a076f6c..f8705d3dadec3c0004e77b48b5d7422fb8d063a2 --- a/daemon/test/configurationtest.h +++ b/daemon/test/configurationtest.h @@ -57,50 +57,50 @@ class ConfigurationTest: public CppUnit::TestFixture { - /* - * Use cppunit library macros to add unit test the factory - */ -CPPUNIT_TEST_SUITE( ConfigurationTest ); + /* + * Use cppunit library macros to add unit test the factory + */ + CPPUNIT_TEST_SUITE(ConfigurationTest); // CPPUNIT_TEST( testDefaultValueAudio ); // CPPUNIT_TEST( testDefaultValuePreferences ); // CPPUNIT_TEST( testDefaultValueSignalisation ); // CPPUNIT_TEST( testInitAudioDriver ); // CPPUNIT_TEST( testYamlParser ); - CPPUNIT_TEST( testYamlEmitter ); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST(testYamlEmitter); + CPPUNIT_TEST_SUITE_END(); -public: - /* - * Unit tests related to the audio preferences - */ - void testDefaultValueAudio(); + public: + /* + * Unit tests related to the audio preferences + */ + void testDefaultValueAudio(); - /* - * Unit tests related to the global settings - */ - void testDefaultValuePreferences(); + /* + * Unit tests related to the global settings + */ + void testDefaultValuePreferences(); - /* - * Unit tests related to the global settings - */ - void testDefaultValueSignalisation(); + /* + * Unit tests related to the global settings + */ + void testDefaultValueSignalisation(); - /* - * Try to load one SIP account. - * So be sure to have only one SIP account so that the test could succeed - */ - void testLoadSIPAccount(); + /* + * Try to load one SIP account. + * So be sure to have only one SIP account so that the test could succeed + */ + void testLoadSIPAccount(); - void testUnloadSIPAccount(); + void testUnloadSIPAccount(); - void testInitAudioDriver(); + void testInitAudioDriver(); - void testYamlParser(); + void testYamlParser(); - void testYamlEmitter(); + void testYamlEmitter(); }; /* Register our test module */ CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(ConfigurationTest, "ConfigurationTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( ConfigurationTest ); +CPPUNIT_TEST_SUITE_REGISTRATION(ConfigurationTest); #endif diff --git a/daemon/test/delaydetectiontest.cpp b/daemon/test/delaydetectiontest.cpp index 2bae4c4feb47b254ecddd77245b88849b71073b4..a140d208d52531599c62fd8b836d25072c92692d 100644 --- a/daemon/test/delaydetectiontest.cpp +++ b/daemon/test/delaydetectiontest.cpp @@ -47,20 +47,20 @@ void DelayDetectionTest::testCrossCorrelation() float result[10]; float expected[10] = {0.0, 0.89442719, 1.0, 0.95618289, 0.91350028, 0.88543774, 0.86640023, 0.85280287, 0.8426548, 0.83480969}; - CPPUNIT_ASSERT (_delaydetect.correlate (ref, ref, 3) == 5.0); - CPPUNIT_ASSERT (_delaydetect.correlate (signal, signal, 10) == 285.0); + CPPUNIT_ASSERT(delaydetect_.correlate(ref, ref, 3) == 5.0); + CPPUNIT_ASSERT(delaydetect_.correlate(signal, signal, 10) == 285.0); - _delaydetect.crossCorrelate (ref, signal, result, 3, 10); + delaydetect_.crossCorrelate(ref, signal, result, 3, 10); float tmp; for (int i = 0; i < 10; i++) { - tmp = result[i]-expected[i]; + tmp = result[i] - expected[i]; if (tmp < 0.0) - CPPUNIT_ASSERT (tmp > -0.001); + CPPUNIT_ASSERT(tmp > -0.001); else - CPPUNIT_ASSERT (tmp < 0.001); + CPPUNIT_ASSERT(tmp < 0.001); } } @@ -71,7 +71,7 @@ void DelayDetectionTest::testCrossCorrelationDelay() float result[10]; - _delaydetect.crossCorrelate (ref, signal, result, 3, 10); + delaydetect_.crossCorrelate(ref, signal, result, 3, 10); float expected[10] = {0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0}; @@ -89,7 +89,7 @@ void DelayDetectionTest::testFirFilter() 0.00610982, 0.01463477, 0.02244098, 0.02944626, 0.03630817, 0.04448337, 0.05616626, 0.07473655, -0.09870257 }; - std::vector<double> ird (decimationCoefs, decimationCoefs + sizeof (decimationCoefs) /sizeof (float)); + std::vector<double> ird(decimationCoefs, decimationCoefs + sizeof(decimationCoefs) /sizeof(float)); float bandpassCoefs[] = {0.06278034, -0.0758545, -0.02274943, -0.0084497, 0.0702427, 0.05986113, 0.06436469, -0.02412049, -0.03433526, -0.07568665, -0.03214543, -0.07236507, @@ -98,49 +98,49 @@ void DelayDetectionTest::testFirFilter() -0.03214543, -0.07568665, -0.03433526, -0.02412049, 0.06436469, 0.05986113, 0.0702427, -0.0084497, -0.02274943, -0.0758545, 0.06278034 }; - std::vector<double> irb (bandpassCoefs, bandpassCoefs + sizeof (bandpassCoefs) /sizeof (float)); + std::vector<double> irb(bandpassCoefs, bandpassCoefs + sizeof(bandpassCoefs) /sizeof(float)); float impulse[100]; - memset (impulse, 0, sizeof (float) *100); + memset(impulse, 0, sizeof(float) *100); impulse[0] = 1.0; - FirFilter _decimationFilter (ird); - FirFilter _bandpassFilter (irb); + FirFilter decimationFilter_(ird); + FirFilter bandpassFilter_(irb); float impulseresponse[100]; - memset (impulseresponse, 0, sizeof (float) *100); + memset(impulseresponse, 0, sizeof(float) *100); // compute impulse response for (int i = 0; i < 100; i++) { - impulseresponse[i] = _decimationFilter.getOutputSample (impulse[i]); + impulseresponse[i] = decimationFilter_.getOutputSample(impulse[i]); } float tmp; - int size = sizeof (decimationCoefs) /sizeof (float); + int size = sizeof(decimationCoefs) /sizeof(float); for (int i = 0; i < size; i++) { tmp = decimationCoefs[i] - impulseresponse[i]; if (tmp < 0.0) - CPPUNIT_ASSERT (tmp > -0.000001); + CPPUNIT_ASSERT(tmp > -0.000001); else - CPPUNIT_ASSERT (tmp < 0.000001); + CPPUNIT_ASSERT(tmp < 0.000001); } for (int i = 0; i < 100; i++) { - impulseresponse[i] = _bandpassFilter.getOutputSample (impulse[i]); + impulseresponse[i] = bandpassFilter_.getOutputSample(impulse[i]); } - size = sizeof (bandpassCoefs) /sizeof (float); + size = sizeof(bandpassCoefs) /sizeof(float); for (int i = 0; i < size; i++) { tmp = bandpassCoefs[i] - impulseresponse[i]; if (tmp < 0.0) - CPPUNIT_ASSERT (tmp > -0.000001); + CPPUNIT_ASSERT(tmp > -0.000001); else - CPPUNIT_ASSERT (tmp < 0.000001); + CPPUNIT_ASSERT(tmp < 0.000001); } } @@ -154,16 +154,16 @@ void DelayDetectionTest::testIntToFloatConversion() for (int i = -32768; i < 32768; i++) data[i+32768] = i; - _delaydetect.convertInt16ToFloat32 (data, converted, 32768*2); + delaydetect_.convertInt16ToFloat32(data, converted, 32768*2); for (int i = -32768; i < 0; i++) { - CPPUNIT_ASSERT (converted[i+32768] >= -1.0); - CPPUNIT_ASSERT (converted[i+32768] <= 0.0); + CPPUNIT_ASSERT(converted[i+32768] >= -1.0); + CPPUNIT_ASSERT(converted[i+32768] <= 0.0); } for (int i = 0; i < 32768; i++) { - CPPUNIT_ASSERT (converted[i+32768] >= 0.0); - CPPUNIT_ASSERT (converted[i+32768] <= 1.0); + CPPUNIT_ASSERT(converted[i+32768] >= 0.0); + CPPUNIT_ASSERT(converted[i+32768] <= 1.0); } } @@ -177,18 +177,18 @@ void DelayDetectionTest::testDownSamplingData() for (int i = -32768; i < 32768; i++) data[i+32768] = i; - _delaydetect.convertInt16ToFloat32 (data, converted, 32768*2); + delaydetect_.convertInt16ToFloat32(data, converted, 32768*2); - _delaydetect.downsampleData (converted, resampled, 32768*2, 8); + delaydetect_.downsampleData(converted, resampled, 32768*2, 8); for (int i = 0; i < 32768/8; i++) { - CPPUNIT_ASSERT (resampled[i] >= -1.0); - CPPUNIT_ASSERT (resampled[i] <= 0.0); + CPPUNIT_ASSERT(resampled[i] >= -1.0); + CPPUNIT_ASSERT(resampled[i] <= 0.0); } for (int i = 32768/8+1; i < 32768/4; i++) { - CPPUNIT_ASSERT (resampled[i] >= 0.0); - CPPUNIT_ASSERT (resampled[i] <= 1.0); + CPPUNIT_ASSERT(resampled[i] >= 0.0); + CPPUNIT_ASSERT(resampled[i] <= 1.0); } @@ -201,7 +201,7 @@ void DelayDetectionTest::testDelayDetection() int delay = 100; SFLDataFormat spkr[WINDOW_SIZE]; - memset (spkr, 0, sizeof (SFLDataFormat) *WINDOW_SIZE); + memset(spkr, 0, sizeof(SFLDataFormat) *WINDOW_SIZE); spkr[0] = 32000; spkr[1] = 32000; spkr[2] = 32000; @@ -209,14 +209,13 @@ void DelayDetectionTest::testDelayDetection() spkr[4] = 32000; SFLDataFormat mic[DELAY_BUFF_SIZE]; - memset (mic, 0, sizeof (SFLDataFormat) *DELAY_BUFF_SIZE); + memset(mic, 0, sizeof(SFLDataFormat) *DELAY_BUFF_SIZE); mic[delay] = 32000; mic[delay+1] = 32000; mic[delay+2] = 32000; mic[delay+3] = 32000; mic[delay+4] = 32000; - _delaydetect.putData (spkr, WINDOW_SIZE); - _delaydetect.process (mic, DELAY_BUFF_SIZE); - + delaydetect_.putData(spkr, WINDOW_SIZE); + delaydetect_.process(mic, DELAY_BUFF_SIZE); } diff --git a/daemon/test/delaydetectiontest.h b/daemon/test/delaydetectiontest.h index 92816ba2060244773c6b186ba333499e6c7194f7..11d4eef7d5a3afc917ebdbc7217a969fb7e0b2ba 100644 --- a/daemon/test/delaydetectiontest.h +++ b/daemon/test/delaydetectiontest.h @@ -64,49 +64,49 @@ #define _DELAYDETECTION_TEST_ /* - * @file delaydetection.cpp + * @file delaydetection.cpp * @brief Regroups unitary tests related to the delay detection algorithm. */ class DelayDetectionTest : public CppUnit::TestCase { - - CPPUNIT_TEST_SUITE( DelayDetectionTest ); - CPPUNIT_TEST( testCrossCorrelation ); - CPPUNIT_TEST( testCrossCorrelationDelay ); - CPPUNIT_TEST( testFirFilter ); - CPPUNIT_TEST( testIntToFloatConversion ); - CPPUNIT_TEST( testDownSamplingData ); - CPPUNIT_TEST( testDelayDetection ); - CPPUNIT_TEST_SUITE_END(); - public: + CPPUNIT_TEST_SUITE(DelayDetectionTest); + CPPUNIT_TEST(testCrossCorrelation); + CPPUNIT_TEST(testCrossCorrelationDelay); + CPPUNIT_TEST(testFirFilter); + CPPUNIT_TEST(testIntToFloatConversion); + CPPUNIT_TEST(testDownSamplingData); + CPPUNIT_TEST(testDelayDetection); + CPPUNIT_TEST_SUITE_END(); - DelayDetectionTest() : CppUnit::TestCase("Delay Detection Tests") {} + public: - void setUp(); + DelayDetectionTest() : CppUnit::TestCase("Delay Detection Tests") {} - void tearDown(); + void setUp(); - void testCrossCorrelation(); + void tearDown(); - void testCrossCorrelationDelay(); + void testCrossCorrelation(); - void testFirFilter(); + void testCrossCorrelationDelay(); - void testIntToFloatConversion(); + void testFirFilter(); - void testDownSamplingData(); + void testIntToFloatConversion(); - void testDelayDetection(); + void testDownSamplingData(); - private: + void testDelayDetection(); + + private: + + DelayDetection delaydetect_; - DelayDetection _delaydetect; - }; /* Register our test module */ CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(DelayDetectionTest, "DelayDetectionTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( DelayDetectionTest ); +CPPUNIT_TEST_SUITE_REGISTRATION(DelayDetectionTest); #endif diff --git a/daemon/test/echocanceltest.cpp b/daemon/test/echocanceltest.cpp index 9a5230f010305b7c1a8d51f46bc1e508e0d4f41d..53b03faed8b26b8237e923cb2d6452079c095d83 100644 --- a/daemon/test/echocanceltest.cpp +++ b/daemon/test/echocanceltest.cpp @@ -35,10 +35,10 @@ using namespace std; +EchoCancelTest::EchoCancelTest() : echoCanceller_() {} + void EchoCancelTest::testEchoCancelProcessing() { -// _debug ("-------------------- EchoCancelTest::testEchoCancelTest --------------------\n"); - const int nbSamples = 160; int inputFileLength = 0; int remainingLength = 0; @@ -47,33 +47,30 @@ void EchoCancelTest::testEchoCancelProcessing() SFLDataFormat spkrData[1000]; SFLDataFormat echoCancelData[1000]; - // near end input with echo ifstream micFile("sample_no_echo_8kHz_16bit.raw", ifstream::in); - // far end input to train filter + // far end input to train filter ifstream spkrFile("sample_ecno_500ms_8kHz_16bit.raw", ifstream::in); // echo cancelled output ofstream echoCancelFile("sample_echocancel_500ms_8kHz_16bit.raw", ofstream::out); - micFile.seekg(0, ios::end); inputFileLength = micFile.tellg() / sizeof(SFLDataFormat); micFile.seekg(0, ios::beg); remainingLength = inputFileLength; - while(remainingLength >= nbSamples) { + + while (remainingLength >= nbSamples) { micFile.read(reinterpret_cast<char *>(micData), nbSamples * sizeof(SFLDataFormat)); spkrFile.read(reinterpret_cast<char *>(spkrData), nbSamples * sizeof(SFLDataFormat)); - echoCanceller.putData(spkrData, nbSamples); - echoCanceller.process(micData, echoCancelData, nbSamples); + echoCanceller_.putData(spkrData, nbSamples); + echoCanceller_.process(micData, echoCancelData, nbSamples); echoCancelFile.write(reinterpret_cast<char *>(echoCancelData), nbSamples * sizeof(SFLDataFormat)); - + remainingLength -= nbSamples; } - - CPPUNIT_ASSERT(true); } diff --git a/daemon/test/echocanceltest.h b/daemon/test/echocanceltest.h index f856c207af3d3dfc3eb6fe5416ebd61d1379204a..6bd8f3a4c8358e2a8e82ddd11ea3e1d16e7cc370 100644 --- a/daemon/test/echocanceltest.h +++ b/daemon/test/echocanceltest.h @@ -42,28 +42,25 @@ #include <cppunit/TestCase.h> #include <cppunit/TestSuite.h> -#include <assert.h> +#include <cassert> #include "audio/speexechocancel.h" - - class EchoCancelTest: public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE( EchoCancelTest ); - CPPUNIT_TEST( testEchoCancelProcessing ); - CPPUNIT_TEST_SUITE_END(); - -public: + CPPUNIT_TEST_SUITE(EchoCancelTest); + CPPUNIT_TEST(testEchoCancelProcessing); + CPPUNIT_TEST_SUITE_END(); - void testEchoCancelProcessing(); - -private: - - SpeexEchoCancel echoCanceller; + public: + EchoCancelTest(); + void testEchoCancelProcessing(); + private: + SpeexEchoCancel echoCanceller_; }; + CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(EchoCancelTest, "EchoCancelTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( EchoCancelTest ); +CPPUNIT_TEST_SUITE_REGISTRATION(EchoCancelTest); #endif diff --git a/daemon/test/gaincontroltest.cpp b/daemon/test/gaincontroltest.cpp index d9461d95172a840e2ed7ab6a99300708e0134ecd..916a110d71e0126a3d6d3ac18d96d8a20cc31ec6 100644 --- a/daemon/test/gaincontroltest.cpp +++ b/daemon/test/gaincontroltest.cpp @@ -65,7 +65,7 @@ void GainControlTest::testGainProcessing() } inputFile.close(); - outputFile.close(); + outputFile.close(); */ CPPUNIT_ASSERT(true); diff --git a/daemon/test/gaincontroltest.h b/daemon/test/gaincontroltest.h index 34238a00bbc903ae98d419b2dcba329318d58049..14f55d09b36a209961efd5893eba6e16c021941d 100644 --- a/daemon/test/gaincontroltest.h +++ b/daemon/test/gaincontroltest.h @@ -48,19 +48,19 @@ class GainControlTest: public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE( GainControlTest ); - CPPUNIT_TEST( testGainProcessing ); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(GainControlTest); + CPPUNIT_TEST(testGainProcessing); + CPPUNIT_TEST_SUITE_END(); -public: + public: - void testGainProcessing(); + void testGainProcessing(); -private: + private: }; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(GainControlTest, "GainControlTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( GainControlTest ); +CPPUNIT_TEST_SUITE_REGISTRATION(GainControlTest); #endif diff --git a/daemon/test/historytest.cpp b/daemon/test/historytest.cpp index c9cbd0e76e9f18dd1d778ce0589c29710582dd16..58d3cfbff8bfc1d185369624bc1d077fae177ff6 100644 --- a/daemon/test/historytest.cpp +++ b/daemon/test/historytest.cpp @@ -40,100 +40,114 @@ using std::cout; using std::endl; +namespace { +void restore() +{ + if (system("mv " HISTORY_SAMPLE ".bak " HISTORY_SAMPLE) < 0) + ERROR("Restoration of %s failed" HISTORY_SAMPLE); +} + +void backup() +{ + if (system("cp " HISTORY_SAMPLE " " HISTORY_SAMPLE ".bak") < 0) + ERROR("Backup of %s failed", HISTORY_SAMPLE); +} +} + void HistoryTest::setUp() { - system("cp " HISTORY_SAMPLE " " HISTORY_SAMPLE ".bak"); - // Instanciate the cleaner singleton + backup(); + // Instantiate the cleaner singleton history = new HistoryManager(); } void HistoryTest::test_create_history_path() { - _debug ("-------------------- HistoryTest::test_create_history_path --------------------\n"); + DEBUG("-------------------- HistoryTest::test_create_history_path --------------------\n"); int result; std::string path(HISTORY_SAMPLE); result = history->create_history_path(path); - CPPUNIT_ASSERT (result == 0); - CPPUNIT_ASSERT (!history->is_loaded ()); - CPPUNIT_ASSERT (history->_history_path == path); + CPPUNIT_ASSERT(result == 0); + CPPUNIT_ASSERT(!history->is_loaded()); + CPPUNIT_ASSERT(history->history_path_ == path); } void HistoryTest::test_load_history_from_file() { - _debug ("-------------------- HistoryTest::test_load_history_from_file --------------------\n"); + DEBUG("-------------------- HistoryTest::test_load_history_from_file --------------------\n"); bool res; Conf::ConfigTree history_list; history->create_history_path(HISTORY_SAMPLE); - res = history->load_history_from_file (&history_list); + res = history->load_history_from_file(&history_list); - CPPUNIT_ASSERT (history->is_loaded ()); - CPPUNIT_ASSERT (res == true); + CPPUNIT_ASSERT(history->is_loaded()); + CPPUNIT_ASSERT(res == true); } void HistoryTest::test_load_history_items_map() { - _debug ("-------------------- HistoryTest::test_load_history_items_map --------------------\n"); + DEBUG("-------------------- HistoryTest::test_load_history_items_map --------------------\n"); std::string path; int nb_items; Conf::ConfigTree history_list; - history->set_history_path (HISTORY_SAMPLE); - history->load_history_from_file (&history_list); - nb_items = history->load_history_items_map (&history_list, + history->set_history_path(HISTORY_SAMPLE); + history->load_history_from_file(&history_list); + nb_items = history->load_history_items_map(&history_list, HUGE_HISTORY_LIMIT); - CPPUNIT_ASSERT (nb_items == HISTORY_SAMPLE_SIZE); - CPPUNIT_ASSERT (history->get_history_size () == HISTORY_SAMPLE_SIZE); + CPPUNIT_ASSERT(nb_items == HISTORY_SAMPLE_SIZE); + CPPUNIT_ASSERT(history->get_history_size() == HISTORY_SAMPLE_SIZE); } void HistoryTest::test_save_history_items_map() { - _debug ("-------------------- HistoryTest::test_save_history_items_map --------------------\n"); + DEBUG("-------------------- HistoryTest::test_save_history_items_map --------------------\n"); std::string path; int nb_items_loaded, nb_items_saved; Conf::ConfigTree history_list, history_list2; - history->set_history_path (HISTORY_SAMPLE); - history->load_history_from_file (&history_list); - nb_items_loaded = history->load_history_items_map (&history_list, + history->set_history_path(HISTORY_SAMPLE); + history->load_history_from_file(&history_list); + nb_items_loaded = history->load_history_items_map(&history_list, HUGE_HISTORY_LIMIT); - nb_items_saved = history->save_history_items_map (&history_list2); - CPPUNIT_ASSERT (nb_items_loaded == nb_items_saved); + nb_items_saved = history->save_history_items_map(&history_list2); + CPPUNIT_ASSERT(nb_items_loaded == nb_items_saved); } void HistoryTest::test_save_history_to_file() { - _debug ("-------------------- HistoryTest::test_save_history_to_file --------------------\n"); + DEBUG("-------------------- HistoryTest::test_save_history_to_file --------------------\n"); std::string path; Conf::ConfigTree history_list, history_list2; std::map<std::string, std::string> res; std::map<std::string, std::string>::iterator iter; - history->set_history_path (HISTORY_SAMPLE); - history->load_history_from_file (&history_list); - history->load_history_items_map (&history_list, HUGE_HISTORY_LIMIT); - history->save_history_items_map (&history_list2); - CPPUNIT_ASSERT (history->save_history_to_file (&history_list2)); + history->set_history_path(HISTORY_SAMPLE); + history->load_history_from_file(&history_list); + history->load_history_items_map(&history_list, HUGE_HISTORY_LIMIT); + history->save_history_items_map(&history_list2); + CPPUNIT_ASSERT(history->save_history_to_file(&history_list2)); } void HistoryTest::test_get_history_serialized() { - _debug ("-------------------- HistoryTest::test_get_history_serialized --------------------\n"); + DEBUG("-------------------- HistoryTest::test_get_history_serialized --------------------\n"); std::vector<std::string> res; std::vector<std::string>::iterator iter; std::string tmp; - CPPUNIT_ASSERT (history->load_history (HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); + CPPUNIT_ASSERT(history->load_history(HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); res = history->get_history_serialized(); - CPPUNIT_ASSERT (res.size() == HISTORY_SAMPLE_SIZE); + CPPUNIT_ASSERT(res.size() == HISTORY_SAMPLE_SIZE); // Warning - If you change the history-sample file, you must change the following lines also so that the tests could work @@ -153,7 +167,7 @@ void HistoryTest::test_get_history_serialized() void HistoryTest::test_set_serialized_history() { - _debug ("-------------------- HistoryTest::test_set_serialized_history --------------------\n"); + DEBUG("-------------------- HistoryTest::test_set_serialized_history --------------------\n"); // We build a map to have an efficient test std::vector<std::string> test_vector; @@ -164,40 +178,40 @@ void HistoryTest::test_set_serialized_history() test_vector.push_back("2|136|Emmanuel Milou|747638685|747638765|Account:1239059899||||"); test_vector.push_back("1|5143848557|empty|775354456|775354987|Account:43789459478||||"); - CPPUNIT_ASSERT (history->load_history (HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); + CPPUNIT_ASSERT(history->load_history(HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); // We use a large history limit to be able to interpret results - CPPUNIT_ASSERT (history->set_serialized_history (test_vector, HUGE_HISTORY_LIMIT) == 3); - CPPUNIT_ASSERT (history->get_history_size () == 3); + CPPUNIT_ASSERT(history->set_serialized_history(test_vector, HUGE_HISTORY_LIMIT) == 3); + CPPUNIT_ASSERT(history->get_history_size() == 3); test_vector.clear(); test_vector = history->get_history_serialized(); - CPPUNIT_ASSERT (test_vector.size() == 3); + CPPUNIT_ASSERT(test_vector.size() == 3); // Check the first tmp = "0|514-276-5468|Savoir-faire Linux|144562000|144562458||empty|||"; - // CPPUNIT_ASSERT (Validator::isEqual (tmp, test_vector[0])); + // CPPUNIT_ASSERT (Validator::isEqual (tmp, test_vector[0])); // the account ID does not correspond to a loaded account tmp = "2|136|Emmanuel Milou|747638685|747638765|Account:1239059899|empty|||"; // std::cout << "test vector : " << test_vector[1] << std::endl; // CPPUNIT_ASSERT (Validator::isEqual (tmp, test_vector[1])); - history->save_history_items_map (&history_list); - CPPUNIT_ASSERT (history->save_history_to_file (&history_list)); + history->save_history_items_map(&history_list); + CPPUNIT_ASSERT(history->save_history_to_file(&history_list)); } void HistoryTest::test_set_serialized_history_with_limit() { - _debug ("-------------------- HistoryTest::test_set_serialized_history_with_limit --------------------\n"); + DEBUG("-------------------- HistoryTest::test_set_serialized_history_with_limit --------------------\n"); // We build a map to have an efficient test std::vector<std::string> test_vector; std::string tmp; - + Conf::ConfigTree history_list; time_t current, day = 86400; // One day in unix timestamp std::stringstream current_1, current_2, current_3; - (void) time (¤t); + (void) time(¤t); current_1 << "0|514-276-5468|Savoir-faire Linux|" << (current - 2 * day) << "|144562458|empty|" << std::endl; current_2 << "2|136|Emmanuel Milou|" << (current - 5 * day) << "|747638765|Account:1239059899|" << std::endl; current_3 << "1|5143848557|empty|" << (current - 11 * day) << "|775354987|Account:43789459478|" << std::endl; @@ -206,19 +220,19 @@ void HistoryTest::test_set_serialized_history_with_limit() test_vector.push_back(current_2.str()); test_vector.push_back(current_3.str()); - CPPUNIT_ASSERT (history->load_history (HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); + CPPUNIT_ASSERT(history->load_history(HUGE_HISTORY_LIMIT, HISTORY_SAMPLE) == HISTORY_SAMPLE_SIZE); // We use different value of history limit // 10 days - the last entry should not be saved - CPPUNIT_ASSERT (history->set_serialized_history (test_vector, 10) == 2); - CPPUNIT_ASSERT (history->get_history_size () == 2); + CPPUNIT_ASSERT(history->set_serialized_history(test_vector, 10) == 2); + CPPUNIT_ASSERT(history->get_history_size() == 2); // 4 days - the two last entries should not be saved - CPPUNIT_ASSERT (history->set_serialized_history (test_vector, 4) == 1); - CPPUNIT_ASSERT (history->get_history_size () == 1); + CPPUNIT_ASSERT(history->set_serialized_history(test_vector, 4) == 1); + CPPUNIT_ASSERT(history->get_history_size() == 1); // 1 day - no entry should not be saved - CPPUNIT_ASSERT (history->set_serialized_history (test_vector, 1) == 0); - CPPUNIT_ASSERT (history->get_history_size () == 0); + CPPUNIT_ASSERT(history->set_serialized_history(test_vector, 1) == 0); + CPPUNIT_ASSERT(history->get_history_size() == 0); } void HistoryTest::tearDown() @@ -226,5 +240,5 @@ void HistoryTest::tearDown() // Delete the history object delete history; history = 0; - system("mv " HISTORY_SAMPLE ".bak " HISTORY_SAMPLE); + restore(); } diff --git a/daemon/test/historytest.h b/daemon/test/historytest.h index 9ae11ffc1c2c54c2e7e0b5155e38e0c3d0afa9d2..9fb3b97d0f35a222626d4bab3603a58e0795d638 100644 --- a/daemon/test/historytest.h +++ b/daemon/test/historytest.h @@ -34,13 +34,14 @@ #include <cppunit/TestCase.h> #include <cppunit/TestSuite.h> -#include <assert.h> +#include <cassert> // Application import +#include "noncopyable.h" #include "history/historymanager.h" /* - * @file historyTest.h + * @file historyTest.h * @brief Regroups unitary tests related to the phone number cleanup function. */ @@ -49,57 +50,58 @@ class HistoryTest : public CppUnit::TestCase { - /** - * Use cppunit library macros to add unit test the factory - */ - CPPUNIT_TEST_SUITE (HistoryTest); - CPPUNIT_TEST (test_create_history_path); - CPPUNIT_TEST (test_save_history_items_map); - CPPUNIT_TEST (test_load_history_from_file); - CPPUNIT_TEST (test_load_history_items_map); - CPPUNIT_TEST (test_get_history_serialized); - CPPUNIT_TEST (test_set_serialized_history); - CPPUNIT_TEST (test_set_serialized_history_with_limit); - // CPPUNIT_TEST (test_save_history_to_file); - CPPUNIT_TEST_SUITE_END (); + /** + * Use cppunit library macros to add unit test the factory + */ + CPPUNIT_TEST_SUITE(HistoryTest); + CPPUNIT_TEST(test_create_history_path); + CPPUNIT_TEST(test_save_history_items_map); + CPPUNIT_TEST(test_load_history_from_file); + CPPUNIT_TEST(test_load_history_items_map); + CPPUNIT_TEST(test_get_history_serialized); + CPPUNIT_TEST(test_set_serialized_history); + CPPUNIT_TEST(test_set_serialized_history_with_limit); + // CPPUNIT_TEST (test_save_history_to_file); + CPPUNIT_TEST_SUITE_END(); public: - HistoryTest() : CppUnit::TestCase("History Tests") {} - + HistoryTest() : CppUnit::TestCase("History Tests"), history(0) {} + /* * Code factoring - Common resources can be initialized here. * This method is called by unitcpp before each test */ void setUp(); - void test_create_history_path (); + void test_create_history_path(); + + void test_load_history_from_file(); + + void test_load_history_items_map(); - void test_load_history_from_file (); + void test_save_history_items_map(); - void test_load_history_items_map (); + void test_save_history_to_file(); - void test_save_history_items_map (); + void test_get_history_serialized(); - void test_save_history_to_file (); - - void test_get_history_serialized (); + void test_set_serialized_history(); - void test_set_serialized_history (); + void test_set_serialized_history_with_limit(); - void test_set_serialized_history_with_limit (); - /* * Code factoring - Common resources can be released here. * This method is called by unitcpp after each test */ - void tearDown (); + void tearDown(); private: + NON_COPYABLE(HistoryTest); HistoryManager *history; }; /* Register our test module */ CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(HistoryTest, "HistoryTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( HistoryTest ); +CPPUNIT_TEST_SUITE_REGISTRATION(HistoryTest); #endif diff --git a/daemon/test/hookmanagertest.cpp b/daemon/test/hookmanagertest.cpp deleted file mode 100644 index 6dda48987813e56995fbb688e862f2876e486f5d..0000000000000000000000000000000000000000 --- a/daemon/test/hookmanagertest.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Savoir-Faire Linux Inc. - * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - -#include <stdio.h> -#include <sstream> -#include <dlfcn.h> -#include "global.h" - -#include "hookmanagertest.h" - -using std::cout; -using std::endl; - - -void HookManagerTest::setUp() -{ - // Instanciate the hook manager singleton - urlhook = new UrlHook (); -} - -void HookManagerTest::testAddAction () -{ - _debug ("-------------------- HookManagerTest::testAddAction --------------------\n"); - - // CPPUNIT_ASSERT (urlhook->addAction ("http://www.google.ca/?arg1=arg1&arg2=nvls&x=2&y=45&z=1", "x-www-browser") == 0); -} - -void HookManagerTest::testLargeUrl () -{ - _debug ("-------------------- HookManagerTest::testLargeUrl --------------------\n"); - - std::string url; - std::cout << url.max_size() << std::endl; -} - -void HookManagerTest::tearDown() -{ - // Delete the hook manager object - delete urlhook; - urlhook=0; -} diff --git a/daemon/test/hookmanagertest.h b/daemon/test/hookmanagertest.h deleted file mode 100644 index 5f1e138b4d875e861bf72c7b15d8eea509e68da2..0000000000000000000000000000000000000000 --- a/daemon/test/hookmanagertest.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Savoir-Faire Linux Inc. - * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - -/* - * @file hookmanagerTest.cpp - * @brief Regroups unitary tests related to the hook manager. - */ - -#ifndef _HOOKMANAGER_TEST_ -#define _HOOKMANAGER_TEST_ - -// Cppunit import -#include <cppunit/extensions/HelperMacros.h> -#include <cppunit/TestCaller.h> -#include <cppunit/TestCase.h> -#include <cppunit/TestSuite.h> - -#include <assert.h> - -// Application import -#include "hooks/urlhook.h" - -class HookManagerTest : public CppUnit::TestFixture { - - /** - * Use cppunit library macros to add unit test the factory - */ - CPPUNIT_TEST_SUITE (HookManagerTest); - CPPUNIT_TEST (testAddAction); - CPPUNIT_TEST (testLargeUrl); - CPPUNIT_TEST_SUITE_END (); - - public: - /* - * Code factoring - Common resources can be initialized here. - * This method is called by unitcpp before each test - */ - void setUp(); - - void testAddAction (); - - void testLargeUrl (); - /* - * Code factoring - Common resources can be released here. - * This method is called by unitcpp after each test - */ - void tearDown (); - - private: - UrlHook *urlhook; -}; -CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(HookManagerTest, "HookManagerTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( HookManagerTest ); - -#endif diff --git a/daemon/test/instantmessagingtest.cpp b/daemon/test/instantmessagingtest.cpp index c6571636b826b0cd5c2127625e89450d1f49c190..89f0041a3f465f168c1d798a37c14d1fa448bc81 100644 --- a/daemon/test/instantmessagingtest.cpp +++ b/daemon/test/instantmessagingtest.cpp @@ -46,59 +46,59 @@ using std::endl; void InstantMessagingTest::setUp() { - _im = new sfl::InstantMessaging (); + im_ = new sfl::InstantMessaging(); } -void InstantMessagingTest::testSaveSingleMessage () +void InstantMessagingTest::testSaveSingleMessage() { - _debug ("-------------------- InstantMessagingTest::testSaveSingleMessage --------------------\n"); + DEBUG("-------------------- InstantMessagingTest::testSaveSingleMessage --------------------\n"); std::string input, tmp; std::string callID = "testfile1.txt"; std::string filename = "im:"; // Open a file stream and try to write in it - CPPUNIT_ASSERT (_im->saveMessage ("Bonjour, c'est un test d'archivage de message", "Manu", callID, std::ios::out) == true); + CPPUNIT_ASSERT(im_->saveMessage("Bonjour, c'est un test d'archivage de message", "Manu", callID, std::ios::out) == true); filename.append(callID); // Read it to check it has been successfully written - std::ifstream testfile (filename.c_str (), std::ios::in); - CPPUNIT_ASSERT (testfile.is_open () == true); + std::ifstream testfile(filename.c_str(), std::ios::in); + CPPUNIT_ASSERT(testfile.is_open() == true); - while (!testfile.eof ()) { - std::getline (testfile, tmp); - input.append (tmp); + while (!testfile.eof()) { + std::getline(testfile, tmp); + input.append(tmp); } - testfile.close (); - CPPUNIT_ASSERT (input == "[Manu] Bonjour, c'est un test d'archivage de message"); + testfile.close(); + CPPUNIT_ASSERT(input == "[Manu] Bonjour, c'est un test d'archivage de message"); } -void InstantMessagingTest::testSaveMultipleMessage () +void InstantMessagingTest::testSaveMultipleMessage() { - _debug ("-------------------- InstantMessagingTest::testSaveMultipleMessage --------------------\n"); + DEBUG("-------------------- InstantMessagingTest::testSaveMultipleMessage --------------------\n"); std::string input, tmp; std::string callID = "testfile2.txt"; std::string filename = "im:"; // Open a file stream and try to write in it - CPPUNIT_ASSERT (_im->saveMessage ("Bonjour, c'est un test d'archivage de message", "Manu", callID, std::ios::out) == true); - CPPUNIT_ASSERT (_im->saveMessage ("Cool", "Alex", callID, std::ios::out || std::ios::app) == true); + CPPUNIT_ASSERT(im_->saveMessage("Bonjour, c'est un test d'archivage de message", "Manu", callID, std::ios::out) == true); + CPPUNIT_ASSERT(im_->saveMessage("Cool", "Alex", callID, std::ios::out || std::ios::app) == true); filename.append(callID); // Read it to check it has been successfully written - std::ifstream testfile (filename.c_str (), std::ios::in); - CPPUNIT_ASSERT (testfile.is_open () == true); + std::ifstream testfile(filename.c_str(), std::ios::in); + CPPUNIT_ASSERT(testfile.is_open() == true); - while (!testfile.eof ()) { - std::getline (testfile, tmp); - input.append (tmp); + while (!testfile.eof()) { + std::getline(testfile, tmp); + input.append(tmp); } - testfile.close (); - printf ("%s\n", input.c_str()); - CPPUNIT_ASSERT (input == "[Manu] Bonjour, c'est un test d'archivage de message[Alex] Cool"); + testfile.close(); + printf("%s\n", input.c_str()); + CPPUNIT_ASSERT(input == "[Manu] Bonjour, c'est un test d'archivage de message[Alex] Cool"); } static inline char* duplicateString(char dst[], const char src[], size_t len) @@ -110,7 +110,7 @@ static inline char* duplicateString(char dst[], const char src[], size_t len) static void XMLCALL startElementCallback(void *userData, const char *name, const char **atts) { - + std::cout << "startElement " << name << std::endl; int *nbEntry = (int *)userData; @@ -119,23 +119,24 @@ static void XMLCALL startElementCallback(void *userData, const char *name, const char value[50]; const char **att; + for (att = atts; *att; att += 2) { - const char **val = att+1; - - duplicateString(attribute, *att, strlen(*att)); - std::cout << "att: " << attribute << std::endl; - - duplicateString(value, *val, strlen(*val)); - std::cout << "val: " << value << std::endl; - - if (strcmp(attribute, "uri") == 0) { - if((strcmp(value, "sip:alex@example.com") == 0) || - (strcmp(value, "sip:manu@example.com") == 0)) - CPPUNIT_ASSERT(true); - else - CPPUNIT_ASSERT(false); - } + const char **val = att+1; + + duplicateString(attribute, *att, strlen(*att)); + std::cout << "att: " << attribute << std::endl; + + duplicateString(value, *val, strlen(*val)); + std::cout << "val: " << value << std::endl; + + if (strcmp(attribute, "uri") == 0) { + if ((strcmp(value, "sip:alex@example.com") == 0) || + (strcmp(value, "sip:manu@example.com") == 0)) + CPPUNIT_ASSERT(true); + else + CPPUNIT_ASSERT(false); + } } *nbEntry += 1; @@ -144,12 +145,12 @@ static void XMLCALL startElementCallback(void *userData, const char *name, const static void XMLCALL endElementCallback(void * /*userData*/, const char * /*name*/) { - // std::cout << "endElement " << name << std::endl; + // std::cout << "endElement " << name << std::endl; } -void InstantMessagingTest::testGenerateXmlUriList () +void InstantMessagingTest::testGenerateXmlUriList() { - + std::cout << std::endl; // Create a test list with two entries @@ -164,21 +165,23 @@ void InstantMessagingTest::testGenerateXmlUriList () list.push_front(entry1); list.push_front(entry2); - std::string buffer = _im->generateXmlUriList(list); + std::string buffer = im_->generateXmlUriList(list); CPPUNIT_ASSERT(buffer.size() != 0); std::cout << buffer << std::endl; - + // parse the resuling xml (further tests are performed in callbacks) XML_Parser parser = XML_ParserCreate(NULL); int nbEntry = 0; XML_SetUserData(parser, &nbEntry); XML_SetElementHandler(parser, startElementCallback, endElementCallback); + if (XML_Parse(parser, buffer.c_str(), buffer.size(), 1) == XML_STATUS_ERROR) { - std::cout << "Error: " << XML_ErrorString(XML_GetErrorCode(parser)) + std::cout << "Error: " << XML_ErrorString(XML_GetErrorCode(parser)) << " at line " << XML_GetCurrentLineNumber(parser) << std::endl; CPPUNIT_ASSERT(false); } + XML_ParserFree(parser); CPPUNIT_ASSERT(nbEntry == 4); @@ -186,18 +189,18 @@ void InstantMessagingTest::testGenerateXmlUriList () CPPUNIT_ASSERT(true); } -void InstantMessagingTest::testXmlUriListParsing () +void InstantMessagingTest::testXmlUriListParsing() { std::string xmlbuffer = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; - xmlbuffer.append ("<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\" xmlns:cp=\"urn:ietf:params:xml:ns:copycontrol\">"); - xmlbuffer.append ("<list>"); - xmlbuffer.append ("<entry uri=\"sip:alex@example.com\" cp:copyControl=\"to\" />"); - xmlbuffer.append ("<entry uri=\"sip:manu@example.com\" cp:copyControl=\"to\" />"); - xmlbuffer.append ("</list>"); - xmlbuffer.append ("</resource-lists>"); + xmlbuffer.append("<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\" xmlns:cp=\"urn:ietf:params:xml:ns:copycontrol\">"); + xmlbuffer.append("<list>"); + xmlbuffer.append("<entry uri=\"sip:alex@example.com\" cp:copyControl=\"to\" />"); + xmlbuffer.append("<entry uri=\"sip:manu@example.com\" cp:copyControl=\"to\" />"); + xmlbuffer.append("</list>"); + xmlbuffer.append("</resource-lists>"); - sfl::InstantMessaging::UriList list = _im->parseXmlUriList(xmlbuffer); + sfl::InstantMessaging::UriList list = im_->parseXmlUriList(xmlbuffer); CPPUNIT_ASSERT(list.size() == 2); // An iterator over xml attribute @@ -206,38 +209,39 @@ void InstantMessagingTest::testXmlUriListParsing () // An iterator over list entries sfl::InstantMessaging::UriList::iterator iterEntry = list.begin(); - + while (iterEntry != list.end()) { - sfl::InstantMessaging::UriEntry entry = static_cast<sfl::InstantMessaging::UriEntry> (*iterEntry); - iterAttr = entry.find (sfl::IM_XML_URI); - - if((iterAttr->second == std::string("sip:alex@example.com")) || - (iterAttr->second == std::string("sip:manu@example.com"))) - CPPUNIT_ASSERT(true); - else - CPPUNIT_ASSERT(false); + sfl::InstantMessaging::UriEntry entry = static_cast<sfl::InstantMessaging::UriEntry>(*iterEntry); + iterAttr = entry.find(sfl::IM_XML_URI); + + if ((iterAttr->second == std::string("sip:alex@example.com")) || + (iterAttr->second == std::string("sip:manu@example.com"))) + CPPUNIT_ASSERT(true); + else + CPPUNIT_ASSERT(false); + iterEntry++; } } -void InstantMessagingTest::testGetTextArea () +void InstantMessagingTest::testGetTextArea() { std::string formatedText = "--boundary Content-Type: text/plain"; - formatedText.append ("Here is the text area"); + formatedText.append("Here is the text area"); - formatedText.append ("--boundary Content-Type: application/resource-lists+xml"); - formatedText.append ("Content-Disposition: recipient-list"); - formatedText.append ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); - formatedText.append ("<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\" xmlns:cp=\"urn:ietf:params:xml:ns:copycontrol\">"); - formatedText.append ("<list>"); - formatedText.append ("<entry uri=\"sip:alex@example.com\" cp:copyControl=\"to\" />"); - formatedText.append ("<entry uri=\"sip:manu@example.com\" cp:copyControl=\"to\" />"); - formatedText.append ("</list>"); - formatedText.append ("</resource-lists>"); - formatedText.append ("--boundary--"); + formatedText.append("--boundary Content-Type: application/resource-lists+xml"); + formatedText.append("Content-Disposition: recipient-list"); + formatedText.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); + formatedText.append("<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\" xmlns:cp=\"urn:ietf:params:xml:ns:copycontrol\">"); + formatedText.append("<list>"); + formatedText.append("<entry uri=\"sip:alex@example.com\" cp:copyControl=\"to\" />"); + formatedText.append("<entry uri=\"sip:manu@example.com\" cp:copyControl=\"to\" />"); + formatedText.append("</list>"); + formatedText.append("</resource-lists>"); + formatedText.append("--boundary--"); - std::string message = _im->findTextMessage(formatedText); + std::string message = im_->findTextMessage(formatedText); std::cout << "message " << message << std::endl; @@ -245,40 +249,40 @@ void InstantMessagingTest::testGetTextArea () } -void InstantMessagingTest::testGetUriListArea () +void InstantMessagingTest::testGetUriListArea() { std::string formatedText = "--boundary Content-Type: text/plain"; - formatedText.append ("Here is the text area"); + formatedText.append("Here is the text area"); - formatedText.append ("--boundary Content-Type: application/resource-lists+xml"); - formatedText.append ("Content-Disposition: recipient-list"); - formatedText.append ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); - formatedText.append ("<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\" xmlns:cp=\"urn:ietf:params:xml:ns:copycontrol\">"); - formatedText.append ("<list>"); - formatedText.append ("<entry uri=\"sip:alex@example.com\" cp:copyControl=\"to\" />"); - formatedText.append ("<entry uri=\"sip:manu@example.com\" cp:copyControl=\"to\" />"); - formatedText.append ("</list>"); - formatedText.append ("</resource-lists>"); - formatedText.append ("--boundary--"); + formatedText.append("--boundary Content-Type: application/resource-lists+xml"); + formatedText.append("Content-Disposition: recipient-list"); + formatedText.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); + formatedText.append("<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\" xmlns:cp=\"urn:ietf:params:xml:ns:copycontrol\">"); + formatedText.append("<list>"); + formatedText.append("<entry uri=\"sip:alex@example.com\" cp:copyControl=\"to\" />"); + formatedText.append("<entry uri=\"sip:manu@example.com\" cp:copyControl=\"to\" />"); + formatedText.append("</list>"); + formatedText.append("</resource-lists>"); + formatedText.append("--boundary--"); - std::string urilist = _im->findTextUriList(formatedText); + std::string urilist = im_->findTextUriList(formatedText); CPPUNIT_ASSERT(urilist.compare("<?xml version=\"1.0\" encoding=\"UTF-8\"?><resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\" xmlns:cp=\"urn:ietf:params:xml:ns:copycontrol\"><list><entry uri=\"sip:alex@example.com\" cp:copyControl=\"to\" /><entry uri=\"sip:manu@example.com\" cp:copyControl=\"to\" /></list></resource-lists>") == 0); std::cout << "urilist: " << urilist << std::endl; - sfl::InstantMessaging::UriList list = _im->parseXmlUriList(urilist); + sfl::InstantMessaging::UriList list = im_->parseXmlUriList(urilist); CPPUNIT_ASSERT(list.size() == 2); // order may be important, for example to identify message sender sfl::InstantMessaging::UriEntry entry = list.front(); CPPUNIT_ASSERT(entry.size() == 2); - sfl::InstantMessaging::UriEntry::iterator iterAttr = entry.find (sfl::IM_XML_URI); + sfl::InstantMessaging::UriEntry::iterator iterAttr = entry.find(sfl::IM_XML_URI); - if(iterAttr == entry.end()) { - std::cout << "Error, did not found attribute" << std::endl; - CPPUNIT_ASSERT(false); + if (iterAttr == entry.end()) { + std::cout << "Error, did not found attribute" << std::endl; + CPPUNIT_ASSERT(false); } std::string from = iterAttr->second; @@ -286,41 +290,41 @@ void InstantMessagingTest::testGetUriListArea () } -void InstantMessagingTest::testIllFormatedMessage () +void InstantMessagingTest::testIllFormatedMessage() { bool exceptionCaught = false; // SHOULD BE: Content-Type: text/plain std::string formatedText = "--boundary Content-Ty"; - formatedText.append ("Here is the text area"); - - formatedText.append ("--boundary Content-Type: application/resource-lists+xml"); - formatedText.append ("Content-Disposition: recipient-list"); - formatedText.append ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); - formatedText.append ("<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\" xmlns:cp=\"urn:ietf:params:xml:ns:copycontrol\">"); - formatedText.append ("<list>"); - formatedText.append ("<entry uri=\"sip:alex@example.com\" cp:copyControl=\"to\" />"); - formatedText.append ("<entry uri=\"sip:manu@example.com\" cp:copyControl=\"to\" />"); - formatedText.append ("</list>"); - formatedText.append ("</resource-lists>"); - formatedText.append ("--boundary--"); + formatedText.append("Here is the text area"); + + formatedText.append("--boundary Content-Type: application/resource-lists+xml"); + formatedText.append("Content-Disposition: recipient-list"); + formatedText.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); + formatedText.append("<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\" xmlns:cp=\"urn:ietf:params:xml:ns:copycontrol\">"); + formatedText.append("<list>"); + formatedText.append("<entry uri=\"sip:alex@example.com\" cp:copyControl=\"to\" />"); + formatedText.append("<entry uri=\"sip:manu@example.com\" cp:copyControl=\"to\" />"); + formatedText.append("</list>"); + formatedText.append("</resource-lists>"); + formatedText.append("--boundary--"); try { - std::string message = _im->findTextMessage(formatedText); + std::string message = im_->findTextMessage(formatedText); } catch (sfl::InstantMessageException &e) { - exceptionCaught = true; + exceptionCaught = true; } - if(exceptionCaught) - CPPUNIT_ASSERT(true); + if (exceptionCaught) + CPPUNIT_ASSERT(true); else - CPPUNIT_ASSERT(false); + CPPUNIT_ASSERT(false); } void InstantMessagingTest::tearDown() { - delete _im; - _im = 0; + delete im_; + im_ = 0; } diff --git a/daemon/test/instantmessagingtest.h b/daemon/test/instantmessagingtest.h index 2cab60a80c73acf4981fda4fb4e16ec2fbe8b887..867e19eedfdcfa91424c5870b5d203e9ad04113e 100644 --- a/daemon/test/instantmessagingtest.h +++ b/daemon/test/instantmessagingtest.h @@ -34,13 +34,14 @@ #include <cppunit/TestCase.h> #include <cppunit/TestSuite.h> -#include <assert.h> +#include <cassert> // Application import -#include "im/InstantMessaging.h" +#include "im/instant_messaging.h" +#include "noncopyable.h" /* - * @file instantmessagingtest.h + * @file instantmessagingtest.h * @brief Regroups unitary tests related to the instant messagin module */ @@ -49,22 +50,22 @@ class InstantMessagingTest : public CppUnit::TestCase { - /** - * Use cppunit library macros to add unit test the factory - */ - CPPUNIT_TEST_SUITE( InstantMessagingTest ); - CPPUNIT_TEST (testSaveSingleMessage); - CPPUNIT_TEST (testSaveMultipleMessage); - CPPUNIT_TEST (testGenerateXmlUriList); - CPPUNIT_TEST (testXmlUriListParsing); - CPPUNIT_TEST (testGetTextArea); - CPPUNIT_TEST (testGetUriListArea); - CPPUNIT_TEST (testIllFormatedMessage); - CPPUNIT_TEST_SUITE_END(); + /** + * Use cppunit library macros to add unit test the factory + */ + CPPUNIT_TEST_SUITE(InstantMessagingTest); + CPPUNIT_TEST(testSaveSingleMessage); + CPPUNIT_TEST(testSaveMultipleMessage); + CPPUNIT_TEST(testGenerateXmlUriList); + CPPUNIT_TEST(testXmlUriListParsing); + CPPUNIT_TEST(testGetTextArea); + CPPUNIT_TEST(testGetUriListArea); + CPPUNIT_TEST(testIllFormatedMessage); + CPPUNIT_TEST_SUITE_END(); public: - InstantMessagingTest() : CppUnit::TestCase("Instant messaging module Tests") {} - + InstantMessagingTest() : CppUnit::TestCase("Instant messaging module Tests"), im_(0) {} + /* * Code factoring - Common resources can be initialized here. * This method is called by unitcpp before each test @@ -75,28 +76,29 @@ class InstantMessagingTest : public CppUnit::TestCase { * Code factoring - Common resources can be released here. * This method is called by unitcpp after each test */ - void tearDown (); + void tearDown(); + + void testSaveSingleMessage(); - void testSaveSingleMessage (); - - void testSaveMultipleMessage (); + void testSaveMultipleMessage(); - void testGenerateXmlUriList (); + void testGenerateXmlUriList(); - void testXmlUriListParsing (); + void testXmlUriListParsing(); - void testGetTextArea (); + void testGetTextArea(); - void testGetUriListArea (); + void testGetUriListArea(); - void testIllFormatedMessage (); + void testIllFormatedMessage(); private: - sfl::InstantMessaging *_im; + NON_COPYABLE(InstantMessagingTest); + sfl::InstantMessaging *im_; }; /* Register our test module */ CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(InstantMessagingTest, "InstantMessagingTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( InstantMessagingTest ); +CPPUNIT_TEST_SUITE_REGISTRATION(InstantMessagingTest); #endif diff --git a/daemon/test/main.cpp b/daemon/test/main.cpp index 825101e65aae94c03dec41b1aff02f8511e4241e..72526b3019a7eb339b064482487a60a3f7507f27 100644 --- a/daemon/test/main.cpp +++ b/daemon/test/main.cpp @@ -39,46 +39,59 @@ #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/ui/text/TextTestRunner.h> -int main (int argc, char* argv[]) +namespace { + void restore() + { + if (system("mv " CONFIG_SAMPLE ".bak " CONFIG_SAMPLE) < 0) + ERROR("Restoration of %s failed", CONFIG_SAMPLE); + } + void backup() + { + if (system("cp " CONFIG_SAMPLE " " CONFIG_SAMPLE ".bak") < 0) + ERROR("Backup of %s failed", CONFIG_SAMPLE); + } +} + +int main(int argc, char* argv[]) { - printf ("\nSFLphone Daemon Test Suite, by Savoir-Faire Linux 2004-2010\n\n"); - Logger::setConsoleLog (true); - Logger::setDebugMode (true); + printf("\nSFLphone Daemon Test Suite, by Savoir-Faire Linux 2004-2010\n\n"); + Logger::setConsoleLog(true); + Logger::setDebugMode(true); int argvIndex = 1; - bool xmlOutput = false; + bool xmlOutput = false; if (argc > 1) { - if (strcmp ("--help", argv[1]) == 0) { + if (strcmp("--help", argv[1]) == 0) { argvIndex++; - CPPUNIT_NS::Test* suite = CPPUNIT_NS::TestFactoryRegistry::getRegistry ("All Tests").makeTest(); + CPPUNIT_NS::Test* suite = CPPUNIT_NS::TestFactoryRegistry::getRegistry("All Tests").makeTest(); int testSuiteCount = suite->getChildTestCount(); - printf ("Usage: test [OPTIONS] [TEST_SUITE]\n"); - printf ("\nOptions:\n"); - printf (" --xml - Output results in an XML file, instead of standard output.\n"); - printf (" --debug - Debug mode\n"); - printf (" --help - Print help\n"); - printf ("\nAvailable test suites:\n"); + printf("Usage: test [OPTIONS] [TEST_SUITE]\n"); + printf("\nOptions:\n"); + printf(" --xml - Output results in an XML file, instead of standard output.\n"); + printf(" --debug - Debug mode\n"); + printf(" --help - Print help\n"); + printf("\nAvailable test suites:\n"); for (int i = 0; i < testSuiteCount; i++) { - printf (" - %s\n", suite->getChildTestAt (i)->getName().c_str()); + printf(" - %s\n", suite->getChildTestAt(i)->getName().c_str()); } return 0; - } else if (strcmp ("--debug", argv[1]) == 0) { + } else if (strcmp("--debug", argv[1]) == 0) { argvIndex++; - Logger::setDebugMode (true); - _info ("Debug mode activated"); + Logger::setDebugMode(true); + INFO("Debug mode activated"); } else if (strcmp("--xml", argv[1]) == 0) { argvIndex++; - xmlOutput = true; - _info ("Using XML output"); - } + xmlOutput = true; + INFO("Using XML output"); + } } // Default test suite : all tests @@ -89,40 +102,40 @@ int main (int argc, char* argv[]) argvIndex++; } - printf ("\n\n=== SFLphone initialization ===\n\n"); - system("cp " CONFIG_SAMPLE " " CONFIG_SAMPLE ".bak"); + printf("\n\n=== SFLphone initialization ===\n\n"); + backup(); Manager::instance().init(CONFIG_SAMPLE); // Get the top level suite from the registry - printf ("\n\n=== Test Suite: %s ===\n\n", testSuiteName.c_str()); - CPPUNIT_NS::Test *suite = CPPUNIT_NS::TestFactoryRegistry::getRegistry (testSuiteName).makeTest(); + printf("\n\n=== Test Suite: %s ===\n\n", testSuiteName.c_str()); + CPPUNIT_NS::Test *suite = CPPUNIT_NS::TestFactoryRegistry::getRegistry(testSuiteName).makeTest(); if (suite->getChildTestCount() == 0) { - _error ("Invalid test suite name: %s", testSuiteName.c_str()); - system("mv " CONFIG_SAMPLE ".bak " CONFIG_SAMPLE); + ERROR("Invalid test suite name: %s", testSuiteName.c_str()); + restore(); return 1; } // Adds the test to the list of test to run CppUnit::TextTestRunner runner; - runner.addTest (suite); - /* Specify XML output */ - std::ofstream outfile("cppunitresults.xml"); - - if (xmlOutput) { - CppUnit::XmlOutputter* outputter = new CppUnit::XmlOutputter(&runner.result(), outfile); - runner.setOutputter(outputter); - } else { - // Change the default outputter to a compiler error format outputter - runner.setOutputter (new CppUnit::CompilerOutputter (&runner.result(), std::cerr)); - } + runner.addTest(suite); + /* Specify XML output */ + std::ofstream outfile("cppunitresults.xml"); + + if (xmlOutput) { + CppUnit::XmlOutputter* outputter = new CppUnit::XmlOutputter(&runner.result(), outfile); + runner.setOutputter(outputter); + } else { + // Change the default outputter to a compiler error format outputter + runner.setOutputter(new CppUnit::CompilerOutputter(&runner.result(), std::cerr)); + } // Run the tests. bool wasSuccessful = runner.run(); Manager::instance().terminate(); - system("mv " CONFIG_SAMPLE ".bak " CONFIG_SAMPLE); + restore(); return wasSuccessful ? 0 : 1; } diff --git a/daemon/test/mainbuffertest.cpp b/daemon/test/mainbuffertest.cpp index 05958fe473981f12ed3b41c8a4d597e1b4b2a887..94085b0c9ca68a83392e233d28fcae534006798a 100644 --- a/daemon/test/mainbuffertest.cpp +++ b/daemon/test/mainbuffertest.cpp @@ -64,7 +64,7 @@ void MainBufferTest::tearDown() void MainBufferTest::testRingBufferCreation() { - _debug ("-------------------- MainBufferTest::testRingBufferCreation --------------------\n"); + DEBUG("-------------------- MainBufferTest::testRingBufferCreation --------------------\n"); std::string test_id = "1234"; std::string null_id = "null id"; @@ -73,45 +73,45 @@ void MainBufferTest::testRingBufferCreation() RingBufferMap::iterator iter; // test mainbuffer ringbuffer map size - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 0); - test_ring_buffer = _mainbuffer.createRingBuffer (test_id); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 1); - - // test _mainbuffer.getRingBuffer method - CPPUNIT_ASSERT (test_ring_buffer != NULL); - CPPUNIT_ASSERT (_mainbuffer.getRingBuffer (null_id) == NULL); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 1); - CPPUNIT_ASSERT (_mainbuffer.getRingBuffer (test_id) == test_ring_buffer); - - // test _mainbuffer _ringBufferMap - iter = _mainbuffer._ringBufferMap.find (null_id); - CPPUNIT_ASSERT (iter == _mainbuffer._ringBufferMap.end()); - iter = _mainbuffer._ringBufferMap.find (test_id); - CPPUNIT_ASSERT (iter->first == test_id); - CPPUNIT_ASSERT (iter->second == test_ring_buffer); - CPPUNIT_ASSERT (iter->second == _mainbuffer.getRingBuffer (test_id)); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 0); + test_ring_buffer = mainbuffer_.createRingBuffer(test_id); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 1); + + // test mainbuffer_.getRingBuffer method + CPPUNIT_ASSERT(test_ring_buffer != NULL); + CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(null_id) == NULL); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 1); + CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(test_id) == test_ring_buffer); + + // test mainbuffer_ ringBufferMap_ + iter = mainbuffer_.ringBufferMap_.find(null_id); + CPPUNIT_ASSERT(iter == mainbuffer_.ringBufferMap_.end()); + iter = mainbuffer_.ringBufferMap_.find(test_id); + CPPUNIT_ASSERT(iter->first == test_id); + CPPUNIT_ASSERT(iter->second == test_ring_buffer); + CPPUNIT_ASSERT(iter->second == mainbuffer_.getRingBuffer(test_id)); // test creating twice a buffer (should not create it) - _mainbuffer.createRingBuffer (test_id); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 1); - CPPUNIT_ASSERT (_mainbuffer.getRingBuffer (test_id) == test_ring_buffer); + mainbuffer_.createRingBuffer(test_id); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 1); + CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(test_id) == test_ring_buffer); // test remove ring buffer - CPPUNIT_ASSERT (_mainbuffer.removeRingBuffer (null_id) == true); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 1); - CPPUNIT_ASSERT (_mainbuffer.removeRingBuffer (test_id) == true); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 0); - CPPUNIT_ASSERT (_mainbuffer.getRingBuffer (test_id) == NULL); + CPPUNIT_ASSERT(mainbuffer_.removeRingBuffer(null_id) == true); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 1); + CPPUNIT_ASSERT(mainbuffer_.removeRingBuffer(test_id) == true); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 0); + CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(test_id) == NULL); - iter = _mainbuffer._ringBufferMap.find (test_id); - CPPUNIT_ASSERT (iter == _mainbuffer._ringBufferMap.end()); + iter = mainbuffer_.ringBufferMap_.find(test_id); + CPPUNIT_ASSERT(iter == mainbuffer_.ringBufferMap_.end()); } void MainBufferTest::testRingBufferReadPointer() { - _debug ("-------------------- MainBufferTest::testRingBufferReadPointer --------------------\n"); + DEBUG("-------------------- MainBufferTest::testRingBufferReadPointer --------------------\n"); std::string call_id = "call id"; std::string read_id = "read id"; @@ -121,44 +121,44 @@ void MainBufferTest::testRingBufferReadPointer() RingBuffer* test_ring_buffer; // test ring buffer read pointers (one per participant) - test_ring_buffer = _mainbuffer.createRingBuffer (call_id); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 0); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (read_id) == (int) NULL); + test_ring_buffer = mainbuffer_.createRingBuffer(call_id); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 0); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(read_id) == (int) NULL); // create a read pointer - test_ring_buffer->createReadPointer (read_id); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 1); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (null_id) == (int) NULL); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (read_id) == 0); + test_ring_buffer->createReadPointer(read_id); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 1); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(null_id) == (int) NULL); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(read_id) == 0); // store read pointer - test_ring_buffer->storeReadPointer (4, read_id); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 1); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (read_id) == 4); + test_ring_buffer->storeReadPointer(4, read_id); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 1); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(read_id) == 4); // recreate the same read pointer (should not add a pointer neither chage its value) - test_ring_buffer->createReadPointer (read_id); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 1); - test_ring_buffer->storeReadPointer (8, read_id); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (read_id) == 8); + test_ring_buffer->createReadPointer(read_id); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 1); + test_ring_buffer->storeReadPointer(8, read_id); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(read_id) == 8); // test getSmallest read pointer (to get the length available to put data in the buffer) - test_ring_buffer->createReadPointer (other_id); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 2); - test_ring_buffer->storeReadPointer (4, other_id); - CPPUNIT_ASSERT (test_ring_buffer->getSmallestReadPointer() == 4); + test_ring_buffer->createReadPointer(other_id); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 2); + test_ring_buffer->storeReadPointer(4, other_id); + CPPUNIT_ASSERT(test_ring_buffer->getSmallestReadPointer() == 4); // remove read pointers - test_ring_buffer->removeReadPointer (other_id); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 1); - test_ring_buffer->removeReadPointer (read_id); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 0); + test_ring_buffer->removeReadPointer(other_id); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 1); + test_ring_buffer->removeReadPointer(read_id); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 0); } void MainBufferTest::testCallIDSet() { - _debug ("-------------------- MainBufferTest::testCallIDSet --------------------\n"); + DEBUG("-------------------- MainBufferTest::testCallIDSet --------------------\n"); std::string test_id = "set id"; std::string false_id = "false set id"; @@ -171,69 +171,69 @@ void MainBufferTest::testCallIDSet() std::string call_id_2 = "call id 2"; // test initial settings - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 0); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 0); - iter_map = _mainbuffer._callIDMap.find (test_id); - CPPUNIT_ASSERT (iter_map ==_mainbuffer._callIDMap.end()); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 0); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 0); + iter_map = mainbuffer_.callIDMap_.find(test_id); + CPPUNIT_ASSERT(iter_map ==mainbuffer_.callIDMap_.end()); // test callidset creation - _mainbuffer.createCallIDSet (test_id); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 1); - iter_map = _mainbuffer._callIDMap.find (test_id); - CPPUNIT_ASSERT (iter_map->first == test_id); - CPPUNIT_ASSERT (iter_map->second == _mainbuffer.getCallIDSet (test_id)); + mainbuffer_.createCallIDSet(test_id); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 1); + iter_map = mainbuffer_.callIDMap_.find(test_id); + CPPUNIT_ASSERT(iter_map->first == test_id); + CPPUNIT_ASSERT(iter_map->second == mainbuffer_.getCallIDSet(test_id)); - CPPUNIT_ASSERT (_mainbuffer.getCallIDSet (false_id) == NULL); - CPPUNIT_ASSERT (_mainbuffer.getCallIDSet (test_id) != NULL); + CPPUNIT_ASSERT(mainbuffer_.getCallIDSet(false_id) == NULL); + CPPUNIT_ASSERT(mainbuffer_.getCallIDSet(test_id) != NULL); // Test callIDSet add call_ids - _mainbuffer.addCallIDtoSet (test_id, call_id_1); - iter_map = _mainbuffer._callIDMap.find (test_id); - CPPUNIT_ASSERT (iter_map->second->size() == 1); - iter_set = iter_map->second->find (call_id_1); - CPPUNIT_ASSERT (*iter_set == call_id_1); + mainbuffer_.addCallIDtoSet(test_id, call_id_1); + iter_map = mainbuffer_.callIDMap_.find(test_id); + CPPUNIT_ASSERT(iter_map->second->size() == 1); + iter_set = iter_map->second->find(call_id_1); + CPPUNIT_ASSERT(*iter_set == call_id_1); // test add second call id to set - _mainbuffer.addCallIDtoSet (test_id, call_id_2); - iter_map = _mainbuffer._callIDMap.find (test_id); - CPPUNIT_ASSERT (iter_map->second->size() == 2); - iter_set = iter_map->second->find (call_id_2); - CPPUNIT_ASSERT (*iter_set == call_id_2); + mainbuffer_.addCallIDtoSet(test_id, call_id_2); + iter_map = mainbuffer_.callIDMap_.find(test_id); + CPPUNIT_ASSERT(iter_map->second->size() == 2); + iter_set = iter_map->second->find(call_id_2); + CPPUNIT_ASSERT(*iter_set == call_id_2); // test add a call id twice - _mainbuffer.addCallIDtoSet (test_id, call_id_2); - iter_map = _mainbuffer._callIDMap.find (test_id); - CPPUNIT_ASSERT (iter_map->second->size() == 2); - iter_set = iter_map->second->find (call_id_2); - CPPUNIT_ASSERT (*iter_set == call_id_2); + mainbuffer_.addCallIDtoSet(test_id, call_id_2); + iter_map = mainbuffer_.callIDMap_.find(test_id); + CPPUNIT_ASSERT(iter_map->second->size() == 2); + iter_set = iter_map->second->find(call_id_2); + CPPUNIT_ASSERT(*iter_set == call_id_2); // test remove a call id - _mainbuffer.removeCallIDfromSet (test_id, call_id_2); - iter_map = _mainbuffer._callIDMap.find (test_id); - CPPUNIT_ASSERT (iter_map->second->size() == 1); - iter_set = iter_map->second->find (call_id_1); - CPPUNIT_ASSERT (*iter_set == call_id_1); - iter_set = iter_map->second->find (call_id_2); - CPPUNIT_ASSERT (iter_set == iter_map->second->end()); + mainbuffer_.removeCallIDfromSet(test_id, call_id_2); + iter_map = mainbuffer_.callIDMap_.find(test_id); + CPPUNIT_ASSERT(iter_map->second->size() == 1); + iter_set = iter_map->second->find(call_id_1); + CPPUNIT_ASSERT(*iter_set == call_id_1); + iter_set = iter_map->second->find(call_id_2); + CPPUNIT_ASSERT(iter_set == iter_map->second->end()); // test remove a call id twice - _mainbuffer.removeCallIDfromSet (test_id, call_id_2); - iter_map = _mainbuffer._callIDMap.find (test_id); - CPPUNIT_ASSERT (iter_map->second->size() == 1); - iter_set = iter_map->second->find (call_id_1); - CPPUNIT_ASSERT (*iter_set == call_id_1); - iter_set = iter_map->second->find (call_id_2); - CPPUNIT_ASSERT (iter_set == iter_map->second->end()); + mainbuffer_.removeCallIDfromSet(test_id, call_id_2); + iter_map = mainbuffer_.callIDMap_.find(test_id); + CPPUNIT_ASSERT(iter_map->second->size() == 1); + iter_set = iter_map->second->find(call_id_1); + CPPUNIT_ASSERT(*iter_set == call_id_1); + iter_set = iter_map->second->find(call_id_2); + CPPUNIT_ASSERT(iter_set == iter_map->second->end()); // Test removeCallIDSet - CPPUNIT_ASSERT (_mainbuffer.removeCallIDSet (false_id) == false); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 1); - CPPUNIT_ASSERT (_mainbuffer.removeCallIDSet (test_id) == true); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 0); + CPPUNIT_ASSERT(mainbuffer_.removeCallIDSet(false_id) == false); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 1); + CPPUNIT_ASSERT(mainbuffer_.removeCallIDSet(test_id) == true); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 0); - iter_map = _mainbuffer._callIDMap.find (test_id); - CPPUNIT_ASSERT (iter_map ==_mainbuffer._callIDMap.end()); + iter_map = mainbuffer_.callIDMap_.find(test_id); + CPPUNIT_ASSERT(iter_map ==mainbuffer_.callIDMap_.end()); } @@ -241,7 +241,7 @@ void MainBufferTest::testCallIDSet() void MainBufferTest::testRingBufferInt() { - _debug ("-------------------- MainBufferTest::testRingBufferInt --------------------\n"); + DEBUG("-------------------- MainBufferTest::testRingBufferInt --------------------\n"); // CallID test_id = "test_int"; @@ -251,105 +251,105 @@ void MainBufferTest::testRingBufferInt() // test with default ring buffer - RingBuffer* test_ring_buffer = _mainbuffer.createRingBuffer (default_id); + RingBuffer* test_ring_buffer = mainbuffer_.createRingBuffer(default_id); // initial state init_put_size = test_ring_buffer->AvailForPut(); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer() == 0); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 0); // add some data - CPPUNIT_ASSERT (test_ring_buffer->Put (&testint1, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer() == 0); + CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 0); // add some other data - CPPUNIT_ASSERT (test_ring_buffer->Put (&testint2, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 2*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (init_put_size - 2* (int) sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer() == 0); + CPPUNIT_ASSERT(test_ring_buffer->Put(&testint2, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 2*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - 2* (int) sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 0); int testget = (int) NULL; // get some data (without any read pointers) - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet() == 2*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen() == 2*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->Get (&testget, sizeof (int)) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet() == 2*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen() == 2*sizeof (int)); - CPPUNIT_ASSERT (testget == (int) NULL); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (init_put_size - 2* (int) sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer() == 0); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 2*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen() == 2*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(int)) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 2*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen() == 2*sizeof(int)); + CPPUNIT_ASSERT(testget == (int) NULL); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - 2* (int) sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 0); // get some data (with a read pointer) - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 0); - test_ring_buffer->createReadPointer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 1); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet() == 0); - CPPUNIT_ASSERT (test_ring_buffer->getLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 0); + test_ring_buffer->createReadPointer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 1); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 0); + CPPUNIT_ASSERT(test_ring_buffer->getLen() == 0); // add some data - CPPUNIT_ASSERT (test_ring_buffer->Put (&testint1, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer() == 2*sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 2*sizeof(int)); // add some other data - CPPUNIT_ASSERT (test_ring_buffer->Put (&testint2, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 2*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (init_put_size - 2* (int) sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer() == 2*sizeof (int)); - - CPPUNIT_ASSERT (test_ring_buffer->Get (&testget, sizeof (int), 100, default_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen() == sizeof (int)); - CPPUNIT_ASSERT (testget == testint1); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer() == 3*sizeof (int)); - - CPPUNIT_ASSERT (test_ring_buffer->Get (&testget, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (testget == testint2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet() == 0); - CPPUNIT_ASSERT (test_ring_buffer->getLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_size); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer() == 4*sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->Put(&testint2, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 2*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - 2* (int) sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 2*sizeof(int)); + + CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(int), 100, default_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen() == sizeof(int)); + CPPUNIT_ASSERT(testget == testint1); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 3*sizeof(int)); + + CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(testget == testint2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 0); + CPPUNIT_ASSERT(test_ring_buffer->getLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_size); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 4*sizeof(int)); // test flush data init_put_size = test_ring_buffer->AvailForPut(); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->Put (&testint1, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen() == sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen() == sizeof(int)); test_ring_buffer->flush(); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_size); - CPPUNIT_ASSERT (test_ring_buffer->getLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet() == 0); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer() == 5*sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_size); + CPPUNIT_ASSERT(test_ring_buffer->getLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 0); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 5*sizeof(int)); // test flush data init_put_size = test_ring_buffer->AvailForPut(); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->Put (&testint1, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer() == 5*sizeof (int)); - - test_ring_buffer->Discard (sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_size); - CPPUNIT_ASSERT (test_ring_buffer->getLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet() == 0); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer() == 6*sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 5*sizeof(int)); + + test_ring_buffer->Discard(sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_size); + CPPUNIT_ASSERT(test_ring_buffer->getLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 0); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 6*sizeof(int)); } @@ -357,7 +357,7 @@ void MainBufferTest::testRingBufferInt() void MainBufferTest::testRingBufferNonDefaultID() { - _debug ("-------------------- MainBufferTest::testRingBufferNonDefaultID --------------------\n"); + DEBUG("-------------------- MainBufferTest::testRingBufferNonDefaultID --------------------\n"); std::string test_id = "test_int"; @@ -367,135 +367,135 @@ void MainBufferTest::testRingBufferNonDefaultID() // test putData, getData with arbitrary read pointer id - RingBuffer* test_ring_buffer = _mainbuffer.createRingBuffer (default_id); - test_ring_buffer->createReadPointer (test_id); + RingBuffer* test_ring_buffer = mainbuffer_.createRingBuffer(default_id); + test_ring_buffer->createReadPointer(test_id); init_put_size = test_ring_buffer->AvailForPut(); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->Put (&testint1, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->Put (&testint2, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 2*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (init_put_size - 2* (int) sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->Put(&testint2, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 2*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - 2* (int) sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(default_id) == 0); int testget; - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id) == 2*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_id) == 2*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->Get (&testget, sizeof (int), test_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_id) == sizeof (int)); - CPPUNIT_ASSERT (testget == testint1); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (test_id) == sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id) == 2*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_id) == 2*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(int), test_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_id) == sizeof(int)); + CPPUNIT_ASSERT(testget == testint1); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == sizeof(int)); - CPPUNIT_ASSERT (test_ring_buffer->Get (&testget, sizeof (int), 100, test_id) == sizeof (int)); - CPPUNIT_ASSERT (testget == testint2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_size); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (test_id) == 2*sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(int), 100, test_id) == sizeof(int)); + CPPUNIT_ASSERT(testget == testint2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_size); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == 2*sizeof(int)); // test flush data init_put_size = test_ring_buffer->AvailForPut(); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->Put (&testint1, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_id) == sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_id) == sizeof(int)); - test_ring_buffer->flush (test_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_size); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (test_id) == 3*sizeof (int)); + test_ring_buffer->flush(test_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_size); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == 3*sizeof(int)); // test flush data init_put_size = test_ring_buffer->AvailForPut(); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->Put (&testint1, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (test_id) == 3*sizeof (int)); - - test_ring_buffer->Discard (sizeof (int), test_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_size); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (test_id) == 4*sizeof (int)); - - test_ring_buffer->removeReadPointer (test_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (init_put_size - (int) sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == 3*sizeof(int)); + + test_ring_buffer->Discard(sizeof(int), test_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_size); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == 4*sizeof(int)); + + test_ring_buffer->removeReadPointer(test_id); } void MainBufferTest::testRingBufferFloat() { - _debug ("-------------------- MainBufferTest::testRingBufferFloat --------------------\n"); + DEBUG("-------------------- MainBufferTest::testRingBufferFloat --------------------\n"); float testfloat1 = 12.5; float testfloat2 = 13.4; - RingBuffer* test_ring_buffer = _mainbuffer.createRingBuffer (default_id); - test_ring_buffer->createReadPointer (default_id); + RingBuffer* test_ring_buffer = mainbuffer_.createRingBuffer(default_id); + test_ring_buffer->createReadPointer(default_id); - CPPUNIT_ASSERT (test_ring_buffer->Put (&testfloat1, sizeof (float)) == sizeof (float)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (float)); + CPPUNIT_ASSERT(test_ring_buffer->Put(&testfloat1, sizeof(float)) == sizeof(float)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(float)); - CPPUNIT_ASSERT (test_ring_buffer->Put (&testfloat2, sizeof (float)) == sizeof (float)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 2*sizeof (float)); + CPPUNIT_ASSERT(test_ring_buffer->Put(&testfloat2, sizeof(float)) == sizeof(float)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 2*sizeof(float)); float testget; - CPPUNIT_ASSERT (test_ring_buffer->Get (&testget, sizeof (float)) == sizeof (float)); - CPPUNIT_ASSERT (test_ring_buffer->getLen() == sizeof (float)); - CPPUNIT_ASSERT (testget == testfloat1); + CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(float)) == sizeof(float)); + CPPUNIT_ASSERT(test_ring_buffer->getLen() == sizeof(float)); + CPPUNIT_ASSERT(testget == testfloat1); - CPPUNIT_ASSERT (test_ring_buffer->Get (&testget, sizeof (float)) == sizeof (float)); - CPPUNIT_ASSERT (testget == testfloat2); - CPPUNIT_ASSERT (test_ring_buffer->getLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->Get(&testget, sizeof(float)) == sizeof(float)); + CPPUNIT_ASSERT(testget == testfloat2); + CPPUNIT_ASSERT(test_ring_buffer->getLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->Put (&testfloat1, sizeof (float)) == sizeof (float)); + CPPUNIT_ASSERT(test_ring_buffer->Put(&testfloat1, sizeof(float)) == sizeof(float)); test_ring_buffer->flush(); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); } void MainBufferTest::testTwoPointer() { - _debug ("-------------------- MainBufferTest::testTwoPointer --------------------\n"); + DEBUG("-------------------- MainBufferTest::testTwoPointer --------------------\n"); - RingBuffer* input_buffer = _mainbuffer.createRingBuffer (default_id); - input_buffer->createReadPointer (default_id); - RingBuffer* output_buffer = _mainbuffer.getRingBuffer (default_id); + RingBuffer* input_buffer = mainbuffer_.createRingBuffer(default_id); + input_buffer->createReadPointer(default_id); + RingBuffer* output_buffer = mainbuffer_.getRingBuffer(default_id); int test_input = 12; int test_output; - CPPUNIT_ASSERT (input_buffer->Put (&test_input, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (output_buffer->Get (&test_output, sizeof (float)) == sizeof (float)); - CPPUNIT_ASSERT (test_input == test_output); + CPPUNIT_ASSERT(input_buffer->Put(&test_input, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(output_buffer->Get(&test_output, sizeof(float)) == sizeof(float)); + CPPUNIT_ASSERT(test_input == test_output); } void MainBufferTest::testBindUnbindBuffer() { - _debug ("-------------------- MainBufferTest::testBindUnbindBuffer --------------------\n"); + DEBUG("-------------------- MainBufferTest::testBindUnbindBuffer --------------------\n"); std::string test_id1 = "bind unbind 1"; std::string test_id2 = "bind unbind 2"; @@ -509,397 +509,397 @@ void MainBufferTest::testBindUnbindBuffer() RingBuffer* ringbuffer; // test initial state with no ring brffer created - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 0); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 0); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 0); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 0); - iter_buffer = _mainbuffer._ringBufferMap.find (default_id); - CPPUNIT_ASSERT (iter_buffer == _mainbuffer._ringBufferMap.end()); - iter_idset = _mainbuffer._callIDMap.find (default_id); - CPPUNIT_ASSERT (iter_idset == _mainbuffer._callIDMap.end()); + iter_buffer = mainbuffer_.ringBufferMap_.find(default_id); + CPPUNIT_ASSERT(iter_buffer == mainbuffer_.ringBufferMap_.end()); + iter_idset = mainbuffer_.callIDMap_.find(default_id); + CPPUNIT_ASSERT(iter_idset == mainbuffer_.callIDMap_.end()); // bind test_id1 with default_id (both buffer not already created) - _mainbuffer.bindCallID (test_id1); + mainbuffer_.bindCallID(test_id1); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 2); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 2); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 2); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 2); - iter_buffer = _mainbuffer._ringBufferMap.find (default_id); - CPPUNIT_ASSERT (iter_buffer->first == default_id); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (default_id)); + iter_buffer = mainbuffer_.ringBufferMap_.find(default_id); + CPPUNIT_ASSERT(iter_buffer->first == default_id); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(default_id)); - iter_buffer = _mainbuffer._ringBufferMap.find (test_id1); - CPPUNIT_ASSERT (iter_buffer->first == test_id1); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (test_id1)); + iter_buffer = mainbuffer_.ringBufferMap_.find(test_id1); + CPPUNIT_ASSERT(iter_buffer->first == test_id1); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id1)); - iter_idset = _mainbuffer._callIDMap.find (default_id); - CPPUNIT_ASSERT (iter_idset->second->size() == 1); - iter_id = iter_idset->second->find (test_id1); - CPPUNIT_ASSERT (*iter_id == test_id1); + iter_idset = mainbuffer_.callIDMap_.find(default_id); + CPPUNIT_ASSERT(iter_idset->second->size() == 1); + iter_id = iter_idset->second->find(test_id1); + CPPUNIT_ASSERT(*iter_id == test_id1); - iter_idset = _mainbuffer._callIDMap.find (test_id1); - CPPUNIT_ASSERT (iter_idset->second->size() == 1); - iter_id = iter_idset->second->find (default_id); - CPPUNIT_ASSERT (*iter_id == default_id); + iter_idset = mainbuffer_.callIDMap_.find(test_id1); + CPPUNIT_ASSERT(iter_idset->second->size() == 1); + iter_id = iter_idset->second->find(default_id); + CPPUNIT_ASSERT(*iter_id == default_id); - ringbuffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 1); - iter_readpointer = ringbuffer->_readpointer.find (test_id1); - CPPUNIT_ASSERT (iter_readpointer->first == test_id1); - CPPUNIT_ASSERT (iter_readpointer->second == 0); + ringbuffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1); + iter_readpointer = ringbuffer->_readpointer.find(test_id1); + CPPUNIT_ASSERT(iter_readpointer->first == test_id1); + CPPUNIT_ASSERT(iter_readpointer->second == 0); - ringbuffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 1); - iter_readpointer = ringbuffer->_readpointer.find (default_id); - CPPUNIT_ASSERT (iter_readpointer->first == default_id); - CPPUNIT_ASSERT (iter_readpointer->second == 0); + ringbuffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1); + iter_readpointer = ringbuffer->_readpointer.find(default_id); + CPPUNIT_ASSERT(iter_readpointer->first == default_id); + CPPUNIT_ASSERT(iter_readpointer->second == 0); // unbind test_id1 with default_id - _mainbuffer.unBindCallID (test_id1); + mainbuffer_.unBindCallID(test_id1); - _debug ("%i", (int) (_mainbuffer._ringBufferMap.size())); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 0); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 0); + DEBUG("%i", (int)(mainbuffer_.ringBufferMap_.size())); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 0); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 0); - CPPUNIT_ASSERT (_mainbuffer.getRingBuffer (default_id) == NULL); - CPPUNIT_ASSERT (_mainbuffer.getRingBuffer (test_id1) == NULL); + CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(default_id) == NULL); + CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(test_id1) == NULL); // bind test_id2 with default_id (default_id already created) // calling it twice not supposed to break anything - _mainbuffer.bindCallID (test_id1, default_id); - _mainbuffer.bindCallID (test_id1, default_id); - - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 2); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 2); - - iter_buffer = _mainbuffer._ringBufferMap.find (test_id2); - CPPUNIT_ASSERT (iter_buffer == _mainbuffer._ringBufferMap.end()); - iter_idset = _mainbuffer._callIDMap.find (test_id2); - CPPUNIT_ASSERT (iter_idset == _mainbuffer._callIDMap.end()); - - _mainbuffer.bindCallID (test_id2, default_id); - _mainbuffer.bindCallID (test_id2, default_id); - - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 3); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 3); - - iter_buffer = _mainbuffer._ringBufferMap.find (default_id); - CPPUNIT_ASSERT (iter_buffer->first == default_id); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (default_id)); - - iter_buffer = _mainbuffer._ringBufferMap.find (test_id1); - CPPUNIT_ASSERT (iter_buffer->first == test_id1); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (test_id1)); - - iter_buffer = _mainbuffer._ringBufferMap.find (test_id2); - CPPUNIT_ASSERT (iter_buffer->first == test_id2); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (test_id2)); - - iter_idset = _mainbuffer._callIDMap.find (default_id); - CPPUNIT_ASSERT (iter_idset->second->size() == 2); - iter_id = iter_idset->second->find (test_id1); - CPPUNIT_ASSERT (*iter_id == test_id1); - iter_id = iter_idset->second->find (test_id2); - CPPUNIT_ASSERT (*iter_id == test_id2); - - iter_idset = _mainbuffer._callIDMap.find (test_id1); - CPPUNIT_ASSERT (iter_idset->second->size() == 1); - iter_id = iter_idset->second->find (default_id); - CPPUNIT_ASSERT (*iter_id == default_id); - - iter_idset = _mainbuffer._callIDMap.find (test_id2); - CPPUNIT_ASSERT (iter_idset->second->size() == 1); - iter_id = iter_idset->second->find (default_id); - CPPUNIT_ASSERT (*iter_id == default_id); - - ringbuffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 2); - iter_readpointer = ringbuffer->_readpointer.find (test_id1); - CPPUNIT_ASSERT (iter_readpointer->first == test_id1); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - iter_readpointer = ringbuffer->_readpointer.find (test_id2); - CPPUNIT_ASSERT (iter_readpointer->first == test_id2); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - - ringbuffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 1); - iter_readpointer = ringbuffer->_readpointer.find (default_id); - CPPUNIT_ASSERT (iter_readpointer->first == default_id); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - - ringbuffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 1); - iter_readpointer = ringbuffer->_readpointer.find (default_id); - CPPUNIT_ASSERT (iter_readpointer->first == default_id); - CPPUNIT_ASSERT (iter_readpointer->second == 0); + mainbuffer_.bindCallID(test_id1, default_id); + mainbuffer_.bindCallID(test_id1, default_id); + + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 2); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 2); + + iter_buffer = mainbuffer_.ringBufferMap_.find(test_id2); + CPPUNIT_ASSERT(iter_buffer == mainbuffer_.ringBufferMap_.end()); + iter_idset = mainbuffer_.callIDMap_.find(test_id2); + CPPUNIT_ASSERT(iter_idset == mainbuffer_.callIDMap_.end()); + + mainbuffer_.bindCallID(test_id2, default_id); + mainbuffer_.bindCallID(test_id2, default_id); + + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 3); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 3); + + iter_buffer = mainbuffer_.ringBufferMap_.find(default_id); + CPPUNIT_ASSERT(iter_buffer->first == default_id); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(default_id)); + + iter_buffer = mainbuffer_.ringBufferMap_.find(test_id1); + CPPUNIT_ASSERT(iter_buffer->first == test_id1); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id1)); + + iter_buffer = mainbuffer_.ringBufferMap_.find(test_id2); + CPPUNIT_ASSERT(iter_buffer->first == test_id2); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id2)); + + iter_idset = mainbuffer_.callIDMap_.find(default_id); + CPPUNIT_ASSERT(iter_idset->second->size() == 2); + iter_id = iter_idset->second->find(test_id1); + CPPUNIT_ASSERT(*iter_id == test_id1); + iter_id = iter_idset->second->find(test_id2); + CPPUNIT_ASSERT(*iter_id == test_id2); + + iter_idset = mainbuffer_.callIDMap_.find(test_id1); + CPPUNIT_ASSERT(iter_idset->second->size() == 1); + iter_id = iter_idset->second->find(default_id); + CPPUNIT_ASSERT(*iter_id == default_id); + + iter_idset = mainbuffer_.callIDMap_.find(test_id2); + CPPUNIT_ASSERT(iter_idset->second->size() == 1); + iter_id = iter_idset->second->find(default_id); + CPPUNIT_ASSERT(*iter_id == default_id); + + ringbuffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 2); + iter_readpointer = ringbuffer->_readpointer.find(test_id1); + CPPUNIT_ASSERT(iter_readpointer->first == test_id1); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + iter_readpointer = ringbuffer->_readpointer.find(test_id2); + CPPUNIT_ASSERT(iter_readpointer->first == test_id2); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + + ringbuffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1); + iter_readpointer = ringbuffer->_readpointer.find(default_id); + CPPUNIT_ASSERT(iter_readpointer->first == default_id); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + + ringbuffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1); + iter_readpointer = ringbuffer->_readpointer.find(default_id); + CPPUNIT_ASSERT(iter_readpointer->first == default_id); + CPPUNIT_ASSERT(iter_readpointer->second == 0); // bind test_id1 with test_id2 (both testid1 and test_id2 already created) // calling it twice not supposed to break anything - _mainbuffer.bindCallID (test_id1, test_id2); - _mainbuffer.bindCallID (test_id1, test_id2); - - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 3); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 3); - - iter_buffer = _mainbuffer._ringBufferMap.find (default_id); - CPPUNIT_ASSERT (iter_buffer->first == default_id); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (default_id)); - - iter_buffer = _mainbuffer._ringBufferMap.find (test_id1); - CPPUNIT_ASSERT (iter_buffer->first == test_id1); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (test_id1)); - - iter_buffer = _mainbuffer._ringBufferMap.find (test_id2); - CPPUNIT_ASSERT (iter_buffer->first == test_id2); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (test_id2)); - - iter_idset = _mainbuffer._callIDMap.find (default_id); - CPPUNIT_ASSERT (iter_idset->second->size() == 2); - iter_id = iter_idset->second->find (test_id1); - CPPUNIT_ASSERT (*iter_id == test_id1); - iter_id = iter_idset->second->find (test_id2); - CPPUNIT_ASSERT (*iter_id == test_id2); - - iter_idset = _mainbuffer._callIDMap.find (test_id1); - CPPUNIT_ASSERT (iter_idset->second->size() == 2); - iter_id = iter_idset->second->find (default_id); - CPPUNIT_ASSERT (*iter_id == default_id); - iter_id = iter_idset->second->find (test_id2); - CPPUNIT_ASSERT (*iter_id == test_id2); - - iter_idset = _mainbuffer._callIDMap.find (test_id2); - CPPUNIT_ASSERT (iter_idset->second->size() == 2); - iter_id = iter_idset->second->find (default_id); - CPPUNIT_ASSERT (*iter_id == default_id); - iter_id = iter_idset->second->find (test_id1); - CPPUNIT_ASSERT (*iter_id == test_id1); - - ringbuffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 2); - iter_readpointer = ringbuffer->_readpointer.find (test_id1); - CPPUNIT_ASSERT (iter_readpointer->first == test_id1); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - iter_readpointer = ringbuffer->_readpointer.find (test_id2); - CPPUNIT_ASSERT (iter_readpointer->first == test_id2); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - - ringbuffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 2); - iter_readpointer = ringbuffer->_readpointer.find (default_id); - CPPUNIT_ASSERT (iter_readpointer->first == default_id); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - iter_readpointer = ringbuffer->_readpointer.find (test_id2); - CPPUNIT_ASSERT (iter_readpointer->first == test_id2); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - - ringbuffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 2); - iter_readpointer = ringbuffer->_readpointer.find (default_id); - CPPUNIT_ASSERT (iter_readpointer->first == default_id); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - iter_readpointer = ringbuffer->_readpointer.find (test_id1); - CPPUNIT_ASSERT (iter_readpointer->first == test_id1); - CPPUNIT_ASSERT (iter_readpointer->second == 0); + mainbuffer_.bindCallID(test_id1, test_id2); + mainbuffer_.bindCallID(test_id1, test_id2); + + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 3); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 3); + + iter_buffer = mainbuffer_.ringBufferMap_.find(default_id); + CPPUNIT_ASSERT(iter_buffer->first == default_id); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(default_id)); + + iter_buffer = mainbuffer_.ringBufferMap_.find(test_id1); + CPPUNIT_ASSERT(iter_buffer->first == test_id1); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id1)); + + iter_buffer = mainbuffer_.ringBufferMap_.find(test_id2); + CPPUNIT_ASSERT(iter_buffer->first == test_id2); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id2)); + + iter_idset = mainbuffer_.callIDMap_.find(default_id); + CPPUNIT_ASSERT(iter_idset->second->size() == 2); + iter_id = iter_idset->second->find(test_id1); + CPPUNIT_ASSERT(*iter_id == test_id1); + iter_id = iter_idset->second->find(test_id2); + CPPUNIT_ASSERT(*iter_id == test_id2); + + iter_idset = mainbuffer_.callIDMap_.find(test_id1); + CPPUNIT_ASSERT(iter_idset->second->size() == 2); + iter_id = iter_idset->second->find(default_id); + CPPUNIT_ASSERT(*iter_id == default_id); + iter_id = iter_idset->second->find(test_id2); + CPPUNIT_ASSERT(*iter_id == test_id2); + + iter_idset = mainbuffer_.callIDMap_.find(test_id2); + CPPUNIT_ASSERT(iter_idset->second->size() == 2); + iter_id = iter_idset->second->find(default_id); + CPPUNIT_ASSERT(*iter_id == default_id); + iter_id = iter_idset->second->find(test_id1); + CPPUNIT_ASSERT(*iter_id == test_id1); + + ringbuffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 2); + iter_readpointer = ringbuffer->_readpointer.find(test_id1); + CPPUNIT_ASSERT(iter_readpointer->first == test_id1); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + iter_readpointer = ringbuffer->_readpointer.find(test_id2); + CPPUNIT_ASSERT(iter_readpointer->first == test_id2); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + + ringbuffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 2); + iter_readpointer = ringbuffer->_readpointer.find(default_id); + CPPUNIT_ASSERT(iter_readpointer->first == default_id); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + iter_readpointer = ringbuffer->_readpointer.find(test_id2); + CPPUNIT_ASSERT(iter_readpointer->first == test_id2); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + + ringbuffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 2); + iter_readpointer = ringbuffer->_readpointer.find(default_id); + CPPUNIT_ASSERT(iter_readpointer->first == default_id); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + iter_readpointer = ringbuffer->_readpointer.find(test_id1); + CPPUNIT_ASSERT(iter_readpointer->first == test_id1); + CPPUNIT_ASSERT(iter_readpointer->second == 0); // unbind test_id1 with test_id2 // calling it twice not supposed to break anything - _mainbuffer.unBindCallID (test_id1, test_id2); - _mainbuffer.unBindCallID (test_id1, test_id2); - - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 3); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 3); - - iter_buffer = _mainbuffer._ringBufferMap.find (default_id); - CPPUNIT_ASSERT (iter_buffer->first == default_id); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (default_id)); - - iter_buffer = _mainbuffer._ringBufferMap.find (test_id1); - CPPUNIT_ASSERT (iter_buffer->first == test_id1); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (test_id1)); - - iter_buffer = _mainbuffer._ringBufferMap.find (test_id2); - CPPUNIT_ASSERT (iter_buffer->first == test_id2); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (test_id2)); - - iter_idset = _mainbuffer._callIDMap.find (default_id); - CPPUNIT_ASSERT (iter_idset->second->size() == 2); - iter_id = iter_idset->second->find (test_id1); - CPPUNIT_ASSERT (*iter_id == test_id1); - iter_id = iter_idset->second->find (test_id2); - CPPUNIT_ASSERT (*iter_id == test_id2); - - iter_idset = _mainbuffer._callIDMap.find (test_id1); - CPPUNIT_ASSERT (iter_idset->second->size() == 1); - iter_id = iter_idset->second->find (default_id); - CPPUNIT_ASSERT (*iter_id == default_id); - - iter_idset = _mainbuffer._callIDMap.find (test_id2); - CPPUNIT_ASSERT (iter_idset->second->size() == 1); - iter_id = iter_idset->second->find (default_id); - CPPUNIT_ASSERT (*iter_id == default_id); - - ringbuffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 2); - iter_readpointer = ringbuffer->_readpointer.find (test_id1); - CPPUNIT_ASSERT (iter_readpointer->first == test_id1); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - iter_readpointer = ringbuffer->_readpointer.find (test_id2); - CPPUNIT_ASSERT (iter_readpointer->first == test_id2); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - - ringbuffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 1); - iter_readpointer = ringbuffer->_readpointer.find (default_id); - CPPUNIT_ASSERT (iter_readpointer->first == default_id); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - - ringbuffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 1); - iter_readpointer = ringbuffer->_readpointer.find (default_id); - CPPUNIT_ASSERT (iter_readpointer->first == default_id); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - - - _debug ("ok1"); + mainbuffer_.unBindCallID(test_id1, test_id2); + mainbuffer_.unBindCallID(test_id1, test_id2); + + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 3); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 3); + + iter_buffer = mainbuffer_.ringBufferMap_.find(default_id); + CPPUNIT_ASSERT(iter_buffer->first == default_id); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(default_id)); + + iter_buffer = mainbuffer_.ringBufferMap_.find(test_id1); + CPPUNIT_ASSERT(iter_buffer->first == test_id1); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id1)); + + iter_buffer = mainbuffer_.ringBufferMap_.find(test_id2); + CPPUNIT_ASSERT(iter_buffer->first == test_id2); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id2)); + + iter_idset = mainbuffer_.callIDMap_.find(default_id); + CPPUNIT_ASSERT(iter_idset->second->size() == 2); + iter_id = iter_idset->second->find(test_id1); + CPPUNIT_ASSERT(*iter_id == test_id1); + iter_id = iter_idset->second->find(test_id2); + CPPUNIT_ASSERT(*iter_id == test_id2); + + iter_idset = mainbuffer_.callIDMap_.find(test_id1); + CPPUNIT_ASSERT(iter_idset->second->size() == 1); + iter_id = iter_idset->second->find(default_id); + CPPUNIT_ASSERT(*iter_id == default_id); + + iter_idset = mainbuffer_.callIDMap_.find(test_id2); + CPPUNIT_ASSERT(iter_idset->second->size() == 1); + iter_id = iter_idset->second->find(default_id); + CPPUNIT_ASSERT(*iter_id == default_id); + + ringbuffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 2); + iter_readpointer = ringbuffer->_readpointer.find(test_id1); + CPPUNIT_ASSERT(iter_readpointer->first == test_id1); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + iter_readpointer = ringbuffer->_readpointer.find(test_id2); + CPPUNIT_ASSERT(iter_readpointer->first == test_id2); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + + ringbuffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1); + iter_readpointer = ringbuffer->_readpointer.find(default_id); + CPPUNIT_ASSERT(iter_readpointer->first == default_id); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + + ringbuffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1); + iter_readpointer = ringbuffer->_readpointer.find(default_id); + CPPUNIT_ASSERT(iter_readpointer->first == default_id); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + + + DEBUG("ok1"); // unbind test_id1 with test_id2 // calling it twice not supposed to break anything - _mainbuffer.unBindCallID (default_id, test_id2); - _mainbuffer.unBindCallID (default_id, test_id2); + mainbuffer_.unBindCallID(default_id, test_id2); + mainbuffer_.unBindCallID(default_id, test_id2); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 2); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 2); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 2); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 2); - iter_buffer = _mainbuffer._ringBufferMap.find (default_id); - CPPUNIT_ASSERT (iter_buffer->first == default_id); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (default_id)); + iter_buffer = mainbuffer_.ringBufferMap_.find(default_id); + CPPUNIT_ASSERT(iter_buffer->first == default_id); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(default_id)); - iter_buffer = _mainbuffer._ringBufferMap.find (test_id1); - CPPUNIT_ASSERT (iter_buffer->first == test_id1); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (test_id1)); + iter_buffer = mainbuffer_.ringBufferMap_.find(test_id1); + CPPUNIT_ASSERT(iter_buffer->first == test_id1); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id1)); - iter_buffer = _mainbuffer._ringBufferMap.find (test_id2); - CPPUNIT_ASSERT (iter_buffer == _mainbuffer._ringBufferMap.end()); + iter_buffer = mainbuffer_.ringBufferMap_.find(test_id2); + CPPUNIT_ASSERT(iter_buffer == mainbuffer_.ringBufferMap_.end()); - iter_idset = _mainbuffer._callIDMap.find (default_id); - CPPUNIT_ASSERT (iter_idset->second->size() == 1); - iter_id = iter_idset->second->find (test_id1); - CPPUNIT_ASSERT (*iter_id == test_id1); - iter_id = iter_idset->second->find (test_id2); - CPPUNIT_ASSERT (iter_id == iter_idset->second->end()); + iter_idset = mainbuffer_.callIDMap_.find(default_id); + CPPUNIT_ASSERT(iter_idset->second->size() == 1); + iter_id = iter_idset->second->find(test_id1); + CPPUNIT_ASSERT(*iter_id == test_id1); + iter_id = iter_idset->second->find(test_id2); + CPPUNIT_ASSERT(iter_id == iter_idset->second->end()); - iter_idset = _mainbuffer._callIDMap.find (test_id1); - CPPUNIT_ASSERT (iter_idset->second->size() == 1); - iter_id = iter_idset->second->find (default_id); - CPPUNIT_ASSERT (*iter_id == default_id); + iter_idset = mainbuffer_.callIDMap_.find(test_id1); + CPPUNIT_ASSERT(iter_idset->second->size() == 1); + iter_id = iter_idset->second->find(default_id); + CPPUNIT_ASSERT(*iter_id == default_id); - iter_idset = _mainbuffer._callIDMap.find (test_id2); - CPPUNIT_ASSERT (iter_idset == _mainbuffer._callIDMap.end()); + iter_idset = mainbuffer_.callIDMap_.find(test_id2); + CPPUNIT_ASSERT(iter_idset == mainbuffer_.callIDMap_.end()); - ringbuffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 1); - iter_readpointer = ringbuffer->_readpointer.find (test_id1); - CPPUNIT_ASSERT (iter_readpointer->first == test_id1); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - iter_readpointer = ringbuffer->_readpointer.find (test_id2); - CPPUNIT_ASSERT (iter_readpointer == ringbuffer->_readpointer.end()); + ringbuffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1); + iter_readpointer = ringbuffer->_readpointer.find(test_id1); + CPPUNIT_ASSERT(iter_readpointer->first == test_id1); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + iter_readpointer = ringbuffer->_readpointer.find(test_id2); + CPPUNIT_ASSERT(iter_readpointer == ringbuffer->_readpointer.end()); - ringbuffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 1); - iter_readpointer = ringbuffer->_readpointer.find (default_id); - CPPUNIT_ASSERT (iter_readpointer->first == default_id); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - iter_readpointer = ringbuffer->_readpointer.find (test_id2); - CPPUNIT_ASSERT (iter_readpointer == ringbuffer->_readpointer.end()); + ringbuffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1); + iter_readpointer = ringbuffer->_readpointer.find(default_id); + CPPUNIT_ASSERT(iter_readpointer->first == default_id); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + iter_readpointer = ringbuffer->_readpointer.find(test_id2); + CPPUNIT_ASSERT(iter_readpointer == ringbuffer->_readpointer.end()); - CPPUNIT_ASSERT (_mainbuffer.getRingBuffer (test_id2) == NULL); + CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(test_id2) == NULL); - _mainbuffer.unBindCallID (default_id, test_id1); + mainbuffer_.unBindCallID(default_id, test_id1); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 0); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 0); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 0); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 0); // test unbind all function - _mainbuffer.bindCallID (default_id, test_id1); - _mainbuffer.bindCallID (default_id, test_id2); - _mainbuffer.bindCallID (test_id1, test_id2); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 3); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 3); - - _mainbuffer.unBindAll (test_id2); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 2); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 2); - - iter_buffer = _mainbuffer._ringBufferMap.find (default_id); - CPPUNIT_ASSERT (iter_buffer->first == default_id); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (default_id)); - - iter_buffer = _mainbuffer._ringBufferMap.find (test_id1); - CPPUNIT_ASSERT (iter_buffer->first == test_id1); - CPPUNIT_ASSERT (iter_buffer->second == _mainbuffer.getRingBuffer (test_id1)); - - iter_buffer = _mainbuffer._ringBufferMap.find (test_id2); - CPPUNIT_ASSERT (iter_buffer == _mainbuffer._ringBufferMap.end()); - - iter_idset = _mainbuffer._callIDMap.find (default_id); - CPPUNIT_ASSERT (iter_idset->second->size() == 1); - iter_id = iter_idset->second->find (test_id1); - CPPUNIT_ASSERT (*iter_id == test_id1); - iter_id = iter_idset->second->find (test_id2); - CPPUNIT_ASSERT (iter_id == iter_idset->second->end()); - - iter_idset = _mainbuffer._callIDMap.find (test_id1); - CPPUNIT_ASSERT (iter_idset->second->size() == 1); - iter_id = iter_idset->second->find (default_id); - CPPUNIT_ASSERT (*iter_id == default_id); - - iter_idset = _mainbuffer._callIDMap.find (test_id2); - CPPUNIT_ASSERT (iter_idset == _mainbuffer._callIDMap.end()); - - ringbuffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 1); - iter_readpointer = ringbuffer->_readpointer.find (test_id1); - CPPUNIT_ASSERT (iter_readpointer->first == test_id1); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - iter_readpointer = ringbuffer->_readpointer.find (test_id2); - CPPUNIT_ASSERT (iter_readpointer == ringbuffer->_readpointer.end()); - - ringbuffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (ringbuffer != NULL); - CPPUNIT_ASSERT (ringbuffer->getNbReadPointer() == 1); - iter_readpointer = ringbuffer->_readpointer.find (default_id); - CPPUNIT_ASSERT (iter_readpointer->first == default_id); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - iter_readpointer = ringbuffer->_readpointer.find (test_id2); - CPPUNIT_ASSERT (iter_readpointer == ringbuffer->_readpointer.end()); + mainbuffer_.bindCallID(default_id, test_id1); + mainbuffer_.bindCallID(default_id, test_id2); + mainbuffer_.bindCallID(test_id1, test_id2); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 3); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 3); + + mainbuffer_.unBindAll(test_id2); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 2); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 2); + + iter_buffer = mainbuffer_.ringBufferMap_.find(default_id); + CPPUNIT_ASSERT(iter_buffer->first == default_id); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(default_id)); + + iter_buffer = mainbuffer_.ringBufferMap_.find(test_id1); + CPPUNIT_ASSERT(iter_buffer->first == test_id1); + CPPUNIT_ASSERT(iter_buffer->second == mainbuffer_.getRingBuffer(test_id1)); + + iter_buffer = mainbuffer_.ringBufferMap_.find(test_id2); + CPPUNIT_ASSERT(iter_buffer == mainbuffer_.ringBufferMap_.end()); + + iter_idset = mainbuffer_.callIDMap_.find(default_id); + CPPUNIT_ASSERT(iter_idset->second->size() == 1); + iter_id = iter_idset->second->find(test_id1); + CPPUNIT_ASSERT(*iter_id == test_id1); + iter_id = iter_idset->second->find(test_id2); + CPPUNIT_ASSERT(iter_id == iter_idset->second->end()); + + iter_idset = mainbuffer_.callIDMap_.find(test_id1); + CPPUNIT_ASSERT(iter_idset->second->size() == 1); + iter_id = iter_idset->second->find(default_id); + CPPUNIT_ASSERT(*iter_id == default_id); + + iter_idset = mainbuffer_.callIDMap_.find(test_id2); + CPPUNIT_ASSERT(iter_idset == mainbuffer_.callIDMap_.end()); + + ringbuffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1); + iter_readpointer = ringbuffer->_readpointer.find(test_id1); + CPPUNIT_ASSERT(iter_readpointer->first == test_id1); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + iter_readpointer = ringbuffer->_readpointer.find(test_id2); + CPPUNIT_ASSERT(iter_readpointer == ringbuffer->_readpointer.end()); + + ringbuffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(ringbuffer != NULL); + CPPUNIT_ASSERT(ringbuffer->getNbReadPointer() == 1); + iter_readpointer = ringbuffer->_readpointer.find(default_id); + CPPUNIT_ASSERT(iter_readpointer->first == default_id); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + iter_readpointer = ringbuffer->_readpointer.find(test_id2); + CPPUNIT_ASSERT(iter_readpointer == ringbuffer->_readpointer.end()); } void MainBufferTest::testGetPutDataByID() { - _debug ("-------------------- MainBufferTest::testGetPutDataByID --------------------\n"); + DEBUG("-------------------- MainBufferTest::testGetPutDataByID --------------------\n"); std::string test_id = "getData putData"; std::string false_id = "false id"; - _mainbuffer.bindCallID (test_id); + mainbuffer_.bindCallID(test_id); int test_input1 = 12; int test_input2 = 13; @@ -909,39 +909,39 @@ void MainBufferTest::testGetPutDataByID() int avail_for_put_defaultid; // put by default_id get by test_id without preleminary put - avail_for_put_defaultid = _mainbuffer.availForPut(); - CPPUNIT_ASSERT (_mainbuffer.availForGetByID (default_id, test_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.getDataByID (&test_output, sizeof (int), default_id, test_id) == 0); + avail_for_put_defaultid = mainbuffer_.availForPut(); + CPPUNIT_ASSERT(mainbuffer_.availForGetByID(default_id, test_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.getDataByID(&test_output, sizeof(int), default_id, test_id) == 0); // put by default_id, get by test_id - CPPUNIT_ASSERT (_mainbuffer.availForPut() == avail_for_put_defaultid); - CPPUNIT_ASSERT (_mainbuffer.putData (&test_input1, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForPut() == (avail_for_put_defaultid - (int) sizeof (int))); - CPPUNIT_ASSERT (_mainbuffer.availForGetByID (default_id, test_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.getDataByID (&test_output, sizeof (int), 100, default_id, test_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGetByID (default_id, test_id) == 0); - CPPUNIT_ASSERT (test_input1 == test_output); + CPPUNIT_ASSERT(mainbuffer_.availForPut() == avail_for_put_defaultid); + CPPUNIT_ASSERT(mainbuffer_.putData(&test_input1, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForPut() == (avail_for_put_defaultid - (int) sizeof(int))); + CPPUNIT_ASSERT(mainbuffer_.availForGetByID(default_id, test_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.getDataByID(&test_output, sizeof(int), 100, default_id, test_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGetByID(default_id, test_id) == 0); + CPPUNIT_ASSERT(test_input1 == test_output); // get by default_id without preliminary input - avail_for_put_testid = _mainbuffer.availForPut (test_id); - CPPUNIT_ASSERT (_mainbuffer.availForGetByID (test_id, default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.getDataByID (&test_output, sizeof (int), 100, test_id, default_id) == 0); + avail_for_put_testid = mainbuffer_.availForPut(test_id); + CPPUNIT_ASSERT(mainbuffer_.availForGetByID(test_id, default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.getDataByID(&test_output, sizeof(int), 100, test_id, default_id) == 0); // pu by test_id get by test_id - CPPUNIT_ASSERT (_mainbuffer.availForPut (test_id) == avail_for_put_defaultid); - CPPUNIT_ASSERT (_mainbuffer.putData (&test_input2, sizeof (int), test_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGetByID (test_id, default_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.getDataByID (&test_output, sizeof (int), 100, test_id, default_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGetByID (test_id, default_id) == 0); - CPPUNIT_ASSERT (test_input2 == test_output); + CPPUNIT_ASSERT(mainbuffer_.availForPut(test_id) == avail_for_put_defaultid); + CPPUNIT_ASSERT(mainbuffer_.putData(&test_input2, sizeof(int), test_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGetByID(test_id, default_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.getDataByID(&test_output, sizeof(int), 100, test_id, default_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGetByID(test_id, default_id) == 0); + CPPUNIT_ASSERT(test_input2 == test_output); // put/get by false id - CPPUNIT_ASSERT (_mainbuffer.putData (&test_input2, sizeof (int), false_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.getDataByID (&test_input2, sizeof (int), 100, false_id, false_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.getDataByID (&test_input2, sizeof (int), 100, default_id, false_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.getDataByID (&test_input2, sizeof (int), 100, false_id, default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.putData(&test_input2, sizeof(int), false_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.getDataByID(&test_input2, sizeof(int), 100, false_id, false_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.getDataByID(&test_input2, sizeof(int), 100, default_id, false_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.getDataByID(&test_input2, sizeof(int), 100, false_id, default_id) == 0); - _mainbuffer.unBindCallID (test_id); + mainbuffer_.unBindCallID(test_id); } @@ -949,11 +949,11 @@ void MainBufferTest::testGetPutDataByID() void MainBufferTest::testGetPutData() { - _debug ("-------------------- MainBufferTest::testGetPutData --------------------\n"); + DEBUG("-------------------- MainBufferTest::testGetPutData --------------------\n"); std::string test_id = "incoming rtp session"; - _mainbuffer.bindCallID (test_id); + mainbuffer_.bindCallID(test_id); int test_input1 = 12; int test_input2 = 13; @@ -963,120 +963,120 @@ void MainBufferTest::testGetPutData() int avail_for_put_defaultid; // get by test_id without preleminary put - avail_for_put_defaultid = _mainbuffer.availForPut(); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.getData (&test_output, sizeof (int), 100, test_id) == 0); + avail_for_put_defaultid = mainbuffer_.availForPut(); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.getData(&test_output, sizeof(int), 100, test_id) == 0); // put by default_id, get by test_id - CPPUNIT_ASSERT (_mainbuffer.availForPut() == avail_for_put_defaultid); - CPPUNIT_ASSERT (_mainbuffer.putData (&test_input1, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForPut() == (avail_for_put_defaultid - (int) sizeof (int))); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.getData (&test_output, sizeof (int), 100, test_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id) == 0); - CPPUNIT_ASSERT (test_input1 == test_output); + CPPUNIT_ASSERT(mainbuffer_.availForPut() == avail_for_put_defaultid); + CPPUNIT_ASSERT(mainbuffer_.putData(&test_input1, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForPut() == (avail_for_put_defaultid - (int) sizeof(int))); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.getData(&test_output, sizeof(int), 100, test_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id) == 0); + CPPUNIT_ASSERT(test_input1 == test_output); // get by default_id without preleminary put - avail_for_put_testid = _mainbuffer.availForPut (test_id); - CPPUNIT_ASSERT (_mainbuffer.availForGet() == 0); - CPPUNIT_ASSERT (_mainbuffer.getData (&test_output, sizeof (int)) == 0); + avail_for_put_testid = mainbuffer_.availForPut(test_id); + CPPUNIT_ASSERT(mainbuffer_.availForGet() == 0); + CPPUNIT_ASSERT(mainbuffer_.getData(&test_output, sizeof(int)) == 0); // put by test_id, get by default_id - CPPUNIT_ASSERT (_mainbuffer.availForPut (test_id) == avail_for_put_testid); - CPPUNIT_ASSERT (_mainbuffer.putData (&test_input2, sizeof (int), test_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForPut (test_id) == (avail_for_put_testid - (int) sizeof (int))); - CPPUNIT_ASSERT (_mainbuffer.availForGet() == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.getData (&test_output, sizeof (int), 100) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet() == 0); - CPPUNIT_ASSERT (test_input2 == test_output); + CPPUNIT_ASSERT(mainbuffer_.availForPut(test_id) == avail_for_put_testid); + CPPUNIT_ASSERT(mainbuffer_.putData(&test_input2, sizeof(int), test_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForPut(test_id) == (avail_for_put_testid - (int) sizeof(int))); + CPPUNIT_ASSERT(mainbuffer_.availForGet() == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.getData(&test_output, sizeof(int), 100) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet() == 0); + CPPUNIT_ASSERT(test_input2 == test_output); - _mainbuffer.unBindCallID (test_id); + mainbuffer_.unBindCallID(test_id); } void MainBufferTest::testDiscardFlush() { - _debug ("-------------------- MainBufferTest::testDiscardFlush --------------------\n"); + DEBUG("-------------------- MainBufferTest::testDiscardFlush --------------------\n"); std::string test_id = "flush discard"; - // _mainbuffer.createRingBuffer(test_id); - _mainbuffer.bindCallID (test_id); + // mainbuffer_.createRingBuffer(test_id); + mainbuffer_.bindCallID(test_id); int test_input1 = 12; // int test_output_size; // int init_size; - CPPUNIT_ASSERT (_mainbuffer.putData (&test_input1, sizeof (int), test_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet() == sizeof (int)); - _mainbuffer.discard (sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet() == 0); + CPPUNIT_ASSERT(mainbuffer_.putData(&test_input1, sizeof(int), test_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet() == sizeof(int)); + mainbuffer_.discard(sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet() == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id) == 0); - _mainbuffer.discard (sizeof (int), test_id); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id) == 0); + mainbuffer_.discard(sizeof(int), test_id); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.getRingBuffer (test_id)->getReadPointer (default_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.getRingBuffer (test_id)->getReadPointer (test_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(test_id)->getReadPointer(default_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(test_id)->getReadPointer(test_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.getRingBuffer (default_id)->getReadPointer (test_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.putData (&test_input1, sizeof (int), 100) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.getRingBuffer (default_id)->getReadPointer (test_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(default_id)->getReadPointer(test_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.putData(&test_input1, sizeof(int), 100) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(default_id)->getReadPointer(test_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id) == sizeof(int)); - CPPUNIT_ASSERT (_mainbuffer.getRingBuffer (default_id)->getReadPointer (test_id) == 0); - _mainbuffer.discard (sizeof (int), test_id); - CPPUNIT_ASSERT (_mainbuffer.getRingBuffer (default_id)->getReadPointer (test_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(default_id)->getReadPointer(test_id) == 0); + mainbuffer_.discard(sizeof(int), test_id); + CPPUNIT_ASSERT(mainbuffer_.getRingBuffer(default_id)->getReadPointer(test_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id) == 0); - // _mainbuffer.removeRingBuffer(test_id); - _mainbuffer.unBindCallID (test_id); + // mainbuffer_.removeRingBuffer(test_id); + mainbuffer_.unBindCallID(test_id); } void MainBufferTest::testReadPointerInit() { - _debug ("-------------------- MainBufferTest::testReadPointerInit --------------------\n"); + DEBUG("-------------------- MainBufferTest::testReadPointerInit --------------------\n"); std::string test_id = "test read pointer init"; - // RingBuffer* test_ring_buffer = _mainbuffer.createRingBuffer(test_id); + // RingBuffer* test_ring_buffer = mainbuffer_.createRingBuffer(test_id); - _mainbuffer.bindCallID (test_id); + mainbuffer_.bindCallID(test_id); - RingBuffer* test_ring_buffer = _mainbuffer.getRingBuffer (test_id); + RingBuffer* test_ring_buffer = mainbuffer_.getRingBuffer(test_id); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer() == 0); - test_ring_buffer->storeReadPointer (30); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer() == 30); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 0); + test_ring_buffer->storeReadPointer(30); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer() == 30); - test_ring_buffer->createReadPointer (test_id); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (test_id) == 0); - test_ring_buffer->storeReadPointer (10, test_id); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (test_id) == 10); - test_ring_buffer->removeReadPointer (test_id); - CPPUNIT_ASSERT (test_ring_buffer->getReadPointer (test_id) == (int) NULL); - test_ring_buffer->removeReadPointer ("false id"); + test_ring_buffer->createReadPointer(test_id); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == 0); + test_ring_buffer->storeReadPointer(10, test_id); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == 10); + test_ring_buffer->removeReadPointer(test_id); + CPPUNIT_ASSERT(test_ring_buffer->getReadPointer(test_id) == (int) NULL); + test_ring_buffer->removeReadPointer("false id"); - // _mainbuffer.removeRingBuffer(test_id); - _mainbuffer.unBindCallID (test_id); + // mainbuffer_.removeRingBuffer(test_id); + mainbuffer_.unBindCallID(test_id); } void MainBufferTest::testRingBufferSeveralPointers() { - _debug ("-------------------- MainBufferTest::testRingBufferSeveralPointers --------------------\n"); + DEBUG("-------------------- MainBufferTest::testRingBufferSeveralPointers --------------------\n"); std::string test_id = "test multiple read pointer"; - RingBuffer* test_ring_buffer = _mainbuffer.createRingBuffer (test_id); + RingBuffer* test_ring_buffer = mainbuffer_.createRingBuffer(test_id); std::string test_pointer1 = "test pointer 1"; std::string test_pointer2 = "test pointer 2"; - test_ring_buffer->createReadPointer (test_pointer1); - test_ring_buffer->createReadPointer (test_pointer2); + test_ring_buffer->createReadPointer(test_pointer1); + test_ring_buffer->createReadPointer(test_pointer2); int testint1 = 12; int testint2 = 13; @@ -1087,100 +1087,100 @@ void MainBufferTest::testRingBufferSeveralPointers() int initPutLen = test_ring_buffer->AvailForPut(); - CPPUNIT_ASSERT (test_ring_buffer->Put (&testint1, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == initPutLen - (int) sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_pointer1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_pointer2) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer2) == sizeof (int)); - - CPPUNIT_ASSERT (test_ring_buffer->Put (&testint2, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 2*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == initPutLen - 2* (int) sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_pointer1) == 2*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_pointer2) == 2*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer1) == 2*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer2) == 2*sizeof (int)); - - CPPUNIT_ASSERT (test_ring_buffer->Put (&testint3, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 3*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == initPutLen - 3* (int) sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_pointer1) == 3*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_pointer2) == 3*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer1) == 3*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer2) == 3*sizeof (int)); - - CPPUNIT_ASSERT (test_ring_buffer->Put (&testint4, sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 4*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == initPutLen - 4* (int) sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_pointer1) == 4*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->getLen (test_pointer2) == 4*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer1) == 4*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer2) == 4*sizeof (int)); - - - CPPUNIT_ASSERT (test_ring_buffer->Get (&testoutput, sizeof (int), test_pointer1) == sizeof (int)); - CPPUNIT_ASSERT (testoutput == testint1); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == initPutLen - 4* (int) sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer1) == 3*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer2) == 4*sizeof (int)); - - CPPUNIT_ASSERT (test_ring_buffer->Get (&testoutput, sizeof (int), test_pointer2) == sizeof (int)); - CPPUNIT_ASSERT (testoutput == testint1); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == initPutLen - 3* (int) sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer1) == 3*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer2) == 3*sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->Put(&testint1, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - (int) sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer2) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == sizeof(int)); + + CPPUNIT_ASSERT(test_ring_buffer->Put(&testint2, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 2*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 2* (int) sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer1) == 2*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer2) == 2*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == 2*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 2*sizeof(int)); + + CPPUNIT_ASSERT(test_ring_buffer->Put(&testint3, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 3*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 3* (int) sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer1) == 3*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer2) == 3*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == 3*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 3*sizeof(int)); + + CPPUNIT_ASSERT(test_ring_buffer->Put(&testint4, sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 4*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 4* (int) sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer1) == 4*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->getLen(test_pointer2) == 4*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == 4*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 4*sizeof(int)); + + + CPPUNIT_ASSERT(test_ring_buffer->Get(&testoutput, sizeof(int), test_pointer1) == sizeof(int)); + CPPUNIT_ASSERT(testoutput == testint1); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 4* (int) sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == 3*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 4*sizeof(int)); + + CPPUNIT_ASSERT(test_ring_buffer->Get(&testoutput, sizeof(int), test_pointer2) == sizeof(int)); + CPPUNIT_ASSERT(testoutput == testint1); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 3* (int) sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == 3*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 3*sizeof(int)); // AvailForPut() is ok but AvailForGet(default_id) is not ok // However, we should no be alowed to read in our own ring buffer // if we are either an AudioLayer or and RTP session - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet() == 4*sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 4*sizeof(int)); - CPPUNIT_ASSERT (test_ring_buffer->Get (&testoutput, sizeof (int), 100, test_pointer1) == sizeof (int)); - CPPUNIT_ASSERT (testoutput == testint2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == initPutLen - 3* (int) sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer1) == 2*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer2) == 3*sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->Get(&testoutput, sizeof(int), 100, test_pointer1) == sizeof(int)); + CPPUNIT_ASSERT(testoutput == testint2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 3* (int) sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == 2*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 3*sizeof(int)); // AvailForPut() is ok but AvailForGet(default_id) is not ok // However, we should no be alowed to read in our own ring buffer // if we are either an AudioLayer or and RTP session - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet() == 4*sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 4*sizeof(int)); - CPPUNIT_ASSERT (test_ring_buffer->Get (&testoutput, sizeof (int), 100, test_pointer2) == sizeof (int)); - CPPUNIT_ASSERT (testoutput == testint2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == initPutLen - 2* (int) sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer1) == 2*sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer2) == 2*sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->Get(&testoutput, sizeof(int), 100, test_pointer2) == sizeof(int)); + CPPUNIT_ASSERT(testoutput == testint2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 2* (int) sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == 2*sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 2*sizeof(int)); // AvailForPut() is ok but AvailForGet(default_id) is not ok // However, we should no be alowed to read in our own ring buffer // if we are either an AudioLayer or and RTP session - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet() == 4*sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet() == 4*sizeof(int)); - CPPUNIT_ASSERT (test_ring_buffer->Discard (sizeof (int), test_pointer1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == initPutLen - 2* (int) sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer2) == 2*sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->Discard(sizeof(int), test_pointer1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - 2* (int) sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == 2*sizeof(int)); - CPPUNIT_ASSERT (test_ring_buffer->Discard (sizeof (int), test_pointer2) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == initPutLen - (int) sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_pointer2) == sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->Discard(sizeof(int), test_pointer2) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == initPutLen - (int) sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_pointer2) == sizeof(int)); - test_ring_buffer->removeReadPointer (test_pointer1); - test_ring_buffer->removeReadPointer (test_pointer2); + test_ring_buffer->removeReadPointer(test_pointer1); + test_ring_buffer->removeReadPointer(test_pointer2); - _mainbuffer.removeRingBuffer (test_id); + mainbuffer_.removeRingBuffer(test_id); } void MainBufferTest::testConference() { - _debug ("-------------------- MainBufferTest::testConference --------------------\n"); + DEBUG("-------------------- MainBufferTest::testConference --------------------\n"); std::string test_id1 = "participant A"; std::string test_id2 = "participant B"; @@ -1195,137 +1195,137 @@ void MainBufferTest::testConference() // test initial setup // ringbuffers - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer == NULL); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer == NULL); // callidmap - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 0); - iter_callidmap = _mainbuffer._callIDMap.find (default_id); - CPPUNIT_ASSERT (iter_callidmap == _mainbuffer._callIDMap.end()); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 0); + iter_callidmap = mainbuffer_.callIDMap_.find(default_id); + CPPUNIT_ASSERT(iter_callidmap == mainbuffer_.callIDMap_.end()); // test bind Participant A with default - _mainbuffer.bindCallID (test_id1); + mainbuffer_.bindCallID(test_id1); // ringbuffers - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 2); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 1); - iter_readpointer = test_ring_buffer->_readpointer.find (test_id1); - CPPUNIT_ASSERT (iter_readpointer->first == test_id1); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 1); - iter_readpointer = test_ring_buffer->_readpointer.find (default_id); - CPPUNIT_ASSERT (iter_readpointer->first == default_id); - CPPUNIT_ASSERT (iter_readpointer->second == 0); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 2); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 1); + iter_readpointer = test_ring_buffer->_readpointer.find(test_id1); + CPPUNIT_ASSERT(iter_readpointer->first == test_id1); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 1); + iter_readpointer = test_ring_buffer->_readpointer.find(default_id); + CPPUNIT_ASSERT(iter_readpointer->first == default_id); + CPPUNIT_ASSERT(iter_readpointer->second == 0); // callidmap - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 2); - iter_callidmap = _mainbuffer._callIDMap.find (default_id); - CPPUNIT_ASSERT (iter_callidmap->first == default_id); - CPPUNIT_ASSERT (iter_callidmap->second->size() == 1); - iter_callidset = iter_callidmap->second->find (test_id1); - CPPUNIT_ASSERT (*iter_callidset == test_id1); - iter_callidmap = _mainbuffer._callIDMap.find (test_id1); - CPPUNIT_ASSERT (iter_callidmap->first == test_id1); - CPPUNIT_ASSERT (iter_callidmap->second->size() == 1); - iter_callidset = iter_callidmap->second->find (default_id); - CPPUNIT_ASSERT (*iter_callidset == default_id); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 2); + iter_callidmap = mainbuffer_.callIDMap_.find(default_id); + CPPUNIT_ASSERT(iter_callidmap->first == default_id); + CPPUNIT_ASSERT(iter_callidmap->second->size() == 1); + iter_callidset = iter_callidmap->second->find(test_id1); + CPPUNIT_ASSERT(*iter_callidset == test_id1); + iter_callidmap = mainbuffer_.callIDMap_.find(test_id1); + CPPUNIT_ASSERT(iter_callidmap->first == test_id1); + CPPUNIT_ASSERT(iter_callidmap->second->size() == 1); + iter_callidset = iter_callidmap->second->find(default_id); + CPPUNIT_ASSERT(*iter_callidset == default_id); // test bind Participant B with default - _mainbuffer.bindCallID (test_id2); + mainbuffer_.bindCallID(test_id2); // ringbuffers - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 3); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 2); - iter_readpointer = test_ring_buffer->_readpointer.find (test_id1); - CPPUNIT_ASSERT (iter_readpointer->first == test_id1); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - iter_readpointer = test_ring_buffer->_readpointer.find (test_id2); - CPPUNIT_ASSERT (iter_readpointer->first == test_id2); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 1); - iter_readpointer = test_ring_buffer->_readpointer.find (default_id); - CPPUNIT_ASSERT (iter_readpointer->first == default_id); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 1); - iter_readpointer = test_ring_buffer->_readpointer.find (default_id); - CPPUNIT_ASSERT (iter_readpointer->first == default_id); - CPPUNIT_ASSERT (iter_readpointer->second == 0); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 3); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 2); + iter_readpointer = test_ring_buffer->_readpointer.find(test_id1); + CPPUNIT_ASSERT(iter_readpointer->first == test_id1); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + iter_readpointer = test_ring_buffer->_readpointer.find(test_id2); + CPPUNIT_ASSERT(iter_readpointer->first == test_id2); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 1); + iter_readpointer = test_ring_buffer->_readpointer.find(default_id); + CPPUNIT_ASSERT(iter_readpointer->first == default_id); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 1); + iter_readpointer = test_ring_buffer->_readpointer.find(default_id); + CPPUNIT_ASSERT(iter_readpointer->first == default_id); + CPPUNIT_ASSERT(iter_readpointer->second == 0); // callidmap - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 3); - iter_callidmap = _mainbuffer._callIDMap.find (default_id); - CPPUNIT_ASSERT (iter_callidmap->first == default_id); - CPPUNIT_ASSERT (iter_callidmap->second->size() == 2); - iter_callidset = iter_callidmap->second->find (test_id1); - CPPUNIT_ASSERT (*iter_callidset == test_id1); - iter_callidset = iter_callidmap->second->find (test_id2); - CPPUNIT_ASSERT (*iter_callidset == test_id2); - iter_callidmap = _mainbuffer._callIDMap.find (test_id1); - CPPUNIT_ASSERT (iter_callidmap->first == test_id1); - CPPUNIT_ASSERT (iter_callidmap->second->size() == 1); - iter_callidset = iter_callidmap->second->find (default_id); - CPPUNIT_ASSERT (*iter_callidset == default_id); - iter_callidmap = _mainbuffer._callIDMap.find (test_id2); - CPPUNIT_ASSERT (iter_callidmap->first == test_id2); - CPPUNIT_ASSERT (iter_callidmap->second->size() == 1); - iter_callidset = iter_callidmap->second->find (default_id); - CPPUNIT_ASSERT (*iter_callidset == default_id); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 3); + iter_callidmap = mainbuffer_.callIDMap_.find(default_id); + CPPUNIT_ASSERT(iter_callidmap->first == default_id); + CPPUNIT_ASSERT(iter_callidmap->second->size() == 2); + iter_callidset = iter_callidmap->second->find(test_id1); + CPPUNIT_ASSERT(*iter_callidset == test_id1); + iter_callidset = iter_callidmap->second->find(test_id2); + CPPUNIT_ASSERT(*iter_callidset == test_id2); + iter_callidmap = mainbuffer_.callIDMap_.find(test_id1); + CPPUNIT_ASSERT(iter_callidmap->first == test_id1); + CPPUNIT_ASSERT(iter_callidmap->second->size() == 1); + iter_callidset = iter_callidmap->second->find(default_id); + CPPUNIT_ASSERT(*iter_callidset == default_id); + iter_callidmap = mainbuffer_.callIDMap_.find(test_id2); + CPPUNIT_ASSERT(iter_callidmap->first == test_id2); + CPPUNIT_ASSERT(iter_callidmap->second->size() == 1); + iter_callidset = iter_callidmap->second->find(default_id); + CPPUNIT_ASSERT(*iter_callidset == default_id); // test bind Participant A with Participant B - _mainbuffer.bindCallID (test_id1, test_id2); + mainbuffer_.bindCallID(test_id1, test_id2); // ringbuffers - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 3); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 2); - iter_readpointer = test_ring_buffer->_readpointer.find (test_id1); - CPPUNIT_ASSERT (iter_readpointer->first == test_id1); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - iter_readpointer = test_ring_buffer->_readpointer.find (test_id2); - CPPUNIT_ASSERT (iter_readpointer->first == test_id2); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 2); - iter_readpointer = test_ring_buffer->_readpointer.find (default_id); - CPPUNIT_ASSERT (iter_readpointer->first == default_id); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - iter_readpointer = test_ring_buffer->_readpointer.find (test_id2); - CPPUNIT_ASSERT (iter_readpointer->first == test_id2); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->getNbReadPointer() == 2); - iter_readpointer = test_ring_buffer->_readpointer.find (default_id); - CPPUNIT_ASSERT (iter_readpointer->first == default_id); - CPPUNIT_ASSERT (iter_readpointer->second == 0); - iter_readpointer = test_ring_buffer->_readpointer.find (test_id1); - CPPUNIT_ASSERT (iter_readpointer->first == test_id1); - CPPUNIT_ASSERT (iter_readpointer->second == 0); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 3); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 2); + iter_readpointer = test_ring_buffer->_readpointer.find(test_id1); + CPPUNIT_ASSERT(iter_readpointer->first == test_id1); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + iter_readpointer = test_ring_buffer->_readpointer.find(test_id2); + CPPUNIT_ASSERT(iter_readpointer->first == test_id2); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 2); + iter_readpointer = test_ring_buffer->_readpointer.find(default_id); + CPPUNIT_ASSERT(iter_readpointer->first == default_id); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + iter_readpointer = test_ring_buffer->_readpointer.find(test_id2); + CPPUNIT_ASSERT(iter_readpointer->first == test_id2); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->getNbReadPointer() == 2); + iter_readpointer = test_ring_buffer->_readpointer.find(default_id); + CPPUNIT_ASSERT(iter_readpointer->first == default_id); + CPPUNIT_ASSERT(iter_readpointer->second == 0); + iter_readpointer = test_ring_buffer->_readpointer.find(test_id1); + CPPUNIT_ASSERT(iter_readpointer->first == test_id1); + CPPUNIT_ASSERT(iter_readpointer->second == 0); // callidmap - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 3); - iter_callidmap = _mainbuffer._callIDMap.find (default_id); - CPPUNIT_ASSERT (iter_callidmap->first == default_id); - CPPUNIT_ASSERT (iter_callidmap->second->size() == 2); - iter_callidset = iter_callidmap->second->find (test_id1); - CPPUNIT_ASSERT (*iter_callidset == test_id1); - iter_callidset = iter_callidmap->second->find (test_id2); - CPPUNIT_ASSERT (*iter_callidset == test_id2); - iter_callidmap = _mainbuffer._callIDMap.find (test_id1); - CPPUNIT_ASSERT (iter_callidmap->first == test_id1); - CPPUNIT_ASSERT (iter_callidmap->second->size() == 2); - iter_callidset = iter_callidmap->second->find (default_id); - CPPUNIT_ASSERT (*iter_callidset == default_id); - iter_callidset = iter_callidmap->second->find (test_id2); - CPPUNIT_ASSERT (*iter_callidset == test_id2); - iter_callidmap = _mainbuffer._callIDMap.find (test_id2); - CPPUNIT_ASSERT (iter_callidmap->first == test_id2); - CPPUNIT_ASSERT (iter_callidmap->second->size() == 2); - iter_callidset = iter_callidmap->second->find (default_id); - CPPUNIT_ASSERT (*iter_callidset == default_id); - iter_callidset = iter_callidmap->second->find (test_id1); - CPPUNIT_ASSERT (*iter_callidset == test_id1); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 3); + iter_callidmap = mainbuffer_.callIDMap_.find(default_id); + CPPUNIT_ASSERT(iter_callidmap->first == default_id); + CPPUNIT_ASSERT(iter_callidmap->second->size() == 2); + iter_callidset = iter_callidmap->second->find(test_id1); + CPPUNIT_ASSERT(*iter_callidset == test_id1); + iter_callidset = iter_callidmap->second->find(test_id2); + CPPUNIT_ASSERT(*iter_callidset == test_id2); + iter_callidmap = mainbuffer_.callIDMap_.find(test_id1); + CPPUNIT_ASSERT(iter_callidmap->first == test_id1); + CPPUNIT_ASSERT(iter_callidmap->second->size() == 2); + iter_callidset = iter_callidmap->second->find(default_id); + CPPUNIT_ASSERT(*iter_callidset == default_id); + iter_callidset = iter_callidmap->second->find(test_id2); + CPPUNIT_ASSERT(*iter_callidset == test_id2); + iter_callidmap = mainbuffer_.callIDMap_.find(test_id2); + CPPUNIT_ASSERT(iter_callidmap->first == test_id2); + CPPUNIT_ASSERT(iter_callidmap->second->size() == 2); + iter_callidset = iter_callidmap->second->find(default_id); + CPPUNIT_ASSERT(*iter_callidset == default_id); + iter_callidset = iter_callidmap->second->find(test_id1); + CPPUNIT_ASSERT(*iter_callidset == test_id1); // test putData default @@ -1334,436 +1334,436 @@ void MainBufferTest::testConference() int init_put_id1; int init_put_id2; - init_put_defaultid = _mainbuffer.getRingBuffer (default_id)->AvailForPut(); - init_put_id1 = _mainbuffer.getRingBuffer (test_id1)->AvailForPut(); - init_put_id2 = _mainbuffer.getRingBuffer (test_id2)->AvailForPut(); - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == 0); + init_put_defaultid = mainbuffer_.getRingBuffer(default_id)->AvailForPut(); + init_put_id1 = mainbuffer_.getRingBuffer(test_id1)->AvailForPut(); + init_put_id2 = mainbuffer_.getRingBuffer(test_id2)->AvailForPut(); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == 0); // put data test ring buffers - CPPUNIT_ASSERT (_mainbuffer.putData (&testint, sizeof (int)) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id1); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int)) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id1); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); // test mainbuffer availforget (get data even if some participant missing) - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); //putdata test ring buffers - CPPUNIT_ASSERT (_mainbuffer.putData (&testint, sizeof (int), 100, test_id1) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id1 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100, test_id1) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); // test mainbuffer availforget (get data even if some participant missing) - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); //putdata test ring buffers - CPPUNIT_ASSERT (_mainbuffer.putData (&testint, sizeof (int), 100, test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id1 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id2 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100, test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id2 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); int test_output; // test getData default id (audio layer) - CPPUNIT_ASSERT (_mainbuffer.getData (&test_output, sizeof (int), 100) == sizeof (int)); - CPPUNIT_ASSERT (test_output == (testint + testint)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id1 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id2 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.getData(&test_output, sizeof(int), 100) == sizeof(int)); + CPPUNIT_ASSERT(test_output == (testint + testint)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id2 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); // test getData test_id1 (audio layer) - CPPUNIT_ASSERT (_mainbuffer.getData (&test_output, sizeof (int), 100, test_id1) == sizeof (int)); - CPPUNIT_ASSERT (test_output == (testint + testint)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id1 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.getData(&test_output, sizeof(int), 100, test_id1) == sizeof(int)); + CPPUNIT_ASSERT(test_output == (testint + testint)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); // test getData test_id2 (audio layer) - CPPUNIT_ASSERT (_mainbuffer.getData (&test_output, sizeof (int), 100, test_id2) == sizeof (int)); - CPPUNIT_ASSERT (test_output == (testint + testint)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_defaultid); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id1); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.getData(&test_output, sizeof(int), 100, test_id2) == sizeof(int)); + CPPUNIT_ASSERT(test_output == (testint + testint)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_defaultid); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id1); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == 0); // test putData default (for discarting) - init_put_defaultid = _mainbuffer.getRingBuffer (default_id)->AvailForPut(); - init_put_id1 = _mainbuffer.getRingBuffer (test_id1)->AvailForPut(); - init_put_id2 = _mainbuffer.getRingBuffer (test_id2)->AvailForPut(); - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == 0); + init_put_defaultid = mainbuffer_.getRingBuffer(default_id)->AvailForPut(); + init_put_id1 = mainbuffer_.getRingBuffer(test_id1)->AvailForPut(); + init_put_id2 = mainbuffer_.getRingBuffer(test_id2)->AvailForPut(); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == 0); // put data test ring buffers - CPPUNIT_ASSERT (_mainbuffer.putData (&testint, sizeof (int), 100) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id1); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id1); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); //putdata test ring buffers - CPPUNIT_ASSERT (_mainbuffer.putData (&testint, sizeof (int), 100, test_id1) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id1 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100, test_id1) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); //putdata test ring buffers - CPPUNIT_ASSERT (_mainbuffer.putData (&testint, sizeof (int), 100, test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id1 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id2 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100, test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id2 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); // test discardData default id (audio layer) - CPPUNIT_ASSERT (_mainbuffer.discard (sizeof (int)) == sizeof (int)); - CPPUNIT_ASSERT (test_output == (testint + testint)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id1 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id2 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.discard(sizeof(int)) == sizeof(int)); + CPPUNIT_ASSERT(test_output == (testint + testint)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id2 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); // test discardData test_id1 (audio layer) - CPPUNIT_ASSERT (_mainbuffer.discard (sizeof (int), test_id1) == sizeof (int)); - CPPUNIT_ASSERT (test_output == (testint + testint)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id1 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.discard(sizeof(int), test_id1) == sizeof(int)); + CPPUNIT_ASSERT(test_output == (testint + testint)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); // test discardData test_id2 (audio layer) - CPPUNIT_ASSERT (_mainbuffer.discard (sizeof (int), test_id2) == sizeof (int)); - CPPUNIT_ASSERT (test_output == (testint + testint)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_defaultid); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id1); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.discard(sizeof(int), test_id2) == sizeof(int)); + CPPUNIT_ASSERT(test_output == (testint + testint)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_defaultid); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id1); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == 0); // test putData default (for flushing) - init_put_defaultid = _mainbuffer.getRingBuffer (default_id)->AvailForPut(); - init_put_id1 = _mainbuffer.getRingBuffer (test_id1)->AvailForPut(); - init_put_id2 = _mainbuffer.getRingBuffer (test_id2)->AvailForPut(); - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == 0); + init_put_defaultid = mainbuffer_.getRingBuffer(default_id)->AvailForPut(); + init_put_id1 = mainbuffer_.getRingBuffer(test_id1)->AvailForPut(); + init_put_id2 = mainbuffer_.getRingBuffer(test_id2)->AvailForPut(); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == 0); // put data test ring buffers - CPPUNIT_ASSERT (_mainbuffer.putData (&testint, sizeof (int), 100) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id1); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id1); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); //putdata test ring buffers - CPPUNIT_ASSERT (_mainbuffer.putData (&testint, sizeof (int), 100, test_id1) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id1 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100, test_id1) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); //putdata test ring buffers - CPPUNIT_ASSERT (_mainbuffer.putData (&testint, sizeof (int), 100, test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id1 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id2 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.putData(&testint, sizeof(int), 100, test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id2 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); // test flush default id (audio layer) - _mainbuffer.flush(); - CPPUNIT_ASSERT (test_output == (testint + testint)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - _debug ("%i", test_ring_buffer->putLen()); + mainbuffer_.flush(); + CPPUNIT_ASSERT(test_output == (testint + testint)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + DEBUG("%i", test_ring_buffer->putLen()); test_ring_buffer->debug(); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id1 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id2 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == sizeof (int)); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id2 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == sizeof(int)); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == sizeof (int)); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == sizeof(int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); // test flush test_id1 (audio layer) - _mainbuffer.flush (test_id1); - CPPUNIT_ASSERT (test_output == (testint + testint)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_defaultid - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == sizeof (int)); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == (int) (init_put_id1 - sizeof (int))); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == sizeof (int)); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); + mainbuffer_.flush(test_id1); + CPPUNIT_ASSERT(test_output == (testint + testint)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_defaultid - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == sizeof(int)); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == (int)(init_put_id1 - sizeof(int))); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == sizeof(int)); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == sizeof (int)); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == sizeof(int)); // test flush test_id2 (audio layer) - _mainbuffer.flush (test_id2); - CPPUNIT_ASSERT (test_output == (testint + testint)); - test_ring_buffer = _mainbuffer.getRingBuffer (default_id); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_defaultid); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id1); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id1); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id2) == 0); - test_ring_buffer = _mainbuffer.getRingBuffer (test_id2); - CPPUNIT_ASSERT (test_ring_buffer->putLen() == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForPut() == init_put_id2); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (default_id) == 0); - CPPUNIT_ASSERT (test_ring_buffer->AvailForGet (test_id1) == 0); + mainbuffer_.flush(test_id2); + CPPUNIT_ASSERT(test_output == (testint + testint)); + test_ring_buffer = mainbuffer_.getRingBuffer(default_id); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_defaultid); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id1); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id1); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id2) == 0); + test_ring_buffer = mainbuffer_.getRingBuffer(test_id2); + CPPUNIT_ASSERT(test_ring_buffer->putLen() == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForPut() == init_put_id2); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(default_id) == 0); + CPPUNIT_ASSERT(test_ring_buffer->AvailForGet(test_id1) == 0); // test mainbuffer availforget - CPPUNIT_ASSERT (_mainbuffer.availForGet (default_id) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id1) == 0); - CPPUNIT_ASSERT (_mainbuffer.availForGet (test_id2) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(default_id) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id1) == 0); + CPPUNIT_ASSERT(mainbuffer_.availForGet(test_id2) == 0); - _mainbuffer.unBindCallID (test_id1, test_id2); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 3); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 3); + mainbuffer_.unBindCallID(test_id1, test_id2); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 3); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 3); - _mainbuffer.unBindCallID (test_id1); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 2); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 2); + mainbuffer_.unBindCallID(test_id1); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 2); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 2); - _mainbuffer.unBindCallID (test_id2); - CPPUNIT_ASSERT (_mainbuffer._ringBufferMap.size() == 0); - CPPUNIT_ASSERT (_mainbuffer._callIDMap.size() == 0); + mainbuffer_.unBindCallID(test_id2); + CPPUNIT_ASSERT(mainbuffer_.ringBufferMap_.size() == 0); + CPPUNIT_ASSERT(mainbuffer_.callIDMap_.size() == 0); } diff --git a/daemon/test/mainbuffertest.h b/daemon/test/mainbuffertest.h index 87a13685809e40d86d259243cf307f04b8ff60df..316191f4964ab92f8d1c3fbc2e10f8d5eefb2e65 100644 --- a/daemon/test/mainbuffertest.h +++ b/daemon/test/mainbuffertest.h @@ -59,7 +59,7 @@ /* - * @file audiorecorderTest.cpp + * @file audiorecorderTest.cpp * @brief Regroups unitary tests related to the plugin manager. */ @@ -70,30 +70,30 @@ class MainBufferTest : public CppUnit::TestCase { - /* - * Use cppunit library macros to add unit test the factory - */ - CPPUNIT_TEST_SUITE( MainBufferTest ); - CPPUNIT_TEST( testRingBufferCreation ); - CPPUNIT_TEST( testRingBufferReadPointer ); - CPPUNIT_TEST( testCallIDSet ); - CPPUNIT_TEST( testRingBufferInt ); - CPPUNIT_TEST( testRingBufferNonDefaultID ); - CPPUNIT_TEST( testRingBufferFloat ); - CPPUNIT_TEST( testTwoPointer ); - CPPUNIT_TEST( testBindUnbindBuffer ); - CPPUNIT_TEST( testGetPutDataByID ); - CPPUNIT_TEST( testGetPutData ); - CPPUNIT_TEST( testDiscardFlush ); - CPPUNIT_TEST( testReadPointerInit ); - CPPUNIT_TEST( testRingBufferSeveralPointers ); - CPPUNIT_TEST( testConference ); - CPPUNIT_TEST_SUITE_END(); + /* + * Use cppunit library macros to add unit test the factory + */ + CPPUNIT_TEST_SUITE(MainBufferTest); + CPPUNIT_TEST(testRingBufferCreation); + CPPUNIT_TEST(testRingBufferReadPointer); + CPPUNIT_TEST(testCallIDSet); + CPPUNIT_TEST(testRingBufferInt); + CPPUNIT_TEST(testRingBufferNonDefaultID); + CPPUNIT_TEST(testRingBufferFloat); + CPPUNIT_TEST(testTwoPointer); + CPPUNIT_TEST(testBindUnbindBuffer); + CPPUNIT_TEST(testGetPutDataByID); + CPPUNIT_TEST(testGetPutData); + CPPUNIT_TEST(testDiscardFlush); + CPPUNIT_TEST(testReadPointerInit); + CPPUNIT_TEST(testRingBufferSeveralPointers); + CPPUNIT_TEST(testConference); + CPPUNIT_TEST_SUITE_END(); public: MainBufferTest() : CppUnit::TestCase("Audio Layer Tests") {} - + /* * Code factoring - Common resources can be initialized here. * This method is called by unitcpp before each test @@ -108,41 +108,41 @@ class MainBufferTest : public CppUnit::TestCase { void testRingBufferCreation(); - void testRingBufferReadPointer(); + void testRingBufferReadPointer(); - void testCallIDSet(); + void testCallIDSet(); - void testRingBufferInt(); + void testRingBufferInt(); - void testRingBufferNonDefaultID(); + void testRingBufferNonDefaultID(); - void testRingBufferFloat(); + void testRingBufferFloat(); - void testTwoPointer(); + void testTwoPointer(); - void testBindUnbindBuffer(); + void testBindUnbindBuffer(); - void testGetPutDataByID(); + void testGetPutDataByID(); - void testGetPutData(); + void testGetPutData(); - void testAvailForGetPut(); + void testAvailForGetPut(); - void testDiscardFlush(); + void testDiscardFlush(); - void testReadPointerInit(); + void testReadPointerInit(); - void testRingBufferSeveralPointers(); + void testRingBufferSeveralPointers(); - void testConference(); + void testConference(); private: - MainBuffer _mainbuffer; + MainBuffer mainbuffer_; }; /* Register our test module */ CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(MainBufferTest, "MainBufferTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( MainBufferTest ); +CPPUNIT_TEST_SUITE_REGISTRATION(MainBufferTest); #endif diff --git a/daemon/test/numbercleanertest.cpp b/daemon/test/numbercleanertest.cpp index 172e28ef14ea95a5ab87f4694e1e8bef2972e319..d9642a7201aae83b6d2b95506f0d8969776c547f 100644 --- a/daemon/test/numbercleanertest.cpp +++ b/daemon/test/numbercleanertest.cpp @@ -51,78 +51,78 @@ #define VALID_PREPENDED_NUMBER "95143334444" #define VALID_EXTENSION "136" -void NumberCleanerTest::test_format_1 (void) +void NumberCleanerTest::test_format_1(void) { - _debug ("-------------------- NumberCleanerTest::test_format_1 --------------------\n"); - CPPUNIT_ASSERT (NumberCleaner::clean (NUMBER_TEST_1) == VALID_NUMBER); + DEBUG("-------------------- NumberCleanerTest::test_format_1 --------------------\n"); + CPPUNIT_ASSERT(NumberCleaner::clean(NUMBER_TEST_1) == VALID_NUMBER); } -void NumberCleanerTest::test_format_2 (void) +void NumberCleanerTest::test_format_2(void) { - _debug ("-------------------- NumberCleanerTest::test_format_2 --------------------\n"); + DEBUG("-------------------- NumberCleanerTest::test_format_2 --------------------\n"); - CPPUNIT_ASSERT (NumberCleaner::clean (NUMBER_TEST_2) == VALID_NUMBER); + CPPUNIT_ASSERT(NumberCleaner::clean(NUMBER_TEST_2) == VALID_NUMBER); } -void NumberCleanerTest::test_format_3 (void) +void NumberCleanerTest::test_format_3(void) { - _debug ("-------------------- NumberCleanerTest::test_format_3 --------------------\n"); + DEBUG("-------------------- NumberCleanerTest::test_format_3 --------------------\n"); - CPPUNIT_ASSERT (NumberCleaner::clean (NUMBER_TEST_3) == VALID_NUMBER); + CPPUNIT_ASSERT(NumberCleaner::clean(NUMBER_TEST_3) == VALID_NUMBER); } -void NumberCleanerTest::test_format_4 (void) +void NumberCleanerTest::test_format_4(void) { - _debug ("-------------------- NumberCleanerTest::test_format_4 --------------------\n"); + DEBUG("-------------------- NumberCleanerTest::test_format_4 --------------------\n"); - CPPUNIT_ASSERT (NumberCleaner::clean (NUMBER_TEST_4) == VALID_NUMBER); + CPPUNIT_ASSERT(NumberCleaner::clean(NUMBER_TEST_4) == VALID_NUMBER); } -void NumberCleanerTest::test_format_5 (void) +void NumberCleanerTest::test_format_5(void) { - _debug ("-------------------- NumberCleanerTest::test_format_5 --------------------\n"); + DEBUG("-------------------- NumberCleanerTest::test_format_5 --------------------\n"); - CPPUNIT_ASSERT (NumberCleaner::clean (NUMBER_TEST_5) == VALID_NUMBER); + CPPUNIT_ASSERT(NumberCleaner::clean(NUMBER_TEST_5) == VALID_NUMBER); } -void NumberCleanerTest::test_format_6 (void) +void NumberCleanerTest::test_format_6(void) { - _debug ("-------------------- NumberCleanerTest::test_format_6 --------------------\n"); + DEBUG("-------------------- NumberCleanerTest::test_format_6 --------------------\n"); - CPPUNIT_ASSERT (NumberCleaner::clean (NUMBER_TEST_6) == VALID_NUMBER); + CPPUNIT_ASSERT(NumberCleaner::clean(NUMBER_TEST_6) == VALID_NUMBER); } -void NumberCleanerTest::test_format_7 (void) +void NumberCleanerTest::test_format_7(void) { - _debug ("-------------------- NumberCleanerTest::test_format_7 --------------------\n"); + DEBUG("-------------------- NumberCleanerTest::test_format_7 --------------------\n"); - CPPUNIT_ASSERT (NumberCleaner::clean (NUMBER_TEST_7) == VALID_EXTENSION); + CPPUNIT_ASSERT(NumberCleaner::clean(NUMBER_TEST_7) == VALID_EXTENSION); } -void NumberCleanerTest::test_format_8 (void) +void NumberCleanerTest::test_format_8(void) { - _debug ("-------------------- NumberCleanerTest::test_format_8 --------------------\n"); + DEBUG("-------------------- NumberCleanerTest::test_format_8 --------------------\n"); - CPPUNIT_ASSERT (NumberCleaner::clean (NUMBER_TEST_8) == VALID_NUMBER); + CPPUNIT_ASSERT(NumberCleaner::clean(NUMBER_TEST_8) == VALID_NUMBER); } -void NumberCleanerTest::test_format_9 (void) +void NumberCleanerTest::test_format_9(void) { - _debug ("-------------------- NumberCleanerTest::test_format_9 --------------------\n"); + DEBUG("-------------------- NumberCleanerTest::test_format_9 --------------------\n"); - CPPUNIT_ASSERT (NumberCleaner::clean (NUMBER_TEST_9) == VALID_NUMBER); + CPPUNIT_ASSERT(NumberCleaner::clean(NUMBER_TEST_9) == VALID_NUMBER); } -void NumberCleanerTest::test_format_10 (void) +void NumberCleanerTest::test_format_10(void) { - _debug ("-------------------- NumberCleanerTest::test_format_10 --------------------\n"); + DEBUG("-------------------- NumberCleanerTest::test_format_10 --------------------\n"); - CPPUNIT_ASSERT (NumberCleaner::clean (NUMBER_TEST_1, "9") == VALID_PREPENDED_NUMBER); + CPPUNIT_ASSERT(NumberCleaner::clean(NUMBER_TEST_1, "9") == VALID_PREPENDED_NUMBER); } -void NumberCleanerTest::test_format_11 (void) +void NumberCleanerTest::test_format_11(void) { - _debug ("-------------------- NumberCleanerTest::test_format_11 --------------------\n"); + DEBUG("-------------------- NumberCleanerTest::test_format_11 --------------------\n"); - CPPUNIT_ASSERT (NumberCleaner::clean (NUMBER_TEST_10, "9") == VALID_EXTENSION); + CPPUNIT_ASSERT(NumberCleaner::clean(NUMBER_TEST_10, "9") == VALID_EXTENSION); } diff --git a/daemon/test/numbercleanertest.h b/daemon/test/numbercleanertest.h index 71f22c61bf979d80552fa17cee18933109b8d726..fe1f2c298635f1ac1808443f15fba5d0f8acdc17 100644 --- a/daemon/test/numbercleanertest.h +++ b/daemon/test/numbercleanertest.h @@ -40,7 +40,7 @@ #include "numbercleaner.h" // #include "../src/conference.h" /* - * @file numbercleanerTest.cpp + * @file numbercleanerTest.cpp * @brief Regroups unitary tests related to the phone number cleanup function. */ @@ -49,40 +49,40 @@ class NumberCleanerTest : public CppUnit::TestCase { - /** - * Use cppunit library macros to add unit test the factory - */ - CPPUNIT_TEST_SUITE (NumberCleanerTest); - CPPUNIT_TEST (test_format_1); - CPPUNIT_TEST (test_format_2); - CPPUNIT_TEST (test_format_3); - CPPUNIT_TEST (test_format_4); - CPPUNIT_TEST (test_format_5); - CPPUNIT_TEST (test_format_6); + /** + * Use cppunit library macros to add unit test the factory + */ + CPPUNIT_TEST_SUITE(NumberCleanerTest); + CPPUNIT_TEST(test_format_1); + CPPUNIT_TEST(test_format_2); + CPPUNIT_TEST(test_format_3); + CPPUNIT_TEST(test_format_4); + CPPUNIT_TEST(test_format_5); + CPPUNIT_TEST(test_format_6); /*CPPUNIT_TEST (test_format_7); CPPUNIT_TEST (test_format_8); CPPUNIT_TEST (test_format_9);*/ - CPPUNIT_TEST (test_format_10); - CPPUNIT_TEST_SUITE_END (); + CPPUNIT_TEST(test_format_10); + CPPUNIT_TEST_SUITE_END(); public: NumberCleanerTest() : CppUnit::TestCase("Hook Manager Tests") {} - - void test_format_1 (); - void test_format_2 (); - void test_format_3 (); - void test_format_4 (); - void test_format_5 (); - void test_format_6 (); - void test_format_7 (); - void test_format_8 (); - void test_format_9 (); - void test_format_10 (); - void test_format_11 (); + + void test_format_1(); + void test_format_2(); + void test_format_3(); + void test_format_4(); + void test_format_5(); + void test_format_6(); + void test_format_7(); + void test_format_8(); + void test_format_9(); + void test_format_10(); + void test_format_11(); }; /* Register our test module */ CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(NumberCleanerTest, "NumberCleanerTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( NumberCleanerTest ); +CPPUNIT_TEST_SUITE_REGISTRATION(NumberCleanerTest); #endif diff --git a/daemon/test/pluginmanagertest.cpp b/daemon/test/pluginmanagertest.cpp deleted file mode 100644 index 0a6929576ac3a72089dd8b9e293c376a96895c0b..0000000000000000000000000000000000000000 --- a/daemon/test/pluginmanagertest.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Savoir-Faire Linux Inc. - * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - -#include <stdio.h> -#include <sstream> -#include <dlfcn.h> - -#include "pluginmanagertest.h" - -using std::cout; -using std::endl; - -#define FAKE_PLUGIN_DESC "mytest" - - -void PluginManagerTest::setUp() -{ - FAKE_PLUGIN_DIR = std::string(getenv("FAKE_PLUGIN_DIR")); - FAKE_PLUGIN_NAME = std::string(getenv("FAKE_PLUGIN_NAME")); - // Instanciate the plugin manager singleton - _pm = PluginManager::instance(); - library = 0; - plugin = 0; -} - -void PluginManagerTest::testLoadDynamicLibrary() -{ - _debug ("-------------------- PluginManagerTest::testLoadDynamicLibrary --------------------\n"); - - CPPUNIT_ASSERT (_pm->loadDynamicLibrary (FAKE_PLUGIN_NAME) != NULL); -} - -void PluginManagerTest::testUnloadDynamicLibrary() -{ - _debug ("-------------------- PluginManagerTest::testUnloadDynamicLibrary --------------------\n"); - - library = _pm->loadDynamicLibrary (FAKE_PLUGIN_NAME); - CPPUNIT_ASSERT (library != NULL); - CPPUNIT_ASSERT (_pm->unloadDynamicLibrary (library) == 0); -} - -void PluginManagerTest::testInstanciatePlugin() -{ - _debug ("-------------------- PluginManagerTest::testInstanciatePlugin --------------------\n"); - - library = _pm->loadDynamicLibrary (FAKE_PLUGIN_NAME); - CPPUNIT_ASSERT (library != NULL); - CPPUNIT_ASSERT (_pm->instanciatePlugin (library, &plugin) == 0); - CPPUNIT_ASSERT (plugin!=NULL); -} - -void PluginManagerTest::testInitPlugin() -{ - _debug ("-------------------- PluginManagerTest::testInitPlugin --------------------\n"); - - library = _pm->loadDynamicLibrary (FAKE_PLUGIN_NAME); - CPPUNIT_ASSERT (library != NULL); - CPPUNIT_ASSERT (_pm->instanciatePlugin (library, &plugin) == 0); - CPPUNIT_ASSERT (plugin!=NULL); - CPPUNIT_ASSERT (plugin->getPluginName() == FAKE_PLUGIN_DESC); -} - -void PluginManagerTest::testRegisterPlugin() -{ - _debug ("-------------------- PluginManagerTest::testRegisterPlugin --------------------\n"); - - library = _pm->loadDynamicLibrary (FAKE_PLUGIN_NAME); - CPPUNIT_ASSERT (library != NULL); - CPPUNIT_ASSERT (_pm->instanciatePlugin (library, &plugin) == 0); - CPPUNIT_ASSERT (_pm->isPluginLoaded (FAKE_PLUGIN_DESC) == false); - CPPUNIT_ASSERT (_pm->registerPlugin (plugin, library) == 0); - CPPUNIT_ASSERT (_pm->isPluginLoaded (FAKE_PLUGIN_DESC) == true); -} - -void PluginManagerTest::testLoadPlugins () -{ - _debug ("-------------------- PluginManagerTest::testLoadPlugins --------------------\n"); - try { - CPPUNIT_ASSERT (_pm->loadPlugins (FAKE_PLUGIN_DIR) == 0); - CPPUNIT_ASSERT (_pm->isPluginLoaded (FAKE_PLUGIN_DESC) == true); - } - catch (LibraryManagerException &e){ - - } -} - -void PluginManagerTest::testUnloadPlugins () -{ - _debug ("-------------------- PluginManagerTest::testUnloadPlugins --------------------\n"); - - try { - - CPPUNIT_ASSERT (_pm->loadPlugins (FAKE_PLUGIN_DIR) == 0); - CPPUNIT_ASSERT (_pm->isPluginLoaded (FAKE_PLUGIN_DESC) == true); - CPPUNIT_ASSERT (_pm->unloadPlugins () == 0); - CPPUNIT_ASSERT (_pm->isPluginLoaded (FAKE_PLUGIN_DESC) == false); - } - catch (LibraryManagerException &e) { - - } -} - -void PluginManagerTest::tearDown() -{ - // Delete the plugin manager object - delete _pm; - _pm=0; - - delete plugin; - plugin = 0; - - delete library; - library = 0; -} diff --git a/daemon/test/pluginmanagertest.h b/daemon/test/pluginmanagertest.h deleted file mode 100644 index 69dabb017742b171a7ccb82bd23ee0dc89a96517..0000000000000000000000000000000000000000 --- a/daemon/test/pluginmanagertest.h +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Savoir-Faire Linux Inc. - * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - -// Cppunit import -#include <cppunit/extensions/HelperMacros.h> -#include <cppunit/TestCaller.h> -#include <cppunit/TestCase.h> -#include <cppunit/TestSuite.h> - -#include <assert.h> - -// Application import -#include "plug-in/pluginmanager.h" -#include "plug-in/librarymanager.h" -#include "plug-in/plugin.h" - -/* - * @file pluginManagerTest.cpp - * @brief Regroups unitary tests related to the plugin manager. - */ - -#ifndef _PLUGINMANAGER_TEST_ -#define _PLUGINMANAGER_TEST_ - -class PluginManagerTest : public CppUnit::TestCase { - - /** - * Use cppunit library macros to add unit test the factory - */ - CPPUNIT_TEST_SUITE( PluginManagerTest ); - CPPUNIT_TEST( testLoadDynamicLibrary ); - CPPUNIT_TEST( testUnloadDynamicLibrary ); - CPPUNIT_TEST( testInstanciatePlugin ); - CPPUNIT_TEST( testInitPlugin ); - CPPUNIT_TEST( testRegisterPlugin ); - CPPUNIT_TEST( testLoadPlugins ); - CPPUNIT_TEST( testUnloadPlugins ); - CPPUNIT_TEST_SUITE_END(); - - public: - PluginManagerTest() : CppUnit::TestCase("Plugin Manager Tests") - , _pm(0) - , library(0) - , plugin(0) - {} - - /* - * Code factoring - Common resources can be initialized here. - * This method is called by unitcpp before each test - */ - void setUp(); - - /* - * Code factoring - Common resources can be released here. - * This method is called by unitcpp after each test - */ - void tearDown (); - - void testLoadDynamicLibrary (); - - void testUnloadDynamicLibrary (); - - void testInstanciatePlugin (); - - void testInitPlugin (); - - void testRegisterPlugin (); - - void testLoadPlugins (); - - void testUnloadPlugins (); - - private: - std::string FAKE_PLUGIN_DIR; - std::string FAKE_PLUGIN_NAME; - PluginManager *_pm; - LibraryManager *library; - Plugin *plugin; -}; - -/* Register our test module */ -CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(PluginManagerTest, "PluginManagerTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( PluginManagerTest ); - -#endif diff --git a/daemon/test/ringtonetest.cpp b/daemon/test/ringtonetest.cpp index 8857c4f8e22484086820545ef33bc4f9393afaa0..eaa0e90833a72162131407a83a58639de6ef60b6 100644 --- a/daemon/test/ringtonetest.cpp +++ b/daemon/test/ringtonetest.cpp @@ -35,11 +35,11 @@ void RingtoneTest::testLoadWavefile() WavFile *wav = new WavFile(); // Test initial values - CPPUNIT_ASSERT (wav->isStarted() == false); - CPPUNIT_ASSERT (wav->getSize() == 0); + CPPUNIT_ASSERT(wav->isStarted() == false); + CPPUNIT_ASSERT(wav->getSize() == 0); // Test protection against wrong file name - CPPUNIT_ASSERT (wav->loadFile (std::string ("wrongfilename.wav"), NULL, 44100) == false); + CPPUNIT_ASSERT(wav->loadFile(std::string("wrongfilename.wav"), NULL, 44100) == false); diff --git a/daemon/test/ringtonetest.h b/daemon/test/ringtonetest.h index 78b3e7d82f16d9e94c1c8cf11daa78f0ea0811b1..8791629c2b0a20541d9533f87fe3a97c7eeed42f 100644 --- a/daemon/test/ringtonetest.h +++ b/daemon/test/ringtonetest.h @@ -53,22 +53,22 @@ class RingtoneTest: public CppUnit::TestFixture { - /* - * Use cppunit library macros to add unit test the factory - */ - CPPUNIT_TEST_SUITE( RingtoneTest ); - CPPUNIT_TEST( testLoadWavefile ); - CPPUNIT_TEST_SUITE_END(); + /* + * Use cppunit library macros to add unit test the factory + */ + CPPUNIT_TEST_SUITE(RingtoneTest); + CPPUNIT_TEST(testLoadWavefile); + CPPUNIT_TEST_SUITE_END(); -public: - /* - * Unit tests related to the audio preferences - */ - void testLoadWavefile(); + public: + /* + * Unit tests related to the audio preferences + */ + void testLoadWavefile(); }; /* Register our test module */ CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(RingtoneTest, "RingtoneTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( RingtoneTest ); +CPPUNIT_TEST_SUITE_REGISTRATION(RingtoneTest); #endif diff --git a/daemon/test/rtptest.h b/daemon/test/rtptest.h deleted file mode 100644 index 2cc460163edb0683b770df855d1e3ae3b207c8cd..0000000000000000000000000000000000000000 --- a/daemon/test/rtptest.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Savoir-Faire Linux Inc. - * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> - * - * 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 - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - * Additional permission under GNU GPL version 3 section 7: - * - * If you modify this program, or any covered work, by linking or - * combining it with the OpenSSL project's OpenSSL library (or a - * modified version of that library), containing parts covered by the - * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. - * grants you additional permission to convey the resulting work. - * Corresponding Source for a non-source form of such a combination - * shall include the source code for the parts of OpenSSL used as well - * as that of the covered work. - */ - -#ifndef _RTP_TEST_ -#define _RTP_TEST_ - -// Cppunit import -#include <cppunit/extensions/HelperMacros.h> -#include <cppunit/TestCaller.h> -#include <cppunit/TestCase.h> -#include <cppunit/TestSuite.h> - -#include <assert.h> - -#include <stdio.h> -#include <sstream> -#include <ccrtp/rtp.h> - -// pjsip import -#include <pjsip.h> -#include <pjlib.h> -#include <pjsip_ua.h> -#include <pjlib-util.h> -#include <pjnath/stun_config.h> - -// Application import -#include "audio/audiortp/AudioRtpFactory.h" -#include "manager.h" -#include "call.h" -#include "sip/sipcall.h" -#include "sip/sipvoiplink.h" - -#include "config/config.h" - -using namespace sfl; - -class AudioSymmetricRtpSession; -//class AudioRtpFactory; -class SIPVoIPLink; - -class RtpTest: public CppUnit::TestCase { - - /* - * Use cppunit library macros to add unit test the factory - */ -CPPUNIT_TEST_SUITE( RtpTest ); - CPPUNIT_TEST( testRtpInitClose ); - CPPUNIT_TEST_SUITE_END(); - -public: - - RtpTest() : - CppUnit::TestCase("Audio Layer Tests") { - } - - /* - * Code factoring - Common resources can be initialized here. - * This method is called by unitcpp before each test - */ - void setUp(); - - /* - * Code factoring - Common resources can be released here. - * This method is called by unitcpp after each test - */ - void tearDown(); - - bool pjsipInit(); - - void testRtpInitClose(); - -private: - - enum CallType { - Incoming, Outgoing - }; - - ManagerImpl* manager; - - AudioRtpFactory *audiortp; - - SIPCall *sipcall; - - pj_caching_pool _cp; - - pj_pool_t *_pool; -}; -/* Register our test module */ -CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(RtpTest, "RtpTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( RtpTest ); - -#endif diff --git a/daemon/test/run_tests.sh b/daemon/test/run_tests.sh index 69649f1ffa2b93c9eb95c886d580851b9d29e420..85a3a785019821bd50704031b3a63feea6dad5a6 100755 --- a/daemon/test/run_tests.sh +++ b/daemon/test/run_tests.sh @@ -1,2 +1,2 @@ #!/bin/bash -CODECS_PATH="../src/audio/codecs" FAKE_PLUGIN_DIR="../src/plug-in/test/" FAKE_PLUGIN_NAME="../src/plug-in/test/libplugintest.so" exec ./test --xml +CODECS_PATH="../src/audio/codecs" exec ./test --xml diff --git a/daemon/test/sdesnegotiatortest.cpp b/daemon/test/sdesnegotiatortest.cpp index 7e376db04b86b6f6f107d0a77540ed1fcceab82e..2330412ff1a28b8d928b4bc26582acee8e3a56a6 100644 --- a/daemon/test/sdesnegotiatortest.cpp +++ b/daemon/test/sdesnegotiatortest.cpp @@ -41,26 +41,30 @@ #include <sstream> #include "sdesnegotiatortest.h" +#include "sip/pattern.h" +#include "sip/sdes_negotiator.h" #include <unistd.h> #include "global.h" - using std::cout; using std::endl; +SdesNegotiatorTest::SdesNegotiatorTest() : pattern(0), sdesnego(0), + remoteOffer(0), localCapabilities(0) +{} void SdesNegotiatorTest::testTagPattern() { - _debug ("-------------------- SdesNegotiatorTest::testTagPattern --------------------\n"); + DEBUG("-------------------- SdesNegotiatorTest::testTagPattern --------------------\n"); std::string subject = "a=crypto:4"; - pattern = new sfl::Pattern ("^a=crypto:(?P<tag>[0-9]{1,9})"); + pattern = new sfl::Pattern("^a=crypto:(?P<tag>[0-9]{1,9})"); *pattern << subject; - CPPUNIT_ASSERT (pattern->matches()); - CPPUNIT_ASSERT (pattern->group ("tag").compare ("4") == 0); + CPPUNIT_ASSERT(pattern->matches()); + CPPUNIT_ASSERT(pattern->group("tag").compare("4") == 0); delete pattern; pattern = NULL; @@ -69,18 +73,18 @@ void SdesNegotiatorTest::testTagPattern() void SdesNegotiatorTest::testCryptoSuitePattern() { - _debug ("-------------------- SdesNegotiatorTest::testCryptoSuitePattern --------------------\n"); + DEBUG("-------------------- SdesNegotiatorTest::testCryptoSuitePattern --------------------\n"); std::string subject = "AES_CM_128_HMAC_SHA1_80"; - pattern = new sfl::Pattern ("(?P<cryptoSuite>AES_CM_128_HMAC_SHA1_80|" \ - "AES_CM_128_HMAC_SHA1_32|" \ - "F8_128_HMAC_SHA1_80|" \ - "[A-Za-z0-9_]+)"); + pattern = new sfl::Pattern("(?P<cryptoSuite>AES_CM_128_HMAC_SHA1_80|" \ + "AES_CM_128_HMAC_SHA1_32|" \ + "F8_128_HMAC_SHA1_80|" \ + "[A-Za-z0-9_]+)"); *pattern << subject; - CPPUNIT_ASSERT (pattern->matches()); - CPPUNIT_ASSERT (pattern->group ("cryptoSuite").compare ("AES_CM_128_HMAC_SHA1_80") == 0); + CPPUNIT_ASSERT(pattern->matches()); + CPPUNIT_ASSERT(pattern->group("cryptoSuite").compare("AES_CM_128_HMAC_SHA1_80") == 0); delete pattern; pattern = NULL; @@ -89,25 +93,25 @@ void SdesNegotiatorTest::testCryptoSuitePattern() void SdesNegotiatorTest::testKeyParamsPattern() { - _debug ("-------------------- SdesNegotiatorTest::testKeyParamsPattern --------------------\n"); + DEBUG("-------------------- SdesNegotiatorTest::testKeyParamsPattern --------------------\n"); std::string subject = "inline:d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj|2^20|1:32"; - pattern = new sfl::Pattern ("(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ - "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)\\|" \ - "(2\\^(?P<lifetime>[0-9]+)\\|" \ - "(?P<mkiValue>[0-9]+)\\:" \ - "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); + pattern = new sfl::Pattern("(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ + "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)\\|" \ + "(2\\^(?P<lifetime>[0-9]+)\\|" \ + "(?P<mkiValue>[0-9]+)\\:" \ + "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); *pattern << subject; pattern->matches(); - CPPUNIT_ASSERT (pattern->group ("srtpKeyMethod").compare ("inline:")); - CPPUNIT_ASSERT (pattern->group ("srtpKeyInfo").compare ("d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj") - == 0); - CPPUNIT_ASSERT (pattern->group ("lifetime").compare ("20") == 0); - CPPUNIT_ASSERT (pattern->group ("mkiValue").compare ("1") == 0); - CPPUNIT_ASSERT (pattern->group ("mkiLength").compare ("32") == 0); + CPPUNIT_ASSERT(pattern->group("srtpKeyMethod").compare("inline:")); + CPPUNIT_ASSERT(pattern->group("srtpKeyInfo").compare("d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj") + == 0); + CPPUNIT_ASSERT(pattern->group("lifetime").compare("20") == 0); + CPPUNIT_ASSERT(pattern->group("mkiValue").compare("1") == 0); + CPPUNIT_ASSERT(pattern->group("mkiLength").compare("32") == 0); delete pattern; pattern = NULL; @@ -116,21 +120,21 @@ void SdesNegotiatorTest::testKeyParamsPattern() void SdesNegotiatorTest::testKeyParamsPatternWithoutMKI() { - _debug ("-------------------- SdesNegotiatorTest::testKeyParamsPatternWithoutMKI --------------------\n"); + DEBUG("-------------------- SdesNegotiatorTest::testKeyParamsPatternWithoutMKI --------------------\n"); std::string subject = "inline:d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj"; - pattern = new sfl::Pattern ("(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ - "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)" \ - "(\\|2\\^(?P<lifetime>[0-9]+)\\|" \ - "(?P<mkiValue>[0-9]+)\\:" \ - "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); + pattern = new sfl::Pattern("(?P<srtpKeyMethod>inline|[A-Za-z0-9_]+)\\:" \ + "(?P<srtpKeyInfo>[A-Za-z0-9\x2B\x2F\x3D]+)" \ + "(\\|2\\^(?P<lifetime>[0-9]+)\\|" \ + "(?P<mkiValue>[0-9]+)\\:" \ + "(?P<mkiLength>[0-9]{1,3})\\;?)?", "g"); *pattern << subject; pattern->matches(); - CPPUNIT_ASSERT (pattern->group ("srtpKeyMethod").compare ("inline:")); - CPPUNIT_ASSERT (pattern->group ("srtpKeyInfo").compare ("d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj") - == 0); + CPPUNIT_ASSERT(pattern->group("srtpKeyMethod").compare("inline:")); + CPPUNIT_ASSERT(pattern->group("srtpKeyInfo").compare("d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj") + == 0); delete pattern; pattern = NULL; @@ -143,23 +147,23 @@ void SdesNegotiatorTest::testKeyParamsPatternWithoutMKI() */ void SdesNegotiatorTest::testNegotiation() { - _debug ("-------------------- SdesNegotiatorTest::testNegotiation --------------------\n"); + DEBUG("-------------------- SdesNegotiatorTest::testNegotiation --------------------\n"); // Add a new SDES crypto line to be processed. remoteOffer = new std::vector<std::string>(); - remoteOffer->push_back (std::string ("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd|2^20|1:32")); - remoteOffer->push_back (std::string ("a=crypto:2 AES_CM_128_HMAC_SHA1_32 inline:NzB4d1BINUAvLEw6UzF3WSJ+PSdFcGdUJShpX1Zj|2^20|1:32")); + remoteOffer->push_back(std::string("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd|2^20|1:32")); + remoteOffer->push_back(std::string("a=crypto:2 AES_CM_128_HMAC_SHA1_32 inline:NzB4d1BINUAvLEw6UzF3WSJ+PSdFcGdUJShpX1Zj|2^20|1:32")); // Register the local capabilities. localCapabilities = new std::vector<sfl::CryptoSuiteDefinition>(); for (int i = 0; i < 3; i++) { - localCapabilities->push_back (sfl::CryptoSuites[i]); + localCapabilities->push_back(sfl::CryptoSuites[i]); } - sdesnego = new sfl::SdesNegotiator (*localCapabilities, *remoteOffer); + sdesnego = new sfl::SdesNegotiator(*localCapabilities, *remoteOffer); - CPPUNIT_ASSERT (sdesnego->negotiate()); + CPPUNIT_ASSERT(sdesnego->negotiate()); // CPPUNIT_ASSERT(sdesnego->getKeyInfo().compare("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd|2^20|1:32")==0); delete remoteOffer; @@ -177,24 +181,24 @@ void SdesNegotiatorTest::testNegotiation() */ void SdesNegotiatorTest::testComponent() { - _debug ("-------------------- SdesNegotiatorTest::testComponent --------------------\n"); + DEBUG("-------------------- SdesNegotiatorTest::testComponent --------------------\n"); // Register the local capabilities. std::vector<sfl::CryptoSuiteDefinition> * capabilities = new std::vector<sfl::CryptoSuiteDefinition>(); //Support all the CryptoSuites for (int i = 0; i < 3; i++) { - capabilities->push_back (sfl::CryptoSuites[i]); + capabilities->push_back(sfl::CryptoSuites[i]); } // Make sure that if a component is missing, negotiate will fail - std::string cryptoLine ("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:|2^20|1:32"); + std::string cryptoLine("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:|2^20|1:32"); std::vector<std::string> * cryptoOffer = new std::vector<std::string>(); - cryptoOffer->push_back (cryptoLine); + cryptoOffer->push_back(cryptoLine); - sfl::SdesNegotiator * negotiator = new sfl::SdesNegotiator (*capabilities, *cryptoOffer); + sfl::SdesNegotiator * negotiator = new sfl::SdesNegotiator(*capabilities, *cryptoOffer); - CPPUNIT_ASSERT (negotiator->negotiate() == false); + CPPUNIT_ASSERT(negotiator->negotiate() == false); } @@ -204,32 +208,32 @@ void SdesNegotiatorTest::testComponent() */ void SdesNegotiatorTest::testMostSimpleCase() { - _debug ("-------------------- SdesNegotiatorTest::testMostSimpleCase --------------------\n"); + DEBUG("-------------------- SdesNegotiatorTest::testMostSimpleCase --------------------\n"); // Register the local capabilities. std::vector<sfl::CryptoSuiteDefinition> * capabilities = new std::vector<sfl::CryptoSuiteDefinition>(); //Support all the CryptoSuites for (int i = 0; i < 3; i++) { - capabilities->push_back (sfl::CryptoSuites[i]); + capabilities->push_back(sfl::CryptoSuites[i]); } // Make sure taht this case works (since it's default for most application) - std::string cryptoLine ("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd"); + std::string cryptoLine("a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd"); std::vector<std::string> * cryptoOffer = new std::vector<std::string>(); - cryptoOffer->push_back (cryptoLine); + cryptoOffer->push_back(cryptoLine); - sfl::SdesNegotiator * negotiator = new sfl::SdesNegotiator (*capabilities, *cryptoOffer); + sfl::SdesNegotiator * negotiator = new sfl::SdesNegotiator(*capabilities, *cryptoOffer); - CPPUNIT_ASSERT (negotiator->negotiate() == true); + CPPUNIT_ASSERT(negotiator->negotiate() == true); - CPPUNIT_ASSERT (negotiator->getCryptoSuite() == "AES_CM_128_HMAC_SHA1_80"); - CPPUNIT_ASSERT (negotiator->getKeyMethod() == "inline"); - CPPUNIT_ASSERT (negotiator->getKeyInfo() == "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd"); - CPPUNIT_ASSERT (negotiator->getLifeTime() == ""); - CPPUNIT_ASSERT (negotiator->getMkiValue() == ""); - CPPUNIT_ASSERT (negotiator->getMkiLength() == ""); - CPPUNIT_ASSERT (negotiator->getAuthTagLength() == "80"); + CPPUNIT_ASSERT(negotiator->getCryptoSuite() == "AES_CM_128_HMAC_SHA1_80"); + CPPUNIT_ASSERT(negotiator->getKeyMethod() == "inline"); + CPPUNIT_ASSERT(negotiator->getKeyInfo() == "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd"); + CPPUNIT_ASSERT(negotiator->getLifeTime() == ""); + CPPUNIT_ASSERT(negotiator->getMkiValue() == ""); + CPPUNIT_ASSERT(negotiator->getMkiLength() == ""); + CPPUNIT_ASSERT(negotiator->getAuthTagLength() == "80"); delete capabilities; @@ -243,31 +247,31 @@ void SdesNegotiatorTest::testMostSimpleCase() void SdesNegotiatorTest::test32ByteKeyLength() { - _debug ("-------------------- SdesNegotiatorTest::test32ByteKeyLength --------------------\n"); + DEBUG("-------------------- SdesNegotiatorTest::test32ByteKeyLength --------------------\n"); // Register the local capabilities. std::vector<sfl::CryptoSuiteDefinition> * capabilities = new std::vector<sfl::CryptoSuiteDefinition>(); //Support all the CryptoSuites for (int i = 0; i < 3; i++) { - capabilities->push_back (sfl::CryptoSuites[i]); + capabilities->push_back(sfl::CryptoSuites[i]); } - std::string cryptoLine ("a=crypto:1 AES_CM_128_HMAC_SHA1_32 inline:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd"); + std::string cryptoLine("a=crypto:1 AES_CM_128_HMAC_SHA1_32 inline:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd"); std::vector<std::string> * cryptoOffer = new std::vector<std::string>(); - cryptoOffer->push_back (cryptoLine); + cryptoOffer->push_back(cryptoLine); - sfl::SdesNegotiator * negotiator = new sfl::SdesNegotiator (*capabilities, *cryptoOffer); + sfl::SdesNegotiator * negotiator = new sfl::SdesNegotiator(*capabilities, *cryptoOffer); - CPPUNIT_ASSERT (negotiator->negotiate() == true); + CPPUNIT_ASSERT(negotiator->negotiate() == true); - CPPUNIT_ASSERT (negotiator->getCryptoSuite() == "AES_CM_128_HMAC_SHA1_32"); - CPPUNIT_ASSERT (negotiator->getKeyMethod() == "inline"); - CPPUNIT_ASSERT (negotiator->getKeyInfo() == "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd"); - CPPUNIT_ASSERT (negotiator->getLifeTime() == ""); - CPPUNIT_ASSERT (negotiator->getMkiValue() == ""); - CPPUNIT_ASSERT (negotiator->getMkiLength() == ""); - CPPUNIT_ASSERT (negotiator->getAuthTagLength() == "32"); + CPPUNIT_ASSERT(negotiator->getCryptoSuite() == "AES_CM_128_HMAC_SHA1_32"); + CPPUNIT_ASSERT(negotiator->getKeyMethod() == "inline"); + CPPUNIT_ASSERT(negotiator->getKeyInfo() == "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwd"); + CPPUNIT_ASSERT(negotiator->getLifeTime() == ""); + CPPUNIT_ASSERT(negotiator->getMkiValue() == ""); + CPPUNIT_ASSERT(negotiator->getMkiLength() == ""); + CPPUNIT_ASSERT(negotiator->getAuthTagLength() == "32"); delete capabilities; capabilities = NULL; diff --git a/daemon/test/sdesnegotiatortest.h b/daemon/test/sdesnegotiatortest.h index 7257b57244a93d7cd71380fff8c4e9782cbd149d..eb9bb74cde8fc360dcc456e8d70eaf0114e252c0 100644 --- a/daemon/test/sdesnegotiatortest.h +++ b/daemon/test/sdesnegotiatortest.h @@ -34,8 +34,6 @@ #include <cppunit/TestCase.h> #include <cppunit/TestSuite.h> -#include <assert.h> - #include <cstddef> #include <stdio.h> #include <sstream> @@ -50,73 +48,73 @@ #include <pjlib-util.h> #include <pjnath/stun_config.h> -// Application import -#include "sip/SdesNegotiator.h" -#include "sip/Pattern.h" - +#include "noncopyable.h" /* - * @file sdesnegotiationTest.cpp + * @file sdesnegotiationTest.cpp * @brief Regroups unitary tests related to the plugin manager. */ -#ifndef _SDESNEGOTIATOR_TEST_ -#define _SDESNEGOTIATOR_TEST_ +#ifndef __SDESNEGOTIATOR_TEST_H__ +#define __SDESNEGOTIATOR_TEST_H__ +#include "sip/sdes_negotiator.h" // for CryptoSuiteDefinition +namespace sfl { + class Pattern; +} class SdesNegotiatorTest : public CppUnit::TestCase { - /* - * Use cppunit library macros to add unit test the factory - */ - CPPUNIT_TEST_SUITE( SdesNegotiatorTest ); - CPPUNIT_TEST( testTagPattern ); - CPPUNIT_TEST( testCryptoSuitePattern ); - CPPUNIT_TEST( testKeyParamsPattern ); - CPPUNIT_TEST( testKeyParamsPatternWithoutMKI ); - CPPUNIT_TEST( testNegotiation ); - CPPUNIT_TEST( testMostSimpleCase ); - CPPUNIT_TEST( test32ByteKeyLength ); - CPPUNIT_TEST_SUITE_END(); + /* + * Use cppunit library macros to add unit test the factory + */ + CPPUNIT_TEST_SUITE(SdesNegotiatorTest); + CPPUNIT_TEST(testTagPattern); + CPPUNIT_TEST(testCryptoSuitePattern); + CPPUNIT_TEST(testKeyParamsPattern); + CPPUNIT_TEST(testKeyParamsPatternWithoutMKI); + CPPUNIT_TEST(testNegotiation); + CPPUNIT_TEST(testMostSimpleCase); + CPPUNIT_TEST(test32ByteKeyLength); + CPPUNIT_TEST_SUITE_END(); public: + SdesNegotiatorTest(); /* * Code factoring - Common resources can be released here. * This method is called by unitcpp after each test */ - void testTagPattern(); + void testTagPattern(); - void testCryptoSuitePattern(); + void testCryptoSuitePattern(); - void testKeyParamsPattern(); - - void testKeyParamsPatternCiscoStyle(); + void testKeyParamsPattern(); - void testKeyParamsPatternWithoutMKI(); + void testKeyParamsPatternCiscoStyle(); - void testNegotiation(); - - void testComponent(); + void testKeyParamsPatternWithoutMKI(); - void testMostSimpleCase(); + void testNegotiation(); - void test32ByteKeyLength(); + void testComponent(); - private: - - sfl::Pattern *pattern; + void testMostSimpleCase(); - sfl::SdesNegotiator *sdesnego; + void test32ByteKeyLength(); - std::vector<std::string> *remoteOffer; + private: + NON_COPYABLE(SdesNegotiatorTest); - std::vector<sfl::CryptoSuiteDefinition> *localCapabilities; + sfl::Pattern *pattern; + sfl::SdesNegotiator *sdesnego; + std::vector<std::string> *remoteOffer; + std::vector<sfl::CryptoSuiteDefinition> *localCapabilities; }; /* Register our test module */ CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(SdesNegotiatorTest, "SdesNegotiatorTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( SdesNegotiatorTest ); +CPPUNIT_TEST_SUITE_REGISTRATION(SdesNegotiatorTest); -#endif +#endif // __SDESNEGOTIATOR_TEST_H__ diff --git a/daemon/test/sdptest.cpp b/daemon/test/sdptest.cpp index 03066c54c15a16791e06c23bd9f7abdf98ea9cba..046c9a219c3ed11c750723e75524271b981b5e95 100644 --- a/daemon/test/sdptest.cpp +++ b/daemon/test/sdptest.cpp @@ -35,279 +35,277 @@ #include "audio/codecs/audiocodec.h" -enum session_type -{ +enum session_type { REMOTE_OFFER, LOCAL_OFFER, }; static const char *sdp_answer1 = "v=0\r\n" - "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" - "s= \r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 49920 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "m=video 53002 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n"; + "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" + "s= \r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 49920 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "m=video 53002 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n"; static const char *sdp_offer1 = "v=0\r\n" - "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" - "s= \r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 49920 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "m=video 53002 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n"; + "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" + "s= \r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 49920 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "m=video 53002 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n"; static const char *sdp_answer2 = "v=0\r\n" - "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" - "s= \r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 49920 RTP/AVP 3 97 9\r\n" - "a=rtpmap:3 GSM/8000\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "a=rtpmap:9 G722/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "m=video 53002 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n"; + "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" + "s= \r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 49920 RTP/AVP 3 97 9\r\n" + "a=rtpmap:3 GSM/8000\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "a=rtpmap:9 G722/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "m=video 53002 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n"; static const char *sdp_offer2 = "v=0\r\n" - "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" - "s= \r\n" - "c=IN IP4 host.example.com\r\n" - "t=0 0\r\n" - "m=audio 49920 RTP/AVP 3 97 9\r\n" - "a=rtpmap:3 GSM/8000\r\n" - "a=rtpmap:97 iLBC/8000\r\n" - "a=rtpmap:9 G722/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "m=video 53002 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n"; + "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" + "s= \r\n" + "c=IN IP4 host.example.com\r\n" + "t=0 0\r\n" + "m=audio 49920 RTP/AVP 3 97 9\r\n" + "a=rtpmap:3 GSM/8000\r\n" + "a=rtpmap:97 iLBC/8000\r\n" + "a=rtpmap:9 G722/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "m=video 53002 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n"; static const char *sdp_reinvite = "v=0\r\n" - "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" - "s= \r\n" - "c=IN IP4 host.exampleReinvite.com\r\n" - "t=0 0\r\n" - "m=audio 42445 RTP/AVP 0\r\n" - "a=rtpmap:0 PCMU/8000\r\n" - "m=video 0 RTP/AVP 31\r\n" - "m=video 53002 RTP/AVP 32\r\n" - "a=rtpmap:32 MPV/90000\r\n"; + "o=bob 2890844730 2890844730 IN IP4 host.example.com\r\n" + "s= \r\n" + "c=IN IP4 host.exampleReinvite.com\r\n" + "t=0 0\r\n" + "m=audio 42445 RTP/AVP 0\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "m=video 0 RTP/AVP 31\r\n" + "m=video 53002 RTP/AVP 32\r\n" + "a=rtpmap:32 MPV/90000\r\n"; void SDPTest::setUp() { - pj_caching_pool_init (&_poolCache, &pj_pool_factory_default_policy, 0); + pj_caching_pool_init(&poolCache_, &pj_pool_factory_default_policy, 0); - _testPool = pj_pool_create (&_poolCache.factory, "sdptest", 4000, 4000, NULL); + testPool_ = pj_pool_create(&poolCache_.factory, "sdptest", 4000, 4000, NULL); - _session = new Sdp(_testPool); + session_ = new Sdp(testPool_); } void SDPTest::tearDown() { - delete _session; - _session = NULL; - pj_pool_release (_testPool); + delete session_; + session_ = NULL; + pj_pool_release(testPool_); } -void SDPTest::testInitialOfferFirstCodec () +void SDPTest::testInitialOfferFirstCodec() { - std::cout << "------------ SDPTest::testInitialOfferFirstCodec --------------" << std::endl; + std::cout << "------------ SDPTest::testInitialOfferFirstCodec --------------" << std::endl; - CPPUNIT_ASSERT(_session->getLocalPublishedAudioPort() == 0); - CPPUNIT_ASSERT(_session->getRemoteAudioPort() == 0); - CPPUNIT_ASSERT(_session->getLocalIP() == ""); - CPPUNIT_ASSERT(_session->getRemoteIP() == ""); + CPPUNIT_ASSERT(session_->getLocalPublishedAudioPort() == 0); + CPPUNIT_ASSERT(session_->getRemoteAudioPort() == 0); + CPPUNIT_ASSERT(session_->getLocalIP() == ""); + CPPUNIT_ASSERT(session_->getRemoteIP() == ""); - CodecOrder codecSelection; + CodecOrder codecSelection; pjmedia_sdp_session *remoteAnswer; - codecSelection.push_back(PAYLOAD_CODEC_ULAW); - codecSelection.push_back(PAYLOAD_CODEC_ALAW); - codecSelection.push_back(PAYLOAD_CODEC_G722); + codecSelection.push_back(PAYLOAD_CODEC_ULAW); + codecSelection.push_back(PAYLOAD_CODEC_ALAW); + codecSelection.push_back(PAYLOAD_CODEC_G722); - _session->setLocalIP("127.0.0.1"); - _session->setLocalPublishedAudioPort(49567); + session_->setLocalIP("127.0.0.1"); + session_->setLocalPublishedAudioPort(49567); - _session->createOffer(codecSelection); + session_->createOffer(codecSelection); - // pjmedia_sdp_parse(_testPool, test[0].offer_answer[0].sdp2, strlen(test[0].offer_answer[0].sdp2), &remoteAnswer); - pjmedia_sdp_parse(_testPool, (char*)sdp_answer1, strlen(sdp_answer1), &remoteAnswer); + // pjmedia_sdp_parse(testPool_, test[0].offer_answer[0].sdp2, strlen(test[0].offer_answer[0].sdp2), &remoteAnswer); + pjmedia_sdp_parse(testPool_, (char*)sdp_answer1, strlen(sdp_answer1), &remoteAnswer); - _session->receivingAnswerAfterInitialOffer(remoteAnswer); - _session->startNegotiation(); + session_->receivingAnswerAfterInitialOffer(remoteAnswer); + session_->startNegotiation(); - _session->setMediaTransportInfoFromRemoteSdp(); + session_->setMediaTransportInfoFromRemoteSdp(); - CPPUNIT_ASSERT(_session->getLocalPublishedAudioPort() == 49567); - CPPUNIT_ASSERT(_session->getRemoteAudioPort() == 49920); - CPPUNIT_ASSERT(_session->getLocalIP() == "127.0.0.1"); - CPPUNIT_ASSERT(_session->getRemoteIP() == "host.example.com"); - CPPUNIT_ASSERT(_session->getSessionMedia()->getMimeSubtype() == "PCMU"); + CPPUNIT_ASSERT(session_->getLocalPublishedAudioPort() == 49567); + CPPUNIT_ASSERT(session_->getRemoteAudioPort() == 49920); + CPPUNIT_ASSERT(session_->getLocalIP() == "127.0.0.1"); + CPPUNIT_ASSERT(session_->getRemoteIP() == "host.example.com"); + CPPUNIT_ASSERT(session_->getSessionMedia()->getMimeSubtype() == "PCMU"); } -void SDPTest::testInitialAnswerFirstCodec () +void SDPTest::testInitialAnswerFirstCodec() { - std::cout << "------------ SDPTest::testInitialAnswerFirstCodec -------------" << std::endl; + std::cout << "------------ SDPTest::testInitialAnswerFirstCodec -------------" << std::endl; - CPPUNIT_ASSERT(_session->getLocalPublishedAudioPort() == 0); - CPPUNIT_ASSERT(_session->getRemoteAudioPort() == 0); - CPPUNIT_ASSERT(_session->getLocalIP() == ""); - CPPUNIT_ASSERT(_session->getRemoteIP() == ""); + CPPUNIT_ASSERT(session_->getLocalPublishedAudioPort() == 0); + CPPUNIT_ASSERT(session_->getRemoteAudioPort() == 0); + CPPUNIT_ASSERT(session_->getLocalIP() == ""); + CPPUNIT_ASSERT(session_->getRemoteIP() == ""); - CodecOrder codecSelection; + CodecOrder codecSelection; pjmedia_sdp_session *remoteOffer; - codecSelection.push_back(PAYLOAD_CODEC_ULAW); - codecSelection.push_back(PAYLOAD_CODEC_ALAW); - codecSelection.push_back(PAYLOAD_CODEC_G722); + codecSelection.push_back(PAYLOAD_CODEC_ULAW); + codecSelection.push_back(PAYLOAD_CODEC_ALAW); + codecSelection.push_back(PAYLOAD_CODEC_G722); - pjmedia_sdp_parse(_testPool, (char*)sdp_offer1, strlen(sdp_offer1), &remoteOffer); + pjmedia_sdp_parse(testPool_, (char*)sdp_offer1, strlen(sdp_offer1), &remoteOffer); - _session->setLocalIP("127.0.0.1"); - _session->setLocalPublishedAudioPort(49567); + session_->setLocalIP("127.0.0.1"); + session_->setLocalPublishedAudioPort(49567); - _session->receiveOffer(remoteOffer, codecSelection); + session_->receiveOffer(remoteOffer, codecSelection); - _session->startNegotiation(); + session_->startNegotiation(); - _session->setMediaTransportInfoFromRemoteSdp(); + session_->setMediaTransportInfoFromRemoteSdp(); - CPPUNIT_ASSERT(_session->getLocalPublishedAudioPort() == 49567); - CPPUNIT_ASSERT(_session->getRemoteAudioPort() == 49920); - CPPUNIT_ASSERT(_session->getLocalIP() == "127.0.0.1"); - CPPUNIT_ASSERT(_session->getRemoteIP() == "host.example.com"); - CPPUNIT_ASSERT(_session->getSessionMedia()->getMimeSubtype() == "PCMU"); + CPPUNIT_ASSERT(session_->getLocalPublishedAudioPort() == 49567); + CPPUNIT_ASSERT(session_->getRemoteAudioPort() == 49920); + CPPUNIT_ASSERT(session_->getLocalIP() == "127.0.0.1"); + CPPUNIT_ASSERT(session_->getRemoteIP() == "host.example.com"); + CPPUNIT_ASSERT(session_->getSessionMedia()->getMimeSubtype() == "PCMU"); } -void SDPTest::testInitialOfferLastCodec () +void SDPTest::testInitialOfferLastCodec() { - std::cout << "------------ SDPTest::testInitialOfferLastCodec --------------------" << std::endl; + std::cout << "------------ SDPTest::testInitialOfferLastCodec --------------------" << std::endl; - CPPUNIT_ASSERT(_session->getLocalPublishedAudioPort() == 0); - CPPUNIT_ASSERT(_session->getRemoteAudioPort() == 0); - CPPUNIT_ASSERT(_session->getLocalIP() == ""); - CPPUNIT_ASSERT(_session->getRemoteIP() == ""); + CPPUNIT_ASSERT(session_->getLocalPublishedAudioPort() == 0); + CPPUNIT_ASSERT(session_->getRemoteAudioPort() == 0); + CPPUNIT_ASSERT(session_->getLocalIP() == ""); + CPPUNIT_ASSERT(session_->getRemoteIP() == ""); - CodecOrder codecSelection; + CodecOrder codecSelection; pjmedia_sdp_session *remoteAnswer; - codecSelection.push_back(PAYLOAD_CODEC_ULAW); - codecSelection.push_back(PAYLOAD_CODEC_ALAW); - codecSelection.push_back(PAYLOAD_CODEC_G722); + codecSelection.push_back(PAYLOAD_CODEC_ULAW); + codecSelection.push_back(PAYLOAD_CODEC_ALAW); + codecSelection.push_back(PAYLOAD_CODEC_G722); - _session->setLocalIP("127.0.0.1"); - _session->setLocalPublishedAudioPort(49567); + session_->setLocalIP("127.0.0.1"); + session_->setLocalPublishedAudioPort(49567); - _session->createOffer(codecSelection); + session_->createOffer(codecSelection); - // pjmedia_sdp_parse(_testPool, test[0].offer_answer[0].sdp2, strlen(test[0].offer_answer[0].sdp2), &remoteAnswer); - pjmedia_sdp_parse(_testPool, (char*)sdp_answer2, strlen(sdp_answer2), &remoteAnswer); + // pjmedia_sdp_parse(testPool_, test[0].offer_answer[0].sdp2, strlen(test[0].offer_answer[0].sdp2), &remoteAnswer); + pjmedia_sdp_parse(testPool_, (char*)sdp_answer2, strlen(sdp_answer2), &remoteAnswer); - _session->receivingAnswerAfterInitialOffer(remoteAnswer); - _session->startNegotiation(); + session_->receivingAnswerAfterInitialOffer(remoteAnswer); + session_->startNegotiation(); - _session->setMediaTransportInfoFromRemoteSdp(); + session_->setMediaTransportInfoFromRemoteSdp(); - CPPUNIT_ASSERT(_session->getLocalPublishedAudioPort() == 49567); - CPPUNIT_ASSERT(_session->getRemoteAudioPort() == 49920); - CPPUNIT_ASSERT(_session->getLocalIP() == "127.0.0.1"); - CPPUNIT_ASSERT(_session->getRemoteIP() == "host.example.com"); - CPPUNIT_ASSERT(_session->getSessionMedia()->getMimeSubtype() == "G722"); + CPPUNIT_ASSERT(session_->getLocalPublishedAudioPort() == 49567); + CPPUNIT_ASSERT(session_->getRemoteAudioPort() == 49920); + CPPUNIT_ASSERT(session_->getLocalIP() == "127.0.0.1"); + CPPUNIT_ASSERT(session_->getRemoteIP() == "host.example.com"); + CPPUNIT_ASSERT(session_->getSessionMedia()->getMimeSubtype() == "G722"); } -void SDPTest::testInitialAnswerLastCodec () +void SDPTest::testInitialAnswerLastCodec() { - std::cout << "------------ SDPTest::testInitialAnswerLastCodec ------------" << std::endl; + std::cout << "------------ SDPTest::testInitialAnswerLastCodec ------------" << std::endl; - CPPUNIT_ASSERT(_session->getLocalPublishedAudioPort() == 0); - CPPUNIT_ASSERT(_session->getRemoteAudioPort() == 0); - CPPUNIT_ASSERT(_session->getLocalIP() == ""); - CPPUNIT_ASSERT(_session->getRemoteIP() == ""); + CPPUNIT_ASSERT(session_->getLocalPublishedAudioPort() == 0); + CPPUNIT_ASSERT(session_->getRemoteAudioPort() == 0); + CPPUNIT_ASSERT(session_->getLocalIP() == ""); + CPPUNIT_ASSERT(session_->getRemoteIP() == ""); - CodecOrder codecSelection; + CodecOrder codecSelection; pjmedia_sdp_session *remoteOffer; - codecSelection.push_back(PAYLOAD_CODEC_ULAW); - codecSelection.push_back(PAYLOAD_CODEC_ALAW); - codecSelection.push_back(PAYLOAD_CODEC_G722); + codecSelection.push_back(PAYLOAD_CODEC_ULAW); + codecSelection.push_back(PAYLOAD_CODEC_ALAW); + codecSelection.push_back(PAYLOAD_CODEC_G722); - pjmedia_sdp_parse(_testPool, (char*)sdp_offer2, strlen(sdp_offer2), &remoteOffer); + pjmedia_sdp_parse(testPool_, (char*)sdp_offer2, strlen(sdp_offer2), &remoteOffer); - _session->setLocalIP("127.0.0.1"); - _session->setLocalPublishedAudioPort(49567); + session_->setLocalIP("127.0.0.1"); + session_->setLocalPublishedAudioPort(49567); - _session->receiveOffer(remoteOffer, codecSelection); + session_->receiveOffer(remoteOffer, codecSelection); - _session->startNegotiation(); + session_->startNegotiation(); - _session->setMediaTransportInfoFromRemoteSdp(); + session_->setMediaTransportInfoFromRemoteSdp(); - CPPUNIT_ASSERT(_session->getLocalPublishedAudioPort() == 49567); - CPPUNIT_ASSERT(_session->getRemoteAudioPort() == 49920); - CPPUNIT_ASSERT(_session->getLocalIP() == "127.0.0.1"); - CPPUNIT_ASSERT(_session->getRemoteIP() == "host.example.com"); - CPPUNIT_ASSERT(_session->getSessionMedia()->getMimeSubtype() == "G722"); + CPPUNIT_ASSERT(session_->getLocalPublishedAudioPort() == 49567); + CPPUNIT_ASSERT(session_->getRemoteAudioPort() == 49920); + CPPUNIT_ASSERT(session_->getLocalIP() == "127.0.0.1"); + CPPUNIT_ASSERT(session_->getRemoteIP() == "host.example.com"); + CPPUNIT_ASSERT(session_->getSessionMedia()->getMimeSubtype() == "G722"); } -void SDPTest::testReinvite () +void SDPTest::testReinvite() { - std::cout << "------------ SDPTest::testReinvite --------------------" << std::endl; + std::cout << "------------ SDPTest::testReinvite --------------------" << std::endl; - CPPUNIT_ASSERT(_session->getLocalPublishedAudioPort() == 0); - CPPUNIT_ASSERT(_session->getRemoteAudioPort() == 0); - CPPUNIT_ASSERT(_session->getLocalIP() == ""); - CPPUNIT_ASSERT(_session->getRemoteIP() == ""); + CPPUNIT_ASSERT(session_->getLocalPublishedAudioPort() == 0); + CPPUNIT_ASSERT(session_->getRemoteAudioPort() == 0); + CPPUNIT_ASSERT(session_->getLocalIP() == ""); + CPPUNIT_ASSERT(session_->getRemoteIP() == ""); - CodecOrder codecSelection; + CodecOrder codecSelection; pjmedia_sdp_session *remoteAnswer; pjmedia_sdp_session *reinviteOffer; - codecSelection.push_back(PAYLOAD_CODEC_ULAW); - codecSelection.push_back(PAYLOAD_CODEC_ALAW); - codecSelection.push_back(PAYLOAD_CODEC_G722); - - _session->setLocalIP("127.0.0.1"); - _session->setLocalPublishedAudioPort(49567); + codecSelection.push_back(PAYLOAD_CODEC_ULAW); + codecSelection.push_back(PAYLOAD_CODEC_ALAW); + codecSelection.push_back(PAYLOAD_CODEC_G722); - _session->createOffer(codecSelection); + session_->setLocalIP("127.0.0.1"); + session_->setLocalPublishedAudioPort(49567); - // pjmedia_sdp_parse(_testPool, test[0].offer_answer[0].sdp2, strlen(test[0].offer_answer[0].sdp2), &remoteAnswer); - pjmedia_sdp_parse(_testPool, (char*)sdp_answer1, strlen(sdp_answer1), &remoteAnswer); + session_->createOffer(codecSelection); - _session->receivingAnswerAfterInitialOffer(remoteAnswer); - _session->startNegotiation(); + // pjmedia_sdp_parse(testPool_, test[0].offer_answer[0].sdp2, strlen(test[0].offer_answer[0].sdp2), &remoteAnswer); + pjmedia_sdp_parse(testPool_, (char*)sdp_answer1, strlen(sdp_answer1), &remoteAnswer); - _session->setMediaTransportInfoFromRemoteSdp(); + session_->receivingAnswerAfterInitialOffer(remoteAnswer); + session_->startNegotiation(); - CPPUNIT_ASSERT(_session->getLocalPublishedAudioPort() == 49567); - CPPUNIT_ASSERT(_session->getRemoteAudioPort() == 49920); - CPPUNIT_ASSERT(_session->getLocalIP() == "127.0.0.1"); - CPPUNIT_ASSERT(_session->getRemoteIP() == "host.example.com"); - CPPUNIT_ASSERT(_session->getSessionMedia()->getMimeSubtype() == "PCMU"); + session_->setMediaTransportInfoFromRemoteSdp(); - pjmedia_sdp_parse(_testPool, (char*)sdp_reinvite, strlen(sdp_reinvite), &reinviteOffer); + CPPUNIT_ASSERT(session_->getLocalPublishedAudioPort() == 49567); + CPPUNIT_ASSERT(session_->getRemoteAudioPort() == 49920); + CPPUNIT_ASSERT(session_->getLocalIP() == "127.0.0.1"); + CPPUNIT_ASSERT(session_->getRemoteIP() == "host.example.com"); + CPPUNIT_ASSERT(session_->getSessionMedia()->getMimeSubtype() == "PCMU"); - _session->receiveOffer(reinviteOffer, codecSelection); + pjmedia_sdp_parse(testPool_, (char*)sdp_reinvite, strlen(sdp_reinvite), &reinviteOffer); - _session->startNegotiation(); + session_->receiveOffer(reinviteOffer, codecSelection); - _session->setMediaTransportInfoFromRemoteSdp(); + session_->startNegotiation(); - CPPUNIT_ASSERT(_session->getRemoteAudioPort() == 42445); - CPPUNIT_ASSERT(_session->getRemoteIP() == "host.exampleReinvite.com"); + session_->setMediaTransportInfoFromRemoteSdp(); + CPPUNIT_ASSERT(session_->getRemoteAudioPort() == 42445); + CPPUNIT_ASSERT(session_->getRemoteIP() == "host.exampleReinvite.com"); } diff --git a/daemon/test/sdptest.h b/daemon/test/sdptest.h index d7336fb2847dd367f8eb6489e39febe7576fd2f6..e149f9b03aa25e434f406607b362df640a7e97b3 100644 --- a/daemon/test/sdptest.h +++ b/daemon/test/sdptest.h @@ -59,17 +59,17 @@ #include "global.h" #include "sip/sdp.h" +#include "noncopyable.h" -class SdpSessionException : public std::exception -{ +class SdpSessionException : public std::exception { public: - SdpSessionException (const std::string& str="") throw() : errstr (str) {} + SdpSessionException(const std::string& str="") throw() : errstr(str) {} virtual ~SdpSessionException() throw() {} virtual const char *what() const throw() { - std::string expt ("SdpSession: SdpSessionException occured: "); - expt.append (errstr); + std::string expt("SdpSession: SdpSessionException occured: "); + expt.append(errstr); return expt.c_str(); } private: @@ -79,54 +79,53 @@ class SdpSessionException : public std::exception class SDPTest : public CppUnit::TestCase { - /** - * Use cppunit library macros to add unit test the factory - */ - CPPUNIT_TEST_SUITE( SDPTest ); - CPPUNIT_TEST ( testInitialOfferLastCodec ); - CPPUNIT_TEST ( testInitialAnswerLastCodec ); - CPPUNIT_TEST ( testInitialOfferLastCodec ); - CPPUNIT_TEST ( testInitialAnswerLastCodec ); - CPPUNIT_TEST ( testReinvite ); - CPPUNIT_TEST_SUITE_END(); + /** + * Use cppunit library macros to add unit test the factory + */ + CPPUNIT_TEST_SUITE(SDPTest); + CPPUNIT_TEST(testInitialOfferLastCodec); + CPPUNIT_TEST(testInitialAnswerLastCodec); + CPPUNIT_TEST(testInitialOfferLastCodec); + CPPUNIT_TEST(testInitialAnswerLastCodec); + CPPUNIT_TEST(testReinvite); + CPPUNIT_TEST_SUITE_END(); -public: - SDPTest() : CppUnit::TestCase("SDP module Tests") {} - - /** - * Code factoring - Common resources can be initialized here. - * This method is called by unitcpp before each test - */ - void setUp(); - - /** - * Code factoring - Common resources can be released here. - * This method is called by unitcpp after each test - */ - void tearDown (); - - void testInitialOfferFirstCodec(); + public: + SDPTest() : CppUnit::TestCase("SDP module Tests"), session_(0), + testPool_(0), poolCache_() {} - void testInitialAnswerFirstCodec(); + /** + * Code factoring - Common resources can be initialized here. + * This method is called by unitcpp before each test + */ + void setUp(); - void testInitialOfferLastCodec(); + /** + * Code factoring - Common resources can be released here. + * This method is called by unitcpp after each test + */ + void tearDown(); - void testInitialAnswerLastCodec(); + void testInitialOfferFirstCodec(); - void testReinvite (); + void testInitialAnswerFirstCodec(); -private: + void testInitialOfferLastCodec(); - Sdp *_session; + void testInitialAnswerLastCodec(); - pj_pool_t *_testPool; + void testReinvite(); - pj_caching_pool _poolCache; + private: + NON_COPYABLE(SDPTest); + Sdp *session_; + pj_pool_t *testPool_; + pj_caching_pool poolCache_; }; /* Register our test module */ CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(SDPTest, "SDPTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( SDPTest ); +CPPUNIT_TEST_SUITE_REGISTRATION(SDPTest); #endif diff --git a/daemon/test/siptest.cpp b/daemon/test/siptest.cpp index a3ec55cbd5df51f7203753c9edf80187f64b2d23..0e0d95219948a6c00552d1666e24d9fe608a6ccd 100644 --- a/daemon/test/siptest.cpp +++ b/daemon/test/siptest.cpp @@ -37,20 +37,21 @@ #include <string> #include "siptest.h" -#include "manager.h" +#include "manager.h" #include "sip/sipvoiplink.h" using std::cout; using std::endl; +// anonymous namespace +namespace { pthread_mutex_t count_mutex; pthread_cond_t count_nb_thread; int counter = 0; - +} void *sippThreadWithCount(void *str) { - pthread_mutex_lock(&count_mutex); counter++; pthread_mutex_unlock(&count_mutex); @@ -59,48 +60,47 @@ void *sippThreadWithCount(void *str) std::cout << "SIPTest: " << command << std::endl; - // Set up the sipp instance in this thread in order to catch return value + // Set up the sipp instance in this thread in order to catch return value // 0: All calls were successful // 1: At least one call failed // 97: exit on internal command. Calls may have been processed // 99: Normal exit without calls processed // -1: Fatal error - // -2: Fatal error binding a socket + // -2: Fatal error binding a socket int i = system(command->c_str()); CPPUNIT_ASSERT(i!=0); pthread_mutex_lock(&count_mutex); counter--; - if(counter == 0) - pthread_cond_signal(&count_nb_thread); + + if (counter == 0) + pthread_cond_signal(&count_nb_thread); + pthread_mutex_unlock(&count_mutex); pthread_exit(NULL); - } void *sippThread(void *str) { - - std::string *command = (std::string *)(str); + std::string *command = (std::string *)(str); std::cout << "SIPTest: " << command << std::endl; - // Set up the sipp instance in this thread in order to catch return value + // Set up the sipp instance in this thread in order to catch return value // 0: All calls were successful // 1: At least one call failed // 97: exit on internal command. Calls may have been processed // 99: Normal exit without calls processed // -1: Fatal error - // -2: Fatal error binding a socket + // -2: Fatal error binding a socket int i = system(command->c_str()); - + CPPUNIT_ASSERT(i==0); pthread_exit(NULL); - } @@ -117,24 +117,24 @@ void SIPTest::tearDown() // in order to stop any currently running threads std::cout << "SIPTest: Clean all remaining sipp instances" << std::endl; int ret = system("killall sipp"); - if(!ret) - std::cout << "SIPTest: Error from system call, killall sipp" << std::endl; + + if (!ret) + std::cout << "SIPTest: Error from system call, killall sipp" << std::endl; } -void SIPTest::testSimpleOutgoingIpCall () +void SIPTest::testSimpleOutgoingIpCall() { pthread_t thethread; - void *status; // command to be executed by the thread, user agent server waiting for a call std::string command("sipp -sn uas -i 127.0.0.1 -p 5062 -m 1"); int rc = pthread_create(&thethread, NULL, sippThread, (void *)(&command)); - if (rc) { + + if (rc) std::cout << "SIPTest: ERROR; return code from pthread_create()" << std::endl; - } - + std::string testaccount("IP2IP"); std::string testcallid("callid1234"); std::string testcallnumber("sip:test@127.0.0.1:5062"); @@ -154,12 +154,12 @@ void SIPTest::testSimpleOutgoingIpCall () CPPUNIT_ASSERT(Manager::instance().getCurrentCallId() == testcallid); std::map<std::string, std::string>::iterator iterCallDetails; - std::map<std::string, std::string> callDetails = Manager::instance().getCallDetails (testcallid); - + std::map<std::string, std::string> callDetails = Manager::instance().getCallDetails(testcallid); + iterCallDetails = callDetails.find("ACCOUNTID"); CPPUNIT_ASSERT((iterCallDetails != callDetails.end()) && (iterCallDetails->second == "")); iterCallDetails = callDetails.find("PEER_NUMBER"); - CPPUNIT_ASSERT((iterCallDetails != callDetails.end()) && (iterCallDetails->second == "<sip:test@127.0.0.1:5062>")); + CPPUNIT_ASSERT((iterCallDetails != callDetails.end()) && (iterCallDetails->second == "<sip:test@127.0.0.1:5062>")); iterCallDetails = callDetails.find("PEER_NAME"); CPPUNIT_ASSERT((iterCallDetails != callDetails.end()) && (iterCallDetails->second == "")); iterCallDetails = callDetails.find("DISPLAY_NAME"); @@ -171,20 +171,18 @@ void SIPTest::testSimpleOutgoingIpCall () Manager::instance().hangupCall(testcallid); + void *status; rc = pthread_join(thethread, &status); - if (rc) { + + if (rc) std::cout << "SIPTest: ERROR; return code from pthread_join(): " << rc << std::endl; - } else std::cout << "SIPTest: completed join with thread" << std::endl; - - } -void SIPTest::testSimpleIncomingIpCall () +void SIPTest::testSimpleIncomingIpCall() { - pthread_t thethread; void *status; @@ -192,60 +190,58 @@ void SIPTest::testSimpleIncomingIpCall () std::string command("sipp -sn uac 127.0.0.1 -i 127.0.0.1 -p 5062 -m 1"); int rc = pthread_create(&thethread, NULL, sippThread, (void *)(&command)); - if (rc) { + + if (rc) std::cout << "SIPTest: ERROR; return code from pthread_create()" << std::endl; - } - // sleep a while to make sure that sipp insdtance is initialized and sflphoned received // the incoming invite. sleep(2); - // gtrab call id from sipvoiplink - SIPVoIPLink *siplink = SIPVoIPLink::instance (); + // gtrab call id from sipvoiplink + SIPVoIPLink *siplink = SIPVoIPLink::instance(); - CPPUNIT_ASSERT(siplink->_callMap.size() == 1); - CallMap::iterator iterCallId = siplink->_callMap.begin(); + CPPUNIT_ASSERT(siplink->callMap_.size() == 1); + CallMap::iterator iterCallId = siplink->callMap_.begin(); std::string testcallid = iterCallId->first; - + // TODO: hmmm, should IP2IP call be stored in call list.... CPPUNIT_ASSERT(Manager::instance().getCallList().size() == 0); - + // Answer this call CPPUNIT_ASSERT(Manager::instance().answerCall(testcallid)); - sleep(1); rc = pthread_join(thethread, &status); - if (rc) { + + if (rc) std::cout << "SIPTest: ERROR; return code from pthread_join(): " << rc << std::endl; - } else std::cout << "SIPTest: completed join with thread" << std::endl; } -void SIPTest::testTwoOutgoingIpCall () +void SIPTest::testTwoOutgoingIpCall() { pthread_t firstCallThread, secondCallThread; void *status; - // This scenario expect to be put on hold before hangup + // This scenario expect to be put on hold before hangup std::string firstCallCommand("sipp -sf tools/sippxml/test_1.xml -i 127.0.0.1 -p 5062 -m 1"); // The second call uses the default user agent scenario std::string secondCallCommand("sipp -sn uas -i 127.0.0.1 -p 5064 -m 1"); int rc = pthread_create(&firstCallThread, NULL, sippThread, (void *)(&firstCallCommand)); - if (rc) { + + if (rc) std::cout << "SIPTest: ERROR; return code from pthread_create()" << std::endl; - } rc = pthread_create(&secondCallThread, NULL, sippThread, (void *)(&secondCallCommand)); - if(rc) { - std::cout << "SIPTest: ERROR; return code from pthread_create()" << std::endl; - } + + if (rc) + std::cout << "SIPTest: ERROR; return code from pthread_create()" << std::endl; sleep(1); @@ -260,7 +256,7 @@ void SIPTest::testTwoOutgoingIpCall () CPPUNIT_ASSERT(!Manager::instance().hasCurrentCall()); // start a new call sending INVITE message to sipp instance - // this call should be put on hold when making the second call + // this call should be put on hold when making the second call Manager::instance().outgoingCall(testAccount, firstCallID, firstCallNumber); // must sleep here until receiving 180 and 200 message from peer @@ -273,26 +269,26 @@ void SIPTest::testTwoOutgoingIpCall () Manager::instance().hangupCall(firstCallID); rc = pthread_join(firstCallThread, &status); - if(rc) { - std::cout << "SIPTest: ERROR; return code from pthread_join(): " << rc << std::endl; - } - std::cout << "SIPTest: completed join with thread" << std::endl; + + if (rc) + std::cout << "SIPTest: ERROR; return code from pthread_join(): " << rc << std::endl; + + std::cout << "SIPTest: completed join with thread" << std::endl; Manager::instance().hangupCall(secondCallID); rc = pthread_join(secondCallThread, &status); - if (rc) { + + if (rc) std::cout << "SIPTest: ERROR; return code from pthread_join(): " << rc << std::endl; - } else std::cout << "SIPTest: completed join with thread" << std::endl; } -void SIPTest::testTwoIncomingIpCall () +void SIPTest::testTwoIncomingIpCall() { - pthread_mutex_init(&count_mutex, NULL); - pthread_cond_init (&count_nb_thread, NULL); + pthread_cond_init(&count_nb_thread, NULL); pthread_t firstCallThread, secondCallThread; @@ -308,20 +304,19 @@ void SIPTest::testTwoIncomingIpCall () std::string secondCallCommand("sipp -sn uac 127.0.0.1 -i 127.0.0.1 -p 5062 -m 1 -d 250 > testfile2.txt"); int rc = pthread_create(&firstCallThread, &attr, sippThreadWithCount, (void *)(&firstCallCommand)); - if (rc) { - std::cout << "SIPTest: ERROR; return code from pthread_create()" << std::endl; - } + if (rc) + std::cout << "SIPTest: ERROR; return code from pthread_create()" << std::endl; // sleep a while to make sure that sipp insdtance is initialized and sflphoned received // the incoming invite. sleep(1); - // gtrab call id from sipvoiplink - SIPVoIPLink *sipLink = SIPVoIPLink::instance (); + // gtrab call id from sipvoiplink + SIPVoIPLink *sipLink = SIPVoIPLink::instance(); - CPPUNIT_ASSERT(sipLink->_callMap.size() == 1); - CallMap::iterator iterCallId = sipLink->_callMap.begin(); + CPPUNIT_ASSERT(sipLink->callMap_.size() == 1); + CallMap::iterator iterCallId = sipLink->callMap_.begin(); std::string firstCallID = iterCallId->first; // Answer this call @@ -330,16 +325,19 @@ void SIPTest::testTwoIncomingIpCall () sleep(1); rc = pthread_create(&secondCallThread, &attr, sippThread, (void *)(&secondCallCommand)); - if(rc) { - std::cout << "SIPTest: Error; return code from pthread_create()" << std::endl; + + if (rc) { + std::cout << "SIPTest: Error; return code from pthread_create()" << std::endl; } sleep(1); - CPPUNIT_ASSERT(sipLink->_callMap.size() == 2); - iterCallId = sipLink->_callMap.begin(); - if(iterCallId->first == firstCallID) - iterCallId++; + CPPUNIT_ASSERT(sipLink->callMap_.size() == 2); + iterCallId = sipLink->callMap_.begin(); + + if (iterCallId->first == firstCallID) + iterCallId++; + std::string secondCallID = iterCallId->first; CPPUNIT_ASSERT(Manager::instance().answerCall(secondCallID)); @@ -347,29 +345,14 @@ void SIPTest::testTwoIncomingIpCall () sleep(2); pthread_mutex_lock(&count_mutex); - while(counter > 0) - pthread_cond_wait(&count_nb_thread, &count_mutex); - pthread_mutex_unlock(&count_mutex); - /* - rc = pthread_join(firstCallThread, &status); - if (rc) { - std::cout << "SIPTest: ERROR; return code from pthread_join(): " << rc << std::endl; - } - else - std::cout << "SIPTest: completed join with thread 1" << std::endl; + while (counter > 0) + pthread_cond_wait(&count_nb_thread, &count_mutex); - rc = pthread_join(secondCallThread, &status); - if (rc) { - std::cout << "SIPTest: ERROR; return code from pthread_join(): " << rc << std::endl; - } - else - std::cout << "SIPTest: completed join with thread 2" << std::endl; - */ + pthread_mutex_unlock(&count_mutex); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_nb_thread); - } @@ -380,11 +363,11 @@ void SIPTest::testHoldIpCall() std::string callCommand("sipp -sf tools/sippxml/test_3.xml -i 127.0.0.1 -p 5062 -m 1"); int rc = pthread_create(&callThread, NULL, sippThread, (void *)(&callCommand)); - if(rc) { - std::cout << "SIPTest: ERROR; return code from pthread_create(): " << rc << std::endl; - } - else - std::cout << "SIPTest: completed thread creation" << std::endl; + + if (rc) { + std::cout << "SIPTest: ERROR; return code from pthread_create(): " << rc << std::endl; + } else + std::cout << "SIPTest: completed thread creation" << std::endl; std::string testAccount("IP2IP"); @@ -400,7 +383,7 @@ void SIPTest::testHoldIpCall() sleep(1); - Manager::instance().offHoldCall(testCallID); + Manager::instance().offHoldCall(testCallID); sleep(1); @@ -408,9 +391,8 @@ void SIPTest::testHoldIpCall() } -void SIPTest::testIncomingIpCallSdp () +void SIPTest::testIncomingIpCallSdp() { - pthread_t thethread; void *status; @@ -418,20 +400,19 @@ void SIPTest::testIncomingIpCallSdp () std::string command("sipp -sf tools/sippxml/test_4.xml 127.0.0.1 -i 127.0.0.1 -p 5062 -m 1"); int rc = pthread_create(&thethread, NULL, sippThread, (void *)(&command)); - if (rc) { - std::cout << "SIPTest: ERROR; return code from pthread_create()" << std::endl; - } + if (rc) + std::cout << "SIPTest: ERROR; return code from pthread_create()" << std::endl; // sleep a while to make sure that sipp insdtance is initialized and sflphoned received // the incoming invite. sleep(2); - // gtrab call id from sipvoiplink - SIPVoIPLink *siplink = SIPVoIPLink::instance (); + // gtrab call id from sipvoiplink + SIPVoIPLink *siplink = SIPVoIPLink::instance(); - CPPUNIT_ASSERT(siplink->_callMap.size() == 1); - CallMap::iterator iterCallId = siplink->_callMap.begin(); + CPPUNIT_ASSERT(siplink->callMap_.size() == 1); + CallMap::iterator iterCallId = siplink->callMap_.begin(); std::string testcallid = iterCallId->first; // TODO: hmmm, should IP2IP call be stored in call list.... @@ -444,9 +425,9 @@ void SIPTest::testIncomingIpCallSdp () sleep(1); rc = pthread_join(thethread, &status); - if (rc) { + + if (rc) std::cout << "SIPTest: ERROR; return code from pthread_join(): " << rc << std::endl; - } else std::cout << "SIPTest: completed join with thread" << std::endl; } diff --git a/daemon/test/siptest.h b/daemon/test/siptest.h index 126c30798ffe265b32821eb0634865b49b1992a7..4603ed6598bb8d2978da65fd7c768ec10632c84a 100644 --- a/daemon/test/siptest.h +++ b/daemon/test/siptest.h @@ -40,7 +40,7 @@ #include "manager.h" /* - * @file siptest.h + * @file siptest.h * @brief Regroups unitary tests related to the SIP module */ @@ -49,21 +49,21 @@ class SIPTest : public CppUnit::TestCase { - /** - * Use cppunit library macros to add unit test the factory - */ - CPPUNIT_TEST_SUITE( SIPTest ); - // CPPUNIT_TEST ( testSimpleOutgoingIpCall ); - // CPPUNIT_TEST ( testSimpleIncomingIpCall ); - // CPPUNIT_TEST ( testTwoOutgoingIpCall ); - // CPPUNIT_TEST ( testTwoIncomingIpCall ); - // CPPUNIT_TEST ( testHoldIpCall); - // CPPUNIT_TEST ( testIncomingIpCallSdp ); - CPPUNIT_TEST_SUITE_END(); + /** + * Use cppunit library macros to add unit test the factory + */ + CPPUNIT_TEST_SUITE(SIPTest); + // CPPUNIT_TEST ( testSimpleOutgoingIpCall ); + // CPPUNIT_TEST ( testSimpleIncomingIpCall ); + // CPPUNIT_TEST ( testTwoOutgoingIpCall ); + // CPPUNIT_TEST ( testTwoIncomingIpCall ); + // CPPUNIT_TEST ( testHoldIpCall); + // CPPUNIT_TEST ( testIncomingIpCallSdp ); + CPPUNIT_TEST_SUITE_END(); public: SIPTest() : CppUnit::TestCase("SIP module Tests") {} - + /* * Code factoring - Common resources can be initialized here. * This method is called by unitcpp before each test @@ -74,18 +74,18 @@ class SIPTest : public CppUnit::TestCase { * Code factoring - Common resources can be released here. * This method is called by unitcpp after each test */ - void tearDown (); + void tearDown(); - void testSimpleOutgoingIpCall(void); + void testSimpleOutgoingIpCall(void); - void testSimpleIncomingIpCall(void); + void testSimpleIncomingIpCall(void); - void testTwoOutgoingIpCall(void); + void testTwoOutgoingIpCall(void); - void testTwoIncomingIpCall(void); + void testTwoIncomingIpCall(void); - void testHoldIpCall(void); + void testHoldIpCall(void); void testIncomingIpCallSdp(void); private: @@ -93,6 +93,6 @@ class SIPTest : public CppUnit::TestCase { /* Register our test module */ CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(SIPTest, "SIPTest"); -CPPUNIT_TEST_SUITE_REGISTRATION( SIPTest ); +CPPUNIT_TEST_SUITE_REGISTRATION(SIPTest); #endif diff --git a/daemon/test/validator.cpp b/daemon/test/validator.cpp index c5b803e3e52998fd339900b112ea7b92c6a62129..0b87bc3f64477d669320724c11725c81ce384bf6 100644 --- a/daemon/test/validator.cpp +++ b/daemon/test/validator.cpp @@ -30,17 +30,17 @@ #include "validator.h" -bool Validator::isNumber (std::string str) +bool Validator::isNumber(std::string str) { unsigned int i = 0; if (!str.empty() && (str[i] == '-' || str[i] == '+')) i++; - return string::npos == str.find_first_not_of (".eE0123456789", i); + return string::npos == str.find_first_not_of(".eE0123456789", i); } -bool Validator::isNotNull (std::string str) +bool Validator::isNotNull(std::string str) { if (!str.empty()) return true; @@ -48,7 +48,7 @@ bool Validator::isNotNull (std::string str) return false; } -bool Validator::isEqual (std::string str1, std::string str2) +bool Validator::isEqual(std::string str1, std::string str2) { - return str1.compare (str2) == 0; + return str1.compare(str2) == 0; } diff --git a/daemon/test/validator.h b/daemon/test/validator.h index 34a08b800b251536de98c93c958a1f5222ed4666..5cc1f7224e971948eb33bea8f0f1a22adbba0f16 100644 --- a/daemon/test/validator.h +++ b/daemon/test/validator.h @@ -37,9 +37,9 @@ using namespace std; class Validator { - public: - static bool isNumber(std::string str); - static bool isNotNull(std::string str); - static bool isEqual(std::string str1, std::string str2); + public: + static bool isNumber(std::string str); + static bool isNotNull(std::string str); + static bool isEqual(std::string str1, std::string str2); }; #endif /* VALIDATOR_H_ */ diff --git a/gnome/configure.ac b/gnome/configure.ac index a8df44ef04869f3c2f0ce74b8fc903531655fdb1..93d2703c9878b051aceb4966e632d1928987973b 100644 --- a/gnome/configure.ac +++ b/gnome/configure.ac @@ -1,4 +1,4 @@ -AC_INIT([sflphone],[1.0.0],[sflphoneteam@savoirfairelinux.com],[sflphone-client-gnome]) +AC_INIT([sflphone],[1.0.1],[sflphoneteam@savoirfairelinux.com],[sflphone-client-gnome]) AC_CONFIG_HEADERS([config.h]) AM_INIT_AUTOMAKE @@ -9,14 +9,16 @@ AC_CONFIG_MACRO_DIR([m4]) dnl Silent build by default. Use make V=1 to increase verbosity m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES([yes])]) -CFLAGS="$CFLAGS -g -Wall -Wextra" - AC_PROG_CC_C99 AM_PROG_CC_C_O dnl for per target flags, i.e. test_program_CFLAGS AC_PROG_INSTALL AC_HEADER_STDC LT_INIT +dnl Only need these for moving to gtk3 +MIGRATION_CFLAGS="-DGDK_DISABLE_DEPRECATED -DGTK_DISABLE_DEPRECATED -DGTK_DISABLE_SINGLE_INCLUDES" +CFLAGS="$CFLAGS -g -Wall -Wextra -Wshadow $MIGRATION_CFLAGS" + dnl GCONF utilities AM_GCONF_SOURCE_2 @@ -25,20 +27,16 @@ AC_DEFINE_UNQUOTED(SFLPHONE_UIDIR_UNINSTALLED, "`pwd`/src/", [path to uninstalled SFLphone UI dir]) PKG_CHECK_MODULES(DBUSGLIB, dbus-glib-1 >= 0.75, HAVE_DBUS_G_PROXY_SET_DEFAULT_TIMEOUT=true, HAVE_DBUS_G_PROXY_SET_DEFAULT_TIMEOUT=false); -PKG_CHECK_MODULES([LIBNOTIFY], [libnotify >= 0.7.2], [AC_DEFINE([LIBNOTIFY_VERSION_0_7_2],[],[Using libnotify-0.7.2 or higher])],[PKG_CHECK_MODULES([LIBNOTIFY], [libnotify >= 0.4])]) -PKG_CHECK_MODULES(GTK, gtk+-2.0 >= 2.20) +PKG_CHECK_MODULES([LIBNOTIFY], [libnotify >= 0.5.0]) +if echo "$LIBNOTIFY_LIBS" | grep -q gtk+-x11-2.0; then + AC_MSG_ERROR([Your libnotify is linked with GTK+2 ! Install libnotify4-dev]) + exit 1 +fi +PKG_CHECK_MODULES(GTK, gtk+-3.0) +PKG_CHECK_MODULES(GCONF, gconf-2.0) PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.24) -PKG_CHECK_MODULES(WEBKIT, webkit-1.0) -PKG_CHECK_MODULES(LIBGNOMEUI, libgnomeui-2.0) -PKG_CHECK_MODULES(GNOMEDOCUTILS, gnome-doc-utils) - +PKG_CHECK_MODULES(WEBKIT, webkitgtk-3.0) -# This macro is defined in check.m4 and tests if check.h and -# libcheck.a are installed in your system. It sets CHECK_CFLAGS and -# CHECK_LIBS accordingly. -# AM_PATH_CHECK([MINIMUM-VERSION, -# [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]]) -dnl AM_PATH_CHECK() DEPRECATED PKG_CHECK_MODULES([CHECK], [check >= 0.9.4]) AC_CONFIG_FILES([ diff --git a/gnome/src/Makefile.am b/gnome/src/Makefile.am index 778f6d3e097cb0258a746e622cd86163ba9f739c..bded0118565e9d790f6c94e3dc8edb98f6600023 100644 --- a/gnome/src/Makefile.am +++ b/gnome/src/Makefile.am @@ -26,21 +26,21 @@ sflphone_client_gnome_SOURCES = \ statusicon.c \ codeclist.c \ reqaccount.c \ - shortcuts.c \ - eel-gconf-extensions.c + eel-gconf-extensions.c \ + shortcuts.c noinst_HEADERS = actions.h sflnotify.h mainwindow.h dialpad.h codeclist.h \ reqaccount.h sflphone_const.h uimanager.h \ accountlist.h sliders.h statusicon.h callable_obj.h conference_obj.h \ - shortcuts.h eel-gconf-extensions.h logger.h imwindow.h + shortcuts.h eel-gconf-extensions.h logger.h imwindow.h unused.h sflphone_client_gnome_LDADD = $(DBUSGLIB_LIBS) $(LIBNOTIFY_LIBS) $(NOTIFY_LIBS) $(SFLPHONEGTK_LIBS) $(X11_LIBS) \ - $(GTK_LIBS) $(GLIB_LIBS) $(WEBKIT_LIBS) $(LIBGNOMEUI_LIBS) $(GNOMEDOCUTILS_LIBS) $(LD_LIBS) + $(GTK_LIBS) $(GLIB_LIBS) $(WEBKIT_LIBS) $(LD_LIBS) $(GCONF_LIBS) -sflphone_client_gnome_CFLAGS = $(DBUSGLIB_CFLAGS) $(LIBNOTIFY_CFLAGS) $(NOTIFY_CFLAGS) $(SFLPHONEGTK_CFLAGS) $(X11_CFLAGS) \ - $(GTK_CFLAGS) $(GLIB_CFLAGS) $(WEBKIT_CFLAGS) $(LIBGNOMEUI_CFLAGS) $(GNOMEDOCUTILS_CFLAGS) +sflphone_client_gnome_CFLAGS = $(DBUSGLIB_CFLAGS) $(LIBNOTIFY_CFLAGS) $(NOTIFY_CFLAGS) $(GTK_CFLAGS) $(X11_CFLAGS) \ + $(GLIB_CFLAGS) $(WEBKIT_CFLAGS) $(GCONF_CFLAGS) -# add symbolic link +# add symbolic link install-exec-local: echo $(prefix); echo $(bindir); echo $(datadir); echo $(libdir) cd $(DESTDIR)$(bindir); ln -sf sflphone-client-gnome sflphone diff --git a/gnome/src/accountlist.c b/gnome/src/accountlist.c index b92c3123519a3109545ec63c5f2384780cebe45c..662c7bc8729bbfb53cf32df66501c91944844eaf 100644 --- a/gnome/src/accountlist.c +++ b/gnome/src/accountlist.c @@ -29,19 +29,20 @@ * as that of the covered work. */ -#include <accountlist.h> -#include <actions.h> +#include "accountlist.h" +#include "actions.h" +#include "unused.h" static GQueue * accountQueue; -static guint account_list_get_position (account_t *account) +static guint account_list_get_position(account_t *account) { - guint size = account_list_get_size (); + guint size = account_list_get_size(); for (guint i = 0; i < size; i++) { - account_t *tmp = account_list_get_nth (i); + account_t *tmp = account_list_get_nth(i); - if (g_strcasecmp (tmp->accountID, account->accountID) == 0) + if (g_strcasecmp(tmp->accountID, account->accountID) == 0) return i; } @@ -51,7 +52,7 @@ static guint account_list_get_position (account_t *account) /* GCompareFunc to compare a accountID (gchar* and a account_t) */ -static gint is_accountID_struct (gconstpointer a, gconstpointer b) +static gint is_accountID_struct(gconstpointer a, gconstpointer b) { if (!a || !b) return 1; @@ -59,32 +60,32 @@ static gint is_accountID_struct (gconstpointer a, gconstpointer b) account_t * c = (account_t*) a; /* We only want it to return 0 or 1 */ - return !!(g_strcmp0 (c->accountID, (gchar*) b)); + return !!(g_strcmp0(c->accountID, (gchar*) b)); } /* GCompareFunc to get current call (gchar* and a account_t) */ -static gint get_state_struct (gconstpointer a, gconstpointer b) +static gint get_state_struct(gconstpointer a, gconstpointer b) { account_t * c = (account_t*) a; return !(c->state == *((account_state_t*) b)); } -void account_list_init () +void account_list_init() { - accountQueue = g_queue_new (); + accountQueue = g_queue_new(); } void -account_list_add (account_t * c) +account_list_add(account_t * c) { - g_queue_push_tail (accountQueue, (gpointer) c); + g_queue_push_tail(accountQueue, (gpointer) c); } account_t * -account_list_get_by_state (account_state_t state) +account_list_get_by_state(account_state_t state) { - GList * c = g_queue_find_custom (accountQueue, &state, get_state_struct); + GList * c = g_queue_find_custom(accountQueue, &state, get_state_struct); if (c) return (account_t *) c->data; @@ -93,9 +94,9 @@ account_list_get_by_state (account_state_t state) } account_t * -account_list_get_by_id (gchar * accountID) +account_list_get_by_id(const gchar * const accountID) { - GList * c = g_queue_find_custom (accountQueue, accountID, is_accountID_struct); + GList * c = g_queue_find_custom(accountQueue, accountID, is_accountID_struct); if (c) return (account_t *) c->data; @@ -103,45 +104,45 @@ account_list_get_by_id (gchar * accountID) return NULL; } -guint account_list_get_size (void) +guint account_list_get_size(void) { - return g_queue_get_length (accountQueue); + return g_queue_get_length(accountQueue); } -account_t * account_list_get_nth (guint n) +account_t * account_list_get_nth(guint n) { - return g_queue_peek_nth (accountQueue, n); + return g_queue_peek_nth(accountQueue, n); } account_t* account_list_get_current() { // No account registered - if (account_list_get_registered_accounts () == 0) + if (account_list_get_registered_accounts() == 0) return NULL; // if we are here, it means that we have at least one registered account in the list // So we get the first one - account_t *current = account_list_get_by_state (ACCOUNT_STATE_REGISTERED); + account_t *current = account_list_get_by_state(ACCOUNT_STATE_REGISTERED); return current; } -void account_list_set_current (account_t *current) +void account_list_set_current(account_t *current) { // 2 steps: // 1 - retrieve the index of the current account in the Queue // 2 - then set it as first - guint pos = account_list_get_position (current); + guint pos = account_list_get_position(current); if (pos > 0) { - gpointer acc = g_queue_pop_nth (accountQueue, pos); - g_queue_push_nth (accountQueue, acc, 0); + gpointer acc = g_queue_pop_nth(accountQueue, pos); + g_queue_push_nth(accountQueue, acc, 0); } } -const gchar * account_state_name (account_state_t s) +const gchar * account_state_name(account_state_t s) { gchar * state; @@ -191,46 +192,45 @@ void account_list_free_elm(gpointer elm, gpointer data UNUSED) g_free(a); } -void account_list_free () +void account_list_free() { g_queue_foreach(accountQueue, account_list_free_elm, NULL); g_queue_free(accountQueue); } void -account_list_move_up (guint index) +account_list_move_up(guint account_index) { - if (index != 0) { - gpointer acc = g_queue_pop_nth (accountQueue, index); - g_queue_push_nth (accountQueue, acc, index-1); + if (account_index != 0) { + gpointer acc = g_queue_pop_nth(accountQueue, account_index); + g_queue_push_nth(accountQueue, acc, account_index - 1); } } void -account_list_move_down (guint index) +account_list_move_down(guint account_index) { - if (index != accountQueue->length) { - gpointer acc = g_queue_pop_nth (accountQueue, index); - g_queue_push_nth (accountQueue, acc, index+1); + if (account_index != accountQueue->length) { + gpointer acc = g_queue_pop_nth(accountQueue, account_index); + g_queue_push_nth(accountQueue, acc, account_index + 1); } } guint -account_list_get_registered_accounts (void) +account_list_get_registered_accounts(void) { guint res = 0; for (guint i = 0; i < account_list_get_size(); i++) - if (account_list_get_nth (i) -> state == (ACCOUNT_STATE_REGISTERED)) + if (account_list_get_nth(i) -> state == (ACCOUNT_STATE_REGISTERED)) res++; + return res; } -gchar* account_list_get_current_id (void) +gchar* account_list_get_current_id(void) { - account_t *current; - - current = account_list_get_current (); + account_t *current = account_list_get_current(); if (current) return current->accountID; @@ -238,17 +238,17 @@ gchar* account_list_get_current_id (void) return ""; } -gchar * account_list_get_ordered_list (void) +gchar * account_list_get_ordered_list(void) { gchar *order = strdup(""); for (guint i = 0; i < account_list_get_size(); i++) { account_t * account = NULL; - account = account_list_get_nth (i); + account = account_list_get_nth(i); if (account != NULL) { - gchar *new_order = g_strconcat (order, account->accountID, "/", NULL); - g_free (order); + gchar *new_order = g_strconcat(order, account->accountID, "/", NULL); + g_free(order); order = new_order; } } @@ -257,32 +257,32 @@ gchar * account_list_get_ordered_list (void) } -gboolean current_account_has_mailbox (void) +gboolean current_account_has_mailbox(void) { // Check if the current account has a voicemail number configured - account_t *current = account_list_get_current (); + account_t *current = account_list_get_current(); if (current) { - gchar * account_mailbox = g_hash_table_lookup (current->properties, ACCOUNT_MAILBOX); + gchar * account_mailbox = g_hash_table_lookup(current->properties, ACCOUNT_MAILBOX); - if (account_mailbox && g_strcasecmp (account_mailbox, "") != 0) + if (account_mailbox && g_strcasecmp(account_mailbox, "") != 0) return TRUE; } return FALSE; } -void current_account_set_message_number (guint nb) +void current_account_set_message_number(guint nb) { - account_t *current = account_list_get_current (); + account_t *current = account_list_get_current(); if (current) current->_messages_number = nb; } -guint current_account_get_message_number (void) +guint current_account_get_message_number(void) { - account_t *current = account_list_get_current (); + account_t *current = account_list_get_current(); if (current) return current->_messages_number; @@ -290,9 +290,9 @@ guint current_account_get_message_number (void) return 0; } -gboolean current_account_has_new_message (void) +gboolean current_account_has_new_message(void) { - account_t *current = account_list_get_current (); + account_t *current = account_list_get_current(); if (current) return (current->_messages_number > 0); diff --git a/gnome/src/accountlist.h b/gnome/src/accountlist.h index fefcab66b135f84b14dda915f2cd1867708de8b2..559bb4a030dd625489b1b9194f39f4cc63fb3476 100644 --- a/gnome/src/accountlist.h +++ b/gnome/src/accountlist.h @@ -153,7 +153,7 @@ void account_list_free (); * @param accountID The ID of the account * @return An account or NULL */ -account_t * account_list_get_by_id (gchar * accountID); +account_t * account_list_get_by_id (const gchar * const accountID); /** * Move the account from an unit up in the account_list diff --git a/gnome/src/actions.c b/gnome/src/actions.c index 9a746782e59b5cb285e0b44afc5b446544ed231d..a02a9fe0af88bfeb602c66ac2a935391365b6693 100644 --- a/gnome/src/actions.c +++ b/gnome/src/actions.c @@ -54,6 +54,8 @@ #include "actions.h" #include "dbus/dbus.h" +#include "logger.h" +#include "contacts/calltab.h" #include "contacts/searchbar.h" #include "contacts/addrbookfactory.h" #include "icons/icon_factory.h" @@ -71,15 +73,19 @@ static gchar ** sflphone_order_history_hash_table(GHashTable *result) gchar **ordered_list = NULL; assert(result); - while (g_hash_table_size (result)) { - gpointer key, key_to_min, value; + + while (g_hash_table_size(result)) { + gpointer key, value; + gpointer key_to_min = NULL; // find lowest timestamp in map - g_hash_table_iter_init (&iter, result); + g_hash_table_iter_init(&iter, result); gint min_timestamp = G_MAXINT; - while (g_hash_table_iter_next (&iter, &key, &value)) { - gint timestamp = atoi ( (gchar*) key); + + while (g_hash_table_iter_next(&iter, &key, &value)) { + gint timestamp = atoi((gchar*) key); + if (timestamp < min_timestamp) { min_timestamp = timestamp; key_to_min = key; @@ -88,45 +94,47 @@ static gchar ** sflphone_order_history_hash_table(GHashTable *result) if (g_hash_table_lookup_extended(result, key_to_min, &key, &value)) { GSList *llist = (GSList *)value; + while (llist) { - ordered_list = (void *) g_realloc(ordered_list, (size + 1) * sizeof (void *)); + ordered_list = (gchar **) g_realloc(ordered_list, (size + 1) * sizeof(gchar *)); *(ordered_list + size) = g_strdup((gchar *)llist->data); size++; llist = g_slist_next(llist); } + g_hash_table_remove(result, key_to_min); } } - ordered_list = (void *) g_realloc(ordered_list, (size + 1) * sizeof(void *)); - *(ordered_list + size) = NULL; + ordered_list = (gchar **) g_realloc(ordered_list, (size + 1) * sizeof(gchar *)); + ordered_list[size] = NULL; return ordered_list; } void -sflphone_notify_voice_mail (const gchar* accountID , guint count) +sflphone_notify_voice_mail(const gchar* accountID , guint count) { // We want to notify only the current account; ie the first in the list - gchar *id = g_strdup (accountID); - const gchar * const current_id = account_list_get_current_id (); + gchar *id = g_strdup(accountID); + const gchar * const current_id = account_list_get_current_id(); - DEBUG ("sflphone_notify_voice_mail begin"); + DEBUG("sflphone_notify_voice_mail begin"); - if (g_ascii_strcasecmp (id, current_id) != 0 || account_list_get_size() == 0) + if (g_ascii_strcasecmp(id, current_id) != 0 || account_list_get_size() == 0) return; // Set the number of voice messages for the current account - current_account_set_message_number (count); - account_t *current = account_list_get_current (); + current_account_set_message_number(count); + account_t *current = account_list_get_current(); // Update the voicemail tool button - update_voicemail_status (); + update_voicemail_status(); if (current) - notify_voice_mails (count, current); + notify_voice_mails(count, current); - DEBUG ("sflphone_notify_voice_mail end"); + DEBUG("sflphone_notify_voice_mail end"); } /* @@ -136,220 +144,222 @@ sflphone_notify_voice_mail (const gchar* accountID , guint count) * Else, check if it an IP call. if not, popup an error message */ -static gboolean _is_direct_call (callable_obj_t * c) +static gboolean _is_direct_call(callable_obj_t * c) { - if (g_strcasecmp (c->_accountID, "empty") == 0) { - if (!g_str_has_prefix (c->_peer_number, "sip:")) { - gchar * new_number = g_strconcat ("sip:", c->_peer_number, NULL); - g_free (c->_peer_number); + if (g_strcasecmp(c->_accountID, "empty") == 0) { + if (!g_str_has_prefix(c->_peer_number, "sip:")) { + gchar * new_number = g_strconcat("sip:", c->_peer_number, NULL); + g_free(c->_peer_number); c->_peer_number = new_number; } return TRUE; } - return g_str_has_prefix (c->_peer_number, "sip:") || - g_str_has_prefix (c->_peer_number, "sips:"); + return g_str_has_prefix(c->_peer_number, "sip:") || + g_str_has_prefix(c->_peer_number, "sips:"); } void -status_bar_display_account () +status_bar_display_account() { gchar* msg; - statusbar_pop_message (__MSG_ACCOUNT_DEFAULT); + statusbar_pop_message(__MSG_ACCOUNT_DEFAULT); - account_t *acc = account_list_get_current (); - status_tray_icon_online (acc != NULL); + account_t *acc = account_list_get_current(); + status_tray_icon_online(acc != NULL); if (acc) { - msg = g_markup_printf_escaped ("%s %s (%s)" , - _ ("Using account"), - (gchar*) g_hash_table_lookup (acc->properties , ACCOUNT_ALIAS), - (gchar*) g_hash_table_lookup (acc->properties , ACCOUNT_TYPE)); + msg = g_markup_printf_escaped("%s %s (%s)" , + _("Using account"), + (gchar*) g_hash_table_lookup(acc->properties , ACCOUNT_ALIAS), + (gchar*) g_hash_table_lookup(acc->properties , ACCOUNT_TYPE)); } else { - msg = g_markup_printf_escaped (_ ("No registered accounts")); + msg = g_markup_printf_escaped(_("No registered accounts")); } - statusbar_push_message (msg, NULL, __MSG_ACCOUNT_DEFAULT); - g_free (msg); + statusbar_push_message(msg, NULL, __MSG_ACCOUNT_DEFAULT); + g_free(msg); } void -sflphone_quit () +sflphone_quit() { - if (calllist_get_size(current_calls) == 0 || main_window_ask_quit()) { + if (calllist_get_size(current_calls_tab) == 0 || main_window_ask_quit()) { // Save the history - sflphone_save_history (); + sflphone_save_history(); - dbus_unregister (getpid()); - dbus_clean (); + dbus_unregister(getpid()); + dbus_clean(); account_list_free(); - calllist_clean (current_calls); - calllist_clean (contacts); - calllist_clean (history); - gtk_tree_store_clear(history->store); - gtk_tree_store_clear(current_calls->store); - gtk_tree_store_clear(contacts->store); - gtk_main_quit (); + calllist_clean(current_calls_tab); + calllist_clean(contacts_tab); + calllist_clean(history_tab); + gtk_tree_store_clear(history_tab->store); + gtk_tree_store_clear(current_calls_tab->store); + gtk_tree_store_clear(contacts_tab->store); + gtk_main_quit(); } } void -sflphone_hold (callable_obj_t * c) +sflphone_hold(callable_obj_t * c) { c->_state = CALL_STATE_HOLD; - calltree_update_call (current_calls, c, NULL); + calltree_update_call(current_calls_tab, c); update_actions(); } void -sflphone_ringing (callable_obj_t * c) +sflphone_ringing(callable_obj_t * c) { c->_state = CALL_STATE_RINGING; - calltree_update_call (current_calls, c, NULL); + calltree_update_call(current_calls_tab, c); update_actions(); } void -sflphone_hung_up (callable_obj_t * c) +sflphone_hung_up(callable_obj_t * c) { - DEBUG ("SFLphone: Hung up"); + DEBUG("SFLphone: Hung up"); - calllist_remove_call (current_calls, c->_callID); - calltree_remove_call (current_calls, c, NULL); + calllist_remove_call(current_calls_tab, c->_callID); + calltree_remove_call(current_calls_tab, c); c->_state = CALL_STATE_DIALING; - call_remove_all_errors (c); + call_remove_all_errors(c); update_actions(); - if(c->_confID) { - g_free(c->_confID); - c->_confID = NULL; + if (c->_confID) { + g_free(c->_confID); + c->_confID = NULL; } // test wether the widget contain text, if not remove it - if ( (im_window_get_nb_tabs() > 1) && c->_im_widget && ! (IM_WIDGET (c->_im_widget)->containText)) - im_window_remove_tab (c->_im_widget); + if ((im_window_get_nb_tabs() > 1) && c->_im_widget && !(IM_WIDGET(c->_im_widget)->containText)) + im_window_remove_tab(c->_im_widget); else - im_widget_update_state (IM_WIDGET (c->_im_widget), FALSE); + im_widget_update_state(IM_WIDGET(c->_im_widget), FALSE); - status_tray_icon_blink (FALSE); + status_tray_icon_blink(FALSE); statusbar_update_clock(""); } /** Internal to actions: Fill account list */ -void sflphone_fill_account_list (void) +void sflphone_fill_account_list(void) { - int count = current_account_get_message_number (); + int count = current_account_get_message_number(); account_list_free(); account_list_init(); gchar **array = dbus_account_list(); + if (array) { - for (gchar **accountID = array; *accountID; accountID++) { - account_t * a = g_new0 (account_t,1); - a->accountID = g_strdup (*accountID); + for (gchar **accountID = array; accountID && *accountID; accountID++) { + account_t * a = g_new0(account_t,1); + a->accountID = g_strdup(*accountID); a->credential_information = NULL; - account_list_add (a); + account_list_add(a); } - g_strfreev (array); + g_strfreev(array); } for (unsigned i = 0; i < account_list_get_size(); i++) { - account_t * a = account_list_get_nth (i); - if(a == NULL) { + account_t * a = account_list_get_nth(i); + + if (a == NULL) { ERROR("SFLphone: Error: Could not find account %d in list", i); break; } - GHashTable * details = (GHashTable *) dbus_get_account_details (a->accountID); + GHashTable * details = (GHashTable *) dbus_get_account_details(a->accountID); + if (details == NULL) { ERROR("SFLphone: Error: Could not fetch detais for account %s", a->accountID); - break; + break; } a->properties = details; /* Fill the actual array of credentials */ - dbus_get_credentials (a); + dbus_get_credentials(a); - gchar * status = g_hash_table_lookup (details, REGISTRATION_STATUS); + gchar * status = g_hash_table_lookup(details, REGISTRATION_STATUS); - if (g_strcmp0 (status, "REGISTERED") == 0) { + if (g_strcmp0(status, "REGISTERED") == 0) a->state = ACCOUNT_STATE_REGISTERED; - } else if (g_strcmp0 (status, "UNREGISTERED") == 0) { + else if (g_strcmp0(status, "UNREGISTERED") == 0) a->state = ACCOUNT_STATE_UNREGISTERED; - } else if (g_strcmp0 (status, "TRYING") == 0) { + else if (g_strcmp0(status, "TRYING") == 0) a->state = ACCOUNT_STATE_TRYING; - } else if (g_strcmp0 (status, "ERROR") == 0) { + else if (g_strcmp0(status, "ERROR") == 0) a->state = ACCOUNT_STATE_ERROR; - } else if (g_strcmp0 (status , "ERROR_AUTH") == 0) { + else if (g_strcmp0(status , "ERROR_AUTH") == 0) a->state = ACCOUNT_STATE_ERROR_AUTH; - } else if (g_strcmp0 (status , "ERROR_NETWORK") == 0) { + else if (g_strcmp0(status , "ERROR_NETWORK") == 0) a->state = ACCOUNT_STATE_ERROR_NETWORK; - } else if (g_strcmp0 (status , "ERROR_HOST") == 0) { + else if (g_strcmp0(status , "ERROR_HOST") == 0) a->state = ACCOUNT_STATE_ERROR_HOST; - } else if (g_strcmp0 (status , "ERROR_CONF_STUN") == 0) { + else if (g_strcmp0(status , "ERROR_CONF_STUN") == 0) a->state = ACCOUNT_STATE_ERROR_CONF_STUN; - } else if (g_strcmp0 (status , "ERROR_EXIST_STUN") == 0) { + else if (g_strcmp0(status , "ERROR_EXIST_STUN") == 0) a->state = ACCOUNT_STATE_ERROR_EXIST_STUN; - } else if (g_strcmp0 (status, "READY") == 0) { + else if (g_strcmp0(status, "READY") == 0) a->state = IP2IP_PROFILE_STATUS; - } else { + else a->state = ACCOUNT_STATE_INVALID; - } - gchar * code = g_hash_table_lookup (details, REGISTRATION_STATE_CODE); + gchar * code = g_hash_table_lookup(details, REGISTRATION_STATE_CODE); + if (code != NULL) - a->protocol_state_code = atoi (code); + a->protocol_state_code = atoi(code); - g_free (a->protocol_state_description); - a->protocol_state_description = g_hash_table_lookup (details, REGISTRATION_STATE_DESCRIPTION); + g_free(a->protocol_state_description); + a->protocol_state_description = g_hash_table_lookup(details, REGISTRATION_STATE_DESCRIPTION); } // Set the current account message number - current_account_set_message_number (count); + current_account_set_message_number(count); - sflphone_fill_codec_list (); + sflphone_fill_codec_list(); } -gboolean sflphone_init (GError **error) +gboolean sflphone_init(GError **error) { - if (!dbus_connect (error) || !dbus_register (getpid (), "Gtk+ Client", error)) + if (!dbus_connect(error) || !dbus_register(getpid(), "Gtk+ Client", error)) return FALSE; abook_init(); // Init icons factory - init_icon_factory (); + init_icon_factory(); - current_calls = calltab_init (FALSE, CURRENT_CALLS); - contacts = calltab_init (TRUE, CONTACTS); - history = calltab_init (TRUE, HISTORY); + current_calls_tab = calltab_init(FALSE, CURRENT_CALLS); + contacts_tab = calltab_init(TRUE, CONTACTS); + history_tab = calltab_init(TRUE, HISTORY); - account_list_init (); - codec_capabilities_load (); - conferencelist_init (current_calls); - conferencelist_init (history); + account_list_init(); + codec_capabilities_load(); + conferencelist_init(current_calls_tab); // Fetch the configured accounts - sflphone_fill_account_list (); + sflphone_fill_account_list(); // Fetch the ip2ip profile sflphone_fill_ip2ip_profile(); // Fetch the conference list - // sflphone_fill_conference_list(); + sflphone_fill_conference_list(); return TRUE; } -void sflphone_fill_ip2ip_profile (void) +void sflphone_fill_ip2ip_profile(void) { ip2ip_profile = (GHashTable *) dbus_get_ip2_ip_details(); } @@ -362,19 +372,22 @@ GHashTable *sflphone_get_ip2ip_properties(void) void sflphone_hang_up() { - callable_obj_t * selectedCall = calltab_get_selected_call (current_calls); - conference_obj_t * selectedConf = calltab_get_selected_conf (active_calltree); + callable_obj_t * selectedCall = calltab_get_selected_call(current_calls_tab); + conference_obj_t * selectedConf = calltab_get_selected_conf(active_calltree_tab); - DEBUG ("SFLphone: Hang up"); + DEBUG("SFLphone: Hang up"); - if (selectedCall) { + if (selectedConf) { + im_widget_update_state(IM_WIDGET(selectedConf->_im_widget), FALSE); + dbus_hang_up_conference(selectedConf); + } else if (selectedCall) { switch (selectedCall->_state) { case CALL_STATE_DIALING: - dbus_hang_up (selectedCall); + dbus_hang_up(selectedCall); break; case CALL_STATE_RINGING: - dbus_hang_up (selectedCall); - call_remove_all_errors (selectedCall); + dbus_hang_up(selectedCall); + call_remove_all_errors(selectedCall); selectedCall->_state = CALL_STATE_DIALING; //selectedCall->_stop = 0; break; @@ -382,40 +395,37 @@ sflphone_hang_up() case CALL_STATE_HOLD: case CALL_STATE_BUSY: case CALL_STATE_RECORD: - dbus_hang_up (selectedCall); - call_remove_all_errors (selectedCall); + dbus_hang_up(selectedCall); + call_remove_all_errors(selectedCall); selectedCall->_state = CALL_STATE_DIALING; - time (&selectedCall->_time_stop); + time(&selectedCall->_time_stop); - im_widget_update_state (IM_WIDGET (selectedCall->_im_widget), FALSE); + im_widget_update_state(IM_WIDGET(selectedCall->_im_widget), FALSE); break; case CALL_STATE_FAILURE: - dbus_hang_up (selectedCall); - call_remove_all_errors (selectedCall); + dbus_hang_up(selectedCall); + call_remove_all_errors(selectedCall); selectedCall->_state = CALL_STATE_DIALING; break; case CALL_STATE_INCOMING: - dbus_refuse (selectedCall); - call_remove_all_errors (selectedCall); + dbus_refuse(selectedCall); + call_remove_all_errors(selectedCall); selectedCall->_state = CALL_STATE_DIALING; - DEBUG ("from sflphone_hang_up : "); + DEBUG("from sflphone_hang_up : "); break; case CALL_STATE_TRANSFER: - dbus_hang_up (selectedCall); - call_remove_all_errors (selectedCall); - time (&selectedCall->_time_stop); + dbus_hang_up(selectedCall); + call_remove_all_errors(selectedCall); + time(&selectedCall->_time_stop); break; default: - WARN ("Should not happen in sflphone_hang_up()!"); + WARN("Should not happen in sflphone_hang_up()!"); break; } - } else if (selectedConf) { - im_widget_update_state (IM_WIDGET (selectedConf->_im_widget), FALSE); - dbus_hang_up_conference (selectedConf); } - calltree_update_call (history, selectedCall, NULL); + calltree_update_call(history_tab, selectedCall); statusbar_update_clock(""); } @@ -423,7 +433,8 @@ sflphone_hang_up() void sflphone_pick_up() { - callable_obj_t *selectedCall = calltab_get_selected_call (active_calltree); + callable_obj_t *selectedCall = calltab_get_selected_call(active_calltree_tab); + if (!selectedCall) { sflphone_new_call(); return; @@ -431,7 +442,7 @@ sflphone_pick_up() switch (selectedCall->_state) { case CALL_STATE_DIALING: - sflphone_place_call (selectedCall); + sflphone_place_call(selectedCall); // if instant messaging window is visible, create new tab (deleted automatically if not used) if (im_window_is_visible()) @@ -441,20 +452,20 @@ sflphone_pick_up() break; case CALL_STATE_INCOMING: selectedCall->_history_state = INCOMING; - calltree_update_call (history, selectedCall, NULL); + calltree_update_call(history_tab, selectedCall); // if instant messaging window is visible, create new tab (deleted automatically if not used) if (im_window_is_visible()) if (!selectedCall->_im_widget) selectedCall->_im_widget = im_widget_display(selectedCall->_callID); - dbus_accept (selectedCall); + dbus_accept(selectedCall); break; case CALL_STATE_TRANSFER: - dbus_transfer (selectedCall); - time (&selectedCall->_time_stop); - calltree_remove_call(current_calls, selectedCall, NULL); - calllist_remove_call(current_calls, selectedCall->_callID); + dbus_transfer(selectedCall); + time(&selectedCall->_time_stop); + calltree_remove_call(current_calls_tab, selectedCall); + calllist_remove_call(current_calls_tab, selectedCall->_callID); break; case CALL_STATE_CURRENT: case CALL_STATE_HOLD: @@ -463,103 +474,100 @@ sflphone_pick_up() sflphone_new_call(); break; default: - WARN ("Should not happen in sflphone_pick_up()!"); + WARN("Should not happen in sflphone_pick_up()!"); break; } } void -sflphone_on_hold () +sflphone_on_hold() { - callable_obj_t * selectedCall = calltab_get_selected_call (current_calls); - conference_obj_t * selectedConf = calltab_get_selected_conf (active_calltree); + callable_obj_t * selectedCall = calltab_get_selected_call(current_calls_tab); + conference_obj_t * selectedConf = calltab_get_selected_conf(active_calltree_tab); if (selectedCall) { switch (selectedCall->_state) { case CALL_STATE_CURRENT: case CALL_STATE_RECORD: - dbus_hold (selectedCall); + dbus_hold(selectedCall); break; default: - WARN ("Should not happen in sflphone_on_hold!"); + WARN("Should not happen in sflphone_on_hold!"); break; } - } else if (selectedConf) { - dbus_hold_conference (selectedConf); - } + } else if (selectedConf) + dbus_hold_conference(selectedConf); } void -sflphone_off_hold () +sflphone_off_hold() { - DEBUG ("sflphone_off_hold"); - callable_obj_t * selectedCall = calltab_get_selected_call (current_calls); - conference_obj_t * selectedConf = calltab_get_selected_conf (active_calltree); + DEBUG("sflphone_off_hold"); + callable_obj_t * selectedCall = calltab_get_selected_call(current_calls_tab); + conference_obj_t * selectedConf = calltab_get_selected_conf(active_calltree_tab); if (selectedCall) { switch (selectedCall->_state) { case CALL_STATE_HOLD: - dbus_unhold (selectedCall); + dbus_unhold(selectedCall); break; default: - WARN ("Should not happen in sflphone_off_hold ()!"); + WARN("Should not happen in sflphone_off_hold ()!"); break; } - } else if (selectedConf) { - dbus_unhold_conference (selectedConf); - } + } else if (selectedConf) + dbus_unhold_conference(selectedConf); } void -sflphone_fail (callable_obj_t * c) +sflphone_fail(callable_obj_t * c) { c->_state = CALL_STATE_FAILURE; - calltree_update_call (current_calls, c, NULL); + calltree_update_call(current_calls_tab, c); update_actions(); } void -sflphone_busy (callable_obj_t * c) +sflphone_busy(callable_obj_t * c) { c->_state = CALL_STATE_BUSY; - calltree_update_call (current_calls, c, NULL); + calltree_update_call(current_calls_tab, c); update_actions(); } void -sflphone_current (callable_obj_t * c) +sflphone_current(callable_obj_t * c) { - if (c->_state != CALL_STATE_HOLD) - time (&c->_time_start); + time(&c->_time_start); c->_state = CALL_STATE_CURRENT; - calltree_update_call (current_calls, c, NULL); + calltree_update_call(current_calls_tab, c); update_actions(); } void -sflphone_record (callable_obj_t * c) +sflphone_record(callable_obj_t * c) { if (c->_state != CALL_STATE_HOLD) - time (&c->_time_start); + time(&c->_time_start); c->_state = CALL_STATE_RECORD; - calltree_update_call (current_calls, c, NULL); + calltree_update_call(current_calls_tab, c); update_actions(); } void sflphone_set_transfer() { - callable_obj_t * c = calltab_get_selected_call (current_calls); + callable_obj_t * c = calltab_get_selected_call(current_calls_tab); if (c) { c->_state = CALL_STATE_TRANSFER; g_free(c->_trsft_to); - c->_trsft_to = g_strdup (""); - calltree_update_call (current_calls, c, NULL); + c->_trsft_to = g_strdup(""); + calltree_update_call(current_calls_tab, c); } update_actions(); @@ -568,71 +576,72 @@ sflphone_set_transfer() void sflphone_unset_transfer() { - callable_obj_t * c = calltab_get_selected_call (current_calls); + callable_obj_t * c = calltab_get_selected_call(current_calls_tab); if (c) { c->_state = CALL_STATE_CURRENT; g_free(c->_trsft_to); - c->_trsft_to = g_strdup (""); - calltree_update_call (current_calls, c, NULL); + c->_trsft_to = g_strdup(""); + calltree_update_call(current_calls_tab, c); } update_actions(); } void -sflphone_display_transfer_status (const gchar* message) +sflphone_display_transfer_status(const gchar* message) { - statusbar_push_message (message , NULL, __MSG_ACCOUNT_DEFAULT); + statusbar_push_message(message , NULL, __MSG_ACCOUNT_DEFAULT); } void -sflphone_incoming_call (callable_obj_t * c) +sflphone_incoming_call(callable_obj_t * c) { c->_history_state = MISSED; - calllist_add_call (current_calls, c); - calltree_add_call (current_calls, c, NULL); + calllist_add_call(current_calls_tab, c); + calltree_add_call(current_calls_tab, c, NULL); update_actions(); - calltree_display (current_calls); + calltree_display(current_calls_tab); // Change the status bar if we are dealing with a direct SIP call - if (_is_direct_call (c)) { - gchar *msg = g_markup_printf_escaped (_ ("Direct SIP call")); - statusbar_pop_message (__MSG_ACCOUNT_DEFAULT); - statusbar_push_message (msg , NULL, __MSG_ACCOUNT_DEFAULT); - g_free (msg); + if (_is_direct_call(c)) { + gchar *msg = g_markup_printf_escaped(_("Direct SIP call")); + statusbar_pop_message(__MSG_ACCOUNT_DEFAULT); + statusbar_push_message(msg , NULL, __MSG_ACCOUNT_DEFAULT); + g_free(msg); } } static void -process_dialing (callable_obj_t *c, guint keyval, gchar *key) +process_dialing(callable_obj_t *c, guint keyval, gchar *key) { // We stop the tone if (!*c->_peer_number && c->_state != CALL_STATE_TRANSFER) - dbus_start_tone (FALSE, 0); + dbus_start_tone(FALSE, 0); switch (keyval) { case GDK_Return: case GDK_KP_Enter: - sflphone_place_call (c); + sflphone_place_call(c); break; case GDK_Escape: - sflphone_hang_up (); + sflphone_hang_up(); break; - case GDK_BackSpace: - { + case GDK_BackSpace: { gchar *num = (c->_state == CALL_STATE_TRANSFER) ? c->_trsft_to : c->_peer_number; size_t len = strlen(num); + if (len) { len--; // delete one character num[len] = '\0'; - calltree_update_call (current_calls, c, NULL); + calltree_update_call(current_calls_tab, c); /* If number is now empty, hang up immediately */ if (c->_state != CALL_STATE_TRANSFER && len == 0) dbus_hang_up(c); } + break; } case GDK_Tab: @@ -644,20 +653,20 @@ process_dialing (callable_obj_t *c, guint keyval, gchar *key) default: if (keyval < 127 /* ascii */ || - (keyval >= GDK_Mode_switch && keyval <= GDK_KP_9) /* num keypad */) { + (keyval >= GDK_Mode_switch && keyval <= GDK_KP_9) /* num keypad */) { if (c->_state == CALL_STATE_TRANSFER) { - gchar *new_trsft = g_strconcat (c->_trsft_to, key, NULL); - g_free (c->_trsft_to); + gchar *new_trsft = g_strconcat(c->_trsft_to, key, NULL); + g_free(c->_trsft_to); c->_trsft_to = new_trsft; } else { - dbus_play_dtmf (key); - gchar *new_peer_number = g_strconcat (c->_peer_number, key, NULL); - g_free (c->_peer_number); + dbus_play_dtmf(key); + gchar *new_peer_number = g_strconcat(c->_peer_number, key, NULL); + g_free(c->_peer_number); c->_peer_number = new_peer_number; } - calltree_update_call (current_calls, c, NULL); + calltree_update_call(current_calls_tab, c); } break; @@ -668,21 +677,21 @@ process_dialing (callable_obj_t *c, guint keyval, gchar *key) callable_obj_t * sflphone_new_call() { - callable_obj_t *current_selected_call = calltab_get_selected_call (current_calls); + callable_obj_t *current_selected_call = calltab_get_selected_call(current_calls_tab); - if ( (current_selected_call != NULL) && (current_selected_call->_confID == NULL)) + if ((current_selected_call != NULL) && (current_selected_call->_confID == NULL)) sflphone_on_hold(); // Play a tone when creating a new call - if (calllist_get_size (current_calls) == 0) - dbus_start_tone (TRUE , (current_account_has_new_message () > 0) ? TONE_WITH_MESSAGE : TONE_WITHOUT_MESSAGE) ; + if (calllist_get_size(current_calls_tab) == 0) + dbus_start_tone(TRUE , (current_account_has_new_message() > 0) ? TONE_WITH_MESSAGE : TONE_WITHOUT_MESSAGE) ; - callable_obj_t *c = create_new_call (CALL, CALL_STATE_DIALING, "", "", "", ""); + callable_obj_t *c = create_new_call(CALL, CALL_STATE_DIALING, "", "", "", ""); c->_history_state = OUTGOING; - calllist_add_call (current_calls, c); - calltree_add_call (current_calls, c, NULL); + calllist_add_call(current_calls_tab, c); + calltree_add_call(current_calls_tab, c, NULL); update_actions(); return c; @@ -690,11 +699,11 @@ sflphone_new_call() void -sflphone_keypad (guint keyval, gchar * key) +sflphone_keypad(guint keyval, gchar * key) { - callable_obj_t * c = calltab_get_selected_call (current_calls); + callable_obj_t * c = calltab_get_selected_call(current_calls_tab); - if ( (active_calltree != current_calls) || (active_calltree == current_calls && !c)) { + if ((active_calltree_tab != current_calls_tab) || (active_calltree_tab == current_calls_tab && !c)) { switch (keyval) { case GDK_Return: case GDK_KP_Enter: @@ -702,27 +711,27 @@ sflphone_keypad (guint keyval, gchar * key) case GDK_BackSpace: break; default: - calltree_display (current_calls); - process_dialing (sflphone_new_call(), keyval, key); + calltree_display(current_calls_tab); + process_dialing(sflphone_new_call(), keyval, key); break; } } else if (c) { switch (c->_state) { case CALL_STATE_DIALING: // Currently dialing => edit number - process_dialing (c, keyval, key); + process_dialing(c, keyval, key); break; case CALL_STATE_RECORD: case CALL_STATE_CURRENT: switch (keyval) { case GDK_Escape: - dbus_hang_up (c); - time (&c->_time_stop); - calltree_update_call (history, c, NULL); + dbus_hang_up(c); + time(&c->_time_stop); + calltree_update_call(history_tab, c); break; default: // To play the dtmf when calling mail box for instance - dbus_play_dtmf (key); + dbus_play_dtmf(key); break; } @@ -733,11 +742,11 @@ sflphone_keypad (guint keyval, gchar * key) case GDK_Return: case GDK_KP_Enter: c->_history_state = INCOMING; - calltree_update_call (history, c, NULL); - dbus_accept (c); + calltree_update_call(history_tab, c); + dbus_accept(c); break; case GDK_Escape: - dbus_refuse (c); + dbus_refuse(c); break; } @@ -747,15 +756,15 @@ sflphone_keypad (guint keyval, gchar * key) switch (keyval) { case GDK_Return: case GDK_KP_Enter: - dbus_transfer (c); - time (&c->_time_stop); - calltree_remove_call(current_calls, c, NULL); + dbus_transfer(c); + time(&c->_time_stop); + calltree_remove_call(current_calls_tab, c); break; case GDK_Escape: - sflphone_unset_transfer (); + sflphone_unset_transfer(); break; default: // When a call is on transfer, typing new numbers will add it to c->_peer_number - process_dialing (c, keyval, key); + process_dialing(c, keyval, key); break; } @@ -765,13 +774,13 @@ sflphone_keypad (guint keyval, gchar * key) switch (keyval) { case GDK_Return: case GDK_KP_Enter: - dbus_unhold (c); + dbus_unhold(c); break; case GDK_Escape: - dbus_hang_up (c); + dbus_hang_up(c); break; default: // When a call is on hold, typing new numbers will create a new call - process_dialing (sflphone_new_call(), keyval, key); + process_dialing(sflphone_new_call(), keyval, key); break; } @@ -782,8 +791,8 @@ sflphone_keypad (guint keyval, gchar * key) switch (keyval) { case GDK_Escape: - dbus_hang_up (c); - calltree_update_call (history, c, NULL); + dbus_hang_up(c); + calltree_update_call(history_tab, c); break; } @@ -796,13 +805,13 @@ sflphone_keypad (guint keyval, gchar * key) sflphone_new_call(); } -static void place_direct_call (const callable_obj_t * c) +static void place_direct_call(const callable_obj_t * c) { g_assert(c->_state == CALL_STATE_DIALING); dbus_place_call(c); } -static int place_registered_call (callable_obj_t * c) +static int place_registered_call(callable_obj_t * c) { account_t * current = NULL; @@ -814,48 +823,48 @@ static int place_registered_call (callable_obj_t * c) if (account_list_get_size() == 0) { notify_no_accounts(); - sflphone_fail (c); + sflphone_fail(c); return -1; } - if (account_list_get_by_state (ACCOUNT_STATE_REGISTERED) == NULL) { - DEBUG ("Actions: No registered account, cannot make a call"); + if (account_list_get_by_state(ACCOUNT_STATE_REGISTERED) == NULL) { + DEBUG("Actions: No registered account, cannot make a call"); notify_no_registered_accounts(); - sflphone_fail (c); + sflphone_fail(c); return -1; } - DEBUG ("Actions: Get account for this call"); + DEBUG("Actions: Get account for this call"); if (strlen(c->_accountID) != 0) { - DEBUG ("Actions: Account %s already set for this call", c->_accountID); - current = account_list_get_by_id (c->_accountID); + DEBUG("Actions: Account %s already set for this call", c->_accountID); + current = account_list_get_by_id(c->_accountID); } else { - DEBUG ("Actions: No account set for this call, use first of the list"); + DEBUG("Actions: No account set for this call, use first of the list"); current = account_list_get_current(); } if (current == NULL) { - DEBUG ("Actions: Unexpected condition: account_t is NULL in %s at %d for accountID %s", __FILE__, __LINE__, c->_accountID); + DEBUG("Actions: Unexpected condition: account_t is NULL in %s at %d for accountID %s", __FILE__, __LINE__, c->_accountID); return -1; } - if (g_strcasecmp (g_hash_table_lookup (current->properties, "Status"), "REGISTERED") ==0) { + if (g_strcasecmp(g_hash_table_lookup(current->properties, "Status"), "REGISTERED") ==0) { /* The call is made with the current account */ // free memory for previous account id and get a new one - g_free (c->_accountID); - c->_accountID = g_strdup (current->accountID); - dbus_place_call (c); + g_free(c->_accountID); + c->_accountID = g_strdup(current->accountID); + dbus_place_call(c); } else { /* Place the call with the first registered account * and switch the current account. * If we are here, we can be sure that there is at least one. */ - current = account_list_get_by_state (ACCOUNT_STATE_REGISTERED); - g_free (c->_accountID); - c->_accountID = g_strdup (current->accountID); - dbus_place_call (c); - notify_current_account (current); + current = account_list_get_by_state(ACCOUNT_STATE_REGISTERED); + g_free(c->_accountID); + c->_accountID = g_strdup(current->accountID); + dbus_place_call(c); + notify_current_account(current); } c->_history_state = OUTGOING; @@ -864,61 +873,52 @@ static int place_registered_call (callable_obj_t * c) } void -sflphone_place_call (callable_obj_t * c) +sflphone_place_call(callable_obj_t * c) { - DEBUG ("Actions: Placing call with %s @ %s and accountid %s", c->_peer_name, c->_peer_number, c->_accountID); + DEBUG("Actions: Placing call with %s @ %s and accountid %s", c->_peer_name, c->_peer_number, c->_accountID); - if (_is_direct_call (c)) { - gchar *msg = g_markup_printf_escaped (_ ("Direct SIP call")); - statusbar_pop_message (__MSG_ACCOUNT_DEFAULT); - statusbar_push_message (msg , NULL, __MSG_ACCOUNT_DEFAULT); - g_free (msg); + if (_is_direct_call(c)) { + gchar *msg = g_markup_printf_escaped(_("Direct SIP call")); + statusbar_pop_message(__MSG_ACCOUNT_DEFAULT); + statusbar_push_message(msg , NULL, __MSG_ACCOUNT_DEFAULT); + g_free(msg); - place_direct_call (c); - } else if (place_registered_call (c) < 0) - DEBUG ("An error occured while placing registered call in %s at %d", __FILE__, __LINE__); + place_direct_call(c); + } else if (place_registered_call(c) < 0) + DEBUG("An error occured while placing registered call in %s at %d", __FILE__, __LINE__); } void -sflphone_detach_participant (const gchar* callID) +sflphone_detach_participant(const gchar* callID) { callable_obj_t * selectedCall; + if (callID == NULL) - selectedCall = calltab_get_selected_call (current_calls); + selectedCall = calltab_get_selected_call(current_calls_tab); else - selectedCall = calllist_get_call (current_calls, callID); + selectedCall = calllist_get_call(current_calls_tab, callID); - DEBUG ("Action: Detach participant %s", selectedCall->_callID); + DEBUG("Action: Detach participant %s", selectedCall->_callID); if (selectedCall->_confID) { - g_free (selectedCall->_confID); + g_free(selectedCall->_confID); selectedCall->_confID = NULL; } - im_widget_update_state (IM_WIDGET (selectedCall->_im_widget), TRUE); - calltree_remove_call (current_calls, selectedCall, NULL); - calltree_add_call (current_calls, selectedCall, NULL); - dbus_detach_participant (selectedCall->_callID); -} - -void -sflphone_join_participant (const gchar* sel_callID, const gchar* drag_callID) -{ - DEBUG ("sflphone join participants %s and %s", sel_callID, drag_callID); - dbus_join_participant (sel_callID, drag_callID); + im_widget_update_state(IM_WIDGET(selectedCall->_im_widget), TRUE); + calltree_remove_call(current_calls_tab, selectedCall); + calltree_add_call(current_calls_tab, selectedCall, NULL); + dbus_detach_participant(selectedCall->_callID); } - void -sflphone_add_participant (const gchar* callID, const gchar* confID) +sflphone_add_participant(const gchar* callID, const gchar* confID) { - GtkTreeIter iter; - callable_obj_t *call; + DEBUG(">SFLphone: Add participant %s to conference %s", callID, confID); - DEBUG (">SFLphone: Add participant %s to conference %s", callID, confID); + callable_obj_t *call = calllist_get_call(current_calls_tab, callID); - call = calllist_get_call(current_calls, callID); if (call == NULL) { ERROR("SFLphone: Error: Could not find call"); return; @@ -926,58 +926,25 @@ sflphone_add_participant (const gchar* callID, const gchar* confID) time(&call->_time_added); - iter = calltree_get_gtkiter_from_id(history, (gchar *)confID); - - calltree_add_call(history, call, &iter); - - dbus_add_participant (callID, confID); + dbus_add_participant(callID, confID); } void -sflphone_add_conference() +sflphone_add_main_participant(const conference_obj_t * c) { - DEBUG ("sflphone add a conference to tree view"); - // dbus_join_participant(selected_call, dragged_call); + DEBUG("sflphone add main participant"); + dbus_add_main_participant(c->_confID); } -void -sflphone_join_conference (const gchar* sel_confID, const gchar* drag_confID) -{ - DEBUG ("sflphone join two conference"); - dbus_join_conference (sel_confID, drag_confID); -} - -void -sflphone_add_main_participant (const conference_obj_t * c) -{ - DEBUG ("sflphone add main participant"); - dbus_add_main_participant (c->_confID); -} - -void -sflphone_conference_on_hold (const conference_obj_t * c) -{ - DEBUG ("sflphone_conference_on_hold"); - dbus_hold_conference (c); -} - -void -sflphone_conference_off_hold (const conference_obj_t * c) -{ - DEBUG ("sflphone_conference_off_hold"); - dbus_unhold_conference (c); -} - - void sflphone_rec_call() { - callable_obj_t * selectedCall = calltab_get_selected_call (current_calls); - conference_obj_t * selectedConf = calltab_get_selected_conf (current_calls); + callable_obj_t * selectedCall = calltab_get_selected_call(current_calls_tab); + conference_obj_t * selectedConf = calltab_get_selected_conf(current_calls_tab); if (selectedCall) { - DEBUG ("SFLphone: Set record for selected call"); - dbus_set_record (selectedCall->_callID); + DEBUG("SFLphone: Set record for selected call"); + dbus_set_record(selectedCall->_callID); switch (selectedCall->_state) { case CALL_STATE_CURRENT: @@ -987,37 +954,42 @@ sflphone_rec_call() selectedCall->_state = CALL_STATE_CURRENT; break; default: - WARN ("Should not happen in sflphone_off_hold ()!"); + WARN("Should not happen in sflphone_off_hold ()!"); break; } - calltree_update_call (current_calls, selectedCall, NULL); + + calltree_update_call(current_calls_tab, selectedCall); } else if (selectedConf) { - DEBUG ("SFLphone: Set record for selected conf"); - dbus_set_record (selectedConf->_confID); + DEBUG("SFLphone: Set record for selected conf"); + dbus_set_record(selectedConf->_confID); + switch (selectedConf->_state) { - case CONFERENCE_STATE_ACTIVE_ATACHED: + case CONFERENCE_STATE_ACTIVE_ATTACHED: selectedConf->_state = CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD; break; case CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD: - selectedConf->_state = CONFERENCE_STATE_ACTIVE_ATACHED; + selectedConf->_state = CONFERENCE_STATE_ACTIVE_ATTACHED; break; case CONFERENCE_STATE_ACTIVE_DETACHED: selectedConf->_state = CONFERENCE_STATE_ACTIVE_DETACHED_RECORD; break; case CONFERENCE_STATE_ACTIVE_DETACHED_RECORD: - selectedConf->_state = CONFERENCE_STATE_ACTIVE_DETACHED_RECORD; - break; + selectedConf->_state = CONFERENCE_STATE_ACTIVE_DETACHED_RECORD; + break; default: - WARN ("Should not happen in sflphone_off_hold ()!"); + WARN("Should not happen in sflphone_off_hold ()!"); break; } - calltree_update_conference(current_calls, selectedConf); + + DEBUG("Actions: Remove and add conference %s", selectedConf->_confID); + calltree_remove_conference(current_calls_tab, selectedConf); + calltree_add_conference_to_current_calls(selectedConf); } update_actions(); } -void sflphone_fill_codec_list () +void sflphone_fill_codec_list() { guint account_list_size = account_list_get_size(); @@ -1029,7 +1001,7 @@ void sflphone_fill_codec_list () } } -void sflphone_fill_codec_list_per_account (account_t *account) +void sflphone_fill_codec_list_per_account(account_t *account) { GArray *order = dbus_get_active_audio_codec_list(account->accountID); @@ -1042,280 +1014,214 @@ void sflphone_fill_codec_list_per_account (account_t *account) gint payload = g_array_index(order, gint, i); // Each account will have a copy of the system-wide capabilities - codec_t *cpy = codec_create_new_from_caps (codec_list_get_by_payload ( (gconstpointer) (uintptr_t) payload, NULL)); + codec_t *cpy = codec_create_new_from_caps(codec_list_get_by_payload((gconstpointer)(uintptr_t) payload, NULL)); - if (cpy) { - codec_list_add (cpy, &codeclist); - } else - ERROR ("SFLphone: Couldn't find codec"); + if (cpy) + codec_list_add(cpy, &codeclist); + else + ERROR("SFLphone: Couldn't find codec"); } g_array_unref(order); - guint caps_size = codec_list_get_size (); + guint caps_size = codec_list_get_size(); for (guint i = 0; i < caps_size; i++) { - codec_t * current_cap = capabilities_get_nth (i); + codec_t * current_cap = capabilities_get_nth(i); // Check if this codec has already been enabled for this account - if (codec_list_get_by_payload ( (gconstpointer) (size_t) (current_cap->_payload), codeclist) == NULL) { + if (codec_list_get_by_payload((gconstpointer)(size_t)(current_cap->_payload), codeclist) == NULL) { current_cap->is_active = FALSE; - codec_list_add (current_cap, &codeclist); + codec_list_add(current_cap, &codeclist); } } + account->codecs = codeclist; } -void sflphone_fill_call_list (void) +void sflphone_fill_call_list(void) { gchar **list = dbus_get_call_list(); - for (gchar **calls = list; calls && *calls; calls++) { + for (gchar **calls = list; calls && *calls; ++calls) { gchar *callID = *calls; - callable_obj_t *c = create_new_call_from_details (*calls, dbus_get_call_details (*calls)); + callable_obj_t *c = create_new_call_from_details(*calls, dbus_get_call_details(*calls)); g_free(callID); c->_zrtp_confirmed = FALSE; - calllist_add_call (current_calls, c); - calltree_add_call (current_calls, c, NULL); + calllist_add_call(current_calls_tab, c); + calltree_add_call(current_calls_tab, c, NULL); } - g_free(list); + g_strfreev(list); } -void sflphone_fill_conference_list (void) +void sflphone_fill_conference_list(void) { // TODO Fetch the active conferences at client startup gchar **conferences = dbus_get_conference_list(); + for (gchar **list = conferences; list && *list; list++) { const gchar * const conf_id = *list; - GHashTable *conference_details = dbus_get_conference_details (conf_id); - conference_obj_t *conf = create_new_conference_from_details (conf_id, conference_details); + GHashTable *conference_details = dbus_get_conference_details(conf_id); + conference_obj_t *conf = create_new_conference_from_details(conf_id, conference_details); - conferencelist_add (current_calls, conf); - calltree_add_conference (current_calls, conf); + conferencelist_add(current_calls_tab, conf); + calltree_add_conference_to_current_calls(conf); } g_strfreev(conferences); } -void sflphone_fill_history (void) +void sflphone_fill_history(void) { gchar **entries, **entries_orig; - callable_obj_t *history_call, *call; - QueueElement *element; - guint i = 0, n = 0; - - entries = entries_orig = dbus_get_history (); + entries = entries_orig = dbus_get_history(); - while (*entries) { + while (entries && *entries) { gchar *current_entry = *entries; + /* do something with key and value */ + callable_obj_t *history_call = create_history_entry_from_serialized_form(current_entry); - // Parsed a conference - if (g_str_has_prefix(current_entry, "9999")) { - // create a conference entry - conference_obj_t *history_conf = create_conference_history_entry_from_serialized(current_entry); - - // verify if this conference has been already created yet - conference_obj_t *conf = conferencelist_get(history, history_conf->_confID); - // if this conference hasn't been created yet, add it to the conference list - if (!conf) - conferencelist_add(history, history_conf); - else { - // if this conference was already created since one of the participant have already - // been unserialized, update the recordfile value - conf->_recordfile = g_strdup(history_conf->_recordfile); - } - } - else { - // do something with key and value - history_call = create_history_entry_from_serialized_form (current_entry); - - // Add it and update the GUI - calllist_add_call (history, history_call); - - if (history_call->_confID && g_strcmp0(history_call->_confID, "") != 0) { - - // process conference - conference_obj_t *conf = conferencelist_get(history, history_call->_confID); - if (!conf) { - // conference does not exist yet, create it - conf = create_new_conference(CONFERENCE_STATE_ACTIVE_ATACHED, history_call->_confID); - conferencelist_add(history, conf); - } - - // add this participant to the conference - conference_add_participant(history_call->_callID, conf); - - // conference start timestamp corespond to - if (conf->_time_start > history_call->_time_added) - conf->_time_start = history_call->_time_added; - } - } - - g_free(*entries++); + /* Add it and update the GUI */ + calllist_add_call(history_tab, history_call); + entries++; } - g_free(entries_orig); + + g_strfreev(entries_orig); // fill the treeview with calls - n = calllist_get_size(history); - for(i = 0; i < n; i++) { - element = calllist_get_nth(history, i); - if(element->type == HIST_CALL) { - call = element->elem.call; - calltree_add_call (history, call, NULL); - } - } + guint n = calllist_get_size(history_tab); + + for (guint i = 0; i < n; i++) { + QueueElement *element = calllist_get_nth(history_tab, i); - // fill the treeview with conferences - n = conferencelist_get_size(history); - for(i = 0; i < n; i++) { - conference_obj_t *conf = conferencelist_get_nth(history, i); - if (!conf) - DEBUG("SFLphone: Error: Could not find conference"); - calltree_add_conference(history, conf); + if (element->type == HIST_CALL) + calltree_add_history_entry(element->elem.call); } } #if ! (GLIB_CHECK_VERSION(2,28,0)) static void -g_slist_free_full (GSList *list, - GDestroyNotify free_func) +g_slist_free_full(GSList *list, + GDestroyNotify free_func) { - g_slist_foreach (list, (GFunc) free_func, NULL); - g_slist_free (list); + g_slist_foreach(list, (GFunc) free_func, NULL); + g_slist_free(list); } #endif static void hist_free_elt(gpointer list) { - g_slist_free_full ((GSList *)list, g_free); + g_slist_free_full((GSList *)list, g_free); } -void sflphone_save_history (void) +void sflphone_save_history(void) { - QueueElement *current; - conference_obj_t *conf; + GHashTable *result = g_hash_table_new_full(NULL, g_str_equal, g_free, hist_free_elt); - GHashTable *result = g_hash_table_new_full (NULL, g_str_equal, g_free, hist_free_elt); + gint size = calllist_get_size(history_tab); + + for (gint i = 0; i < size; ++i) { + QueueElement *current = calllist_get_nth(history_tab, i); - gint size = calllist_get_size (history); - for (gint i = 0; i < size; i++) { - current = calllist_get_nth (history, i); if (!current) { WARN("SFLphone: Warning: %dth element is null", i); break; } gchar *value; - if(current->type == HIST_CALL) - value = serialize_history_call_entry (current->elem.call); - else if(current->type == HIST_CONFERENCE) - value = serialize_history_conference_entry(current->elem.conf); - else { - ERROR("SFLphone: Error: Unknown type for serialization"); - break; - } - gchar *key = g_strdup_printf ("%i", (int) current->elem.call->_time_start); - g_hash_table_replace (result, (gpointer) key, - g_slist_append(g_hash_table_lookup(result, key),(gpointer) value)); - } + if (current->type == HIST_CALL) { + value = serialize_history_call_entry(current->elem.call); + gchar *key = g_strdup_printf("%i", (int) current->elem.call->_time_start); - size = conferencelist_get_size(history); - for(gint i = 0; i < size; i++) { - conf = conferencelist_get_nth(history, i); - if(!conf) { - DEBUG("SFLphone: Error: Could not get %dth conference", i); - break; + g_hash_table_replace(result, (gpointer) key, + g_slist_append(g_hash_table_lookup(result, key),(gpointer) value)); } - - gchar *value = serialize_history_conference_entry(conf); - gchar *key = g_strdup_printf ("%i", (int) conf->_time_start); - - g_hash_table_replace(result, (gpointer) key, - g_slist_append(g_hash_table_lookup(result, key), (gpointer) value)); + else + ERROR("SFLphone: Error: Unknown type for serialization"); } gchar **ordered_result = sflphone_order_history_hash_table(result); - dbus_set_history (ordered_result); + dbus_set_history(ordered_result); g_strfreev(ordered_result); - g_hash_table_unref (result); + g_hash_table_unref(result); } void -sflphone_srtp_sdes_on (callable_obj_t * c) +sflphone_srtp_sdes_on(callable_obj_t * c) { c->_srtp_state = SRTP_STATE_SDES_SUCCESS; - calltree_update_call (current_calls, c, NULL); + calltree_update_call(current_calls_tab, c); update_actions(); } void -sflphone_srtp_sdes_off (callable_obj_t * c) +sflphone_srtp_sdes_off(callable_obj_t * c) { c->_srtp_state = SRTP_STATE_UNLOCKED; - calltree_update_call (current_calls, c, NULL); + calltree_update_call(current_calls_tab, c); update_actions(); } void -sflphone_srtp_zrtp_on (callable_obj_t * c) +sflphone_srtp_zrtp_on(callable_obj_t * c) { c->_srtp_state = SRTP_STATE_ZRTP_SAS_UNCONFIRMED; - calltree_update_call (current_calls, c, NULL); + calltree_update_call(current_calls_tab, c); update_actions(); } void -sflphone_srtp_zrtp_off (callable_obj_t * c) +sflphone_srtp_zrtp_off(callable_obj_t * c) { c->_srtp_state = SRTP_STATE_UNLOCKED; - calltree_update_call (current_calls, c, NULL); + calltree_update_call(current_calls_tab, c); update_actions(); } void -sflphone_srtp_zrtp_show_sas (callable_obj_t * c, const gchar* sas, const gboolean verified) +sflphone_srtp_zrtp_show_sas(callable_obj_t * c, const gchar* sas, const gboolean verified) { - c->_sas = g_strdup (sas); + c->_sas = g_strdup(sas); c->_srtp_state = verified ? SRTP_STATE_ZRTP_SAS_CONFIRMED : SRTP_STATE_ZRTP_SAS_UNCONFIRMED; - calltree_update_call (current_calls, c, NULL); + calltree_update_call(current_calls_tab, c); update_actions(); } void -sflphone_request_go_clear (void) +sflphone_request_go_clear(void) { - callable_obj_t * selectedCall = calltab_get_selected_call (current_calls); + callable_obj_t * selectedCall = calltab_get_selected_call(current_calls_tab); if (selectedCall) - dbus_request_go_clear (selectedCall); + dbus_request_go_clear(selectedCall); } void -sflphone_call_state_changed (callable_obj_t * c, const gchar * description, const guint code) +sflphone_call_state_changed(callable_obj_t * c, const gchar * description, const guint code) { - DEBUG ("SFLPhone: Call State changed %s", description); + DEBUG("SFLPhone: Call State changed %s", description); if (c == NULL) { - ERROR ("SFLphone: Error: callable obj is NULL in %s at %d", __FILE__, __LINE__); + ERROR("SFLphone: Error: callable obj is NULL in %s at %d", __FILE__, __LINE__); return; } g_free(c->_state_code_description); - c->_state_code_description = g_strdup (description); + c->_state_code_description = g_strdup(description); c->_state_code = code; - calltree_update_call (current_calls, c, NULL); + calltree_update_call(current_calls_tab, c); update_actions(); } diff --git a/gnome/src/actions.h b/gnome/src/actions.h index dc9971bf6806ccdead6b3ad147b0e8866f59c023..203460e49964973b719701f8bdc570538d9a26b0 100644 --- a/gnome/src/actions.h +++ b/gnome/src/actions.h @@ -39,6 +39,7 @@ #include "codeclist.h" #include "sflphone_const.h" #include "conference_obj.h" +#include "callable_obj.h" /** @file actions.h * @brief General functions that change the state of the application. @@ -202,11 +203,6 @@ void sflphone_fill_history (void); void sflphone_save_history (void); -/** - * Action called when two single call are dragged on together to create a new conference - */ -void sflphone_join_participant (const gchar* sel_callID, const gchar* drag_callID); - /** * Action called when a new participant is dragged in */ @@ -217,12 +213,6 @@ void sflphone_add_participant (const gchar* callID, const gchar* confID); */ void sflphone_detach_participant (const gchar* callID); -/** - * Action called when two conference are merged together - */ -void sflphone_join_conference (const gchar* sel_confID, const gchar* drag_confID); - - /** * Nofity that the communication is * now secured using SRTP/SDES. @@ -276,14 +266,8 @@ void sflphone_call_state_changed (callable_obj_t * c, const gchar * description, void sflphone_add_main_participant (const conference_obj_t * c); -void -sflphone_conference_off_hold (const conference_obj_t * c); - -void -sflphone_srtp_sdes_off (callable_obj_t * c); +void sflphone_srtp_sdes_off (callable_obj_t * c); void sflphone_fill_conference_list (void); -void sflphone_conference_on_hold (const conference_obj_t * c); - #endif diff --git a/gnome/src/callable_obj.c b/gnome/src/callable_obj.c index d30c962d3add0533670e1ed611fd9bffe9a7fc62..d6e3771c481417289596e30dca8bb3b2c77eba3d 100644 --- a/gnome/src/callable_obj.c +++ b/gnome/src/callable_obj.c @@ -28,16 +28,17 @@ * as that of the covered work. */ -#include <callable_obj.h> -#include <codeclist.h> -#include <sflphone_const.h> +#include "callable_obj.h" +#include "codeclist.h" +#include "sflphone_const.h" #include <time.h> +#include "contacts/calltab.h" #include "contacts/calltree.h" +#include "dbus.h" #include <unistd.h> -#include <assert.h> -gint get_state_callstruct (gconstpointer a, gconstpointer b) +gint get_state_callstruct(gconstpointer a, gconstpointer b) { callable_obj_t * c = (callable_obj_t*) a; call_state_t state = *((call_state_t*)b); @@ -45,39 +46,43 @@ gint get_state_callstruct (gconstpointer a, gconstpointer b) return c->_state == state ? 0 : 1; } -gchar* call_get_peer_name (const gchar *format) +gchar* call_get_peer_name(const gchar *format) { - const gchar *end = g_strrstr (format, "<"); - return g_strndup (format, end ? end - format : 0); + const gchar *end = g_strrstr(format, "<"); + return g_strndup(format, end ? end - format : 0); } -gchar* call_get_peer_number (const gchar *format) +gchar* call_get_peer_number(const gchar *format) { - gchar *number = g_strrstr (format, "<") + 1; - gchar *end = g_strrstr (format, ">"); + gchar *number = g_strrstr(format, "<") + 1; + gchar *end = g_strrstr(format, ">"); if (end && number) - return g_strndup (number, end - number); + return g_strndup(number, end - number); else - return g_strdup (format); + return g_strdup(format); } -gchar* call_get_audio_codec (callable_obj_t *obj) +gchar* call_get_audio_codec(callable_obj_t *obj) { gchar *ret = NULL; gchar *audio_codec = NULL; + if (!obj) goto out; - audio_codec = dbus_get_current_audio_codec_name (obj); + audio_codec = dbus_get_current_audio_codec_name(obj); + if (!audio_codec) goto out; account_t *acc = account_list_get_by_id(obj->_accountID); + if (!acc) goto out; - const codec_t *const codec = codec_list_get_by_name (audio_codec, acc->codecs); + const codec_t *const codec = codec_list_get_by_name(audio_codec, acc->codecs); + if (!codec) goto out; @@ -85,88 +90,91 @@ gchar* call_get_audio_codec (callable_obj_t *obj) out: g_free(audio_codec); + if (ret == NULL) return g_strdup(""); + return ret; } -void call_add_error (callable_obj_t * call, gpointer dialog) +void call_add_error(callable_obj_t * call, gpointer dialog) { - g_ptr_array_add (call->_error_dialogs, dialog); + g_ptr_array_add(call->_error_dialogs, dialog); } -void call_remove_error (callable_obj_t * call, gpointer dialog) +void call_remove_error(callable_obj_t * call, gpointer dialog) { - g_ptr_array_remove (call->_error_dialogs, dialog); + g_ptr_array_remove(call->_error_dialogs, dialog); } -void call_remove_all_errors (callable_obj_t * call) +void call_remove_all_errors(callable_obj_t * call) { - g_ptr_array_foreach (call->_error_dialogs, (GFunc) gtk_widget_destroy, NULL); + g_ptr_array_foreach(call->_error_dialogs, (GFunc) gtk_widget_destroy, NULL); } -callable_obj_t *create_new_call (callable_type_t type, call_state_t state, - const gchar* const callID, - const gchar* const accountID, - const gchar* const peer_name, - const gchar* const peer_number) +callable_obj_t *create_new_call(callable_type_t type, call_state_t state, + const gchar* const callID, + const gchar* const accountID, + const gchar* const peer_name, + const gchar* const peer_number) { - callable_obj_t *obj = g_new0 (callable_obj_t, 1); + callable_obj_t *obj = g_new0(callable_obj_t, 1); obj->_error_dialogs = g_ptr_array_new(); obj->_type = type; obj->_state = state; - obj->_callID = *callID ? g_strdup (callID) : g_strdup_printf("%d", rand()); - obj->_accountID = g_strdup (accountID); + obj->_callID = *callID ? g_strdup(callID) : g_strdup_printf("%d", rand()); + obj->_accountID = g_strdup(accountID); - time (&obj->_time_start); - time (&obj->_time_stop); + time(&obj->_time_start); + time(&obj->_time_stop); - obj->_peer_name = g_strdup (peer_name); - obj->_peer_number = g_strdup (peer_number); - obj->_peer_info = get_peer_info (peer_name, peer_number); + obj->_peer_name = g_strdup(peer_name); + obj->_peer_number = g_strdup(peer_number); + obj->_peer_info = get_peer_info(peer_name, peer_number); return obj; } -callable_obj_t *create_new_call_from_details (const gchar *call_id, GHashTable *details) +callable_obj_t *create_new_call_from_details(const gchar *call_id, GHashTable *details) { call_state_t state; - const gchar * const accountID = g_hash_table_lookup (details, "ACCOUNTID"); - const gchar * const peer_number = g_hash_table_lookup (details, "PEER_NUMBER"); - const gchar * const peer_name = g_hash_table_lookup (details, "DISPLAY_NAME"); - const gchar * const state_str = g_hash_table_lookup (details, "CALL_STATE"); + const gchar * const accountID = g_hash_table_lookup(details, "ACCOUNTID"); + const gchar * const peer_number = g_hash_table_lookup(details, "PEER_NUMBER"); + const gchar * const peer_name = g_hash_table_lookup(details, "DISPLAY_NAME"); + const gchar * const state_str = g_hash_table_lookup(details, "CALL_STATE"); - if (g_strcasecmp (state_str, "CURRENT") == 0) + if (g_strcasecmp(state_str, "CURRENT") == 0) state = CALL_STATE_CURRENT; - else if (g_strcasecmp (state_str, "RINGING") == 0) + else if (g_strcasecmp(state_str, "RINGING") == 0) state = CALL_STATE_RINGING; - else if (g_strcasecmp (state_str, "INCOMING") == 0) + else if (g_strcasecmp(state_str, "INCOMING") == 0) state = CALL_STATE_INCOMING; - else if (g_strcasecmp (state_str, "HOLD") == 0) + else if (g_strcasecmp(state_str, "HOLD") == 0) state = CALL_STATE_HOLD; - else if (g_strcasecmp (state_str, "BUSY") == 0) + else if (g_strcasecmp(state_str, "BUSY") == 0) state = CALL_STATE_BUSY; else state = CALL_STATE_FAILURE; - gchar *number = call_get_peer_number (peer_number); - callable_obj_t *c = create_new_call (CALL, state, call_id, accountID, peer_name, number); + gchar *number = call_get_peer_number(peer_number); + callable_obj_t *c = create_new_call(CALL, state, call_id, accountID, peer_name, number); g_free(number); return c; } -static history_state_t get_history_state_from_id (gchar *indice) +static history_state_t get_history_state_from_id(gchar *indice) { history_state_t state = atoi(indice); + if (state > LAST) state = MISSED; return state; } -callable_obj_t *create_history_entry_from_serialized_form (const gchar *entry) +callable_obj_t *create_history_entry_from_serialized_form(const gchar *entry) { const gchar *peer_name = ""; const gchar *peer_number = ""; @@ -182,32 +190,54 @@ callable_obj_t *create_history_entry_from_serialized_form (const gchar *entry) gchar **ptr_orig = g_strsplit(entry, "|", 10); gchar **ptr; gint token; + for (ptr = ptr_orig, token = 0; ptr && token < 10; token++, ptr++) switch (token) { - case 0: history_state = get_history_state_from_id(*ptr); break; - case 1: peer_number = *ptr; break; - case 2: peer_name = *ptr; break; - case 3: time_start = *ptr; break; - case 4: time_stop = *ptr; break; - case 5: callID = *ptr; break; - case 6: accountID = *ptr; break; - case 7: recordfile = *ptr; break; - case 8: confID = *ptr; break; - case 9: time_added = *ptr; break; - default: break; + case 0: + history_state = get_history_state_from_id(*ptr); + break; + case 1: + peer_number = *ptr; + break; + case 2: + peer_name = *ptr; + break; + case 3: + time_start = *ptr; + break; + case 4: + time_stop = *ptr; + break; + case 5: + callID = *ptr; + break; + case 6: + accountID = *ptr; + break; + case 7: + recordfile = *ptr; + break; + case 8: + confID = *ptr; + break; + case 9: + time_added = *ptr; + break; + default: + break; } - if (g_strcasecmp (peer_name, "empty") == 0) + if (g_strcasecmp(peer_name, "empty") == 0) peer_name = ""; - callable_obj_t *new_call = create_new_call (HISTORY_ENTRY, CALL_STATE_DIALING, callID, accountID, peer_name, peer_number); + callable_obj_t *new_call = create_new_call(HISTORY_ENTRY, CALL_STATE_DIALING, callID, accountID, peer_name, peer_number); new_call->_history_state = history_state; new_call->_time_start = atoi(time_start); new_call->_time_stop = atoi(time_stop); new_call->_recordfile = g_strdup(recordfile); new_call->_confID = g_strdup(confID); new_call->_historyConfID = g_strdup(confID); - new_call->_time_added = atoi(time_start); + new_call->_time_added = atoi(time_added); new_call->_record_is_playing = FALSE; g_strfreev(ptr_orig); @@ -216,56 +246,58 @@ callable_obj_t *create_history_entry_from_serialized_form (const gchar *entry) void free_callable_obj_t (callable_obj_t *c) { - g_free (c->_callID); - g_free (c->_confID); - g_free (c->_historyConfID); - g_free (c->_accountID); - g_free (c->_srtp_cipher); - g_free (c->_sas); - g_free (c->_peer_name); - g_free (c->_peer_number); - g_free (c->_trsft_to); - g_free (c->_peer_info); - g_free (c->_recordfile); - - g_free (c); + g_free(c->_callID); + g_free(c->_confID); + g_free(c->_historyConfID); + g_free(c->_accountID); + g_free(c->_srtp_cipher); + g_free(c->_sas); + g_free(c->_peer_name); + g_free(c->_peer_number); + g_free(c->_trsft_to); + g_free(c->_peer_info); + g_free(c->_recordfile); + + g_free(c); } -gchar* get_peer_info (const gchar* const number, const gchar* const name) +gchar* get_peer_info(const gchar* const number, const gchar* const name) { - return g_strconcat ("\"", name, "\" <", number, ">", NULL); + return g_strconcat("\"", name, "\" <", number, ">", NULL); } -gchar* get_call_duration (callable_obj_t *obj) +gchar* get_call_duration(callable_obj_t *obj) { - long duration = difftime (obj->_time_stop, obj->_time_start); + long duration = difftime(obj->_time_stop, obj->_time_start); + if (duration < 0) duration = 0; + return g_strdup_printf("<small>Duration:</small> %.2ld:%.2ld" , duration/60 , duration%60); } -static const gchar* get_history_id_from_state (history_state_t state) +static const gchar* get_history_id_from_state(history_state_t state) { if (state >= LAST) return ""; + return state + "0"; } -gchar* serialize_history_call_entry (callable_obj_t *entry) +gchar* serialize_history_call_entry(callable_obj_t *entry) { // "0|514-276-5468|Savoir-faire Linux|144562458" for instance gchar *peer_number, *peer_name, *account_id; static const gchar * const separator = "|"; - gchar *time_start, *time_stop ; gchar *record_file; - gchar *confID , *time_added; + gchar *confID; // Need the string form for the history state - const gchar *history_state = get_history_id_from_state (entry->_history_state); + const gchar *history_state = get_history_id_from_state(entry->_history_state); // and the timestamps - time_start = g_strdup_printf ("%i", (int) entry->_time_start); - time_stop = g_strdup_printf ("%i", (int) entry->_time_stop); - time_added = g_strdup_printf ("%i", (int) entry->_time_added); + gchar *time_start = g_strdup_printf("%i", (int) entry->_time_start); + gchar *time_stop = g_strdup_printf("%i", (int) entry->_time_stop); + gchar *time_added = g_strdup_printf("%i", (int) entry->_time_added); peer_number = entry->_peer_number ? entry->_peer_number : ""; peer_name = (entry->_peer_name && *entry->_peer_name) ? entry->_peer_name : "empty"; @@ -274,31 +306,33 @@ gchar* serialize_history_call_entry (callable_obj_t *entry) confID = entry->_historyConfID ? entry->_historyConfID : ""; record_file = entry->_recordfile ? entry->_recordfile : ""; - gchar *result = g_strconcat (history_state, separator, - entry->_peer_number, separator, - peer_name, separator, - time_start, separator, - time_stop, separator, - entry->_callID, separator, - account_id, separator, - record_file, separator, - confID, separator, - time_added, NULL); + gchar *result = g_strconcat(history_state, separator, + peer_number, separator, + peer_name, separator, + time_start, separator, + time_stop, separator, + entry->_callID, separator, + account_id, separator, + record_file, separator, + confID, separator, + time_added, NULL); g_free(time_start); g_free(time_stop); g_free(time_added); return result; } -gchar *get_formatted_start_timestamp (time_t start) +gchar *get_formatted_start_timestamp(time_t start) { - time_t now = time (NULL); + time_t now = time(NULL); struct tm start_tm; - localtime_r (&start, &start_tm); + localtime_r(&start, &start_tm); time_t diff = now - start; + if (diff < 0) diff = 0; + const char *fmt; if (diff < 60 * 60 * 24 * 7) { // less than 1 week @@ -317,5 +351,5 @@ gchar *get_formatted_start_timestamp (time_t start) char str[100]; strftime(str, sizeof str, fmt, &start_tm); - return g_markup_printf_escaped ("%s\n", str); + return g_markup_printf_escaped("%s\n", str); } diff --git a/gnome/src/callable_obj.h b/gnome/src/callable_obj.h index 97c1d75d7711fdb7a26950c42b13a9ce325defab..2f81d683e7e372360487cd75e7ecf2201c066702 100644 --- a/gnome/src/callable_obj.h +++ b/gnome/src/callable_obj.h @@ -31,10 +31,9 @@ #ifndef __CALLABLE_OBJ_H__ #define __CALLABLE_OBJ_H__ -#include <gtk/gtk.h> -#include <glib/gprintf.h> #include <stdlib.h> #include <time.h> +#include <gtk/gtk.h> /** * @enum history_state @@ -98,7 +97,6 @@ typedef enum { * This struct holds information about a call. */ typedef struct { - callable_type_t _type; // CALL - HISTORY ENTRY - CONTACT call_state_t _state; // The state of the call int _state_code; // The numeric state code as defined in SIP or IAX @@ -200,8 +198,7 @@ gchar* call_get_peer_name (const gchar*); */ gchar* call_get_peer_number (const gchar*); -void -free_callable_obj_t (callable_obj_t *c); +void free_callable_obj_t (callable_obj_t *c); gchar* get_peer_info (const gchar* const, const gchar* const); diff --git a/gnome/src/codeclist.c b/gnome/src/codeclist.c index e5570c8ae2fba97f750008fb1f5cbcaf2b3c4cf2..25b69d9c7f985cb326529a2bfe554ff0a3c7d850 100644 --- a/gnome/src/codeclist.c +++ b/gnome/src/codeclist.c @@ -28,8 +28,8 @@ * as that of the covered work. */ -#include <codeclist.h> - +#include "codeclist.h" +#include "logger.h" #include <string.h> #include <stdlib.h> #include <unistd.h> @@ -39,14 +39,14 @@ static GQueue * codecsCapabilities = NULL; gint -is_name_codecstruct (gconstpointer a, gconstpointer b) +is_name_codecstruct(gconstpointer a, gconstpointer b) { const codec_t *c = a; return !!g_strcmp0(c->name, (const gchar *) b); } static gint -is_payload_codecstruct (gconstpointer a, gconstpointer b) +is_payload_codecstruct(gconstpointer a, gconstpointer b) { const codec_t *c = a; return (c->_payload == GPOINTER_TO_INT(b)) ? 0 : 1; @@ -54,13 +54,13 @@ is_payload_codecstruct (gconstpointer a, gconstpointer b) static codec_t *codec_create_new(gint payload) { - gchar **specs = dbus_audio_codec_details (payload); + gchar **specs = dbus_audio_codec_details(payload); - codec_t *codec = g_new0 (codec_t, 1); + codec_t *codec = g_new0(codec_t, 1); codec->_payload = payload; codec->name = strdup(specs[0]); - codec->sample_rate = atoi (specs[1]); - codec->_bitrate = atoi (specs[2]); + codec->sample_rate = atoi(specs[1]); + codec->_bitrate = atoi(specs[2]); codec->is_active = TRUE; g_strfreev(specs); @@ -69,37 +69,37 @@ static codec_t *codec_create_new(gint payload) } -void codec_capabilities_load (void) +void codec_capabilities_load(void) { // Create the queue object that will contain the global list of audio codecs if (codecsCapabilities != NULL) - g_queue_free (codecsCapabilities); + g_queue_free(codecsCapabilities); codecsCapabilities = g_queue_new(); // This is a global list inherited by all accounts - GArray *codecs = dbus_audio_codec_list (); + GArray *codecs = dbus_audio_codec_list(); // Add the codecs in the list for (guint i = 0; i < codecs->len; i++) { gint payload = g_array_index(codecs, gint, i); codec_t *c = codec_create_new(payload); - g_queue_push_tail (codecsCapabilities, (gpointer) c); + g_queue_push_tail(codecsCapabilities, (gpointer) c); } g_array_unref(codecs); // If we didn't load any codecs, problem ... - if (g_queue_get_length (codecsCapabilities) == 0) - ERROR ("No audio codecs found"); + if (g_queue_get_length(codecsCapabilities) == 0) + ERROR("No audio codecs found"); } -codec_t *codec_create_new_from_caps (codec_t *original) +codec_t *codec_create_new_from_caps(codec_t *original) { codec_t *codec = NULL; if (original) { - codec = g_new0 (codec_t, 1); + codec = g_new0(codec_t, 1); codec->_payload = original->_payload; codec->name = original->name; codec->sample_rate = original->sample_rate; @@ -111,147 +111,148 @@ codec_t *codec_create_new_from_caps (codec_t *original) } -void codec_list_clear (GQueue **queue) +void codec_list_clear(GQueue **queue) { if (*queue != NULL) - g_queue_free (*queue); + g_queue_free(*queue); + *queue = g_queue_new(); } -void codec_list_add (codec_t * c, GQueue **queue) +void codec_list_add(codec_t * c, GQueue **queue) { // Add a codec to a specific list - g_queue_push_tail (*queue, (gpointer) c); + g_queue_push_tail(*queue, (gpointer) c); } -void codec_set_active (codec_t *c, gboolean active) +void codec_set_active(codec_t *c, gboolean active) { c->is_active = active; } -guint codec_list_get_size () +guint codec_list_get_size() { // The system wide codec list and the one per account have exactly the same size // The only difference may be the order and the enabled codecs - return g_queue_get_length (codecsCapabilities); + return g_queue_get_length(codecsCapabilities); } -codec_t* codec_list_get_by_name (gconstpointer name, GQueue *q) +codec_t* codec_list_get_by_name(gconstpointer name, GQueue *q) { // If NULL is passed as argument, we look into the global capabilities if (q == NULL) q = codecsCapabilities; - GList * c = g_queue_find_custom (q, name, is_name_codecstruct); + GList * c = g_queue_find_custom(q, name, is_name_codecstruct); return c ? c->data : NULL; } -codec_t* codec_list_get_by_payload (gconstpointer payload, GQueue *q) +codec_t* codec_list_get_by_payload(gconstpointer payload, GQueue *q) { // If NULL is passed as argument, we look into the global capabilities if (q == NULL) q = codecsCapabilities; - GList * c = g_queue_find_custom (q, payload, is_payload_codecstruct); + GList * c = g_queue_find_custom(q, payload, is_payload_codecstruct); return c ? c->data : NULL; } -codec_t* codec_list_get_nth (guint index, GQueue *q) +codec_t* codec_list_get_nth(guint codec_index, GQueue *q) { - return g_queue_peek_nth (q, index); + return g_queue_peek_nth(q, codec_index); } -codec_t* capabilities_get_nth (guint index) +codec_t* capabilities_get_nth(guint caps_index) { - return g_queue_peek_nth (codecsCapabilities, index); + return g_queue_peek_nth(codecsCapabilities, caps_index); } -void codec_set_prefered_order (guint index, GQueue *q) +void codec_set_prefered_order(guint codec_index, GQueue *q) { - codec_t * prefered = codec_list_get_nth (index, q); - g_queue_pop_nth (q, index); - g_queue_push_head (q, prefered); + codec_t * prefered = codec_list_get_nth(codec_index, q); + g_queue_pop_nth(q, codec_index); + g_queue_push_head(q, prefered); } -void codec_list_move_codec_up (guint index, GQueue **q) +void codec_list_move_codec_up(guint codec_index, GQueue **q) { - DEBUG ("Codec list Size: %i \n", codec_list_get_size ()); + DEBUG("Codec list Size: %i \n", codec_list_get_size()); GQueue *tmp = *q; - if (index != 0) { - gpointer codec = g_queue_pop_nth (tmp, index); - g_queue_push_nth (tmp, codec, index-1); + if (codec_index != 0) { + gpointer codec = g_queue_pop_nth(tmp, codec_index); + g_queue_push_nth(tmp, codec, codec_index - 1); } *q = tmp; } -void codec_list_move_codec_down (guint index, GQueue **q) +void codec_list_move_codec_down(guint codec_index, GQueue **q) { - DEBUG ("Codec list Size: %i \n", codec_list_get_size()); + DEBUG("Codec list Size: %i \n", codec_list_get_size()); GQueue *tmp = *q; - if (index != g_queue_get_length(tmp) ) { - gpointer codec = g_queue_pop_nth (tmp, index); - g_queue_push_nth (tmp, codec, index+1); + if (codec_index != g_queue_get_length(tmp)) { + gpointer codec = g_queue_pop_nth(tmp, codec_index); + g_queue_push_nth(tmp, codec, codec_index + 1); } *q = tmp; } -void codec_list_update_to_daemon (account_t *acc) +void codec_list_update_to_daemon(account_t *acc) { // Length of the codec list int length = g_queue_get_length(acc->codecs); // String listing codecs payloads // Initiate double array char list for one string - const gchar **codecList = (void*) g_malloc (sizeof (void*)); + const gchar **codecList = (void*) g_malloc(sizeof(void*)); // Get all codecs in queue int c = 0; int i; for (i = 0; i < length; i++) { - codec_t* currentCodec = codec_list_get_nth (i, acc->codecs); + codec_t* currentCodec = codec_list_get_nth(i, acc->codecs); if (currentCodec) { // Save only if active if (currentCodec->is_active) { // Reallocate memory each time more than one active codec is found if (c != 0) - codecList = (void*) g_realloc (codecList, (c + 1) * sizeof (void*)); + codecList = (void*) g_realloc(codecList, (c + 1) * sizeof(void*)); // Allocate memory for the payload - * (codecList + c) = (gchar*) g_malloc (sizeof (gchar*)); + *(codecList + c) = (gchar*) g_malloc(sizeof(gchar*)); char payload[10]; // Put payload string in char array - sprintf (payload, "%d", currentCodec->_payload); - strcpy ( (char*) * (codecList+c), payload); + sprintf(payload, "%d", currentCodec->_payload); + strcpy((char*) *(codecList+c), payload); c++; } } } // Allocate NULL array at the end for Dbus - codecList = (void*) g_realloc (codecList, (c + 1) * sizeof (void*)); - * (codecList+c) = NULL; + codecList = (void*) g_realloc(codecList, (c + 1) * sizeof(void*)); + *(codecList+c) = NULL; // call dbus function with array of strings - dbus_set_active_audio_codec_list (codecList, acc->accountID); + dbus_set_active_audio_codec_list(codecList, acc->accountID); // Delete memory for (i = 0; i < c; i++) - g_free ( (gchar*) * (codecList+i)); + g_free((gchar*) *(codecList+i)); - g_free (codecList); + g_free(codecList); } -GQueue* get_system_codec_list (void) +GQueue* get_system_codec_list(void) { return codecsCapabilities; } diff --git a/gnome/src/codeclist.h b/gnome/src/codeclist.h index efb3a77415070aafc9b17f2d51a9c65f9ad594d3..242fd6eac553e909a190151f578b5c22d98bf074 100644 --- a/gnome/src/codeclist.h +++ b/gnome/src/codeclist.h @@ -32,7 +32,7 @@ #define __CODECLIST_H__ #include <gtk/gtk.h> -#include <accountlist.h> +#include "accountlist.h" /** @file codeclist.h * @brief A list to hold codecs. */ diff --git a/gnome/src/conference_obj.c b/gnome/src/conference_obj.c index 044491a562f46abc0ff3b79580424f4844f43f8c..f2bda66b51a3310be1f614408da839091b3e0221 100644 --- a/gnome/src/conference_obj.c +++ b/gnome/src/conference_obj.c @@ -31,24 +31,24 @@ #include <time.h> #include "callable_obj.h" +#include "dbus.h" #include "sflphone_const.h" - +#include "logger.h" #include "calltab.h" #include "calllist.h" -conference_obj_t *create_new_conference (conference_state_t state, const gchar* const confID) +conference_obj_t *create_new_conference(conference_state_t state, const gchar* const confID) { - conference_obj_t *new_conf; - if (confID == NULL) { ERROR("Conference: Error: Conference ID is NULL while creating new conference"); return NULL; } - DEBUG ("Conference: Create new conference %s", confID); + DEBUG("Conference: Create new conference %s", confID); // Allocate memory - new_conf = g_new0 (conference_obj_t, 1); + conference_obj_t *new_conf = g_new0(conference_obj_t, 1); + if (!new_conf) { ERROR("Conference: Error: Could not allocate data "); return NULL; @@ -58,13 +58,7 @@ conference_obj_t *create_new_conference (conference_state_t state, const gchar* new_conf->_state = state; // Set the ID field - new_conf->_confID = g_strdup (confID); - - new_conf->participant_list = NULL; - new_conf->participant_number = NULL; - - new_conf->_recordfile = NULL; - new_conf->_record_is_playing = FALSE; + new_conf->_confID = g_strdup(confID); // set conference timestamp time(&new_conf->_time_start); @@ -72,233 +66,108 @@ conference_obj_t *create_new_conference (conference_state_t state, const gchar* return new_conf; } -conference_obj_t *create_new_conference_from_details (const gchar *conf_id, GHashTable *details) +conference_obj_t *create_new_conference_from_details(const gchar *conf_id, GHashTable *details) { - conference_obj_t *new_conf = g_new0 (conference_obj_t, 1); - new_conf->_confID = g_strdup (conf_id); - - new_conf->_conference_secured = FALSE; - new_conf->_conf_srtp_enabled = FALSE; + conference_obj_t *new_conf = g_new0(conference_obj_t, 1); + new_conf->_confID = g_strdup(conf_id); - new_conf->participant_list = NULL; + gchar **participants = dbus_get_participant_list(conf_id); - gchar **participants = dbus_get_participant_list (conf_id); if (participants) { - conference_participant_list_update (participants, new_conf); + conference_participant_list_update(participants, new_conf); g_strfreev(participants); } - gchar *state_str = g_hash_table_lookup (details, "CONF_STATE"); + gchar *state_str = g_hash_table_lookup(details, "CONF_STATE"); - if (g_strcasecmp (state_str, "ACTIVE_ATACHED") == 0) - new_conf->_state = CONFERENCE_STATE_ACTIVE_ATACHED; - else if (g_strcasecmp (state_str, "ACTIVE_ATTACHED_REC") == 0) + if (g_strcasecmp(state_str, "ACTIVE_ATTACHED") == 0) + new_conf->_state = CONFERENCE_STATE_ACTIVE_ATTACHED; + else if (g_strcasecmp(state_str, "ACTIVE_ATTACHED_REC") == 0) new_conf->_state = CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD; - else if (g_strcasecmp (state_str, "ACTIVE_DETACHED") == 0) + else if (g_strcasecmp(state_str, "ACTIVE_DETACHED") == 0) new_conf->_state = CONFERENCE_STATE_ACTIVE_DETACHED; - else if (g_strcasecmp (state_str, "ACTIVE_DETACHED_REC") == 0) + else if (g_strcasecmp(state_str, "ACTIVE_DETACHED_REC") == 0) new_conf->_state = CONFERENCE_STATE_ACTIVE_DETACHED_RECORD; - else if (g_strcasecmp (state_str, "HOLD") == 0) + else if (g_strcasecmp(state_str, "HOLD") == 0) new_conf->_state = CONFERENCE_STATE_HOLD; - else if (g_strcasecmp (state_str, "HOLD_REC") == 0) + else if (g_strcasecmp(state_str, "HOLD_REC") == 0) new_conf->_state = CONFERENCE_STATE_HOLD_RECORD; - - new_conf->_recordfile = NULL; - new_conf->_record_is_playing = FALSE; - return new_conf; } void free_conference_obj_t (conference_obj_t *c) { - g_free (c->_confID); + g_free(c->_confID); if (c->participant_list) g_slist_free(c->participant_list); - g_free (c); + g_free(c); } static void conference_add_participant_number(const gchar *call_id, conference_obj_t *conf) { - callable_obj_t *call = calllist_get_call(current_calls, call_id); + callable_obj_t *call = calllist_get_call(current_calls_tab, call_id); + if (!call) { ERROR("Conference: Error: Could not find %s", call_id); return; } gchar *number_account = g_strconcat(call->_peer_number, ",", call->_accountID, NULL); - conf->participant_number = g_slist_append(conf->participant_number, number_account); } -void conference_add_participant (const gchar* call_id, conference_obj_t* conf) +void conference_add_participant(const gchar* call_id, conference_obj_t* conf) { DEBUG("Conference: Conference %s, adding participant %s", conf->_confID, call_id); // store the new participant list after appending participant id - conf->participant_list = g_slist_append (conf->participant_list, (gpointer) g_strdup(call_id)); + conf->participant_list = g_slist_append(conf->participant_list, (gpointer) g_strdup(call_id)); // store the phone number of this participant conference_add_participant_number(call_id, conf); } -void conference_remove_participant (const gchar* call_id, conference_obj_t* conf) +void conference_remove_participant(const gchar* call_id, conference_obj_t* conf) { // store the new participant list after removing participant id - conf->participant_list = g_slist_remove (conf->participant_list, (gconstpointer) call_id); + conf->participant_list = g_slist_remove(conf->participant_list, (gconstpointer) call_id); } -GSList* conference_next_participant (GSList* participant) +void conference_participant_list_update(gchar** participants, conference_obj_t* conf) { - return g_slist_next (participant); -} - - -void conference_participant_list_update (gchar** participants, conference_obj_t* conf) -{ - gchar* call_id; - gchar** part; - callable_obj_t *call; - - DEBUG ("Conference: Participant list update"); + DEBUG("Conference: Participant list update"); if (!conf) { - ERROR("Conference: Error: Conference is NULL"); + ERROR("Conference: Error: Conference is NULL"); return; } - for (part = participants; *part; part++) { - call_id = (gchar *) (*part); - call = calllist_get_call(current_calls, call_id); - if(call->_confID != NULL) { + for (gchar **part = participants; part && *part; ++part) { + gchar *call_id = (gchar *) (*part); + callable_obj_t *call = calllist_get_call(current_calls_tab, call_id); + + if (call->_confID != NULL) { g_free(call->_confID); call->_confID = NULL; } } if (conf->participant_list) { - g_slist_free (conf->participant_list); + g_slist_free(conf->participant_list); conf->participant_list = NULL; } - for (part = participants; *part; part++) { - call_id = (gchar*) (*part); - call = calllist_get_call(current_calls, call_id); + for (gchar **part = participants; part && *part; ++part) { + gchar *call_id = (gchar *) (*part); + callable_obj_t *call = calllist_get_call(current_calls_tab, call_id); call->_confID = g_strdup(conf->_confID); - conference_add_participant (call_id, conf); + conference_add_participant(call_id, conf); } } -gchar *serialize_history_conference_entry(conference_obj_t *entry) -{ - gchar *result = ""; - static const gchar * const separator = "|"; - gchar *time_start = ""; - gchar *time_stop = ""; - gchar *peer_name = ""; - gchar *participantstr = ""; - gchar *confID = ""; - GSList *participant_list; - gint length = 0; - gint i; - - confID = entry->_confID; - - time_start = g_strdup_printf ("%i", (int) entry->_time_start); - time_stop = g_strdup_printf ("%i", (int) entry->_time_stop); - - peer_name = (entry->_confID == NULL || g_strcasecmp(entry->_confID, "") == 0) ? "empty": entry->_confID; - - length = g_slist_length(entry->participant_list); - participant_list = entry->participant_list; - - for(i = 0; i < length; i++) { - const gchar * const tmp = g_slist_nth_data(participant_list, i); - if (!tmp) - WARN("Conference: Peer number is NULL in conference list"); - participantstr = g_strconcat(participantstr, tmp, ";", NULL); - - DEBUG("Conference: Participant number: %s, concatenation: %s", tmp, participantstr); - } - - result = g_strconcat("9999", separator, - participantstr, separator, // peer number - peer_name, separator, - time_start, separator, - time_stop, separator, - confID, separator, - "empty", separator, // peer AccountID - entry->_recordfile ? entry->_recordfile : "", separator, - "empty", separator, - "empty", NULL); - - return result; -} - -conference_obj_t *create_conference_history_entry_from_serialized(gchar *entry) -{ - history_state_t history_state = MISSED; - conference_state_t state = CONFERENCE_STATE_ACTIVE_ATACHED; - const gchar *participant = NULL; - const gchar *name = NULL; - const gchar *time_start = NULL; - const gchar *time_stop = NULL; - const gchar *accountID = NULL; - const gchar *recordfile = NULL; - const gchar *confID = NULL; - - DEBUG("Conference: Create a conference from serialized form"); - - static const gchar * const delim = "|"; - gchar **ptr = g_strsplit(entry, delim, 10); - gint token = 0; - while (ptr && token < 10) { - switch (token) { - case 0: - history_state = MISSED; - break; - case 1: - participant = *ptr; - break; - case 2: - name = *ptr; - break; - case 3: - time_start = *ptr; - break; - case 4: - time_stop = *ptr; - break; - case 5: - confID = *ptr; - break; - case 6: - accountID = *ptr; - break; - case 7: - recordfile = *ptr; - break; - case 8: - case 9: - default: - break; - } - - token++; - ptr++; - } - - // create a new empty conference - conference_obj_t *conf = create_new_conference(state, confID); - - conf->_time_start = atoi(time_start); - conf->_time_stop = atoi(time_stop); - conf->_recordfile = g_strdup(recordfile); - - return conf; -} diff --git a/gnome/src/conference_obj.h b/gnome/src/conference_obj.h index ed0188f94b24d13b661cf14d168189b4f21585f5..e7f0e3a57cb6c92257a702c24da0ee3ac68876c4 100644 --- a/gnome/src/conference_obj.h +++ b/gnome/src/conference_obj.h @@ -36,13 +36,11 @@ #include <stdlib.h> #include <time.h> - - /** @enum conference_state_t * This enum have all the states a conference can take. */ typedef enum { - CONFERENCE_STATE_ACTIVE_ATACHED = 0, + CONFERENCE_STATE_ACTIVE_ATTACHED = 0, CONFERENCE_STATE_ACTIVE_DETACHED, CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD, CONFERENCE_STATE_ACTIVE_DETACHED_RECORD, @@ -65,7 +63,6 @@ typedef struct { GtkWidget *_im_widget; // associated instant messaging widget time_t _time_start; time_t _time_stop; - time_t _time_current; gchar *_recordfile; gboolean _record_is_playing; } conference_obj_t; @@ -80,12 +77,6 @@ void conference_add_participant (const gchar*, conference_obj_t *); void conference_remove_participant (const gchar*, conference_obj_t *); -GSList* conference_next_participant (GSList* participant); - void conference_participant_list_update (gchar**, conference_obj_t*); -gchar *serialize_history_conference_entry(conference_obj_t *entry); - -conference_obj_t *create_conference_history_entry_from_serialized(gchar *); - #endif diff --git a/gnome/src/config/Makefile.am b/gnome/src/config/Makefile.am index cb21b3a015d69fc503774da9cfe8fca71bd0b8f6..7fc8210f5fe8b3b34c7a512923f1835037dcdf6f 100644 --- a/gnome/src/config/Makefile.am +++ b/gnome/src/config/Makefile.am @@ -26,14 +26,11 @@ libconfig_la_SOURCES = \ utils.h \ zrtpadvanceddialog.h -libconfig_la_LDFLAGS = $(DBUSGLIB_LDFLAGS) $(LIBNOTIFY_LDFLAGS) \ - $(GTK_LDFLAGS) $(GLIB_LDFLAGS) $(WEBKIT_LDFLAGS) $(LIBGNOMEUI_LDFLAGS) \ - $(GNOMEDOCUTILS_LDFLAGS) +libconfig_la_LDFLAGS = $(DBUSGLIB_LDFLAGS) $(LIBNOTIFY_LDFLAGS) $(GCONF_LDFLAGS) \ + $(GTK_LDFLAGS) $(GLIB_LDFLAGS) $(WEBKIT_LDFLAGS) -libconfig_la_LIBADD = $(DBUSGLIB_LIBS) $(LIBNOTIFY_LIBSI) \ - $(GTK_LIBS) $(GLIB_LIBS) $(WEBKIT_LIBS) $(LIBGNOMEUI_LIBS) \ - $(GNOMEDOCUTILS_LIBS) +libconfig_la_LIBADD = $(DBUSGLIB_LIBS) $(LIBNOTIFY_LIBS) $(GCONF_LIBS) \ + $(GTK_LIBS) $(GLIB_LIBS) $(WEBKIT_LIBS) -libconfig_la_CFLAGS = $(DBUSGLIB_CFLAGS) $(LIBNOTIFY_CFLAGS) \ - $(GTK_CFLAGS) $(GLIB_CFLAGS) $(WEBKIT_CFLAGS) $(LIBGNOMEUI_CFLAGS) \ - $(GNOMEDOCUTILS_CFLAGS) +libconfig_la_CFLAGS = $(DBUSGLIB_CFLAGS) $(LIBNOTIFY_CFLAGS) $(GCONF_CFLAGS) \ + $(GTK_CFLAGS) $(GLIB_CFLAGS) $(WEBKIT_CFLAGS) diff --git a/gnome/src/config/accountconfigdialog.c b/gnome/src/config/accountconfigdialog.c index a1d6d1f9cfffce077c896a2c3d0550f9b171180e..ef55ea27cdb81afe93b780576a42d3f60aeb9af0 100644 --- a/gnome/src/config/accountconfigdialog.c +++ b/gnome/src/config/accountconfigdialog.c @@ -31,25 +31,25 @@ * as that of the covered work. */ -#include "actions.h" -#include "mainwindow.h" -#include "accountlist.h" -#include "audioconf.h" -#include "accountconfigdialog.h" -#include "zrtpadvanceddialog.h" -#include "tlsadvanceddialog.h" -#include "audioconf.h" - #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if.h> #include <netinet/in.h> #include <string.h> -#include <dbus/dbus.h> -#include <config.h> #include <gtk/gtk.h> +#include "config.h" +#include "logger.h" +#include "actions.h" +#include "mainwindow.h" +#include "accountlist.h" +#include "audioconf.h" +#include "accountconfigdialog.h" +#include "zrtpadvanceddialog.h" +#include "tlsadvanceddialog.h" +#include "dbus/dbus.h" #include "utils.h" +#include "unused.h" /** * TODO: tidy this up @@ -57,9 +57,6 @@ * in a private structure. * Local variables */ -static GtkDialog * dialog; -static GtkWidget * hbox; -static GtkWidget * label; static GtkWidget * entryAlias; static GtkWidget * protocolComboBox; static GtkWidget * entryUsername; @@ -132,7 +129,7 @@ static void show_password_cb(GtkWidget *widget UNUSED, gpointer data) /* Signal to protocolComboBox 'changed' */ void change_protocol_cb(account_t *currentAccount UNUSED) { - gchar *protocol = gtk_combo_box_get_active_text(GTK_COMBO_BOX(protocolComboBox)); + gchar *protocol = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(protocolComboBox)); // Only if tabs are not NULL if (security_tab && advanced_tab) { @@ -144,6 +141,7 @@ void change_protocol_cb(account_t *currentAccount UNUSED) gtk_widget_show(advanced_tab); } } + g_free(protocol); } @@ -163,18 +161,19 @@ static GPtrArray* getNewCredential(void) GPtrArray *credential_array = g_ptr_array_new(); gboolean valid; + for (valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(credentialStore), &iter) ; - valid; - valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(credentialStore), &iter)) { + valid; + valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(credentialStore), &iter)) { gchar *username; gchar *realm; gchar *password; gtk_tree_model_get(GTK_TREE_MODEL(credentialStore), &iter, - COLUMN_CREDENTIAL_REALM, &realm, - COLUMN_CREDENTIAL_USERNAME, &username, - COLUMN_CREDENTIAL_PASSWORD, &password, - -1); + COLUMN_CREDENTIAL_REALM, &realm, + COLUMN_CREDENTIAL_USERNAME, &username, + COLUMN_CREDENTIAL_PASSWORD, &password, + -1); DEBUG("Row %d: %s %s %s", row_count++, username, password, realm); @@ -192,6 +191,7 @@ static GPtrArray* getNewCredential(void) static void update_credential_cb(GtkWidget *widget, gpointer data UNUSED) { GtkTreeIter iter; + if (credentialStore && gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(credentialStore), &iter, "0")) { gint column = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "column")); gtk_list_store_set(GTK_LIST_STORE(credentialStore), &iter, column,(gchar *) gtk_entry_get_text(GTK_ENTRY(widget)), -1); @@ -200,14 +200,7 @@ static void update_credential_cb(GtkWidget *widget, gpointer data UNUSED) static GtkWidget* create_basic_tab(account_t *currentAccount) { - GtkWidget * frame; - GtkWidget * table; - GtkWidget * clearTextCheckbox; - - int row = 0; - g_assert(currentAccount); - DEBUG("Config: Create basic account tab"); // Load from SIP/IAX/Unknown ? gchar *curAccountType = g_hash_table_lookup(currentAccount->properties, ACCOUNT_TYPE); @@ -218,13 +211,14 @@ static GtkWidget* create_basic_tab(account_t *currentAccount) gchar *curUseragent; gchar *curRouteSet; gchar *curMailbox; + if (g_strcmp0(curAccountType, "SIP") == 0) { - /* get password from credentials list */ - if (currentAccount->credential_information) { - GHashTable * element = g_ptr_array_index(currentAccount->credential_information, 0); - curPassword = g_hash_table_lookup(element, ACCOUNT_PASSWORD); - } else - curPassword = ""; + /* get password from credentials list */ + if (currentAccount->credential_information) { + GHashTable * element = g_ptr_array_index(currentAccount->credential_information, 0); + curPassword = g_hash_table_lookup(element, ACCOUNT_PASSWORD); + } else + curPassword = ""; } else curPassword = g_hash_table_lookup(currentAccount->properties, ACCOUNT_PASSWORD); @@ -234,21 +228,28 @@ static GtkWidget* create_basic_tab(account_t *currentAccount) curMailbox = curMailbox != NULL ? curMailbox : ""; curUseragent = g_hash_table_lookup(currentAccount->properties, ACCOUNT_USERAGENT); - gnome_main_section_new(_("Account Parameters"), &frame); + GtkWidget *frame = gnome_main_section_new(_("Account Parameters")); gtk_widget_show(frame); + GtkWidget * table = NULL; + if (g_strcmp0(curAccountType, "SIP") == 0) table = gtk_table_new(9, 2, FALSE/* homogeneous */); else if (g_strcmp0(curAccountType, "IAX") == 0) table = gtk_table_new(8, 2, FALSE); + else { + ERROR("Unknown account type \"%s\"", curAccountType); + return NULL; + } gtk_table_set_row_spacings(GTK_TABLE(table), 10); gtk_table_set_col_spacings(GTK_TABLE(table), 10); gtk_widget_show(table); gtk_container_add(GTK_CONTAINER(frame) , table); - label = gtk_label_new_with_mnemonic(_("_Alias")); - gtk_table_attach(GTK_TABLE(table), label, 0, 1, row, row+1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + GtkWidget *label = gtk_label_new_with_mnemonic(_("_Alias")); + gint row = 0; + gtk_table_attach(GTK_TABLE(table), label, 0, 1, row, row + 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); entryAlias = gtk_entry_new(); gtk_label_set_mnemonic_widget(GTK_LABEL(label), entryAlias); @@ -259,12 +260,12 @@ static GtkWidget* create_basic_tab(account_t *currentAccount) label = gtk_label_new_with_mnemonic(_("_Protocol")); gtk_table_attach(GTK_TABLE(table), label, 0, 1, row, row+1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - protocolComboBox = gtk_combo_box_new_text(); + protocolComboBox = gtk_combo_box_text_new(); gtk_label_set_mnemonic_widget(GTK_LABEL(label), protocolComboBox); - gtk_combo_box_append_text(GTK_COMBO_BOX(protocolComboBox), "SIP"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(protocolComboBox), "SIP"); if (dbus_is_iax2_enabled()) - gtk_combo_box_append_text(GTK_COMBO_BOX(protocolComboBox), "IAX"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(protocolComboBox), "IAX"); if (g_strcmp0(curAccountType, "SIP") == 0) gtk_combo_box_set_active(GTK_COMBO_BOX(protocolComboBox),0); @@ -273,7 +274,7 @@ static GtkWidget* create_basic_tab(account_t *currentAccount) else { DEBUG("Config: Error: Account protocol not valid"); /* Should never come here, add debug message. */ - gtk_combo_box_append_text(GTK_COMBO_BOX(protocolComboBox), _("Unknown")); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(protocolComboBox), _("Unknown")); gtk_combo_box_set_active(GTK_COMBO_BOX(protocolComboBox), 2); } @@ -281,8 +282,8 @@ static GtkWidget* create_basic_tab(account_t *currentAccount) /* Link signal 'changed' */ g_signal_connect(G_OBJECT(GTK_COMBO_BOX(protocolComboBox)), "changed", - G_CALLBACK(change_protocol_cb), - currentAccount); + G_CALLBACK(change_protocol_cb), + currentAccount); row++; label = gtk_label_new_with_mnemonic(_("_Host name")); @@ -310,7 +311,7 @@ static GtkWidget* create_basic_tab(account_t *currentAccount) row++; label = gtk_label_new_with_mnemonic(_("_Password")); - gtk_table_attach(GTK_TABLE(table), label, 0, 1, row, row+1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, row, row + 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); entryPassword = gtk_entry_new(); gtk_entry_set_icon_from_stock(GTK_ENTRY(entryPassword), GTK_ENTRY_ICON_PRIMARY, GTK_STOCK_DIALOG_AUTHENTICATION); @@ -325,7 +326,7 @@ static GtkWidget* create_basic_tab(account_t *currentAccount) } row++; - clearTextCheckbox = gtk_check_button_new_with_mnemonic(_("Show password")); + GtkWidget *clearTextCheckbox = gtk_check_button_new_with_mnemonic(_("Show password")); g_signal_connect(clearTextCheckbox, "toggled", G_CALLBACK(show_password_cb), entryPassword); gtk_table_attach(GTK_TABLE(table), clearTextCheckbox, 1, 2, row, row+1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); @@ -362,7 +363,7 @@ static GtkWidget* create_basic_tab(account_t *currentAccount) return frame; } -static void fill_treeview_with_credential(GtkListStore * credentialStore, account_t * account) +static void fill_treeview_with_credential(account_t * account) { GtkTreeIter iter; gtk_list_store_clear(credentialStore); @@ -380,20 +381,21 @@ static void fill_treeview_with_credential(GtkListStore * credentialStore, accoun GHashTable * element = g_ptr_array_index(account->credential_information, i); gtk_list_store_append(credentialStore, &iter); gtk_list_store_set(credentialStore, &iter, - COLUMN_CREDENTIAL_REALM, g_hash_table_lookup(element, ACCOUNT_REALM), - COLUMN_CREDENTIAL_USERNAME, g_hash_table_lookup(element, ACCOUNT_USERNAME), - COLUMN_CREDENTIAL_PASSWORD, g_hash_table_lookup(element, ACCOUNT_PASSWORD), - COLUMN_CREDENTIAL_DATA, element, -1); + COLUMN_CREDENTIAL_REALM, g_hash_table_lookup(element, ACCOUNT_REALM), + COLUMN_CREDENTIAL_USERNAME, g_hash_table_lookup(element, ACCOUNT_USERNAME), + COLUMN_CREDENTIAL_PASSWORD, g_hash_table_lookup(element, ACCOUNT_PASSWORD), + COLUMN_CREDENTIAL_DATA, element, -1); } } static void select_credential_cb(GtkTreeSelection *selection, GtkTreeModel *model) { GtkTreeIter iter; + if (gtk_tree_selection_get_selected(selection, NULL, &iter)) { GtkTreePath *path = gtk_tree_model_get_path(model, &iter); - if (gtk_tree_path_get_indices(path) [0] == 0) + if (gtk_tree_path_get_indices(path)[0] == 0) gtk_widget_set_sensitive(deleteCredButton, FALSE); else gtk_widget_set_sensitive(deleteCredButton, TRUE); @@ -439,7 +441,7 @@ static void cell_edited_cb(GtkCellRendererText *renderer, gchar *path_desc, gcha if ((g_strcasecmp(path_desc, "0") == 0) && g_strcasecmp(text, gtk_entry_get_text(GTK_ENTRY(entryUsername))) != 0) - g_signal_handlers_disconnect_by_func(G_OBJECT(entryUsername), G_CALLBACK(update_credential_cb), NULL); + g_signal_handlers_disconnect_by_func(G_OBJECT(entryUsername), G_CALLBACK(update_credential_cb), NULL); GtkTreeIter iter; gtk_tree_model_get_iter(model, &iter, path); @@ -459,7 +461,8 @@ static void editing_started_cb(GtkCellRenderer *cell UNUSED, GtkCellEditable * e static void show_advanced_zrtp_options_cb(GtkWidget *widget UNUSED, gpointer data) { - gchar *proto = gtk_combo_box_get_active_text(GTK_COMBO_BOX(keyExchangeCombo)); + gchar *proto = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(keyExchangeCombo)); + if (g_strcasecmp(proto, "ZRTP") == 0) show_advanced_zrtp_options((GHashTable *) data); else @@ -476,7 +479,7 @@ static void show_advanced_tls_options_cb(GtkWidget *widget UNUSED, gpointer data static void key_exchange_changed_cb(GtkWidget *widget UNUSED, gpointer data UNUSED) { - gchar *active_text = gtk_combo_box_get_active_text(GTK_COMBO_BOX(keyExchangeCombo)); + gchar *active_text = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(keyExchangeCombo)); DEBUG("Key exchange changed %s", active_text); gboolean set_sensitive = FALSE; @@ -538,17 +541,18 @@ get_interface_addr_from_name(const gchar * const iface_name) #define UC(b) (((int)b)&0xff) int fd; - if ((fd = socket (AF_INET, SOCK_DGRAM,0)) < 0) - DEBUG ("getInterfaceAddrFromName error could not open socket\n"); + + if ((fd = socket(AF_INET, SOCK_DGRAM,0)) < 0) + DEBUG("getInterfaceAddrFromName error could not open socket\n"); struct ifreq ifr; - memset(&ifr, 0, sizeof (struct ifreq)); + memset(&ifr, 0, sizeof(struct ifreq)); - strcpy (ifr.ifr_name, iface_name); + strcpy(ifr.ifr_name, iface_name); ifr.ifr_addr.sa_family = AF_INET; - if ( ioctl (fd, SIOCGIFADDR, &ifr) < 0) - DEBUG ("getInterfaceAddrFromName use default interface (0.0.0.0)\n"); + if (ioctl(fd, SIOCGIFADDR, &ifr) < 0) + DEBUG("getInterfaceAddrFromName use default interface (0.0.0.0)\n"); struct sockaddr_in *saddr_in = (struct sockaddr_in *) &ifr.ifr_addr; @@ -557,9 +561,9 @@ get_interface_addr_from_name(const gchar * const iface_name) char *tmp_addr = (char *) addr_in; gchar *iface_addr = g_strdup_printf("%d.%d.%d.%d", UC(tmp_addr[0]), - UC(tmp_addr[1]), UC(tmp_addr[2]), UC(tmp_addr[3])); + UC(tmp_addr[1]), UC(tmp_addr[2]), UC(tmp_addr[3])); - close (fd); + close(fd); return iface_addr; #undef UC } @@ -567,7 +571,7 @@ get_interface_addr_from_name(const gchar * const iface_name) static void local_interface_changed_cb(GtkWidget * widget UNUSED, gpointer data UNUSED) { if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(sameAsLocalRadioButton))) { - gchar *local_iface_name = gtk_combo_box_get_active_text(GTK_COMBO_BOX(localAddressCombo)); + gchar *local_iface_name = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(localAddressCombo)); gchar *local_iface_addr = get_interface_addr_from_name(local_iface_name); gtk_entry_set_text(GTK_ENTRY(localAddressEntry), local_iface_addr); @@ -629,7 +633,7 @@ static void use_stun_cb(GtkWidget *widget, gpointer data UNUSED) static void same_as_local_cb(GtkWidget * widget, gpointer data UNUSED) { if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget))) { - gchar *local_interface = gtk_combo_box_get_active_text(GTK_COMBO_BOX(localAddressCombo)); + gchar *local_interface = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(localAddressCombo)); gchar *local_address = dbus_get_address_from_interface_name(local_interface); gtk_entry_set_text(GTK_ENTRY(publishedAddressEntry), local_address); @@ -661,11 +665,11 @@ GtkWidget* create_credential_widget(account_t *a) gtk_table_attach_defaults(GTK_TABLE(table), scrolledWindowCredential, 0, 1, 0, 1); credentialStore = gtk_list_store_new(COLUMN_CREDENTIAL_COUNT, - G_TYPE_STRING, // Realm - G_TYPE_STRING, // Username - G_TYPE_STRING, // Password - G_TYPE_POINTER // Pointer to the Objectc - ); + G_TYPE_STRING, // Realm + G_TYPE_STRING, // Username + G_TYPE_STRING, // Password + G_TYPE_POINTER // Pointer to the Objectc + ); treeViewCredential = gtk_tree_view_new_with_model(GTK_TREE_MODEL(credentialStore)); treeSelection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeViewCredential)); @@ -704,10 +708,10 @@ GtkWidget* create_credential_widget(account_t *a) gtk_container_add(GTK_CONTAINER(scrolledWindowCredential), treeViewCredential); - fill_treeview_with_credential(credentialStore, a); + fill_treeview_with_credential(a); /* Credential Buttons */ - hbox = gtk_hbox_new(FALSE, 10); + GtkWidget *hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10); gtk_table_attach_defaults(GTK_TABLE(table), hbox, 0, 3, 1, 2); addButton = gtk_button_new_from_stock(GTK_STOCK_ADD); @@ -719,13 +723,7 @@ GtkWidget* create_credential_widget(account_t *a) gtk_box_pack_start(GTK_BOX(hbox), deleteCredButton, FALSE, FALSE, 0); /* Dynamically resize the window to fit the scrolled window */ - GtkRequisition requisitionTable; - GtkRequisition requisitionTreeView; - gtk_widget_size_request(treeViewCredential, &requisitionTreeView); - gtk_widget_size_request(table, &requisitionTable); gtk_widget_set_size_request(scrolledWindowCredential, 400, 120); - // same_as_local_cb(sameAsLocalRadioButton, NULL); - // set_published_addr_manually_cb(publishedAddrRadioButton, NULL); return frame; } @@ -741,21 +739,18 @@ GtkWidget* create_security_widget(account_t *a) if (a) { curKeyExchange = g_hash_table_lookup(a->properties, ACCOUNT_KEY_EXCHANGE); - if (curKeyExchange == NULL) { + if (curKeyExchange == NULL) curKeyExchange = "none"; - } curSRTPEnabled = g_hash_table_lookup(a->properties, ACCOUNT_SRTP_ENABLED); - if (curSRTPEnabled == NULL) { + if (curSRTPEnabled == NULL) curSRTPEnabled = "false"; - } curTLSEnabled = g_hash_table_lookup(a->properties, TLS_ENABLE); - if (curTLSEnabled == NULL) { + if (curTLSEnabled == NULL) curTLSEnabled = "false"; - } } gnome_main_section_new_with_table(_("Security"), &frame, &table, 2, 3); @@ -777,11 +772,11 @@ GtkWidget* create_security_widget(account_t *a) /* ZRTP subsection */ label = gtk_label_new_with_mnemonic(_("SRTP key exchange")); gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - keyExchangeCombo = gtk_combo_box_new_text(); + keyExchangeCombo = gtk_combo_box_text_new(); gtk_label_set_mnemonic_widget(GTK_LABEL(label), keyExchangeCombo); - gtk_combo_box_append_text(GTK_COMBO_BOX(keyExchangeCombo), "ZRTP"); - gtk_combo_box_append_text(GTK_COMBO_BOX(keyExchangeCombo), "SDES"); - gtk_combo_box_append_text(GTK_COMBO_BOX(keyExchangeCombo), _("Disabled")); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(keyExchangeCombo), "ZRTP"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(keyExchangeCombo), "SDES"); + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(keyExchangeCombo), _("Disabled")); advancedZrtpButton = gtk_button_new_from_stock(GTK_STOCK_PREFERENCES); g_signal_connect(G_OBJECT(advancedZrtpButton), "clicked", G_CALLBACK(show_advanced_zrtp_options_cb),a->properties); @@ -790,11 +785,11 @@ GtkWidget* create_security_widget(account_t *a) gtk_combo_box_set_active(GTK_COMBO_BOX(keyExchangeCombo), 2); gtk_widget_set_sensitive(advancedZrtpButton, FALSE); } else { - if (g_strcmp0(curKeyExchange, ZRTP) == 0) { + if (g_strcmp0(curKeyExchange, ZRTP) == 0) gtk_combo_box_set_active(GTK_COMBO_BOX(keyExchangeCombo),0); - } else if (g_strcmp0(curKeyExchange, SDES) == 0) { + else if (g_strcmp0(curKeyExchange, SDES) == 0) gtk_combo_box_set_active(GTK_COMBO_BOX(keyExchangeCombo),1); - } else { + else { gtk_combo_box_set_active(GTK_COMBO_BOX(keyExchangeCombo), 2); gtk_widget_set_sensitive(advancedZrtpButton, FALSE); } @@ -817,7 +812,7 @@ GtkWidget * create_security_tab(account_t *a) GtkWidget * frame; GtkWidget * ret; - ret = gtk_vbox_new(FALSE, 10); + ret = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); gtk_container_set_border_width(GTK_CONTAINER(ret), 10); // Credentials frame @@ -860,7 +855,7 @@ static GtkWidget* create_registration_expire(account_t *a) entryResolveNameOnlyOnce = gtk_check_button_new_with_mnemonic(_("_Comply with RFC 3263")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(entryResolveNameOnlyOnce), - g_strcasecmp(resolve_once,"false") == 0 ? TRUE: FALSE); + g_strcasecmp(resolve_once,"false") == 0 ? TRUE: FALSE); gtk_table_attach_defaults(GTK_TABLE(table), entryResolveNameOnlyOnce, 0, 2, 1, 2); gtk_widget_set_sensitive(entryResolveNameOnlyOnce , TRUE); @@ -886,62 +881,32 @@ GtkWidget* create_network(account_t *a) * Retreive the list of IP interface from the * the daemon and build the combo box. */ + localAddressCombo = gtk_combo_box_text_new(); - GtkListStore * ipInterfaceListStore; - GtkTreeIter iter; - ipInterfaceListStore = gtk_list_store_new(1, G_TYPE_STRING); label = gtk_label_new_with_mnemonic(_("Local address")); gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - GtkTreeIter current_local_iface_iter = iter; - gchar ** iface_list = NULL; - // iface_list =(gchar**) dbus_get_all_ip_interface(); - iface_list =(gchar**) dbus_get_all_ip_interface_by_name(); - gchar ** iface = NULL; - - // flag to determine if local_address is found - gboolean iface_found = FALSE; - - if (iface_list != NULL) { - // fill the iterface combo box - for (iface = iface_list; *iface; iface++) { - DEBUG("Interface %s", *iface); - gtk_list_store_append(ipInterfaceListStore, &iter); - gtk_list_store_set(ipInterfaceListStore, &iter, 0, *iface, -1); - - // set the current local address - if (!iface_found &&(g_strcmp0(*iface, local_interface) == 0)) { - DEBUG("Setting active local address combo box"); - current_local_iface_iter = iter; - iface_found = TRUE; - } - } + gchar **iface_list = dbus_get_all_ip_interface_by_name(); - if (!iface_found) { - DEBUG("Did not find local ip address, take fisrt in the list"); - gtk_tree_model_get_iter_first(GTK_TREE_MODEL(ipInterfaceListStore), ¤t_local_iface_iter); - } + int idx = 0; + for (gchar **iface = iface_list; iface && *iface; iface++, idx++) { + + gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(localAddressCombo), NULL, *iface); + if (g_strcmp0(*iface, local_interface) == 0) + gtk_combo_box_set_active(GTK_COMBO_BOX(localAddressCombo), idx); } + if (!local_interface) + gtk_combo_box_set_active(GTK_COMBO_BOX(localAddressCombo), 0); + - localAddressCombo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(ipInterfaceListStore)); gtk_label_set_mnemonic_widget(GTK_LABEL(label), localAddressCombo); gtk_table_attach(GTK_TABLE(table), localAddressCombo, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - g_object_unref(G_OBJECT(ipInterfaceListStore)); - - - GtkCellRenderer * ipInterfaceCellRenderer; - ipInterfaceCellRenderer = gtk_cell_renderer_text_new(); - - gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(localAddressCombo), ipInterfaceCellRenderer, TRUE); - gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(localAddressCombo), ipInterfaceCellRenderer, "text", 0, NULL); - gtk_combo_box_set_active_iter(GTK_COMBO_BOX(localAddressCombo), ¤t_local_iface_iter); - // Fill the text entry with the ip address of local interface selected localAddressEntry = gtk_entry_new(); - gchar *local_iface_name = gtk_combo_box_get_active_text(GTK_COMBO_BOX(localAddressCombo)); + gchar *local_iface_name = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(localAddressCombo)); gchar *local_iface_addr = get_interface_addr_from_name(local_iface_name); g_free(local_iface_name); gtk_entry_set_text(GTK_ENTRY(localAddressEntry), local_iface_addr); @@ -1000,9 +965,9 @@ GtkWidget* create_published_address(account_t *a) gtk_table_attach_defaults(GTK_TABLE(table), useStunCheckBox, 0, 1, 0, 1); g_signal_connect(useStunCheckBox, "toggled", G_CALLBACK(use_stun_cb), a); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(useStunCheckBox), - g_strcasecmp(stun_enable, "true") == 0 ? TRUE: FALSE); + g_strcasecmp(stun_enable, "true") == 0 ? TRUE: FALSE); gtk_widget_set_sensitive(useStunCheckBox, - g_strcasecmp(use_tls, "true") == 0 ? FALSE: TRUE); + g_strcasecmp(use_tls, "true") == 0 ? FALSE: TRUE); stunServerLabel = gtk_label_new_with_mnemonic(_("STUN server URL")); gtk_table_attach_defaults(GTK_TABLE(table), stunServerLabel, 0, 1, 1, 2); @@ -1063,86 +1028,84 @@ GtkWidget* create_advanced_tab(account_t *a) // Build the advanced tab, to appear on the account configuration panel DEBUG("Config: Build advanced tab"); - GtkWidget *ret, *frame; + GtkWidget *vbox, *frame; - ret = gtk_vbox_new(FALSE, 10); - gtk_container_set_border_width(GTK_CONTAINER(ret), 10); + vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); + + gtk_container_set_border_width(GTK_CONTAINER(vbox), 10); frame = create_registration_expire(a); - gtk_box_pack_start(GTK_BOX(ret), frame, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 0); frame = create_network(a); - gtk_box_pack_start(GTK_BOX(ret), frame, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 0); frame = create_published_address(a); - gtk_box_pack_start(GTK_BOX(ret), frame, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 0); - gtk_widget_show_all(ret); + gtk_widget_show_all(vbox); use_stun_cb(useStunCheckBox, NULL); set_published_addr_manually_cb(publishedAddrRadioButton, NULL); - return ret; + return vbox; } -void ringtone_enabled(GtkWidget *widget UNUSED, gpointer fileChooser, const gchar *accountID UNUSED) +void ringtone_enabled(GtkWidget *widget UNUSED, gpointer data, const gchar *accountID UNUSED) { /* toggle sensitivity */ - gtk_widget_set_sensitive(fileChooser, !gtk_widget_is_sensitive(fileChooser)); + gtk_widget_set_sensitive(data, !gtk_widget_is_sensitive(data)); } static GtkWidget* create_audiocodecs_configuration(account_t *currentAccount) { - // Main widget - GtkWidget *ret, *audiocodecs, *dtmf, *box, *frame, *sipinfo, *table; - gchar *currentDtmfType = ""; - gboolean dtmf_are_rtp = TRUE; - gpointer p; - - ret = gtk_vbox_new(FALSE, 10); - gtk_container_set_border_width(GTK_CONTAINER(ret), 10); + GtkWidget *vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); + gtk_container_set_border_width(GTK_CONTAINER(vbox), 10); - box = audiocodecs_box(currentAccount); + GtkWidget *box = audiocodecs_box(currentAccount); // Box for the audiocodecs - gnome_main_section_new(_("Audio"), &audiocodecs); - gtk_box_pack_start(GTK_BOX(ret), audiocodecs, FALSE, FALSE, 0); + GtkWidget *audiocodecs = gnome_main_section_new(_("Audio")); + gtk_box_pack_start(GTK_BOX(vbox), audiocodecs, FALSE, FALSE, 0); gtk_widget_set_size_request(audiocodecs, -1, 200); gtk_widget_show(audiocodecs); - gtk_container_add(GTK_CONTAINER(audiocodecs) , box); + gtk_container_add(GTK_CONTAINER(audiocodecs), box); // Add DTMF type selection for SIP account only - p = g_hash_table_lookup(currentAccount->properties, ACCOUNT_TYPE); + gpointer p = g_hash_table_lookup(currentAccount->properties, ACCOUNT_TYPE); - if (g_strcmp0(p, "SIP") == 0) { + GtkWidget *table; + if (g_strcmp0(p, "SIP") == 0) { // Box for dtmf + GtkWidget *dtmf; gnome_main_section_new_with_table(_("DTMF"), &dtmf, &table, 1, 2); - gtk_box_pack_start(GTK_BOX(ret), dtmf, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(vbox), dtmf, FALSE, FALSE, 0); gtk_widget_show(dtmf); + const gchar * const currentDtmfType = g_hash_table_lookup(currentAccount->properties, ACCOUNT_DTMF_TYPE); - currentDtmfType = g_hash_table_lookup(currentAccount->properties, ACCOUNT_DTMF_TYPE); + gboolean dtmf_are_rtp = TRUE; - if (g_strcasecmp(currentDtmfType, OVERRTP) != 0) { + if (g_strcasecmp(currentDtmfType, OVERRTP) != 0) dtmf_are_rtp = FALSE; - } overrtp = gtk_radio_button_new_with_label(NULL, _("RTP")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(overrtp), dtmf_are_rtp); gtk_table_attach(GTK_TABLE(table), overrtp, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - sipinfo = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(overrtp), _("SIP")); + GtkWidget *sipinfo = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(overrtp), _("SIP")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(sipinfo), !dtmf_are_rtp); g_signal_connect(G_OBJECT(sipinfo), "clicked", G_CALLBACK(select_dtmf_type), NULL); gtk_table_attach(GTK_TABLE(table), sipinfo, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); } // Box for the ringtones + GtkWidget *frame; gnome_main_section_new_with_table(_("Ringtones"), &frame, &table, 1, 2); - gtk_box_pack_start(GTK_BOX(ret), frame, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 0); fileChooser = gtk_file_chooser_button_new(_("Choose a ringtone"), GTK_FILE_CHOOSER_ACTION_OPEN); @@ -1161,54 +1124,49 @@ static GtkWidget* create_audiocodecs_configuration(account_t *currentAccount) gtk_widget_set_sensitive(fileChooser, ringtoneEnabled); GtkFileFilter *filter = gtk_file_filter_new(); - gtk_file_filter_set_name(filter , _("Audio Files")); - gtk_file_filter_add_pattern(filter , "*.wav"); - gtk_file_filter_add_pattern(filter , "*.ul"); - gtk_file_filter_add_pattern(filter , "*.au"); + gtk_file_filter_set_name(filter, _("Audio Files")); + gtk_file_filter_add_pattern(filter, "*.wav"); + gtk_file_filter_add_pattern(filter, "*.ul"); + gtk_file_filter_add_pattern(filter, "*.au"); + gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(fileChooser) , filter); gtk_table_attach(GTK_TABLE(table), fileChooser, 0, 1, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_show_all(ret); + gtk_widget_show_all(vbox); - return ret; + return vbox; } GtkWidget* create_direct_ip_calls_tab(account_t *a) { - GtkWidget *ret, *frame, *label; - gchar *description; - - ret = gtk_vbox_new(FALSE, 10); - gtk_container_set_border_width(GTK_CONTAINER(ret), 10); - - description = g_markup_printf_escaped(_("This profile is used when you want to reach a remote peer simply by typing a sip URI such as <b>sip:remotepeer</b>. The settings you define here will also be used if no account can be matched to an incoming or outgoing call.")); - label = gtk_label_new(NULL); + GtkWidget *vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); + gtk_container_set_border_width(GTK_CONTAINER(vbox), 10); + + gchar *description = g_markup_printf_escaped(_("This profile is used when " + "you want to reach a remote peer simply by typing a sip URI " + "such as <b>sip:remotepeer</b>. The settings you define here " + "will also be used if no account can be matched to an incoming" + " or outgoing call.")); + GtkWidget *label = gtk_label_new(NULL); gtk_label_set_markup(GTK_LABEL(label), description); gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - gtk_box_pack_start(GTK_BOX(ret), label, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0); - GtkRequisition requisition; - gtk_widget_size_request(ret, &requisition); gtk_widget_set_size_request(label, 350, -1); gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); - frame = create_network(a); - gtk_box_pack_start(GTK_BOX(ret), frame, FALSE, FALSE, 0); + GtkWidget *frame = create_network(a); + gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 0); frame = create_security_widget(a); - gtk_box_pack_start(GTK_BOX(ret), frame, FALSE, FALSE, 0); - - gtk_widget_show_all(ret); - return ret; + gtk_box_pack_start(GTK_BOX(vbox), frame, FALSE, FALSE, 0); + gtk_widget_show_all(vbox); + return vbox; } void show_account_window(account_t * currentAccount) { - GtkWidget * notebook; - GtkWidget *tab, *audiocodecs_tab, *ip_tab; - gint response; - // Firstly we reset reset(); @@ -1221,32 +1179,32 @@ void show_account_window(account_t * currentAccount) sflphone_fill_codec_list_per_account(currentAccount); } - dialog = GTK_DIALOG(gtk_dialog_new_with_buttons(_("Account settings"), - GTK_WINDOW(get_main_window()), - GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, - GTK_STOCK_CANCEL, - GTK_RESPONSE_CANCEL, - GTK_STOCK_APPLY, - GTK_RESPONSE_ACCEPT, - NULL)); + GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Account settings"), + GTK_WINDOW(get_main_window()), + GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_STOCK_CANCEL, + GTK_RESPONSE_CANCEL, + GTK_STOCK_APPLY, + GTK_RESPONSE_ACCEPT, + NULL); gtk_container_set_border_width(GTK_CONTAINER(dialog), 0); - notebook = gtk_notebook_new(); - gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(dialog)), notebook, TRUE, TRUE, 0); + GtkWidget *notebook = gtk_notebook_new(); + gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), notebook, TRUE, TRUE, 0); gtk_container_set_border_width(GTK_CONTAINER(notebook), 10); gtk_widget_show(notebook); // We do not need the global settings for the IP2IP account if (g_strcasecmp(currentAccount->accountID, IP2IP) != 0) { /* General Settings */ - tab = create_basic_tab(currentAccount); - gtk_notebook_append_page(GTK_NOTEBOOK(notebook), tab, gtk_label_new(_("Basic"))); - gtk_notebook_page_num(GTK_NOTEBOOK(notebook), tab); + GtkWidget *basic_tab = create_basic_tab(currentAccount); + gtk_notebook_append_page(GTK_NOTEBOOK(notebook), basic_tab, gtk_label_new(_("Basic"))); + gtk_notebook_page_num(GTK_NOTEBOOK(notebook), basic_tab); } /* Audio Codecs */ - audiocodecs_tab = create_audiocodecs_configuration(currentAccount); + GtkWidget *audiocodecs_tab = create_audiocodecs_configuration(currentAccount); gtk_notebook_append_page(GTK_NOTEBOOK(notebook), audiocodecs_tab, gtk_label_new(_("Audio"))); gtk_notebook_page_num(GTK_NOTEBOOK(notebook), audiocodecs_tab); @@ -1254,7 +1212,7 @@ void show_account_window(account_t * currentAccount) gchar *currentProtocol; if (protocolComboBox) - currentProtocol = gtk_combo_box_get_active_text(GTK_COMBO_BOX(protocolComboBox)); + currentProtocol = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(protocolComboBox)); else currentProtocol = g_strdup("SIP"); @@ -1272,9 +1230,8 @@ void show_account_window(account_t * currentAccount) gtk_notebook_page_num(GTK_NOTEBOOK(notebook),security_tab); } else { - /* Custom tab for the IP to IP profile */ - ip_tab = create_direct_ip_calls_tab(currentAccount); + GtkWidget *ip_tab = create_direct_ip_calls_tab(currentAccount); gtk_notebook_prepend_page(GTK_NOTEBOOK(notebook), ip_tab, gtk_label_new(_("Network"))); gtk_notebook_page_num(GTK_NOTEBOOK(notebook), ip_tab); } @@ -1288,19 +1245,19 @@ void show_account_window(account_t * currentAccount) /**************/ /* Run dialog */ /**************/ - response = gtk_dialog_run(GTK_DIALOG(dialog)); + gint response = gtk_dialog_run(GTK_DIALOG(dialog)); // Update protocol in case it changed gchar *proto; if (protocolComboBox) - proto = gtk_combo_box_get_active_text(GTK_COMBO_BOX(protocolComboBox)); + proto = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(protocolComboBox)); else proto = g_strdup("SIP"); // If cancel button is pressed if (response == GTK_RESPONSE_CANCEL) { - gtk_widget_destroy(GTK_WIDGET(dialog)); + gtk_widget_destroy(dialog); g_free(proto); return; } @@ -1309,75 +1266,75 @@ void show_account_window(account_t * currentAccount) if (g_strcasecmp(currentAccount->accountID, IP2IP) != 0) { g_hash_table_replace(currentAccount->properties, - g_strdup(ACCOUNT_ALIAS), - g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(entryAlias)))); + g_strdup(ACCOUNT_ALIAS), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(entryAlias)))); g_hash_table_replace(currentAccount->properties, - g_strdup(ACCOUNT_TYPE), - g_strdup(proto)); + g_strdup(ACCOUNT_TYPE), + g_strdup(proto)); g_hash_table_replace(currentAccount->properties, - g_strdup(ACCOUNT_HOSTNAME), - g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(entryHostname)))); + g_strdup(ACCOUNT_HOSTNAME), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(entryHostname)))); g_hash_table_replace(currentAccount->properties, - g_strdup(ACCOUNT_USERNAME), - g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(entryUsername)))); + g_strdup(ACCOUNT_USERNAME), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(entryUsername)))); g_hash_table_replace(currentAccount->properties, - g_strdup(ACCOUNT_PASSWORD), - g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(entryPassword)))); + g_strdup(ACCOUNT_PASSWORD), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(entryPassword)))); g_hash_table_replace(currentAccount->properties, - g_strdup(ACCOUNT_MAILBOX), - g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(entryMailbox)))); + g_strdup(ACCOUNT_MAILBOX), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(entryMailbox)))); } if (g_strcmp0(proto, "SIP") == 0) { if (g_strcasecmp(currentAccount->accountID, IP2IP) != 0) { g_hash_table_replace(currentAccount->properties, - g_strdup(ACCOUNT_RESOLVE_ONCE), - g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(entryResolveNameOnlyOnce)) ? "false": "true")); + g_strdup(ACCOUNT_RESOLVE_ONCE), + g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(entryResolveNameOnlyOnce)) ? "false": "true")); g_hash_table_replace(currentAccount->properties, - g_strdup(ACCOUNT_REGISTRATION_EXPIRE), - g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(expireSpinBox)))); + g_strdup(ACCOUNT_REGISTRATION_EXPIRE), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(expireSpinBox)))); // TODO: uncomment this code and implement route g_hash_table_replace(currentAccount->properties, - g_strdup(ACCOUNT_ROUTE), - g_strdup((gchar *)gtk_entry_get_text(GTK_ENTRY(entryRouteSet)))); + g_strdup(ACCOUNT_ROUTE), + g_strdup((gchar *)gtk_entry_get_text(GTK_ENTRY(entryRouteSet)))); g_hash_table_replace(currentAccount->properties, - g_strdup(ACCOUNT_USERAGENT), - g_strdup(gtk_entry_get_text(GTK_ENTRY(entryUseragent)))); + g_strdup(ACCOUNT_USERAGENT), + g_strdup(gtk_entry_get_text(GTK_ENTRY(entryUseragent)))); g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_SIP_STUN_ENABLED), - g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(useStunCheckBox)) ? "true":"false")); + g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(useStunCheckBox)) ? "true":"false")); g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_SIP_STUN_SERVER), - g_strdup(gtk_entry_get_text(GTK_ENTRY(stunServerEntry)))); + g_strdup(gtk_entry_get_text(GTK_ENTRY(stunServerEntry)))); g_hash_table_replace(currentAccount->properties, g_strdup(PUBLISHED_SAMEAS_LOCAL), g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(sameAsLocalRadioButton)) ? "true":"false")); if (!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(sameAsLocalRadioButton))) { g_hash_table_replace(currentAccount->properties, - g_strdup(PUBLISHED_PORT), - g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(publishedPortSpinBox)))); + g_strdup(PUBLISHED_PORT), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(publishedPortSpinBox)))); g_hash_table_replace(currentAccount->properties, - g_strdup(PUBLISHED_ADDRESS), - g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(publishedAddressEntry)))); + g_strdup(PUBLISHED_ADDRESS), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(publishedAddressEntry)))); } else { g_hash_table_replace(currentAccount->properties, - g_strdup(PUBLISHED_PORT), - g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(localPortSpinBox)))); - gchar *local_interface = gtk_combo_box_get_active_text(GTK_COMBO_BOX(localAddressCombo)); + g_strdup(PUBLISHED_PORT), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(localPortSpinBox)))); + gchar *local_interface = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(localAddressCombo)); gchar *published_address = dbus_get_address_from_interface_name(local_interface); g_free(local_interface); g_hash_table_replace(currentAccount->properties, - g_strdup(PUBLISHED_ADDRESS), - published_address); + g_strdup(PUBLISHED_ADDRESS), + published_address); } } @@ -1389,17 +1346,15 @@ void show_account_window(account_t * currentAccount) g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_DTMF_TYPE), g_strdup(SIPINFO)); } - gchar* keyExchange = gtk_combo_box_get_active_text(GTK_COMBO_BOX(keyExchangeCombo)); + gchar* keyExchange = gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(keyExchangeCombo)); if (g_strcasecmp(keyExchange, "ZRTP") == 0) { g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_SRTP_ENABLED), g_strdup("true")); g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_KEY_EXCHANGE), g_strdup(ZRTP)); - } - else if (g_strcasecmp(keyExchange, "SDES") == 0) { + } else if (g_strcasecmp(keyExchange, "SDES") == 0) { g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_SRTP_ENABLED), g_strdup("true")); g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_KEY_EXCHANGE), g_strdup(SDES)); - } - else { + } else { g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_SRTP_ENABLED), g_strdup("false")); g_hash_table_replace(currentAccount->properties, g_strdup(ACCOUNT_KEY_EXCHANGE), g_strdup("")); } @@ -1407,24 +1362,24 @@ void show_account_window(account_t * currentAccount) g_free(keyExchange); g_hash_table_replace(currentAccount->properties, g_strdup(TLS_ENABLE), - g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(useSipTlsCheckBox)) ? "true":"false")); + g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(useSipTlsCheckBox)) ? "true":"false")); gboolean toneEnabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(enableTone)); g_hash_table_replace(currentAccount->properties, - g_strdup(CONFIG_RINGTONE_ENABLED), - g_strdup(toneEnabled ? "true" : "false")); + g_strdup(CONFIG_RINGTONE_ENABLED), + g_strdup(toneEnabled ? "true" : "false")); g_hash_table_replace(currentAccount->properties, - g_strdup(CONFIG_RINGTONE_PATH), - g_strdup(gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(fileChooser)))); + g_strdup(CONFIG_RINGTONE_PATH), + g_strdup(gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(fileChooser)))); g_hash_table_replace(currentAccount->properties, - g_strdup(LOCAL_INTERFACE), - gtk_combo_box_get_active_text(GTK_COMBO_BOX(localAddressCombo))); + g_strdup(LOCAL_INTERFACE), + gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(localAddressCombo))); g_hash_table_replace(currentAccount->properties, - g_strdup(LOCAL_PORT), - g_strdup(gtk_entry_get_text(GTK_ENTRY(localPortSpinBox)))); + g_strdup(LOCAL_PORT), + g_strdup(gtk_entry_get_text(GTK_ENTRY(localPortSpinBox)))); } @@ -1441,15 +1396,16 @@ void show_account_window(account_t * currentAccount) if (g_strcasecmp(currentAccount->accountID, IP2IP) != 0) { DEBUG("Config: Get new credentials"); currentAccount->credential_information = getNewCredential(); + if (currentAccount->credential_information) dbus_set_credentials(currentAccount); } } - // Perpetuate changes to the deamon + // propagate changes to the daemon codec_list_update_to_daemon(currentAccount); - gtk_widget_destroy(GTK_WIDGET(dialog)); + gtk_widget_destroy(dialog); g_free(currentProtocol); g_free(proto); } diff --git a/gnome/src/config/accountlistconfigdialog.c b/gnome/src/config/accountlistconfigdialog.c index 78724bda7f06a4228e6fcccd6528e655e9e46e79..a765c37f9051efca6d15b1f2b5bdecafe22ac0f1 100644 --- a/gnome/src/config/accountlistconfigdialog.c +++ b/gnome/src/config/accountlistconfigdialog.c @@ -36,10 +36,11 @@ #include "actions.h" #include "mainwindow.h" #include "utils.h" +#include "unused.h" +#include "logger.h" #include <string.h> -#include <libgnome/gnome-help.h> -#define CONTEXT_ID_REGISTRATION 0 +static const int CONTEXT_ID_REGISTRATION = 0; static GtkWidget *addButton; static GtkWidget *editButton; @@ -65,36 +66,36 @@ enum { /** * Delete an account */ -static void delete_account_cb (void) +static void delete_account_cb(void) { if (selectedAccount == NULL) { ERROR("Config: Error: No selected account in delete action"); return; } - dbus_remove_account (selectedAccount->accountID); + dbus_remove_account(selectedAccount->accountID); } /** * Edit an account */ -static void edit_account_cb (void) +static void edit_account_cb(void) { if (selectedAccount == NULL) { ERROR("Config: Error: No selected account in edit action"); return; } - show_account_window (selectedAccount); + show_account_window(selectedAccount); } /** * Add an account */ -static void add_account_cb (void) +static void add_account_cb(void) { - show_account_window (NULL); + show_account_window(NULL); } /** @@ -109,29 +110,30 @@ void account_list_config_dialog_fill() GtkTreeIter iter; - gtk_list_store_clear (accountStore); + gtk_list_store_clear(accountStore); // IP2IP account must be first - account_t *a = account_list_get_by_id ("IP2IP"); + account_t *a = account_list_get_by_id("IP2IP"); + if (a == NULL) { ERROR("Config: Error: Could not find IP2IP account"); return; } - gtk_list_store_append (accountStore, &iter); + gtk_list_store_append(accountStore, &iter); - DEBUG ("Config: Filling accounts: Account is enabled :%s", g_hash_table_lookup (a->properties, ACCOUNT_ENABLED)); + DEBUG("Config: Filling accounts: Account is enabled :%s", g_hash_table_lookup(a->properties, ACCOUNT_ENABLED)); - gtk_list_store_set (accountStore, &iter, - COLUMN_ACCOUNT_ALIAS, g_hash_table_lookup (a->properties, ACCOUNT_ALIAS), // Name - COLUMN_ACCOUNT_TYPE, g_hash_table_lookup (a->properties, ACCOUNT_TYPE), // Protocol - COLUMN_ACCOUNT_STATUS, account_state_name (a->state), // Status - COLUMN_ACCOUNT_ACTIVE, (g_strcasecmp (g_hash_table_lookup (a->properties, ACCOUNT_ENABLED),"true") == 0) ? TRUE:FALSE, // Enable/Disable - COLUMN_ACCOUNT_DATA, a, // Pointer - -1); + gtk_list_store_set(accountStore, &iter, + COLUMN_ACCOUNT_ALIAS, g_hash_table_lookup(a->properties, ACCOUNT_ALIAS), // Name + COLUMN_ACCOUNT_TYPE, g_hash_table_lookup(a->properties, ACCOUNT_TYPE), // Protocol + COLUMN_ACCOUNT_STATUS, account_state_name(a->state), // Status + COLUMN_ACCOUNT_ACTIVE, (g_strcasecmp(g_hash_table_lookup(a->properties, ACCOUNT_ENABLED),"true") == 0) ? TRUE:FALSE, // Enable/Disable + COLUMN_ACCOUNT_DATA, a, // Pointer + -1); for (size_t i = 0; i < account_list_get_size(); i++) { - a = account_list_get_nth (i); + a = account_list_get_nth(i); if (a == NULL) { ERROR("Config: Error: Account %d is NULL while parsing the list", i); @@ -139,18 +141,18 @@ void account_list_config_dialog_fill() } // we dont wnat to process account twice - if (g_strcmp0 (a->accountID, "IP2IP") != 0) { - gtk_list_store_append (accountStore, &iter); - - DEBUG ("Config: Filling accounts: Account is enabled :%s", g_hash_table_lookup (a->properties, ACCOUNT_ENABLED)); - - gtk_list_store_set (accountStore, &iter, - COLUMN_ACCOUNT_ALIAS, g_hash_table_lookup (a->properties, ACCOUNT_ALIAS), // Name - COLUMN_ACCOUNT_TYPE, g_hash_table_lookup (a->properties, ACCOUNT_TYPE), // Protocol - COLUMN_ACCOUNT_STATUS, account_state_name (a->state), // Status - COLUMN_ACCOUNT_ACTIVE, (g_strcasecmp (g_hash_table_lookup (a->properties, ACCOUNT_ENABLED),"true") == 0) ? TRUE:FALSE, // Enable/Disable - COLUMN_ACCOUNT_DATA, a, // Pointer - -1); + if (g_strcmp0(a->accountID, "IP2IP") != 0) { + gtk_list_store_append(accountStore, &iter); + + DEBUG("Config: Filling accounts: Account is enabled :%s", g_hash_table_lookup(a->properties, ACCOUNT_ENABLED)); + + gtk_list_store_set(accountStore, &iter, + COLUMN_ACCOUNT_ALIAS, g_hash_table_lookup(a->properties, ACCOUNT_ALIAS), // Name + COLUMN_ACCOUNT_TYPE, g_hash_table_lookup(a->properties, ACCOUNT_TYPE), // Protocol + COLUMN_ACCOUNT_STATUS, account_state_name(a->state), // Status + COLUMN_ACCOUNT_ACTIVE, (g_strcasecmp(g_hash_table_lookup(a->properties, ACCOUNT_ENABLED),"true") == 0) ? TRUE:FALSE, // Enable/Disable + COLUMN_ACCOUNT_DATA, a, // Pointer + -1); } } } @@ -159,73 +161,73 @@ void account_list_config_dialog_fill() * Call back when the user click on an account in the list */ static void -select_account_cb (GtkTreeSelection *selection, GtkTreeModel *model) +select_account_cb(GtkTreeSelection *selection, GtkTreeModel *model) { GtkTreeIter iter; GValue val; gchar *state; - memset (&val, 0, sizeof (val)); + memset(&val, 0, sizeof(val)); - if (!gtk_tree_selection_get_selected (selection, &model, &iter)) { + if (!gtk_tree_selection_get_selected(selection, &model, &iter)) { selectedAccount = NULL; - gtk_widget_set_sensitive (GTK_WIDGET (accountMoveUpButton), FALSE); - gtk_widget_set_sensitive (GTK_WIDGET (accountMoveDownButton), FALSE); - gtk_widget_set_sensitive (GTK_WIDGET (editButton), FALSE); - gtk_widget_set_sensitive (GTK_WIDGET (deleteButton), FALSE); + gtk_widget_set_sensitive(GTK_WIDGET(accountMoveUpButton), FALSE); + gtk_widget_set_sensitive(GTK_WIDGET(accountMoveDownButton), FALSE); + gtk_widget_set_sensitive(GTK_WIDGET(editButton), FALSE); + gtk_widget_set_sensitive(GTK_WIDGET(deleteButton), FALSE); return; } // The Gvalue will be initialized in the following function - gtk_tree_model_get_value (model, &iter, COLUMN_ACCOUNT_DATA, &val); + gtk_tree_model_get_value(model, &iter, COLUMN_ACCOUNT_DATA, &val); - selectedAccount = (account_t*) g_value_get_pointer (&val); - g_value_unset (&val); + selectedAccount = (account_t*) g_value_get_pointer(&val); + g_value_unset(&val); if (selectedAccount != NULL) { - gtk_widget_set_sensitive (GTK_WIDGET (editButton), TRUE); + gtk_widget_set_sensitive(GTK_WIDGET(editButton), TRUE); - if (g_strcasecmp (selectedAccount->accountID, IP2IP) != 0) { - gtk_widget_set_sensitive (GTK_WIDGET (accountMoveUpButton), TRUE); - gtk_widget_set_sensitive (GTK_WIDGET (accountMoveDownButton), TRUE); - gtk_widget_set_sensitive (GTK_WIDGET (deleteButton), TRUE); + if (g_strcasecmp(selectedAccount->accountID, IP2IP) != 0) { + gtk_widget_set_sensitive(GTK_WIDGET(accountMoveUpButton), TRUE); + gtk_widget_set_sensitive(GTK_WIDGET(accountMoveDownButton), TRUE); + gtk_widget_set_sensitive(GTK_WIDGET(deleteButton), TRUE); /* Update status bar about current registration state */ - gtk_statusbar_pop (GTK_STATUSBAR (status_bar), CONTEXT_ID_REGISTRATION); + gtk_statusbar_pop(GTK_STATUSBAR(status_bar), CONTEXT_ID_REGISTRATION); if (selectedAccount->protocol_state_description != NULL && selectedAccount->protocol_state_code != 0) { - gchar * response = g_strdup_printf ( - _ ("Server returned \"%s\" (%d)"), + gchar * response = g_strdup_printf( + _("Server returned \"%s\" (%d)"), selectedAccount->protocol_state_description, selectedAccount->protocol_state_code); - gchar * message = g_strconcat ( - account_state_name (selectedAccount->state), + gchar * message = g_strconcat( + account_state_name(selectedAccount->state), ". ", response, NULL); - gtk_statusbar_push (GTK_STATUSBAR (status_bar), CONTEXT_ID_REGISTRATION, message); + gtk_statusbar_push(GTK_STATUSBAR(status_bar), CONTEXT_ID_REGISTRATION, message); - g_free (response); - g_free (message); + g_free(response); + g_free(message); } else { - state = (gchar*) account_state_name (selectedAccount->state); - gtk_statusbar_push (GTK_STATUSBAR (status_bar), CONTEXT_ID_REGISTRATION, state); + state = (gchar*) account_state_name(selectedAccount->state); + gtk_statusbar_push(GTK_STATUSBAR(status_bar), CONTEXT_ID_REGISTRATION, state); } } else { - gtk_widget_set_sensitive (GTK_WIDGET (accountMoveUpButton), FALSE); - gtk_widget_set_sensitive (GTK_WIDGET (accountMoveDownButton), FALSE); - gtk_widget_set_sensitive (GTK_WIDGET (deleteButton), FALSE); + gtk_widget_set_sensitive(GTK_WIDGET(accountMoveUpButton), FALSE); + gtk_widget_set_sensitive(GTK_WIDGET(accountMoveDownButton), FALSE); + gtk_widget_set_sensitive(GTK_WIDGET(deleteButton), FALSE); } } - DEBUG ("Selecting account in account window"); + DEBUG("Selecting account in account window"); } -static void enable_account_cb (GtkCellRendererToggle *rend UNUSED, gchar* path, gpointer data) +static void enable_account_cb(GtkCellRendererToggle *rend UNUSED, gchar* path, gpointer data) { GtkTreeIter iter; @@ -235,46 +237,46 @@ static void enable_account_cb (GtkCellRendererToggle *rend UNUSED, gchar* path, account_t* acc ; // The IP2IP profile can't be disabled - if (g_strcasecmp (path, "0") == 0) + if (g_strcasecmp(path, "0") == 0) return; // Get pointer on object - treePath = gtk_tree_path_new_from_string (path); - model = gtk_tree_view_get_model (GTK_TREE_VIEW (data)); - gtk_tree_model_get_iter (model, &iter, treePath); - gtk_tree_model_get (model, &iter, - COLUMN_ACCOUNT_ACTIVE, &enable, - COLUMN_ACCOUNT_DATA, &acc, - -1); + treePath = gtk_tree_path_new_from_string(path); + model = gtk_tree_view_get_model(GTK_TREE_VIEW(data)); + gtk_tree_model_get_iter(model, &iter, treePath); + gtk_tree_model_get(model, &iter, + COLUMN_ACCOUNT_ACTIVE, &enable, + COLUMN_ACCOUNT_DATA, &acc, + -1); enable = !enable; - DEBUG ("Account is %d enabled", enable); + DEBUG("Account is %d enabled", enable); // Store value - gtk_list_store_set (GTK_LIST_STORE (model), &iter, - COLUMN_ACCOUNT_ACTIVE, enable, - -1); + gtk_list_store_set(GTK_LIST_STORE(model), &iter, + COLUMN_ACCOUNT_ACTIVE, enable, + -1); // Modify account state gchar * registrationState; if (enable == TRUE) { - registrationState = g_strdup ("true"); + registrationState = g_strdup("true"); } else { - registrationState = g_strdup ("false"); + registrationState = g_strdup("false"); } - DEBUG ("Replacing with %s", registrationState); - g_hash_table_replace (acc->properties , g_strdup (ACCOUNT_ENABLED), registrationState); + DEBUG("Replacing with %s", registrationState); + g_hash_table_replace(acc->properties , g_strdup(ACCOUNT_ENABLED), registrationState); - dbus_send_register (acc->accountID, enable); + dbus_send_register(acc->accountID, enable); } /** * Move account in list depending on direction and selected account */ -static void account_move (gboolean moveUp, gpointer data) +static void account_move(gboolean moveUp, gpointer data) { GtkTreeIter iter; @@ -286,149 +288,146 @@ static void account_move (gboolean moveUp, gpointer data) gchar *path; // Get view, model and selection of codec store - treeView = GTK_TREE_VIEW (data); - model = gtk_tree_view_get_model (GTK_TREE_VIEW (treeView)); - selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeView)); + treeView = GTK_TREE_VIEW(data); + model = gtk_tree_view_get_model(GTK_TREE_VIEW(treeView)); + selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeView)); // Find selected iteration and create a copy - gtk_tree_selection_get_selected (GTK_TREE_SELECTION (selection), &model, &iter); - iter2 = gtk_tree_iter_copy (&iter); + gtk_tree_selection_get_selected(GTK_TREE_SELECTION(selection), &model, &iter); + iter2 = gtk_tree_iter_copy(&iter); // Find path of iteration - path = gtk_tree_model_get_string_from_iter (GTK_TREE_MODEL (model), &iter); + path = gtk_tree_model_get_string_from_iter(GTK_TREE_MODEL(model), &iter); // The first real account in the list can't move up because of the IP2IP account // It can still move down though - if (g_strcasecmp (path, "1") == 0 && moveUp) + if (g_strcasecmp(path, "1") == 0 && moveUp) return; - treePath = gtk_tree_path_new_from_string (path); - gint *indices = gtk_tree_path_get_indices (treePath); + treePath = gtk_tree_path_new_from_string(path); + gint *indices = gtk_tree_path_get_indices(treePath); gint indice = indices[0]; // Depending on button direction get new path if (moveUp) - gtk_tree_path_prev (treePath); + gtk_tree_path_prev(treePath); else - gtk_tree_path_next (treePath); + gtk_tree_path_next(treePath); - gtk_tree_model_get_iter (model, &iter, treePath); + gtk_tree_model_get_iter(model, &iter, treePath); // Swap iterations if valid - if (gtk_list_store_iter_is_valid (GTK_LIST_STORE (model), &iter)) - gtk_list_store_swap (GTK_LIST_STORE (model), &iter, iter2); + if (gtk_list_store_iter_is_valid(GTK_LIST_STORE(model), &iter)) + gtk_list_store_swap(GTK_LIST_STORE(model), &iter, iter2); // Scroll to new position - gtk_tree_view_scroll_to_cell (treeView, treePath, NULL, FALSE, 0, 0); + gtk_tree_view_scroll_to_cell(treeView, treePath, NULL, FALSE, 0, 0); // Free resources - gtk_tree_path_free (treePath); - gtk_tree_iter_free (iter2); - g_free (path); + gtk_tree_path_free(treePath); + gtk_tree_iter_free(iter2); + g_free(path); // Perpetuate changes in account queue if (moveUp) - account_list_move_up (indice); + account_list_move_up(indice); else - account_list_move_down (indice); + account_list_move_down(indice); // Set the order in the configuration file - gchar *ordered_account_list = account_list_get_ordered_list (); - dbus_set_accounts_order (ordered_account_list); - g_free (ordered_account_list); + gchar *ordered_account_list = account_list_get_ordered_list(); + dbus_set_accounts_order(ordered_account_list); + g_free(ordered_account_list); } /** * Called from move up account button signal */ static void -account_move_up_cb (GtkButton *button UNUSED, gpointer data) +account_move_up_cb(GtkButton *button UNUSED, gpointer data) { // Change tree view ordering and get indice changed - account_move (TRUE, data); + account_move(TRUE, data); } /** * Called from move down account button signal */ static void -account_move_down_cb (GtkButton *button UNUSED, gpointer data) +account_move_down_cb(GtkButton *button UNUSED, gpointer data) { // Change tree view ordering and get indice changed - account_move (FALSE, data); + account_move(FALSE, data); } static void -help_contents_cb (GtkWidget * widget UNUSED, - gpointer data UNUSED) +help_contents_cb(GtkWidget * widget UNUSED, + gpointer data UNUSED) { GError *error = NULL; - - gnome_help_display ("sflphone.xml", "accounts", &error); - + gtk_show_uri(NULL, "ghelp:sflphone?accounts", GDK_CURRENT_TIME, &error); if (error != NULL) { - g_warning ("%s", error->message); - - g_error_free (error); + g_warning("%s", error->message); + g_error_free(error); } } static void -close_dialog_cb (GtkWidget * widget UNUSED, - gpointer data UNUSED) +close_dialog_cb(GtkWidget * widget UNUSED, + gpointer data UNUSED) { - gtk_dialog_response (GTK_DIALOG (accountListDialog), GTK_RESPONSE_ACCEPT); + gtk_dialog_response(GTK_DIALOG(accountListDialog), GTK_RESPONSE_ACCEPT); } -void highlight_ip_profile (GtkTreeViewColumn *col UNUSED, GtkCellRenderer *rend, GtkTreeModel *tree_model, GtkTreeIter *iter, gpointer data UNUSED) +void highlight_ip_profile(GtkTreeViewColumn *col UNUSED, GtkCellRenderer *rend, GtkTreeModel *tree_model, GtkTreeIter *iter, gpointer data UNUSED) { GValue val; account_t *current; - memset (&val, 0, sizeof (val)); - gtk_tree_model_get_value (tree_model, iter, COLUMN_ACCOUNT_DATA, &val); - current = (account_t*) g_value_get_pointer (&val); + memset(&val, 0, sizeof(val)); + gtk_tree_model_get_value(tree_model, iter, COLUMN_ACCOUNT_DATA, &val); + current = (account_t*) g_value_get_pointer(&val); - g_value_unset (&val); + g_value_unset(&val); if (current != NULL) { // Make the first line appear differently - (g_strcasecmp (current->accountID, IP2IP) == 0) ? g_object_set (G_OBJECT (rend), "weight", PANGO_WEIGHT_THIN, + (g_strcasecmp(current->accountID, IP2IP) == 0) ? g_object_set(G_OBJECT(rend), "weight", PANGO_WEIGHT_THIN, "style", PANGO_STYLE_ITALIC, "stretch", PANGO_STRETCH_ULTRA_EXPANDED, "scale", 0.95, NULL) : - g_object_set (G_OBJECT (rend), "weight", PANGO_WEIGHT_MEDIUM, - "style", PANGO_STYLE_NORMAL, - "stretch", PANGO_STRETCH_NORMAL, - "scale", 1.0, - NULL) ; + g_object_set(G_OBJECT(rend), "weight", PANGO_WEIGHT_MEDIUM, + "style", PANGO_STYLE_NORMAL, + "stretch", PANGO_STRETCH_NORMAL, + "scale", 1.0, + NULL) ; } } -void highlight_registration (GtkTreeViewColumn *col UNUSED, GtkCellRenderer *rend, GtkTreeModel *tree_model, GtkTreeIter *iter, gpointer data UNUSED) +void highlight_registration(GtkTreeViewColumn *col UNUSED, GtkCellRenderer *rend, GtkTreeModel *tree_model, GtkTreeIter *iter, gpointer data UNUSED) { GValue val; account_t *current; - memset (&val, 0, sizeof (val)); - gtk_tree_model_get_value (tree_model, iter, COLUMN_ACCOUNT_DATA, &val); - current = (account_t*) g_value_get_pointer (&val); + memset(&val, 0, sizeof(val)); + gtk_tree_model_get_value(tree_model, iter, COLUMN_ACCOUNT_DATA, &val); + current = (account_t*) g_value_get_pointer(&val); - g_value_unset (&val); + g_value_unset(&val); if (current != NULL) { - if (g_strcasecmp (current->accountID, IP2IP) != 0) { + if (g_strcasecmp(current->accountID, IP2IP) != 0) { // Color the account state: green -> registered, otherwise red - (current->state == ACCOUNT_STATE_REGISTERED) ? g_object_set (G_OBJECT (rend), "foreground", "Dark Green", NULL) : - g_object_set (G_OBJECT (rend), "foreground", "Dark Red", NULL); + (current->state == ACCOUNT_STATE_REGISTERED) ? g_object_set(G_OBJECT(rend), "foreground", "Dark Green", NULL) : + g_object_set(G_OBJECT(rend), "foreground", "Dark Red", NULL); } else - g_object_set (G_OBJECT (rend), "foreground", "Black", NULL); + g_object_set(G_OBJECT(rend), "foreground", "Black", NULL); } } @@ -436,7 +435,7 @@ void highlight_registration (GtkTreeViewColumn *col UNUSED, GtkCellRenderer *ren /** * Account settings tab */ -GtkWidget* create_account_list (GtkDialog * dialog UNUSED) +GtkWidget* create_account_list(GtkDialog * dialog UNUSED) { GtkWidget *table, *scrolledWindow, *buttonBox; @@ -448,184 +447,179 @@ GtkWidget* create_account_list (GtkDialog * dialog UNUSED) selectedAccount = NULL; - table = gtk_table_new (1, 2, FALSE/* homogeneous */); - gtk_table_set_col_spacings (GTK_TABLE (table), 10); - gtk_container_set_border_width (GTK_CONTAINER (table), 10); + table = gtk_table_new(1, 2, FALSE/* homogeneous */); + gtk_table_set_col_spacings(GTK_TABLE(table), 10); + gtk_container_set_border_width(GTK_CONTAINER(table), 10); - scrolledWindow = gtk_scrolled_window_new (NULL, NULL); - gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolledWindow), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); - gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolledWindow), GTK_SHADOW_IN); - gtk_table_attach (GTK_TABLE (table), scrolledWindow, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + scrolledWindow = gtk_scrolled_window_new(NULL, NULL); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledWindow), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); + gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolledWindow), GTK_SHADOW_IN); + gtk_table_attach(GTK_TABLE(table), scrolledWindow, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - accountStore = gtk_list_store_new (COLUMN_ACCOUNT_COUNT, - G_TYPE_STRING, // Name - G_TYPE_STRING, // Protocol - G_TYPE_STRING, // Status - G_TYPE_BOOLEAN, // Enabled / Disabled - G_TYPE_POINTER // Pointer to the Object - ); + accountStore = gtk_list_store_new(COLUMN_ACCOUNT_COUNT, + G_TYPE_STRING, // Name + G_TYPE_STRING, // Protocol + G_TYPE_STRING, // Status + G_TYPE_BOOLEAN, // Enabled / Disabled + G_TYPE_POINTER // Pointer to the Object + ); account_list_config_dialog_fill(); - treeView = GTK_TREE_VIEW (gtk_tree_view_new_with_model (GTK_TREE_MODEL (accountStore))); - treeSelection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeView)); - g_signal_connect (G_OBJECT (treeSelection), "changed", - G_CALLBACK (select_account_cb), - accountStore); + treeView = GTK_TREE_VIEW(gtk_tree_view_new_with_model(GTK_TREE_MODEL(accountStore))); + treeSelection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeView)); + g_signal_connect(G_OBJECT(treeSelection), "changed", + G_CALLBACK(select_account_cb), + accountStore); renderer = gtk_cell_renderer_toggle_new(); - treeViewColumn = gtk_tree_view_column_new_with_attributes ("Enabled", renderer, "active", COLUMN_ACCOUNT_ACTIVE , NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (treeView), treeViewColumn); - g_signal_connect (G_OBJECT (renderer) , "toggled" , G_CALLBACK (enable_account_cb), (gpointer) treeView); + treeViewColumn = gtk_tree_view_column_new_with_attributes("Enabled", renderer, "active", COLUMN_ACCOUNT_ACTIVE , NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(treeView), treeViewColumn); + g_signal_connect(G_OBJECT(renderer) , "toggled" , G_CALLBACK(enable_account_cb), (gpointer) treeView); // gtk_cell_renderer_toggle_set_activatable (renderer, FALSE); renderer = gtk_cell_renderer_text_new(); - treeViewColumn = gtk_tree_view_column_new_with_attributes ("Alias", + treeViewColumn = gtk_tree_view_column_new_with_attributes("Alias", renderer, "markup", COLUMN_ACCOUNT_ALIAS, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (treeView), treeViewColumn); + gtk_tree_view_append_column(GTK_TREE_VIEW(treeView), treeViewColumn); // A double click on the account line opens the window to edit the account - g_signal_connect (G_OBJECT (treeView) , "row-activated" , G_CALLBACK (edit_account_cb) , NULL); - gtk_tree_view_column_set_cell_data_func (treeViewColumn, renderer, highlight_ip_profile, NULL, NULL); + g_signal_connect(G_OBJECT(treeView) , "row-activated" , G_CALLBACK(edit_account_cb) , NULL); + gtk_tree_view_column_set_cell_data_func(treeViewColumn, renderer, highlight_ip_profile, NULL, NULL); renderer = gtk_cell_renderer_text_new(); - treeViewColumn = gtk_tree_view_column_new_with_attributes (_ ("Protocol"), + treeViewColumn = gtk_tree_view_column_new_with_attributes(_("Protocol"), renderer, "markup", COLUMN_ACCOUNT_TYPE, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (treeView), treeViewColumn); - gtk_tree_view_column_set_cell_data_func (treeViewColumn, renderer, highlight_ip_profile, NULL, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(treeView), treeViewColumn); + gtk_tree_view_column_set_cell_data_func(treeViewColumn, renderer, highlight_ip_profile, NULL, NULL); renderer = gtk_cell_renderer_text_new(); - treeViewColumn = gtk_tree_view_column_new_with_attributes (_ ("Status"), + treeViewColumn = gtk_tree_view_column_new_with_attributes(_("Status"), renderer, "markup", COLUMN_ACCOUNT_STATUS, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (treeView), treeViewColumn); + gtk_tree_view_append_column(GTK_TREE_VIEW(treeView), treeViewColumn); // Highlight IP profile - gtk_tree_view_column_set_cell_data_func (treeViewColumn, renderer, highlight_ip_profile, NULL, NULL); + gtk_tree_view_column_set_cell_data_func(treeViewColumn, renderer, highlight_ip_profile, NULL, NULL); // Highlight account registration state - gtk_tree_view_column_set_cell_data_func (treeViewColumn, renderer, highlight_registration, NULL, NULL); + gtk_tree_view_column_set_cell_data_func(treeViewColumn, renderer, highlight_registration, NULL, NULL); - g_object_unref (G_OBJECT (accountStore)); + g_object_unref(G_OBJECT(accountStore)); - gtk_container_add (GTK_CONTAINER (scrolledWindow), GTK_WIDGET (treeView)); + gtk_container_add(GTK_CONTAINER(scrolledWindow), GTK_WIDGET(treeView)); /* The buttons to press! */ - buttonBox = gtk_vbutton_box_new(); - gtk_box_set_spacing (GTK_BOX (buttonBox), 10); - gtk_button_box_set_layout (GTK_BUTTON_BOX (buttonBox), GTK_BUTTONBOX_START); - gtk_table_attach (GTK_TABLE (table), buttonBox, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - - accountMoveUpButton = gtk_button_new_from_stock (GTK_STOCK_GO_UP); - gtk_widget_set_sensitive (GTK_WIDGET (accountMoveUpButton), FALSE); - gtk_box_pack_start (GTK_BOX (buttonBox), accountMoveUpButton, FALSE, FALSE, 0); - g_signal_connect (G_OBJECT (accountMoveUpButton), "clicked", G_CALLBACK (account_move_up_cb), treeView); - - accountMoveDownButton = gtk_button_new_from_stock (GTK_STOCK_GO_DOWN); - gtk_widget_set_sensitive (GTK_WIDGET (accountMoveDownButton), FALSE); - gtk_box_pack_start (GTK_BOX (buttonBox), accountMoveDownButton, FALSE, FALSE, 0); - g_signal_connect (G_OBJECT (accountMoveDownButton), "clicked", G_CALLBACK (account_move_down_cb), treeView); - - addButton = gtk_button_new_from_stock (GTK_STOCK_ADD); - g_signal_connect_swapped (G_OBJECT (addButton), "clicked", - G_CALLBACK (add_account_cb), NULL); - gtk_box_pack_start (GTK_BOX (buttonBox), addButton, FALSE, FALSE, 0); - - editButton = gtk_button_new_from_stock (GTK_STOCK_EDIT); - gtk_widget_set_sensitive (GTK_WIDGET (editButton), FALSE); - g_signal_connect_swapped (G_OBJECT (editButton), "clicked", - G_CALLBACK (edit_account_cb), NULL); - gtk_box_pack_start (GTK_BOX (buttonBox), editButton, FALSE, FALSE, 0); - - deleteButton = gtk_button_new_from_stock (GTK_STOCK_REMOVE); - gtk_widget_set_sensitive (GTK_WIDGET (deleteButton), FALSE); - g_signal_connect_swapped (G_OBJECT (deleteButton), "clicked", - G_CALLBACK (delete_account_cb), NULL); - gtk_box_pack_start (GTK_BOX (buttonBox), deleteButton, FALSE, FALSE, 0); + buttonBox = gtk_button_box_new(GTK_ORIENTATION_VERTICAL); + gtk_box_set_spacing(GTK_BOX(buttonBox), 10); + gtk_button_box_set_layout(GTK_BUTTON_BOX(buttonBox), GTK_BUTTONBOX_START); + gtk_table_attach(GTK_TABLE(table), buttonBox, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + + accountMoveUpButton = gtk_button_new_from_stock(GTK_STOCK_GO_UP); + gtk_widget_set_sensitive(GTK_WIDGET(accountMoveUpButton), FALSE); + gtk_box_pack_start(GTK_BOX(buttonBox), accountMoveUpButton, FALSE, FALSE, 0); + g_signal_connect(G_OBJECT(accountMoveUpButton), "clicked", G_CALLBACK(account_move_up_cb), treeView); + + accountMoveDownButton = gtk_button_new_from_stock(GTK_STOCK_GO_DOWN); + gtk_widget_set_sensitive(GTK_WIDGET(accountMoveDownButton), FALSE); + gtk_box_pack_start(GTK_BOX(buttonBox), accountMoveDownButton, FALSE, FALSE, 0); + g_signal_connect(G_OBJECT(accountMoveDownButton), "clicked", G_CALLBACK(account_move_down_cb), treeView); + + addButton = gtk_button_new_from_stock(GTK_STOCK_ADD); + g_signal_connect_swapped(G_OBJECT(addButton), "clicked", + G_CALLBACK(add_account_cb), NULL); + gtk_box_pack_start(GTK_BOX(buttonBox), addButton, FALSE, FALSE, 0); + + editButton = gtk_button_new_from_stock(GTK_STOCK_EDIT); + gtk_widget_set_sensitive(GTK_WIDGET(editButton), FALSE); + g_signal_connect_swapped(G_OBJECT(editButton), "clicked", + G_CALLBACK(edit_account_cb), NULL); + gtk_box_pack_start(GTK_BOX(buttonBox), editButton, FALSE, FALSE, 0); + + deleteButton = gtk_button_new_from_stock(GTK_STOCK_REMOVE); + gtk_widget_set_sensitive(GTK_WIDGET(deleteButton), FALSE); + g_signal_connect_swapped(G_OBJECT(deleteButton), "clicked", + G_CALLBACK(delete_account_cb), NULL); + gtk_box_pack_start(GTK_BOX(buttonBox), deleteButton, FALSE, FALSE, 0); /* help and close buttons */ - GtkWidget * buttonHbox = gtk_hbutton_box_new(); - gtk_table_attach (GTK_TABLE (table), buttonHbox, 0, 2, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 10); + GtkWidget * buttonHbox = gtk_button_box_new(GTK_ORIENTATION_HORIZONTAL); + gtk_table_attach(GTK_TABLE(table), buttonHbox, 0, 2, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 10); - GtkWidget * helpButton = gtk_button_new_from_stock (GTK_STOCK_HELP); - g_signal_connect_swapped (G_OBJECT (helpButton), "clicked", - G_CALLBACK (help_contents_cb), NULL); - gtk_box_pack_start (GTK_BOX (buttonHbox), helpButton, FALSE, FALSE, 0); + GtkWidget * helpButton = gtk_button_new_from_stock(GTK_STOCK_HELP); + g_signal_connect_swapped(G_OBJECT(helpButton), "clicked", + G_CALLBACK(help_contents_cb), NULL); + gtk_box_pack_start(GTK_BOX(buttonHbox), helpButton, FALSE, FALSE, 0); - GtkWidget * closeButton = gtk_button_new_from_stock (GTK_STOCK_CLOSE); - g_signal_connect_swapped (G_OBJECT (closeButton), "clicked", G_CALLBACK (close_dialog_cb), NULL); - gtk_box_pack_start (GTK_BOX (buttonHbox), closeButton, FALSE, FALSE, 0); + GtkWidget * closeButton = gtk_button_new_from_stock(GTK_STOCK_CLOSE); + g_signal_connect_swapped(G_OBJECT(closeButton), "clicked", G_CALLBACK(close_dialog_cb), NULL); + gtk_box_pack_start(GTK_BOX(buttonHbox), closeButton, FALSE, FALSE, 0); - gtk_widget_show_all (table); + gtk_widget_show_all(table); // account_list_config_dialog_fill(); /* Resize the scrolledWindow for a better view */ - gtk_widget_size_request (GTK_WIDGET (treeView), &requisition); - gtk_widget_set_size_request (GTK_WIDGET (scrolledWindow), requisition.width + 20, requisition.height); + gtk_widget_get_preferred_size(GTK_WIDGET(treeView), NULL, &requisition); + gtk_widget_set_size_request(GTK_WIDGET(scrolledWindow), requisition.width + 20, requisition.height); GtkRequisition requisitionButton; - gtk_widget_size_request (GTK_WIDGET (deleteButton), &requisitionButton); - gtk_widget_set_size_request (GTK_WIDGET (closeButton), requisitionButton.width, -1); - gtk_widget_set_size_request (GTK_WIDGET (helpButton), requisitionButton.width, -1); + gtk_widget_get_preferred_size(GTK_WIDGET(deleteButton), NULL, &requisitionButton); + gtk_widget_set_size_request(GTK_WIDGET(closeButton), requisitionButton.width, -1); + gtk_widget_set_size_request(GTK_WIDGET(helpButton), requisitionButton.width, -1); - gtk_widget_show_all (table); + gtk_widget_show_all(table); return table; } void -show_account_list_config_dialog (void) +show_account_list_config_dialog(void) { - GtkWidget * accountFrame; - GtkWidget * tab; - - accountListDialog = GTK_DIALOG (gtk_dialog_new_with_buttons (_ ("Accounts"), - GTK_WINDOW (get_main_window()), - GTK_DIALOG_DESTROY_WITH_PARENT, - NULL)); + accountListDialog = GTK_DIALOG(gtk_dialog_new_with_buttons(_("Accounts"), + GTK_WINDOW(get_main_window()), + GTK_DIALOG_DESTROY_WITH_PARENT, + NULL)); /* Set window properties */ - gtk_container_set_border_width (GTK_CONTAINER (accountListDialog), 0); - gtk_window_set_resizable (GTK_WINDOW (accountListDialog), FALSE); + gtk_container_set_border_width(GTK_CONTAINER(accountListDialog), 0); + gtk_window_set_resizable(GTK_WINDOW(accountListDialog), FALSE); - gnome_main_section_new (_ ("Configured Accounts"), &accountFrame); - gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area(accountListDialog)), accountFrame , TRUE, TRUE, 0); - gtk_widget_show (accountFrame); + GtkWidget *accountFrame = gnome_main_section_new(_("Configured Accounts")); + gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(accountListDialog)), + accountFrame, TRUE, TRUE, 0); + gtk_widget_show(accountFrame); /* Accounts tab */ - tab = create_account_list (accountListDialog); - gtk_widget_show (tab); - gtk_container_add (GTK_CONTAINER (accountFrame), tab); + GtkWidget *tab = create_account_list(accountListDialog); + gtk_widget_show(tab); + gtk_container_add(GTK_CONTAINER(accountFrame), tab); /* Status bar for the account list */ status_bar = gtk_statusbar_new(); - gtk_statusbar_set_has_resize_grip (GTK_STATUSBAR (status_bar), FALSE); gtk_widget_show (status_bar); gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area(accountListDialog)), status_bar, TRUE, TRUE, 0); - int number_accounts = account_list_get_registered_accounts (); + int number_accounts = account_list_get_registered_accounts(); if (number_accounts) { - gchar * message = g_strdup_printf (n_ ("There is %d active account", - "There are %d active accounts", number_accounts), - number_accounts); - gtk_statusbar_push (GTK_STATUSBAR (status_bar), CONTEXT_ID_REGISTRATION, message); - g_free (message); - } else { - gtk_statusbar_push (GTK_STATUSBAR (status_bar), CONTEXT_ID_REGISTRATION, _ ("You have no active account")); - } + gchar * message = g_strdup_printf(n_("There is %d active account", + "There are %d active accounts", + number_accounts), number_accounts); + gtk_statusbar_push(GTK_STATUSBAR(status_bar), CONTEXT_ID_REGISTRATION, message); + g_free(message); + } else + gtk_statusbar_push(GTK_STATUSBAR(status_bar), CONTEXT_ID_REGISTRATION, + _("You have no active account")); - gtk_dialog_run (accountListDialog); + gtk_dialog_run(accountListDialog); - status_bar_display_account (); - - gtk_widget_destroy (GTK_WIDGET (accountListDialog)); + status_bar_display_account(); + gtk_widget_destroy(GTK_WIDGET(accountListDialog)); accountListDialog = NULL; - - update_actions (); + update_actions(); } diff --git a/gnome/src/config/addressbook-config.c b/gnome/src/config/addressbook-config.c index 0f3f912529384ad42380e6896ffc570003c3daef..4c56da203677369e5e7f14d7d8c4be75d7b89b60 100644 --- a/gnome/src/config/addressbook-config.c +++ b/gnome/src/config/addressbook-config.c @@ -29,15 +29,26 @@ */ #include "addressbook-config.h" +#include "dbus.h" +#include "unused.h" +#include "logger.h" #include "searchbar.h" #include "contacts/addrbookfactory.h" #include <string.h> #include <stdlib.h> -AddressBook_Config *addressbook_config; -GtkWidget *book_tree_view; +static AddressBook_Config *addressbook_config; +static GtkWidget *book_tree_view; -GtkWidget *photo, *cards_label, *scale_label, *scrolled_label, *scrolled_window, *scale_button, *business, *mobile, *home; +static GtkWidget *photo; +static GtkWidget *cards_label; +static GtkWidget *scale_label; +static GtkWidget *scrolled_label; +static GtkWidget *scrolled_window; +static GtkWidget *scale_button; +static GtkWidget *business; +static GtkWidget *mobile; +static GtkWidget *home; enum { COLUMN_BOOK_ACTIVE, COLUMN_BOOK_NAME, COLUMN_BOOK_UID @@ -57,13 +68,14 @@ AddressBook_Config *addressbook_config_load_parameters() static AddressBook_Config config; GHashTable *params = dbus_get_addressbook_settings(); + if (params) { - config.enable = (size_t) (g_hash_table_lookup (params, ADDRESSBOOK_ENABLE)); - config.max_results = (size_t) (g_hash_table_lookup (params, ADDRESSBOOK_MAX_RESULTS)); - config.display_contact_photo = (size_t) (g_hash_table_lookup (params, ADDRESSBOOK_DISPLAY_CONTACT_PHOTO)); - config.search_phone_business = (size_t) (g_hash_table_lookup (params, ADDRESSBOOK_DISPLAY_PHONE_BUSINESS)); - config.search_phone_home = (size_t) (g_hash_table_lookup (params, ADDRESSBOOK_DISPLAY_PHONE_HOME)); - config.search_phone_mobile = (size_t) (g_hash_table_lookup (params, ADDRESSBOOK_DISPLAY_PHONE_MOBILE)); + config.enable = (size_t)(g_hash_table_lookup(params, ADDRESSBOOK_ENABLE)); + config.max_results = (size_t)(g_hash_table_lookup(params, ADDRESSBOOK_MAX_RESULTS)); + config.display_contact_photo = (size_t)(g_hash_table_lookup(params, ADDRESSBOOK_DISPLAY_CONTACT_PHOTO)); + config.search_phone_business = (size_t)(g_hash_table_lookup(params, ADDRESSBOOK_DISPLAY_PHONE_BUSINESS)); + config.search_phone_home = (size_t)(g_hash_table_lookup(params, ADDRESSBOOK_DISPLAY_PHONE_HOME)); + config.search_phone_mobile = (size_t)(g_hash_table_lookup(params, ADDRESSBOOK_DISPLAY_PHONE_MOBILE)); } else config = defconfig; @@ -71,31 +83,31 @@ AddressBook_Config *addressbook_config_load_parameters() } void -addressbook_config_save_parameters (void) +addressbook_config_save_parameters(void) { GHashTable *params = NULL; - params = g_hash_table_new (NULL, g_str_equal); - g_hash_table_replace (params, (gpointer) ADDRESSBOOK_ENABLE, - (gpointer) (size_t) addressbook_config->enable); - g_hash_table_replace (params, (gpointer) ADDRESSBOOK_MAX_RESULTS, - (gpointer) (size_t) addressbook_config->max_results); - g_hash_table_replace (params, (gpointer) ADDRESSBOOK_DISPLAY_CONTACT_PHOTO, - (gpointer) (size_t) addressbook_config->display_contact_photo); - g_hash_table_replace (params, (gpointer) ADDRESSBOOK_DISPLAY_PHONE_BUSINESS, - (gpointer) (size_t) addressbook_config->search_phone_business); - g_hash_table_replace (params, (gpointer) ADDRESSBOOK_DISPLAY_PHONE_HOME, - (gpointer) (size_t) addressbook_config->search_phone_home); - g_hash_table_replace (params, (gpointer) ADDRESSBOOK_DISPLAY_PHONE_MOBILE, - (gpointer) (size_t) addressbook_config->search_phone_mobile); - - dbus_set_addressbook_settings (params); + params = g_hash_table_new(NULL, g_str_equal); + g_hash_table_replace(params, (gpointer) ADDRESSBOOK_ENABLE, + (gpointer)(size_t) addressbook_config->enable); + g_hash_table_replace(params, (gpointer) ADDRESSBOOK_MAX_RESULTS, + (gpointer)(size_t) addressbook_config->max_results); + g_hash_table_replace(params, (gpointer) ADDRESSBOOK_DISPLAY_CONTACT_PHOTO, + (gpointer)(size_t) addressbook_config->display_contact_photo); + g_hash_table_replace(params, (gpointer) ADDRESSBOOK_DISPLAY_PHONE_BUSINESS, + (gpointer)(size_t) addressbook_config->search_phone_business); + g_hash_table_replace(params, (gpointer) ADDRESSBOOK_DISPLAY_PHONE_HOME, + (gpointer)(size_t) addressbook_config->search_phone_home); + g_hash_table_replace(params, (gpointer) ADDRESSBOOK_DISPLAY_PHONE_MOBILE, + (gpointer)(size_t) addressbook_config->search_phone_mobile); + + dbus_set_addressbook_settings(params); update_searchbar_addressbook_list(); // Decrement the reference count - g_hash_table_unref (params); + g_hash_table_unref(params); } void @@ -103,40 +115,40 @@ enable_options() { if (!addressbook_config->enable) { - DEBUG ("Disable addressbook options\n"); - gtk_widget_set_sensitive (photo, FALSE); - gtk_widget_set_sensitive (scrolled_label, FALSE); - gtk_widget_set_sensitive (cards_label, FALSE); - gtk_widget_set_sensitive (scrolled_window, FALSE); - gtk_widget_set_sensitive (scale_button, FALSE); - gtk_widget_set_sensitive (scale_label, FALSE); - gtk_widget_set_sensitive (business, FALSE); - gtk_widget_set_sensitive (mobile, FALSE); - gtk_widget_set_sensitive (home, FALSE); - gtk_widget_set_sensitive (book_tree_view, FALSE); + DEBUG("Disable addressbook options\n"); + gtk_widget_set_sensitive(photo, FALSE); + gtk_widget_set_sensitive(scrolled_label, FALSE); + gtk_widget_set_sensitive(cards_label, FALSE); + gtk_widget_set_sensitive(scrolled_window, FALSE); + gtk_widget_set_sensitive(scale_button, FALSE); + gtk_widget_set_sensitive(scale_label, FALSE); + gtk_widget_set_sensitive(business, FALSE); + gtk_widget_set_sensitive(mobile, FALSE); + gtk_widget_set_sensitive(home, FALSE); + gtk_widget_set_sensitive(book_tree_view, FALSE); } else { - DEBUG ("Enable addressbook options\n"); - gtk_widget_set_sensitive (photo, TRUE); - gtk_widget_set_sensitive (scrolled_label, TRUE); - gtk_widget_set_sensitive (cards_label, TRUE); - gtk_widget_set_sensitive (scrolled_window, TRUE); - gtk_widget_set_sensitive (scale_button, TRUE); - gtk_widget_set_sensitive (scale_label, TRUE); - gtk_widget_set_sensitive (business, TRUE); - gtk_widget_set_sensitive (mobile, TRUE); - gtk_widget_set_sensitive (home, TRUE); - gtk_widget_set_sensitive (book_tree_view, TRUE); + DEBUG("Enable addressbook options\n"); + gtk_widget_set_sensitive(photo, TRUE); + gtk_widget_set_sensitive(scrolled_label, TRUE); + gtk_widget_set_sensitive(cards_label, TRUE); + gtk_widget_set_sensitive(scrolled_window, TRUE); + gtk_widget_set_sensitive(scale_button, TRUE); + gtk_widget_set_sensitive(scale_label, TRUE); + gtk_widget_set_sensitive(business, TRUE); + gtk_widget_set_sensitive(mobile, TRUE); + gtk_widget_set_sensitive(home, TRUE); + gtk_widget_set_sensitive(book_tree_view, TRUE); } } static void -enable_cb (GtkWidget *widget) +enable_cb(GtkWidget *widget) { addressbook_config->enable - = (guint) gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)); + = (guint) gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)); enable_options(); @@ -144,41 +156,41 @@ enable_cb (GtkWidget *widget) } static void -max_results_cb (GtkSpinButton *button) +max_results_cb(GtkSpinButton *button) { - addressbook_config->max_results = gtk_spin_button_get_value_as_int (button); + addressbook_config->max_results = gtk_spin_button_get_value_as_int(button); } static void -display_contact_photo_cb (GtkWidget *widget) +display_contact_photo_cb(GtkWidget *widget) { addressbook_config->display_contact_photo - = (guint) gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)); + = (guint) gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)); } static void -search_phone_business_cb (GtkWidget *widget) +search_phone_business_cb(GtkWidget *widget) { addressbook_config->search_phone_business - = (guint) gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)); + = (guint) gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)); } static void -search_phone_home_cb (GtkWidget *widget) +search_phone_home_cb(GtkWidget *widget) { - addressbook_config->search_phone_home = (guint) gtk_toggle_button_get_active ( - GTK_TOGGLE_BUTTON (widget)); + addressbook_config->search_phone_home = (guint) gtk_toggle_button_get_active( + GTK_TOGGLE_BUTTON(widget)); } static void -search_phone_mobile_cb (GtkWidget *widget) +search_phone_mobile_cb(GtkWidget *widget) { addressbook_config->search_phone_mobile - = (guint) gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)); + = (guint) gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)); } /** @@ -186,7 +198,7 @@ search_phone_mobile_cb (GtkWidget *widget) * and in configuration files */ static void -addressbook_config_book_active_toggled ( +addressbook_config_book_active_toggled( GtkCellRendererToggle *renderer UNUSED, gchar *path, gpointer data) { GtkTreeIter iter; @@ -197,73 +209,75 @@ addressbook_config_book_active_toggled ( gchar* name; gchar* uid; - if(!addrbook) + if (!addrbook) return; // Get path of clicked book active toggle box - treePath = gtk_tree_path_new_from_string (path); + treePath = gtk_tree_path_new_from_string(path); - if (! (model = gtk_tree_view_get_model (GTK_TREE_VIEW (data)))) { - DEBUG ("Addressbook: No valid model (%s:%d)", __FILE__, __LINE__); + if (!(model = gtk_tree_view_get_model(GTK_TREE_VIEW(data)))) { + DEBUG("Addressbook: No valid model (%s:%d)", __FILE__, __LINE__); return; } - gtk_tree_model_get_iter (model, &iter, treePath); + gtk_tree_model_get_iter(model, &iter, treePath); // Get active value at iteration - gtk_tree_model_get (model, &iter, COLUMN_BOOK_ACTIVE, &active, - COLUMN_BOOK_UID, &uid, COLUMN_BOOK_NAME, &name, -1); + gtk_tree_model_get(model, &iter, COLUMN_BOOK_ACTIVE, &active, + COLUMN_BOOK_UID, &uid, COLUMN_BOOK_NAME, &name, -1); // Toggle active value active = !active; // Store value - gtk_list_store_set (GTK_LIST_STORE (model), &iter, COLUMN_BOOK_ACTIVE, active, -1); + gtk_list_store_set(GTK_LIST_STORE(model), &iter, COLUMN_BOOK_ACTIVE, active, -1); - gtk_tree_path_free (treePath); + gtk_tree_path_free(treePath); // Update current memory stored books data book_data = addrbook->get_book_data_by_uid(uid); - if(book_data == NULL) { - ERROR("Addressbook: Error: Could not find addressbook %s", uid); + + if (book_data == NULL) { + ERROR("Addressbook: Error: Could not find addressbook %s", uid); } + book_data->active = active; // Save data gboolean valid; // Initiate double array char list for one string - const gchar** list = (void*) malloc (sizeof (void*)); + const gchar** list = (void*) malloc(sizeof(void*)); int c = 0; /* Get the first iter in the list */ - valid = gtk_tree_model_get_iter_first (model, &iter); + valid = gtk_tree_model_get_iter_first(model, &iter); while (valid) { // Get active value at iteration - gtk_tree_model_get (model, &iter, COLUMN_BOOK_ACTIVE, &active, - COLUMN_BOOK_UID, &uid, COLUMN_BOOK_NAME, &name, -1); + gtk_tree_model_get(model, &iter, COLUMN_BOOK_ACTIVE, &active, + COLUMN_BOOK_UID, &uid, COLUMN_BOOK_NAME, &name, -1); if (active) { // Reallocate memory each time if (c != 0) - list = (void*) realloc (list, (c + 1) * sizeof (void*)); + list = (void*) realloc(list, (c + 1) * sizeof(void*)); - * (list + c) = uid; + *(list + c) = uid; c++; } - valid = gtk_tree_model_iter_next (model, &iter); + valid = gtk_tree_model_iter_next(model, &iter); } // Allocate NULL array at the end for Dbus - list = (void*) realloc (list, (c + 1) * sizeof (void*)); - * (list + c) = NULL; + list = (void*) realloc(list, (c + 1) * sizeof(void*)); + *(list + c) = NULL; // Call daemon to store in config file - dbus_set_addressbook_list (list); + dbus_set_addressbook_list(list); - free (list); + free(list); } static void @@ -275,43 +289,42 @@ addressbook_config_fill_book_list() book_data_t *book_data; gchar **book_list; - if(!addrbook) + if (!addrbook) return; book_list = dbus_get_addressbook_list(); GSList *books_data = addrbook->get_books_data(book_list); if (!books_data) { - DEBUG ("Addressbook: No valid books data (%s:%d)", __FILE__, __LINE__); + DEBUG("Addressbook: No valid books data (%s:%d)", __FILE__, __LINE__); } // Get model of view and clear it - if (! (store = GTK_LIST_STORE (gtk_tree_view_get_model (GTK_TREE_VIEW (book_tree_view))))) { - DEBUG ("Addressbook: Could not find model from treeview (%s:%d)", __FILE__, __LINE__); + if (!(store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(book_tree_view))))) { + DEBUG("Addressbook: Could not find model from treeview (%s:%d)", __FILE__, __LINE__); return; } - gtk_list_store_clear (store); + gtk_list_store_clear(store); // Populate window for (book_list_iterator = books_data; book_list_iterator != NULL; book_list_iterator = book_list_iterator->next) { book_data = (book_data_t *) book_list_iterator->data; - gtk_list_store_append (store, &list_store_iterator); + gtk_list_store_append(store, &list_store_iterator); DEBUG("-----------------------------------: %s, %s", book_data->name, book_data->active ? "active" : "not-active"); - gtk_list_store_set (store, &list_store_iterator, COLUMN_BOOK_ACTIVE, - book_data->active, COLUMN_BOOK_UID, book_data->uid, COLUMN_BOOK_NAME, - book_data->name, -1); + gtk_list_store_set(store, &list_store_iterator, COLUMN_BOOK_ACTIVE, + book_data->active, COLUMN_BOOK_UID, book_data->uid, COLUMN_BOOK_NAME, + book_data->name, -1); } - store = GTK_LIST_STORE (gtk_tree_view_get_model (GTK_TREE_VIEW (book_tree_view))); + store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(book_tree_view))); } GtkWidget* create_addressbook_settings() { - - GtkWidget *ret, *result_frame, *table, *value, *item; + GtkWidget *result_frame, *table, *value, *item; GtkListStore *store; GtkCellRenderer *renderer; @@ -320,113 +333,104 @@ create_addressbook_settings() // Load the user value addressbook_config = addressbook_config_load_parameters(); - ret = gtk_vbox_new (FALSE, 10); - gtk_container_set_border_width (GTK_CONTAINER (ret), 10); - - gnome_main_section_new_with_table (_ ("General"), &result_frame, &table, 3, 3); - gtk_box_pack_start (GTK_BOX (ret), result_frame, FALSE, FALSE, 0); - // gtk_widget_show (result_frame); + GtkWidget *ret = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); + gtk_container_set_border_width(GTK_CONTAINER(ret), 10); + gnome_main_section_new_with_table(_("General"), &result_frame, &table, 3, 3); + gtk_box_pack_start(GTK_BOX(ret), result_frame, FALSE, FALSE, 0); // PHOTO DISPLAY - item = gtk_check_button_new_with_mnemonic (_ ("_Use Evolution address books")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (item), addressbook_config->enable); - g_signal_connect (G_OBJECT (item) , "clicked" , G_CALLBACK (enable_cb), NULL); - gtk_table_attach (GTK_TABLE (table), item, 1, 3, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + item = gtk_check_button_new_with_mnemonic(_("_Use Evolution address books")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(item), addressbook_config->enable); + g_signal_connect(G_OBJECT(item) , "clicked" , G_CALLBACK(enable_cb), NULL); + gtk_table_attach(GTK_TABLE(table), item, 1, 3, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); // SCALE BUTTON - NUMBER OF RESULTS - scale_button = gtk_hbox_new (FALSE, 0); - scale_label = gtk_label_new (_ ("Download limit :")); - gtk_box_pack_start (GTK_BOX (scale_button),scale_label,FALSE,FALSE,0); - value = gtk_spin_button_new_with_range (1, G_MAXINT, 1); - gtk_label_set_mnemonic_widget (GTK_LABEL (scale_label), value); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (value) , addressbook_config->max_results); - g_signal_connect (G_OBJECT (value) , "value-changed" , G_CALLBACK (max_results_cb), NULL); - gtk_box_pack_start (GTK_BOX (scale_button),value,TRUE,TRUE,10); - gtk_table_attach (GTK_TABLE (table), scale_button, 1, 2, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND |GTK_FILL, 0, 0); - cards_label = gtk_label_new (_ ("cards")); - gtk_table_attach (GTK_TABLE (table), cards_label, 2, 3, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_show_all (scale_button); - + scale_button = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + scale_label = gtk_label_new(_("Download limit :")); + gtk_box_pack_start(GTK_BOX(scale_button),scale_label,FALSE,FALSE,0); + value = gtk_spin_button_new_with_range(1, G_MAXINT, 1); + gtk_label_set_mnemonic_widget(GTK_LABEL(scale_label), value); + gtk_spin_button_set_value(GTK_SPIN_BUTTON(value) , addressbook_config->max_results); + g_signal_connect(G_OBJECT(value) , "value-changed" , G_CALLBACK(max_results_cb), NULL); + gtk_box_pack_start(GTK_BOX(scale_button),value,TRUE,TRUE,10); + gtk_table_attach(GTK_TABLE(table), scale_button, 1, 2, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND |GTK_FILL, 0, 0); + cards_label = gtk_label_new(_("cards")); + gtk_table_attach(GTK_TABLE(table), cards_label, 2, 3, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_widget_show_all(scale_button); // PHOTO DISPLAY - photo = gtk_check_button_new_with_mnemonic (_ ("_Display contact photo if available")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (photo), addressbook_config->display_contact_photo); - g_signal_connect (G_OBJECT (photo) , "clicked" , G_CALLBACK (display_contact_photo_cb), NULL); - gtk_table_attach (GTK_TABLE (table), photo, 1, 3, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - - + photo = gtk_check_button_new_with_mnemonic(_("_Display contact photo if available")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(photo), addressbook_config->display_contact_photo); + g_signal_connect(G_OBJECT(photo) , "clicked" , G_CALLBACK(display_contact_photo_cb), NULL); + gtk_table_attach(GTK_TABLE(table), photo, 1, 3, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); // Fields - gnome_main_section_new_with_table (_ ("Fields from Evolution's address books"), &result_frame, &table, 1, 3); - gtk_box_pack_start (GTK_BOX (ret), result_frame, FALSE, FALSE, 0); - // gtk_widget_show (result_frame); - - business = gtk_check_button_new_with_mnemonic (_ ("_Work")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (business), addressbook_config->search_phone_business); - g_signal_connect (G_OBJECT (business) , "clicked" , G_CALLBACK (search_phone_business_cb) , NULL); - gtk_table_attach (GTK_TABLE (table), business, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_set_sensitive (business, FALSE); - - home = gtk_check_button_new_with_mnemonic (_ ("_Home")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (home), addressbook_config->search_phone_home); - g_signal_connect (G_OBJECT (home) , "clicked" , G_CALLBACK (search_phone_home_cb) , NULL); - gtk_table_attach (GTK_TABLE (table), home, 0, 1, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_set_sensitive (home, FALSE); - - mobile = gtk_check_button_new_with_mnemonic (_ ("_Mobile")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (mobile), addressbook_config->search_phone_mobile); - g_signal_connect (G_OBJECT (mobile) , "clicked" , G_CALLBACK (search_phone_mobile_cb) , NULL); - gtk_table_attach (GTK_TABLE (table), mobile, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - + gnome_main_section_new_with_table(_("Fields from Evolution's address books"), &result_frame, &table, 1, 3); + gtk_box_pack_start(GTK_BOX(ret), result_frame, FALSE, FALSE, 0); + + business = gtk_check_button_new_with_mnemonic(_("_Work")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(business), addressbook_config->search_phone_business); + g_signal_connect(G_OBJECT(business) , "clicked" , G_CALLBACK(search_phone_business_cb) , NULL); + gtk_table_attach(GTK_TABLE(table), business, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_widget_set_sensitive(business, FALSE); + + home = gtk_check_button_new_with_mnemonic(_("_Home")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(home), addressbook_config->search_phone_home); + g_signal_connect(G_OBJECT(home) , "clicked" , G_CALLBACK(search_phone_home_cb) , NULL); + gtk_table_attach(GTK_TABLE(table), home, 0, 1, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_widget_set_sensitive(home, FALSE); + + mobile = gtk_check_button_new_with_mnemonic(_("_Mobile")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(mobile), addressbook_config->search_phone_mobile); + g_signal_connect(G_OBJECT(mobile) , "clicked" , G_CALLBACK(search_phone_mobile_cb) , NULL); + gtk_table_attach(GTK_TABLE(table), mobile, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); // Address Book - gnome_main_section_new_with_table (_ ("Address Books"), &result_frame, &table, 2, 3); - gtk_box_pack_start (GTK_BOX (ret), result_frame, TRUE, TRUE, 0); - gtk_widget_show (result_frame); - - scrolled_label = gtk_label_new (_ ("Select which Evolution address books to use")); - gtk_misc_set_alignment (GTK_MISC (scrolled_label), 0.00, 0.2); + gnome_main_section_new_with_table(_("Address Books"), &result_frame, &table, 2, 3); + gtk_box_pack_start(GTK_BOX(ret), result_frame, TRUE, TRUE, 0); + gtk_widget_show(result_frame); - gtk_table_attach (GTK_TABLE (table), scrolled_label, 1, 4, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_set_sensitive (scrolled_label, FALSE); + scrolled_label = gtk_label_new(_("Select which Evolution address books to use")); + gtk_misc_set_alignment(GTK_MISC(scrolled_label), 0.00, 0.2); - scrolled_window = gtk_scrolled_window_new (NULL, NULL); - gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); - gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolled_window), GTK_SHADOW_IN); + gtk_table_attach(GTK_TABLE(table), scrolled_label, 1, 4, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_widget_set_sensitive(scrolled_label, FALSE); - gtk_table_attach (GTK_TABLE (table), scrolled_window, 1, 4, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + scrolled_window = gtk_scrolled_window_new(NULL, NULL); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); + gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolled_window), GTK_SHADOW_IN); + gtk_table_attach(GTK_TABLE(table), scrolled_window, 1, 4, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - - store = gtk_list_store_new (3, - G_TYPE_BOOLEAN, // Active - G_TYPE_STRING, // uid - G_TYPE_STRING // Name - ); + store = gtk_list_store_new(3, + G_TYPE_BOOLEAN, // Active + G_TYPE_STRING, // uid + G_TYPE_STRING // Name + ); // Create tree view with list store - book_tree_view = gtk_tree_view_new_with_model (GTK_TREE_MODEL (store)); + book_tree_view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); // Active column renderer = gtk_cell_renderer_toggle_new(); - tree_view_column = gtk_tree_view_column_new_with_attributes ("", renderer, "active", COLUMN_BOOK_ACTIVE, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (book_tree_view), tree_view_column); + tree_view_column = gtk_tree_view_column_new_with_attributes("", renderer, "active", COLUMN_BOOK_ACTIVE, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(book_tree_view), tree_view_column); // Toggle active property on clicked - g_signal_connect (G_OBJECT (renderer), "toggled", G_CALLBACK (addressbook_config_book_active_toggled), (gpointer) book_tree_view); + g_signal_connect(G_OBJECT(renderer), "toggled", G_CALLBACK(addressbook_config_book_active_toggled), (gpointer) book_tree_view); // Name column renderer = gtk_cell_renderer_text_new(); - tree_view_column = gtk_tree_view_column_new_with_attributes (_ ("Name"), renderer, "markup", COLUMN_BOOK_NAME, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (book_tree_view), tree_view_column); + tree_view_column = gtk_tree_view_column_new_with_attributes(_("Name"), renderer, "markup", COLUMN_BOOK_NAME, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(book_tree_view), tree_view_column); - g_object_unref (G_OBJECT (store)); - gtk_container_add (GTK_CONTAINER (scrolled_window), book_tree_view); + g_object_unref(G_OBJECT(store)); + gtk_container_add(GTK_CONTAINER(scrolled_window), book_tree_view); addressbook_config_fill_book_list(); - gtk_widget_show_all (ret); + gtk_widget_show_all(ret); enable_options(); @@ -434,23 +438,18 @@ create_addressbook_settings() } gboolean -addressbook_display (AddressBook_Config *settings, const gchar *field) +addressbook_display(AddressBook_Config *settings, const gchar *field) { + gboolean display; - gboolean display = FALSE; - - if (g_strcasecmp (field, ADDRESSBOOK_DISPLAY_CONTACT_PHOTO) == 0) + if (g_strcasecmp(field, ADDRESSBOOK_DISPLAY_CONTACT_PHOTO) == 0) display = (settings->display_contact_photo == 1) ? TRUE : FALSE; - - else if (g_strcasecmp (field, ADDRESSBOOK_DISPLAY_PHONE_BUSINESS) == 0) + else if (g_strcasecmp(field, ADDRESSBOOK_DISPLAY_PHONE_BUSINESS) == 0) display = (settings->search_phone_business == 1) ? TRUE : FALSE; - - else if (g_strcasecmp (field, ADDRESSBOOK_DISPLAY_PHONE_HOME) == 0) + else if (g_strcasecmp(field, ADDRESSBOOK_DISPLAY_PHONE_HOME) == 0) display = (settings->search_phone_home == 1) ? TRUE : FALSE; - - else if (g_strcasecmp (field, ADDRESSBOOK_DISPLAY_PHONE_MOBILE) == 0) + else if (g_strcasecmp(field, ADDRESSBOOK_DISPLAY_PHONE_MOBILE) == 0) display = (settings->search_phone_mobile == 1) ? TRUE : FALSE; - else display = FALSE; diff --git a/gnome/src/config/assistant.c b/gnome/src/config/assistant.c index 56d15e0b4e5d2f837586da14248b9233b71fe9c9..8ca002115543ba01327688b250497f8344797bff 100644 --- a/gnome/src/config/assistant.c +++ b/gnome/src/config/assistant.c @@ -30,7 +30,10 @@ #include <string.h> +#include "unused.h" #include "assistant.h" +#include "logger.h" +#include "dbus.h" #include "reqaccount.h" #define SFLPHONE_ORG_SERVER "sip.sflphone.org" @@ -38,31 +41,30 @@ struct _wizard *wiz; static int account_type; static int use_sflphone_org = 1; -account_t* current; -char message[1024]; +static account_t* current; +static char message[1024]; /** * Forward function */ -static gint forward_page_func (gint current_page , gpointer data); +static gint forward_page_func(gint current_page , gpointer data); /** * Page template */ -static GtkWidget* create_vbox (GtkAssistantPageType type, const gchar *title, const gchar *section); -void prefill_sip (void) ; +static GtkWidget* create_vbox(GtkAssistantPageType type, const gchar *title, const gchar *section); +void prefill_sip(void) ; -void set_account_type (GtkWidget* widget , gpointer data UNUSED) +void set_account_type(GtkWidget* widget , gpointer data UNUSED) { - if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget))) { + if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget))) account_type = _SIP; - } else { + else account_type = _IAX ; - } } -static void show_password_cb (GtkWidget *widget UNUSED, gpointer data) +static void show_password_cb(GtkWidget *widget UNUSED, gpointer data) { - gtk_entry_set_visibility (GTK_ENTRY (data), !gtk_entry_get_visibility (GTK_ENTRY (data))); + gtk_entry_set_visibility(GTK_ENTRY(data), !gtk_entry_get_visibility(GTK_ENTRY(data))); } @@ -70,38 +72,37 @@ static void show_password_cb (GtkWidget *widget UNUSED, gpointer data) * Fills string message with the final message of account registration * with alias, server and username specified. */ -void getMessageSummary (char * message , const gchar * alias, const gchar * server, const gchar * username, const gboolean zrtp) +void getMessageSummary(const gchar * alias, const gchar * server, const gchar * username, const gboolean zrtp) { char var[64]; - sprintf (message, _ ("This assistant is now finished.")); - strcat (message, "\n"); - strcat (message, _ ("You can at any time check your registration state or modify your accounts parameters in the Options/Accounts window.")); - strcat (message, "\n\n"); + sprintf(message, _("This assistant is now finished.")); + strcat(message, "\n"); + strcat(message, _("You can at any time check your registration state or modify your accounts parameters in the Options/Accounts window.")); + strcat(message, "\n\n"); - strcat (message, _ ("Alias")); - snprintf (var, sizeof (var), " : %s\n", alias); - strcat (message, var); + strcat(message, _("Alias")); + snprintf(var, sizeof(var), " : %s\n", alias); + strcat(message, var); - strcat (message, _ ("Server")); - snprintf (var, sizeof (var), " : %s\n", server); - strcat (message, var); + strcat(message, _("Server")); + snprintf(var, sizeof(var), " : %s\n", server); + strcat(message, var); - strcat (message, _ ("Username")); - snprintf (var, sizeof (var), " : %s\n", username); - strcat (message, var); + strcat(message, _("Username")); + snprintf(var, sizeof(var), " : %s\n", username); + strcat(message, var); - strcat (message, _ ("Security: ")); + strcat(message, _("Security: ")); - if (zrtp) { - strcat (message, _ ("SRTP/ZRTP draft-zimmermann")); - } else { - strcat (message, _ ("None")); - } + if (zrtp) + strcat(message, _("SRTP/ZRTP draft-zimmermann")); + else + strcat(message, _("None")); } -void set_sflphone_org (GtkWidget* widget , gpointer data UNUSED) +void set_sflphone_org(GtkWidget* widget , gpointer data UNUSED) { - use_sflphone_org = (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) ?1:0) ; + use_sflphone_org = (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)) ?1:0) ; } @@ -110,33 +111,33 @@ void set_sflphone_org (GtkWidget* widget , gpointer data UNUSED) * Callback when the close button of the dialog is clicked * Action : close the assistant widget and get back to sflphone main window */ -static void close_callback (void) +static void close_callback(void) { - gtk_widget_destroy (wiz->assistant); - g_free (wiz); + gtk_widget_destroy(wiz->assistant); + g_free(wiz); wiz = NULL; - status_bar_display_account (); + status_bar_display_account(); } /** * Callback when the cancel button of the dialog is clicked * Action : close the assistant widget and get back to sflphone main window */ -static void cancel_callback (void) +static void cancel_callback(void) { - gtk_widget_destroy (wiz->assistant); - g_free (wiz); + gtk_widget_destroy(wiz->assistant); + g_free(wiz); wiz = NULL; - status_bar_display_account (); + status_bar_display_account(); } /** * Callback when the button apply is clicked * Action : Set the account parameters with the entries values and called dbus_add_account */ -static void sip_apply_callback (void) +static void sip_apply_callback(void) { if (use_sflphone_org) { prefill_sip(); @@ -144,23 +145,23 @@ static void sip_apply_callback (void) } if (account_type == _SIP) { - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_ALIAS), g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (wiz->sip_alias)))); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_ENABLED), g_strdup ("true")); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_MAILBOX), g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (wiz->sip_voicemail)))); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_TYPE), g_strdup ("SIP")); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_HOSTNAME), g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (wiz->sip_server)))); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_PASSWORD), g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (wiz->sip_password)))); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_USERNAME), g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (wiz->sip_username)))); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_SIP_STUN_ENABLED), g_strdup ( (gchar *) (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (wiz->enable)) ? "true":"false"))); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_SIP_STUN_SERVER), g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (wiz->addr)))); - - if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (wiz->zrtp_enable)) == TRUE) { - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_SRTP_ENABLED), g_strdup ( (gchar *) "true")); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_KEY_EXCHANGE), g_strdup ( (gchar *) ZRTP)); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_ZRTP_DISPLAY_SAS), g_strdup ( (gchar *) "true")); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_ZRTP_NOT_SUPP_WARNING), g_strdup ( (gchar *) "true")); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_ZRTP_HELLO_HASH), g_strdup ( (gchar *) "true")); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_DISPLAY_SAS_ONCE), g_strdup ( (gchar *) "false")); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_ALIAS), g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(wiz->sip_alias)))); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_ENABLED), g_strdup("true")); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_MAILBOX), g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(wiz->sip_voicemail)))); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_TYPE), g_strdup("SIP")); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_HOSTNAME), g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(wiz->sip_server)))); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_PASSWORD), g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(wiz->sip_password)))); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_USERNAME), g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(wiz->sip_username)))); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_SIP_STUN_ENABLED), g_strdup((gchar *)(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(wiz->enable)) ? "true":"false"))); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_SIP_STUN_SERVER), g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(wiz->addr)))); + + if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(wiz->zrtp_enable)) == TRUE) { + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_SRTP_ENABLED), g_strdup((gchar *) "true")); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_KEY_EXCHANGE), g_strdup((gchar *) ZRTP)); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_ZRTP_DISPLAY_SAS), g_strdup((gchar *) "true")); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_ZRTP_NOT_SUPP_WARNING), g_strdup((gchar *) "true")); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_ZRTP_HELLO_HASH), g_strdup((gchar *) "true")); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_DISPLAY_SAS_ONCE), g_strdup((gchar *) "false")); } @@ -171,21 +172,20 @@ static void sip_apply_callback (void) // select the first interface available iface = iface_list; - DEBUG ("Selected interface %s", *iface); + DEBUG("Selected interface %s", *iface); - g_hash_table_insert (current->properties, g_strdup (LOCAL_INTERFACE), g_strdup ( (gchar *) *iface)); + g_hash_table_insert(current->properties, g_strdup(LOCAL_INTERFACE), g_strdup((gchar *) *iface)); - g_hash_table_insert (current->properties, g_strdup (PUBLISHED_ADDRESS), g_strdup ( (gchar *) *iface)); + g_hash_table_insert(current->properties, g_strdup(PUBLISHED_ADDRESS), g_strdup((gchar *) *iface)); - dbus_add_account (current); - getMessageSummary (message, - gtk_entry_get_text (GTK_ENTRY (wiz->sip_alias)), - gtk_entry_get_text (GTK_ENTRY (wiz->sip_server)), - gtk_entry_get_text (GTK_ENTRY (wiz->sip_username)), - (gboolean) (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (wiz->zrtp_enable))) - ); + dbus_add_account(current); + getMessageSummary(gtk_entry_get_text(GTK_ENTRY(wiz->sip_alias)), + gtk_entry_get_text(GTK_ENTRY(wiz->sip_server)), + gtk_entry_get_text(GTK_ENTRY(wiz->sip_username)), + (gboolean)(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(wiz->zrtp_enable))) + ); - gtk_label_set_text (GTK_LABEL (wiz->label_summary), message); + gtk_label_set_text(GTK_LABEL(wiz->label_summary), message); } } @@ -193,58 +193,57 @@ static void sip_apply_callback (void) * Callback when the button apply is clicked * Action : Set the account parameters with the entries values and called dbus_add_account */ -static void iax_apply_callback (void) +static void iax_apply_callback(void) { if (account_type == _IAX) { - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_ALIAS), g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (wiz->iax_alias)))); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_ENABLED), g_strdup ("true")); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_MAILBOX), g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (wiz->iax_voicemail)))); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_TYPE), g_strdup ("IAX")); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_USERNAME), g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (wiz->iax_username)))); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_HOSTNAME), g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (wiz->iax_server)))); - g_hash_table_insert (current->properties, g_strdup (ACCOUNT_PASSWORD), g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (wiz->iax_password)))); - - dbus_add_account (current); - getMessageSummary (message, - gtk_entry_get_text (GTK_ENTRY (wiz->iax_alias)), - gtk_entry_get_text (GTK_ENTRY (wiz->iax_server)), - gtk_entry_get_text (GTK_ENTRY (wiz->iax_username)), - FALSE - ) ; - - gtk_label_set_text (GTK_LABEL (wiz->label_summary), message); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_ALIAS), g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(wiz->iax_alias)))); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_ENABLED), g_strdup("true")); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_MAILBOX), g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(wiz->iax_voicemail)))); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_TYPE), g_strdup("IAX")); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_USERNAME), g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(wiz->iax_username)))); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_HOSTNAME), g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(wiz->iax_server)))); + g_hash_table_insert(current->properties, g_strdup(ACCOUNT_PASSWORD), g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(wiz->iax_password)))); + + dbus_add_account(current); + getMessageSummary(gtk_entry_get_text(GTK_ENTRY(wiz->iax_alias)), + gtk_entry_get_text(GTK_ENTRY(wiz->iax_server)), + gtk_entry_get_text(GTK_ENTRY(wiz->iax_username)), + FALSE + ) ; + + gtk_label_set_text(GTK_LABEL(wiz->label_summary), message); } } -void enable_stun (GtkWidget* widget) +void enable_stun(GtkWidget* widget) { - gtk_widget_set_sensitive (GTK_WIDGET (wiz->addr), gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget))); + gtk_widget_set_sensitive(GTK_WIDGET(wiz->addr), gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget))); } -void build_wizard (void) +void build_wizard(void) { use_sflphone_org = 1; if (wiz) return ; - wiz = (struct _wizard*) g_malloc (sizeof (struct _wizard)); - current = g_new0 (account_t, 1); + wiz = (struct _wizard*) g_malloc(sizeof(struct _wizard)); + current = g_new0(account_t, 1); current->properties = NULL; - current->properties = dbus_get_account_details (NULL); + current->properties = dbus_get_account_details(NULL); if (current->properties == NULL) { - DEBUG ("Failed to get default values. Creating from scratch"); - current->properties = g_hash_table_new (NULL, g_str_equal); + DEBUG("Failed to get default values. Creating from scratch"); + current->properties = g_hash_table_new(NULL, g_str_equal); } current->accountID = g_strdup("new"); wiz->assistant = gtk_assistant_new(); - gtk_window_set_title (GTK_WINDOW (wiz->assistant), _ ("SFLphone account creation wizard")); - gtk_window_set_position (GTK_WINDOW (wiz->assistant), GTK_WIN_POS_CENTER); - gtk_window_set_default_size (GTK_WINDOW (wiz->assistant), 200 , 200); + gtk_window_set_title(GTK_WINDOW(wiz->assistant), _("SFLphone account creation wizard")); + gtk_window_set_position(GTK_WINDOW(wiz->assistant), GTK_WIN_POS_CENTER); + gtk_window_set_default_size(GTK_WINDOW(wiz->assistant), 200 , 200); build_intro(); build_sfl_or_account(); @@ -255,28 +254,28 @@ void build_wizard (void) build_email_configuration(); build_summary(); - g_signal_connect (G_OBJECT (wiz->assistant), "close" , G_CALLBACK (close_callback), NULL); + g_signal_connect(G_OBJECT(wiz->assistant), "close" , G_CALLBACK(close_callback), NULL); - g_signal_connect (G_OBJECT (wiz->assistant), "cancel" , G_CALLBACK (cancel_callback), NULL); + g_signal_connect(G_OBJECT(wiz->assistant), "cancel" , G_CALLBACK(cancel_callback), NULL); - gtk_widget_show_all (wiz->assistant); + gtk_widget_show_all(wiz->assistant); - gtk_assistant_set_forward_page_func (GTK_ASSISTANT (wiz->assistant), (GtkAssistantPageFunc) forward_page_func , NULL , NULL); - gtk_assistant_update_buttons_state (GTK_ASSISTANT (wiz->assistant)); + gtk_assistant_set_forward_page_func(GTK_ASSISTANT(wiz->assistant), (GtkAssistantPageFunc) forward_page_func , NULL , NULL); + gtk_assistant_update_buttons_state(GTK_ASSISTANT(wiz->assistant)); } GtkWidget* build_intro() { GtkWidget *label; - wiz->intro = create_vbox (GTK_ASSISTANT_PAGE_INTRO , "SFLphone GNOME client" , _ ("Welcome to the Account creation wizard of SFLphone!")); - label = gtk_label_new (_ ("This installation wizard will help you configure an account.")) ; - gtk_misc_set_alignment (GTK_MISC (label), 0, 0); - gtk_label_set_line_wrap (GTK_LABEL (label), TRUE); - gtk_widget_set_size_request (GTK_WIDGET (label), 380, -1); - gtk_box_pack_start (GTK_BOX (wiz->intro), label, FALSE, TRUE, 0); + wiz->intro = create_vbox(GTK_ASSISTANT_PAGE_INTRO , "SFLphone GNOME client" , _("Welcome to the Account creation wizard of SFLphone!")); + label = gtk_label_new(_("This installation wizard will help you configure an account.")) ; + gtk_misc_set_alignment(GTK_MISC(label), 0, 0); + gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); + gtk_widget_set_size_request(GTK_WIDGET(label), 380, -1); + gtk_box_pack_start(GTK_BOX(wiz->intro), label, FALSE, TRUE, 0); - gtk_assistant_set_page_complete (GTK_ASSISTANT (wiz->assistant), wiz->intro, TRUE); + gtk_assistant_set_page_complete(GTK_ASSISTANT(wiz->assistant), wiz->intro, TRUE); return wiz->intro; } @@ -285,16 +284,16 @@ GtkWidget* build_select_account() GtkWidget* sip; GtkWidget* iax; - wiz->protocols = create_vbox (GTK_ASSISTANT_PAGE_CONTENT , _ ("VoIP Protocols") , _ ("Select an account type")); + wiz->protocols = create_vbox(GTK_ASSISTANT_PAGE_CONTENT , _("VoIP Protocols") , _("Select an account type")); - sip = gtk_radio_button_new_with_label (NULL, _ ("SIP (Session Initiation Protocol)")); - gtk_box_pack_start (GTK_BOX (wiz->protocols) , sip , TRUE, TRUE, 0); - iax = gtk_radio_button_new_with_label_from_widget (GTK_RADIO_BUTTON (sip), _ ("IAX2 (InterAsterix Exchange)")); - gtk_box_pack_start (GTK_BOX (wiz->protocols) , iax , TRUE, TRUE, 0); + sip = gtk_radio_button_new_with_label(NULL, _("SIP (Session Initiation Protocol)")); + gtk_box_pack_start(GTK_BOX(wiz->protocols) , sip , TRUE, TRUE, 0); + iax = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(sip), _("IAX2 (InterAsterix Exchange)")); + gtk_box_pack_start(GTK_BOX(wiz->protocols) , iax , TRUE, TRUE, 0); - g_signal_connect (G_OBJECT (sip) , "clicked" , G_CALLBACK (set_account_type) , NULL); + g_signal_connect(G_OBJECT(sip) , "clicked" , G_CALLBACK(set_account_type) , NULL); - gtk_assistant_set_page_complete (GTK_ASSISTANT (wiz->assistant), wiz->protocols, TRUE); + gtk_assistant_set_page_complete(GTK_ASSISTANT(wiz->assistant), wiz->protocols, TRUE); return wiz->protocols; } @@ -304,230 +303,230 @@ GtkWidget* build_sfl_or_account() GtkWidget* sfl; GtkWidget* cus; - wiz->sflphone_org = create_vbox (GTK_ASSISTANT_PAGE_CONTENT , _ ("Account") , _ ("Please select one of the following options")); + wiz->sflphone_org = create_vbox(GTK_ASSISTANT_PAGE_CONTENT , _("Account") , _("Please select one of the following options")); - sfl = gtk_radio_button_new_with_label (NULL, _ ("Create a free SIP/IAX2 account on sflphone.org \n(For testing purpose only)")); - gtk_box_pack_start (GTK_BOX (wiz->sflphone_org) , sfl , TRUE, TRUE, 0); - cus = gtk_radio_button_new_with_label_from_widget (GTK_RADIO_BUTTON (sfl), _ ("Register an existing SIP or IAX2 account")); - gtk_box_pack_start (GTK_BOX (wiz->sflphone_org) , cus , TRUE, TRUE, 0); - g_signal_connect (G_OBJECT (sfl) , "clicked" , G_CALLBACK (set_sflphone_org) , NULL); + sfl = gtk_radio_button_new_with_label(NULL, _("Create a free SIP/IAX2 account on sflphone.org \n(For testing purpose only)")); + gtk_box_pack_start(GTK_BOX(wiz->sflphone_org) , sfl , TRUE, TRUE, 0); + cus = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(sfl), _("Register an existing SIP or IAX2 account")); + gtk_box_pack_start(GTK_BOX(wiz->sflphone_org) , cus , TRUE, TRUE, 0); + g_signal_connect(G_OBJECT(sfl) , "clicked" , G_CALLBACK(set_sflphone_org) , NULL); return wiz->sflphone_org; } -GtkWidget* build_sip_account_configuration (void) +GtkWidget* build_sip_account_configuration(void) { GtkWidget* table; GtkWidget* label; GtkWidget * clearTextCheckbox; - wiz->sip_account = create_vbox (GTK_ASSISTANT_PAGE_CONTENT , _ ("SIP account settings") , _ ("Please fill the following information")); + wiz->sip_account = create_vbox(GTK_ASSISTANT_PAGE_CONTENT , _("SIP account settings") , _("Please fill the following information")); // table - table = gtk_table_new (7, 2 , FALSE/* homogeneous */); - gtk_table_set_row_spacings (GTK_TABLE (table), 10); - gtk_table_set_col_spacings (GTK_TABLE (table), 10); - gtk_box_pack_start (GTK_BOX (wiz->sip_account) , table , TRUE, TRUE, 0); + table = gtk_table_new(7, 2 , FALSE/* homogeneous */); + gtk_table_set_row_spacings(GTK_TABLE(table), 10); + gtk_table_set_col_spacings(GTK_TABLE(table), 10); + gtk_box_pack_start(GTK_BOX(wiz->sip_account) , table , TRUE, TRUE, 0); // alias field - label = gtk_label_new_with_mnemonic (_ ("_Alias")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + label = gtk_label_new_with_mnemonic(_("_Alias")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); wiz->sip_alias = gtk_entry_new(); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), wiz->sip_alias); - gtk_table_attach (GTK_TABLE (table), wiz->sip_alias, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), wiz->sip_alias); + gtk_table_attach(GTK_TABLE(table), wiz->sip_alias, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); // server field - label = gtk_label_new_with_mnemonic (_ ("_Host name")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + label = gtk_label_new_with_mnemonic(_("_Host name")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); wiz->sip_server = gtk_entry_new(); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), wiz->sip_server); - gtk_table_attach (GTK_TABLE (table), wiz->sip_server, 1, 2, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), wiz->sip_server); + gtk_table_attach(GTK_TABLE(table), wiz->sip_server, 1, 2, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); // username field - label = gtk_label_new_with_mnemonic (_ ("_User name")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + label = gtk_label_new_with_mnemonic(_("_User name")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); wiz->sip_username = gtk_entry_new(); - gtk_entry_set_icon_from_pixbuf (GTK_ENTRY (wiz->sip_username), GTK_ENTRY_ICON_PRIMARY, gdk_pixbuf_new_from_file (ICONS_DIR "/stock_person.svg", NULL)); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), wiz->sip_username); - gtk_table_attach (GTK_TABLE (table), wiz->sip_username, 1, 2, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(wiz->sip_username), GTK_ENTRY_ICON_PRIMARY, gdk_pixbuf_new_from_file(ICONS_DIR "/stock_person.svg", NULL)); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), wiz->sip_username); + gtk_table_attach(GTK_TABLE(table), wiz->sip_username, 1, 2, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); // password field - label = gtk_label_new_with_mnemonic (_ ("_Password")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + label = gtk_label_new_with_mnemonic(_("_Password")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); wiz->sip_password = gtk_entry_new(); - gtk_entry_set_icon_from_stock (GTK_ENTRY (wiz->sip_password), GTK_ENTRY_ICON_PRIMARY, GTK_STOCK_DIALOG_AUTHENTICATION); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), wiz->sip_password); - gtk_entry_set_visibility (GTK_ENTRY (wiz->sip_password), FALSE); - gtk_table_attach (GTK_TABLE (table), wiz->sip_password, 1, 2, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_entry_set_icon_from_stock(GTK_ENTRY(wiz->sip_password), GTK_ENTRY_ICON_PRIMARY, GTK_STOCK_DIALOG_AUTHENTICATION); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), wiz->sip_password); + gtk_entry_set_visibility(GTK_ENTRY(wiz->sip_password), FALSE); + gtk_table_attach(GTK_TABLE(table), wiz->sip_password, 1, 2, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - clearTextCheckbox = gtk_check_button_new_with_mnemonic (_ ("Show password")); - g_signal_connect (clearTextCheckbox, "toggled", G_CALLBACK (show_password_cb), wiz->sip_password); - gtk_table_attach (GTK_TABLE (table), clearTextCheckbox, 1, 2, 4, 5, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + clearTextCheckbox = gtk_check_button_new_with_mnemonic(_("Show password")); + g_signal_connect(clearTextCheckbox, "toggled", G_CALLBACK(show_password_cb), wiz->sip_password); + gtk_table_attach(GTK_TABLE(table), clearTextCheckbox, 1, 2, 4, 5, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); // voicemail number field - label = gtk_label_new_with_mnemonic (_ ("_Voicemail number")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + label = gtk_label_new_with_mnemonic(_("_Voicemail number")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); wiz->sip_voicemail = gtk_entry_new(); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), wiz->sip_voicemail); - gtk_table_attach (GTK_TABLE (table), wiz->sip_voicemail, 1, 2, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), wiz->sip_voicemail); + gtk_table_attach(GTK_TABLE(table), wiz->sip_voicemail, 1, 2, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); // Security options - wiz->zrtp_enable = gtk_check_button_new_with_mnemonic (_ ("Secure communications with _ZRTP")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (wiz->zrtp_enable), FALSE); - gtk_table_attach (GTK_TABLE (table), wiz->zrtp_enable, 0, 1, 6, 7, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_set_sensitive (GTK_WIDGET (wiz->zrtp_enable) , TRUE); + wiz->zrtp_enable = gtk_check_button_new_with_mnemonic(_("Secure communications with _ZRTP")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(wiz->zrtp_enable), FALSE); + gtk_table_attach(GTK_TABLE(table), wiz->zrtp_enable, 0, 1, 6, 7, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_widget_set_sensitive(GTK_WIDGET(wiz->zrtp_enable) , TRUE); //gtk_assistant_set_page_complete(GTK_ASSISTANT(wiz->assistant), wiz->sip_account, TRUE); return wiz->sip_account; } -GtkWidget* build_email_configuration (void) +GtkWidget* build_email_configuration(void) { GtkWidget* label; GtkWidget* table; - wiz->email = create_vbox (GTK_ASSISTANT_PAGE_CONTENT , _ ("Optional email address") , _ ("This email address will be used to send your voicemail messages.")); + wiz->email = create_vbox(GTK_ASSISTANT_PAGE_CONTENT , _("Optional email address") , _("This email address will be used to send your voicemail messages.")); - table = gtk_table_new (4, 2 , FALSE/* homogeneous */); - gtk_table_set_row_spacings (GTK_TABLE (table), 10); - gtk_table_set_col_spacings (GTK_TABLE (table), 10); - gtk_box_pack_start (GTK_BOX (wiz->email) , table , TRUE, TRUE, 0); + table = gtk_table_new(4, 2 , FALSE/* homogeneous */); + gtk_table_set_row_spacings(GTK_TABLE(table), 10); + gtk_table_set_col_spacings(GTK_TABLE(table), 10); + gtk_box_pack_start(GTK_BOX(wiz->email) , table , TRUE, TRUE, 0); // email field - label = gtk_label_new_with_mnemonic (_ ("_Email address")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + label = gtk_label_new_with_mnemonic(_("_Email address")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); wiz->mailbox = gtk_entry_new(); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), wiz->mailbox); - gtk_table_attach (GTK_TABLE (table), wiz->mailbox, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), wiz->mailbox); + gtk_table_attach(GTK_TABLE(table), wiz->mailbox, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); // Security options - wiz->zrtp_enable = gtk_check_button_new_with_mnemonic (_ ("Secure communications with _ZRTP")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (wiz->zrtp_enable), FALSE); - gtk_table_attach (GTK_TABLE (table), wiz->zrtp_enable, 0, 1, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_set_sensitive (GTK_WIDGET (wiz->zrtp_enable) , TRUE); + wiz->zrtp_enable = gtk_check_button_new_with_mnemonic(_("Secure communications with _ZRTP")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(wiz->zrtp_enable), FALSE); + gtk_table_attach(GTK_TABLE(table), wiz->zrtp_enable, 0, 1, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_widget_set_sensitive(GTK_WIDGET(wiz->zrtp_enable) , TRUE); return wiz->email; } -GtkWidget* build_iax_account_configuration (void) +GtkWidget* build_iax_account_configuration(void) { GtkWidget* label; GtkWidget* table; GtkWidget * clearTextCheckbox; - wiz->iax_account = create_vbox (GTK_ASSISTANT_PAGE_CONFIRM , _ ("IAX2 account settings") , _ ("Please fill the following information")); + wiz->iax_account = create_vbox(GTK_ASSISTANT_PAGE_CONFIRM , _("IAX2 account settings") , _("Please fill the following information")); - table = gtk_table_new (6, 2 , FALSE/* homogeneous */); - gtk_table_set_row_spacings (GTK_TABLE (table), 10); - gtk_table_set_col_spacings (GTK_TABLE (table), 10); - gtk_box_pack_start (GTK_BOX (wiz->iax_account) , table , TRUE, TRUE, 0); + table = gtk_table_new(6, 2 , FALSE/* homogeneous */); + gtk_table_set_row_spacings(GTK_TABLE(table), 10); + gtk_table_set_col_spacings(GTK_TABLE(table), 10); + gtk_box_pack_start(GTK_BOX(wiz->iax_account) , table , TRUE, TRUE, 0); // alias field - label = gtk_label_new_with_mnemonic (_ ("_Alias")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + label = gtk_label_new_with_mnemonic(_("_Alias")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); wiz->iax_alias = gtk_entry_new(); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), wiz->iax_alias); - gtk_table_attach (GTK_TABLE (table), wiz->iax_alias, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), wiz->iax_alias); + gtk_table_attach(GTK_TABLE(table), wiz->iax_alias, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); // server field - label = gtk_label_new_with_mnemonic (_ ("_Host name")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + label = gtk_label_new_with_mnemonic(_("_Host name")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); wiz->iax_server = gtk_entry_new(); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), wiz->iax_server); - gtk_table_attach (GTK_TABLE (table), wiz->iax_server, 1, 2, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), wiz->iax_server); + gtk_table_attach(GTK_TABLE(table), wiz->iax_server, 1, 2, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); // username field - label = gtk_label_new_with_mnemonic (_ ("_User name")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + label = gtk_label_new_with_mnemonic(_("_User name")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); wiz->iax_username = gtk_entry_new(); - gtk_entry_set_icon_from_pixbuf (GTK_ENTRY (wiz->iax_username), GTK_ENTRY_ICON_PRIMARY, gdk_pixbuf_new_from_file (ICONS_DIR "/stock_person.svg", NULL)); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), wiz->iax_username); - gtk_table_attach (GTK_TABLE (table), wiz->iax_username, 1, 2, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_entry_set_icon_from_pixbuf(GTK_ENTRY(wiz->iax_username), GTK_ENTRY_ICON_PRIMARY, gdk_pixbuf_new_from_file(ICONS_DIR "/stock_person.svg", NULL)); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), wiz->iax_username); + gtk_table_attach(GTK_TABLE(table), wiz->iax_username, 1, 2, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); // password field - label = gtk_label_new_with_mnemonic (_ ("_Password")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + label = gtk_label_new_with_mnemonic(_("_Password")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); wiz->iax_password = gtk_entry_new(); - gtk_entry_set_icon_from_stock (GTK_ENTRY (wiz->iax_password), GTK_ENTRY_ICON_PRIMARY, GTK_STOCK_DIALOG_AUTHENTICATION); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), wiz->iax_password); - gtk_entry_set_visibility (GTK_ENTRY (wiz->iax_password), FALSE); - gtk_table_attach (GTK_TABLE (table), wiz->iax_password, 1, 2, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_entry_set_icon_from_stock(GTK_ENTRY(wiz->iax_password), GTK_ENTRY_ICON_PRIMARY, GTK_STOCK_DIALOG_AUTHENTICATION); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), wiz->iax_password); + gtk_entry_set_visibility(GTK_ENTRY(wiz->iax_password), FALSE); + gtk_table_attach(GTK_TABLE(table), wiz->iax_password, 1, 2, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - clearTextCheckbox = gtk_check_button_new_with_mnemonic (_ ("Show password")); - g_signal_connect (clearTextCheckbox, "toggled", G_CALLBACK (show_password_cb), wiz->iax_password); - gtk_table_attach (GTK_TABLE (table), clearTextCheckbox, 1, 2, 4, 5, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + clearTextCheckbox = gtk_check_button_new_with_mnemonic(_("Show password")); + g_signal_connect(clearTextCheckbox, "toggled", G_CALLBACK(show_password_cb), wiz->iax_password); + gtk_table_attach(GTK_TABLE(table), clearTextCheckbox, 1, 2, 4, 5, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); // voicemail number field - label = gtk_label_new_with_mnemonic (_ ("_Voicemail number")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + label = gtk_label_new_with_mnemonic(_("_Voicemail number")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); wiz->iax_voicemail = gtk_entry_new(); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), wiz->iax_voicemail); - gtk_table_attach (GTK_TABLE (table), wiz->iax_voicemail, 1, 2, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), wiz->iax_voicemail); + gtk_table_attach(GTK_TABLE(table), wiz->iax_voicemail, 1, 2, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); current -> state = ACCOUNT_STATE_UNREGISTERED; - g_signal_connect (G_OBJECT (wiz->assistant) , "apply" , G_CALLBACK (iax_apply_callback), NULL); + g_signal_connect(G_OBJECT(wiz->assistant) , "apply" , G_CALLBACK(iax_apply_callback), NULL); return wiz->iax_account; } -GtkWidget* build_nat_settings (void) +GtkWidget* build_nat_settings(void) { GtkWidget* label; GtkWidget* table; - wiz->nat = create_vbox (GTK_ASSISTANT_PAGE_CONFIRM , _ ("Network Address Translation (NAT)") , _ ("You should probably enable this if you are behind a firewall.")); + wiz->nat = create_vbox(GTK_ASSISTANT_PAGE_CONFIRM , _("Network Address Translation (NAT)") , _("You should probably enable this if you are behind a firewall.")); // table - table = gtk_table_new (2, 2 , FALSE/* homogeneous */); - gtk_table_set_row_spacings (GTK_TABLE (table), 10); - gtk_table_set_col_spacings (GTK_TABLE (table), 10); - gtk_box_pack_start (GTK_BOX (wiz->nat), table , TRUE, TRUE, 0); + table = gtk_table_new(2, 2 , FALSE/* homogeneous */); + gtk_table_set_row_spacings(GTK_TABLE(table), 10); + gtk_table_set_col_spacings(GTK_TABLE(table), 10); + gtk_box_pack_start(GTK_BOX(wiz->nat), table , TRUE, TRUE, 0); // enable - wiz->enable = gtk_check_button_new_with_mnemonic (_ ("E_nable STUN")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (wiz->enable), FALSE); - gtk_table_attach (GTK_TABLE (table), wiz->enable, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_set_sensitive (GTK_WIDGET (wiz->enable) , TRUE); - g_signal_connect (G_OBJECT (GTK_TOGGLE_BUTTON (wiz->enable)) , "toggled" , G_CALLBACK (enable_stun), NULL); + wiz->enable = gtk_check_button_new_with_mnemonic(_("E_nable STUN")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(wiz->enable), FALSE); + gtk_table_attach(GTK_TABLE(table), wiz->enable, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_widget_set_sensitive(GTK_WIDGET(wiz->enable) , TRUE); + g_signal_connect(G_OBJECT(GTK_TOGGLE_BUTTON(wiz->enable)) , "toggled" , G_CALLBACK(enable_stun), NULL); // server address - label = gtk_label_new_with_mnemonic (_ ("_STUN server")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + label = gtk_label_new_with_mnemonic(_("_STUN server")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); wiz->addr = gtk_entry_new(); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), wiz->addr); - gtk_table_attach (GTK_TABLE (table), wiz->addr, 1, 2, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_set_sensitive (GTK_WIDGET (wiz->addr), gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (wiz->enable))); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), wiz->addr); + gtk_table_attach(GTK_TABLE(table), wiz->addr, 1, 2, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_widget_set_sensitive(GTK_WIDGET(wiz->addr), gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(wiz->enable))); - g_signal_connect (G_OBJECT (wiz->assistant) , "apply" , G_CALLBACK (sip_apply_callback), NULL); + g_signal_connect(G_OBJECT(wiz->assistant) , "apply" , G_CALLBACK(sip_apply_callback), NULL); return wiz->nat; } GtkWidget* build_summary() { - wiz->summary = create_vbox (GTK_ASSISTANT_PAGE_SUMMARY , _ ("Account Registration") , _ ("Congratulations!")); + wiz->summary = create_vbox(GTK_ASSISTANT_PAGE_SUMMARY , _("Account Registration") , _("Congratulations!")); - strcpy (message,""); - wiz->label_summary = gtk_label_new (message) ; - gtk_label_set_selectable (GTK_LABEL (wiz->label_summary), TRUE); - gtk_misc_set_alignment (GTK_MISC (wiz->label_summary), 0, 0); - gtk_label_set_line_wrap (GTK_LABEL (wiz->label_summary), TRUE); + strcpy(message,""); + wiz->label_summary = gtk_label_new(message) ; + gtk_label_set_selectable(GTK_LABEL(wiz->label_summary), TRUE); + gtk_misc_set_alignment(GTK_MISC(wiz->label_summary), 0, 0); + gtk_label_set_line_wrap(GTK_LABEL(wiz->label_summary), TRUE); //gtk_widget_set_size_request(GTK_WIDGET(wiz->label_summary), 380, -1); - gtk_box_pack_start (GTK_BOX (wiz->summary), wiz->label_summary, FALSE, TRUE, 0); + gtk_box_pack_start(GTK_BOX(wiz->summary), wiz->label_summary, FALSE, TRUE, 0); return wiz->summary; } @@ -535,42 +534,42 @@ GtkWidget* build_summary() GtkWidget* build_registration_error() { GtkWidget *label; - wiz->reg_failed = create_vbox (GTK_ASSISTANT_PAGE_SUMMARY , "Account Registration" , "Registration error"); + wiz->reg_failed = create_vbox(GTK_ASSISTANT_PAGE_SUMMARY , "Account Registration" , "Registration error"); - label = gtk_label_new (" Please correct the information.") ; - gtk_misc_set_alignment (GTK_MISC (label), 0, 0); - gtk_label_set_line_wrap (GTK_LABEL (label), TRUE); - gtk_widget_set_size_request (GTK_WIDGET (label), 380, -1); - gtk_box_pack_start (GTK_BOX (wiz->reg_failed), label, FALSE, TRUE, 0); + label = gtk_label_new(" Please correct the information.") ; + gtk_misc_set_alignment(GTK_MISC(label), 0, 0); + gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); + gtk_widget_set_size_request(GTK_WIDGET(label), 380, -1); + gtk_box_pack_start(GTK_BOX(wiz->reg_failed), label, FALSE, TRUE, 0); return wiz->reg_failed; } -void set_sip_infos_sentivite (gboolean b) +void set_sip_infos_sentivite(gboolean b) { - gtk_widget_set_sensitive (GTK_WIDGET (wiz->sip_alias), b); - gtk_widget_set_sensitive (GTK_WIDGET (wiz->sip_server), b); - gtk_widget_set_sensitive (GTK_WIDGET (wiz->sip_username), b); - gtk_widget_set_sensitive (GTK_WIDGET (wiz->sip_password), b); + gtk_widget_set_sensitive(GTK_WIDGET(wiz->sip_alias), b); + gtk_widget_set_sensitive(GTK_WIDGET(wiz->sip_server), b); + gtk_widget_set_sensitive(GTK_WIDGET(wiz->sip_username), b); + gtk_widget_set_sensitive(GTK_WIDGET(wiz->sip_password), b); } -void prefill_sip (void) +void prefill_sip(void) { if (use_sflphone_org == 1) { char alias[300]; char *email; - email = (char *) gtk_entry_get_text (GTK_ENTRY (wiz->mailbox)); - rest_account ra = get_rest_account (SFLPHONE_ORG_SERVER,email); + email = (char *) gtk_entry_get_text(GTK_ENTRY(wiz->mailbox)); + rest_account ra = get_rest_account(SFLPHONE_ORG_SERVER,email); if (ra.success) { - set_sip_infos_sentivite (FALSE); - strcpy (alias,ra.user); - strcat (alias,"@"); - strcat (alias,"sip.sflphone.org"); - gtk_entry_set_text (GTK_ENTRY (wiz->sip_alias),alias); - gtk_entry_set_text (GTK_ENTRY (wiz->sip_server), SFLPHONE_ORG_SERVER); - gtk_entry_set_text (GTK_ENTRY (wiz->sip_username), ra.user); - gtk_entry_set_text (GTK_ENTRY (wiz->sip_password), ra.passwd); + set_sip_infos_sentivite(FALSE); + strcpy(alias,ra.user); + strcat(alias,"@"); + strcat(alias,"sip.sflphone.org"); + gtk_entry_set_text(GTK_ENTRY(wiz->sip_alias),alias); + gtk_entry_set_text(GTK_ENTRY(wiz->sip_server), SFLPHONE_ORG_SERVER); + gtk_entry_set_text(GTK_ENTRY(wiz->sip_username), ra.user); + gtk_entry_set_text(GTK_ENTRY(wiz->sip_password), ra.passwd); } } } @@ -586,7 +585,7 @@ typedef enum { PAGE_SUMMARY } assistant_state; -static gint forward_page_func (gint current_page , gpointer data UNUSED) +static gint forward_page_func(gint current_page , gpointer data UNUSED) { gint next_page = 0; @@ -605,7 +604,7 @@ static gint forward_page_func (gint current_page , gpointer data UNUSED) case PAGE_TYPE: if (account_type == _SIP) { - set_sip_infos_sentivite (TRUE); + set_sip_infos_sentivite(TRUE); next_page = PAGE_SIP; } else next_page = PAGE_IAX; @@ -634,35 +633,39 @@ static gint forward_page_func (gint current_page , gpointer data UNUSED) } -static GtkWidget* create_vbox (GtkAssistantPageType type, const gchar *title, const gchar *section) +static GtkWidget* create_vbox(GtkAssistantPageType type, const gchar *title, const gchar *section) { GtkWidget *vbox; GtkWidget *label; gchar *str; - vbox = gtk_vbox_new (FALSE, 6); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 24); + vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); + gtk_container_set_border_width(GTK_CONTAINER(vbox), 24); - gtk_assistant_append_page (GTK_ASSISTANT (wiz->assistant), vbox); - gtk_assistant_set_page_type (GTK_ASSISTANT (wiz->assistant), vbox, type); - str = g_strdup_printf (" %s", title); - gtk_assistant_set_page_title (GTK_ASSISTANT (wiz->assistant), vbox, str); + gtk_assistant_append_page(GTK_ASSISTANT(wiz->assistant), vbox); + gtk_assistant_set_page_type(GTK_ASSISTANT(wiz->assistant), vbox, type); + str = g_strdup_printf(" %s", title); + gtk_assistant_set_page_title(GTK_ASSISTANT(wiz->assistant), vbox, str); - g_free (str); + g_free(str); - gtk_assistant_set_page_complete (GTK_ASSISTANT (wiz->assistant), vbox, TRUE); + gtk_assistant_set_page_complete(GTK_ASSISTANT(wiz->assistant), vbox, TRUE); - wiz->logo = gdk_pixbuf_new_from_file (LOGO, NULL); - gtk_assistant_set_page_header_image (GTK_ASSISTANT (wiz->assistant),vbox, wiz->logo); - g_object_unref (wiz->logo); +#if 0 + /* FIXME */ + http://developer.gnome.org/gtk3/stable/GtkAssistant.html#gtk-assistant-set-page-header-image + wiz->logo = gdk_pixbuf_new_from_file(LOGO, NULL); + gtk_assistant_set_page_header_image(GTK_ASSISTANT(wiz->assistant),vbox, wiz->logo); + g_object_unref(wiz->logo); +#endif if (section) { - label = gtk_label_new (NULL); - str = g_strdup_printf ("<b>%s</b>\n", section); - gtk_label_set_markup (GTK_LABEL (label), str); - g_free (str); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0); - gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 0); + label = gtk_label_new(NULL); + str = g_strdup_printf("<b>%s</b>\n", section); + gtk_label_set_markup(GTK_LABEL(label), str); + g_free(str); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0); + gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0); } return vbox; diff --git a/gnome/src/config/assistant.h b/gnome/src/config/assistant.h index 8693b2915fbd98000767b36035905dfc2358be96..79d3c9a8ad83d8878f358cf9f2a283344b890a61 100644 --- a/gnome/src/config/assistant.h +++ b/gnome/src/config/assistant.h @@ -32,9 +32,9 @@ #define __ASSISTANT_H -#include <accountlist.h> -#include <actions.h> -#include <sflphone_const.h> +#include "accountlist.h" +#include "actions.h" +#include "sflphone_const.h" #define _SIP 0 diff --git a/gnome/src/config/audioconf.c b/gnome/src/config/audioconf.c index 2b0a2afa0858d81742385d993944a3bed319a243..e22cea77efa3c115f6b29fa71de46e8c11a25dac 100644 --- a/gnome/src/config/audioconf.c +++ b/gnome/src/config/audioconf.c @@ -29,13 +29,14 @@ */ -#include <audioconf.h> -#include <utils.h> -#include <string.h> -#include <eel-gconf-extensions.h> +#include "audioconf.h" +#include "utils.h" +#include "logger.h" +#include "eel-gconf-extensions.h" #include "dbus/dbus.h" #include "uimanager.h" #include "mainwindow.h" +#include "unused.h" /* FIXME: these should be in a struct rather than at file scope */ static GtkListStore *pluginlist; @@ -63,40 +64,35 @@ enum { CODEC_COLUMN_COUNT }; - -static void active_is_always_recording (void); +static void active_is_always_recording(void); /** * Fills the tree list with supported codecs */ -static void preferences_dialog_fill_codec_list (account_t *a) +static void preferences_dialog_fill_codec_list(account_t *a) { - GtkListStore *codecStore; - GtkTreeIter iter; - GQueue *current; - // Get model of view and clear it - codecStore = GTK_LIST_STORE (gtk_tree_view_get_model (GTK_TREE_VIEW (codecTreeView))); - gtk_list_store_clear (codecStore); + GtkListStore *codecStore = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(codecTreeView))); + gtk_list_store_clear(codecStore); + + GQueue *current = a ? a->codecs : get_system_codec_list(); - current = a ? a->codecs : get_system_codec_list (); if (!a) DEBUG("Using system codec list"); // Insert codecs - unsigned int i; - - for (i = 0; i < g_queue_get_length(current); i++) { - codec_t *c = codec_list_get_nth (i, current); + for (guint i = 0; i < g_queue_get_length(current); i++) { + codec_t *c = codec_list_get_nth(i, current); if (c) { - DEBUG ("%s", c->name); - gtk_list_store_append (codecStore, &iter); - gtk_list_store_set (codecStore, &iter, - COLUMN_CODEC_ACTIVE, c->is_active, // Active - COLUMN_CODEC_NAME, c->name, // Name - COLUMN_CODEC_FREQUENCY, g_strdup_printf ("%d kHz", c->sample_rate/1000), // Frequency (kHz) - COLUMN_CODEC_BITRATE, g_strdup_printf ("%.1f kbps", c->_bitrate), // Bitrate (kbps) - -1); + DEBUG("%s", c->name); + GtkTreeIter iter; + gtk_list_store_append(codecStore, &iter); + gtk_list_store_set(codecStore, &iter, + COLUMN_CODEC_ACTIVE, c->is_active, + COLUMN_CODEC_NAME, c->name, + COLUMN_CODEC_FREQUENCY, g_strdup_printf("%f kHz", c->sample_rate * 0.001), + COLUMN_CODEC_BITRATE, g_strdup_printf("%.1f kbps", c->_bitrate), + -1); } } } @@ -107,123 +103,80 @@ static void preferences_dialog_fill_codec_list (account_t *a) void preferences_dialog_fill_audio_plugin_list() { - GtkTreeIter iter; - gchar** list; - gchar* managerName; - - gtk_list_store_clear (pluginlist); + gtk_list_store_clear(pluginlist); // Call dbus to retreive list - list = dbus_get_audio_plugin_list(); - // For each API name included in list - int c = 0; + gchar **list = dbus_get_audio_plugin_list(); + // For each API name included in list if (list != NULL) { - for (managerName = list[c]; managerName != NULL; managerName = list[c]) { + int c = 0; + + for (gchar *managerName = list[c]; managerName != NULL; managerName = list[c]) { c++; - gtk_list_store_append (pluginlist, &iter); - gtk_list_store_set (pluginlist, &iter, 0 , managerName, -1); + GtkTreeIter iter; + gtk_list_store_append(pluginlist, &iter); + gtk_list_store_set(pluginlist, &iter, 0, managerName, -1); } } - - list = NULL; } - -/** - * Fill output audio device store - */ void preferences_dialog_fill_output_audio_device_list() { + gtk_list_store_clear(outputlist); - GtkTreeIter iter; - gchar** list; - int index; - - gtk_list_store_clear (outputlist); - - // Call dbus to retreive list - list = dbus_get_audio_output_device_list(); - - // For each device name included in list - int c = 0; - - for (; *list ; list++) { - index = dbus_get_audio_device_index (*list); - gtk_list_store_append (outputlist, &iter); - gtk_list_store_set (outputlist, &iter, 0, *list, 1, index, -1); - c++; + // Call dbus to retrieve list + for (gchar **list = dbus_get_audio_output_device_list(); *list ; list++) { + int device_index = dbus_get_audio_device_index(*list); + GtkTreeIter iter; + gtk_list_store_append(outputlist, &iter); + gtk_list_store_set(outputlist, &iter, 0, *list, 1, device_index, -1); } } - -/** - * Fill rigntone audio device store - */ - void preferences_dialog_fill_ringtone_audio_device_list() { - - GtkTreeIter iter; - gchar** list; - int index; - - gtk_list_store_clear (ringtonelist); + gtk_list_store_clear(ringtonelist); // Call dbus to retreive output device - list = dbus_get_audio_output_device_list(); - - // For each device name in the list - int c = 0; - - for (; *list; list++) { - index = dbus_get_audio_device_index (*list); - gtk_list_store_append (ringtonelist, &iter); - gtk_list_store_set (ringtonelist, &iter, 0, *list, 1, index, -1); - c++; + for (gchar **list = dbus_get_audio_output_device_list(); *list; list++) { + int device_index = dbus_get_audio_device_index(*list); + GtkTreeIter iter; + gtk_list_store_append(ringtonelist, &iter); + gtk_list_store_set(ringtonelist, &iter, 0, *list, 1, device_index, -1); } } - - -/** - * Select active output audio device - */ void select_active_output_audio_device() { if (must_show_alsa_conf()) { - - GtkTreeModel* model; - GtkTreeIter iter; - gchar** devices; - int currentDeviceIndex; - int deviceIndex; - // Select active output device on server - devices = dbus_get_current_audio_devices_index(); - currentDeviceIndex = atoi (devices[0]); - DEBUG ("audio device index for output = %d", currentDeviceIndex); - model = gtk_combo_box_get_model (GTK_COMBO_BOX (output)); + gchar **devices = dbus_get_current_audio_devices_index(); + int currentDeviceIndex = atoi(devices[0]); + DEBUG("audio device index for output = %d", currentDeviceIndex); + GtkTreeModel *model = gtk_combo_box_get_model(GTK_COMBO_BOX(output)); // Find the currently set output device - gtk_tree_model_get_iter_first (model, &iter); + GtkTreeIter iter; + gtk_tree_model_get_iter_first(model, &iter); do { - gtk_tree_model_get (model, &iter, 1, &deviceIndex, -1); + int deviceIndex; + gtk_tree_model_get(model, &iter, 1, &deviceIndex, -1); if (deviceIndex == currentDeviceIndex) { // Set current iteration the active one - gtk_combo_box_set_active_iter (GTK_COMBO_BOX (output), &iter); + gtk_combo_box_set_active_iter(GTK_COMBO_BOX(output), &iter); return; } - } while (gtk_tree_model_iter_next (model, &iter)); + } while (gtk_tree_model_iter_next(model, &iter)); // No index was found, select first one - WARN ("Warning : No active output device found"); - gtk_combo_box_set_active (GTK_COMBO_BOX (output), 0); + WARN("Warning : No active output device found"); + gtk_combo_box_set_active(GTK_COMBO_BOX(output), 0); } } @@ -235,238 +188,179 @@ void select_active_ringtone_audio_device() { if (must_show_alsa_conf()) { - - GtkTreeModel* model; - GtkTreeIter iter; - gchar** devices; - int currentDeviceIndex; - int deviceIndex; - // Select active ringtone device on server - devices = dbus_get_current_audio_devices_index(); - currentDeviceIndex = atoi (devices[2]); - DEBUG ("audio device index for ringtone = %d", currentDeviceIndex); - model = gtk_combo_box_get_model (GTK_COMBO_BOX (ringtone)); + gchar **devices = dbus_get_current_audio_devices_index(); + int currentDeviceIndex = atoi(devices[2]); + DEBUG("audio device index for ringtone = %d", currentDeviceIndex); + GtkTreeModel* model = gtk_combo_box_get_model(GTK_COMBO_BOX(ringtone)); // Find the currently set ringtone device - gtk_tree_model_get_iter_first (model, &iter); + GtkTreeIter iter; + gtk_tree_model_get_iter_first(model, &iter); do { - gtk_tree_model_get (model, &iter, 1, &deviceIndex, -1); + int deviceIndex; + gtk_tree_model_get(model, &iter, 1, &deviceIndex, -1); if (deviceIndex == currentDeviceIndex) { // Set current iteration the active one - gtk_combo_box_set_active_iter (GTK_COMBO_BOX (ringtone), &iter); + gtk_combo_box_set_active_iter(GTK_COMBO_BOX(ringtone), &iter); return; } - } while (gtk_tree_model_iter_next (model, &iter)); + } while (gtk_tree_model_iter_next(model, &iter)); // No index was found, select first one - WARN ("Warning : No active ringtone device found"); - gtk_combo_box_set_active (GTK_COMBO_BOX (ringtone), 0); + WARN("Warning : No active ringtone device found"); + gtk_combo_box_set_active(GTK_COMBO_BOX(ringtone), 0); } } -/** - * Fill input audio device store - */ void preferences_dialog_fill_input_audio_device_list() { - - GtkTreeIter iter; - gchar** list; - int index ; - gtk_list_store_clear (inputlist); + gtk_list_store_clear(inputlist); // Call dbus to retreive list - list = dbus_get_audio_input_device_list(); + gchar **list = dbus_get_audio_input_device_list(); // For each device name included in list - //int c = 0; for (; *list; list++) { - index = dbus_get_audio_device_index (*list); - gtk_list_store_append (inputlist, &iter); - gtk_list_store_set (inputlist, &iter, 0, *list, 1, index, -1); - //c++; + int device_index = dbus_get_audio_device_index(*list); + GtkTreeIter iter; + gtk_list_store_append(inputlist, &iter); + gtk_list_store_set(inputlist, &iter, 0, *list, 1, device_index, -1); } } -/** - * Select active input audio device - */ void select_active_input_audio_device() { if (must_show_alsa_conf()) { - - GtkTreeModel* model; - GtkTreeIter iter; - gchar** devices; - int currentDeviceIndex; - int deviceIndex; - // Select active input device on server - devices = dbus_get_current_audio_devices_index(); - currentDeviceIndex = atoi (devices[1]); - model = gtk_combo_box_get_model (GTK_COMBO_BOX (input)); + gchar **devices = dbus_get_current_audio_devices_index(); + int currentDeviceIndex = atoi(devices[1]); + GtkTreeModel *model = gtk_combo_box_get_model(GTK_COMBO_BOX(input)); // Find the currently set input device - gtk_tree_model_get_iter_first (model, &iter); + GtkTreeIter iter; + gtk_tree_model_get_iter_first(model, &iter); do { - gtk_tree_model_get (model, &iter, 1, &deviceIndex, -1); + int deviceIndex; + gtk_tree_model_get(model, &iter, 1, &deviceIndex, -1); if (deviceIndex == currentDeviceIndex) { // Set current iteration the active one - gtk_combo_box_set_active_iter (GTK_COMBO_BOX (input), &iter); + gtk_combo_box_set_active_iter(GTK_COMBO_BOX(input), &iter); return; } - } while (gtk_tree_model_iter_next (model, &iter)); + } while (gtk_tree_model_iter_next(model, &iter)); // No index was found, select first one - WARN ("Warning : No active input device found"); - gtk_combo_box_set_active (GTK_COMBO_BOX (input), 0); + WARN("Warning : No active input device found"); + gtk_combo_box_set_active(GTK_COMBO_BOX(input), 0); } } void -update_device_widget (gchar *pluginName) +update_device_widget(gchar *pluginName) { - if (g_strcasecmp (pluginName, "default") == 0) { - gtk_widget_set_sensitive (output, FALSE); - gtk_widget_set_sensitive (input, FALSE); - gtk_widget_set_sensitive (ringtone, FALSE); + if (g_strcasecmp(pluginName, "default") == 0) { + gtk_widget_set_sensitive(output, FALSE); + gtk_widget_set_sensitive(input, FALSE); + gtk_widget_set_sensitive(ringtone, FALSE); } else { - gtk_widget_set_sensitive (output, TRUE); - gtk_widget_set_sensitive (input, TRUE); - gtk_widget_set_sensitive (ringtone, TRUE); + gtk_widget_set_sensitive(output, TRUE); + gtk_widget_set_sensitive(input, TRUE); + gtk_widget_set_sensitive(ringtone, TRUE); } } -/** - * Select the output audio plugin by calling the server - */ static void -select_output_audio_plugin (GtkComboBox* widget, gpointer data UNUSED) +select_output_audio_plugin(GtkComboBox* widget, gpointer data UNUSED) { - GtkTreeModel* model; - GtkTreeIter iter; - int comboBoxIndex; - gchar* pluginName; - - comboBoxIndex = gtk_combo_box_get_active (widget); + int comboBoxIndex = gtk_combo_box_get_active(widget); if (comboBoxIndex >= 0) { - model = gtk_combo_box_get_model (widget); - gtk_combo_box_get_active_iter (widget, &iter); - gtk_tree_model_get (model, &iter, 0, &pluginName, -1); - dbus_set_audio_plugin (pluginName); - update_device_widget (pluginName); + GtkTreeModel *model = gtk_combo_box_get_model(widget); + GtkTreeIter iter; + gtk_combo_box_get_active_iter(widget, &iter); + gchar* pluginName; + gtk_tree_model_get(model, &iter, 0, &pluginName, -1); + dbus_set_audio_plugin(pluginName); + update_device_widget(pluginName); } } -/** - * Select active output audio plugin - */ void select_active_output_audio_plugin() { - GtkTreeModel* model; - GtkTreeIter iter; - gchar* pluginname; - gchar* tmp; - // Select active output device on server - pluginname = dbus_get_current_audio_output_plugin(); - tmp = pluginname; - model = gtk_combo_box_get_model (GTK_COMBO_BOX (plugin)); + GtkTreeModel *model = gtk_combo_box_get_model(GTK_COMBO_BOX(plugin)); // Find the current alsa plugin - gtk_tree_model_get_iter_first (model, &iter); + GtkTreeIter iter; + gtk_tree_model_get_iter_first(model, &iter); + + gchar *pluginname = dbus_get_current_audio_output_plugin(); + gchar *tmp = pluginname; do { - gtk_tree_model_get (model, &iter, 0, &pluginname , -1); + gtk_tree_model_get(model, &iter, 0, &pluginname, -1); - if (g_strcasecmp (tmp , pluginname) == 0) { + if (g_strcasecmp(tmp, pluginname) == 0) { // Set current iteration the active one - gtk_combo_box_set_active_iter (GTK_COMBO_BOX (plugin), &iter); + gtk_combo_box_set_active_iter(GTK_COMBO_BOX(plugin), &iter); return; } - } while (gtk_tree_model_iter_next (model, &iter)); + } while (gtk_tree_model_iter_next(model, &iter)); // No index was found, select first one - WARN ("Warning : No active output device found"); - gtk_combo_box_set_active (GTK_COMBO_BOX (plugin), 0); + WARN("Warning : No active output device found"); + gtk_combo_box_set_active(GTK_COMBO_BOX(plugin), 0); } -/** - * Set the audio output device on the server with its index - */ static void -select_audio_output_device (GtkComboBox* comboBox, gpointer data UNUSED) +select_audio_output_device(GtkComboBox* comboBox, gpointer data UNUSED) { - GtkTreeModel* model; - GtkTreeIter iter; - int comboBoxIndex; - int deviceIndex; - - comboBoxIndex = gtk_combo_box_get_active (comboBox); + int comboBoxIndex = gtk_combo_box_get_active(comboBox); if (comboBoxIndex >= 0) { - model = gtk_combo_box_get_model (comboBox); - gtk_combo_box_get_active_iter (comboBox, &iter); - gtk_tree_model_get (model, &iter, 1, &deviceIndex, -1); - - dbus_set_audio_output_device (deviceIndex); + GtkTreeModel *model = gtk_combo_box_get_model(comboBox); + GtkTreeIter iter; + gtk_combo_box_get_active_iter(comboBox, &iter); + int deviceIndex; + gtk_tree_model_get(model, &iter, 1, &deviceIndex, -1); + dbus_set_audio_output_device(deviceIndex); } } -/** - * Set the audio input device on the server with its index - */ static void -select_audio_input_device (GtkComboBox* comboBox, gpointer data UNUSED) +select_audio_input_device(GtkComboBox* comboBox, gpointer data UNUSED) { - GtkTreeModel* model; - GtkTreeIter iter; - int comboBoxIndex; - int deviceIndex; - - comboBoxIndex = gtk_combo_box_get_active (comboBox); - - if (comboBoxIndex >= 0) { - model = gtk_combo_box_get_model (comboBox); - gtk_combo_box_get_active_iter (comboBox, &iter); - gtk_tree_model_get (model, &iter, 1, &deviceIndex, -1); - - dbus_set_audio_input_device (deviceIndex); + if (gtk_combo_box_get_active(comboBox) >= 0) { + GtkTreeModel* model = gtk_combo_box_get_model(comboBox); + GtkTreeIter iter; + gtk_combo_box_get_active_iter(comboBox, &iter); + int deviceIndex; + gtk_tree_model_get(model, &iter, 1, &deviceIndex, -1); + dbus_set_audio_input_device(deviceIndex); } } -/** -+ * Set the audio ringtone device on the server with its index -+ */ static void -select_audio_ringtone_device (GtkComboBox *comboBox, gpointer data UNUSED) +select_audio_ringtone_device(GtkComboBox *comboBox, gpointer data UNUSED) { - GtkTreeModel *model; - GtkTreeIter iter; - int comboBoxIndex; - int deviceIndex; - - comboBoxIndex = gtk_combo_box_get_active (comboBox); - - if (comboBoxIndex >= 0) { - model = gtk_combo_box_get_model (comboBox); - gtk_combo_box_get_active_iter (comboBox, &iter); - - gtk_tree_model_get (model, &iter, 1, &deviceIndex, -1); - - dbus_set_audio_ringtone_device (deviceIndex); + if (gtk_combo_box_get_active(comboBox) >= 0) { + GtkTreeModel *model = gtk_combo_box_get_model(comboBox); + GtkTreeIter iter; + gtk_combo_box_get_active_iter(comboBox, &iter); + int deviceIndex; + gtk_tree_model_get(model, &iter, 1, &deviceIndex, -1); + dbus_set_audio_ringtone_device(deviceIndex); } } @@ -475,16 +369,16 @@ select_audio_ringtone_device (GtkComboBox *comboBox, gpointer data UNUSED) * Toggle move buttons on if a codec is selected, off elsewise */ static void -select_codec (GtkTreeSelection *selection, GtkTreeModel *model) +select_codec(GtkTreeSelection *selection, GtkTreeModel *model) { GtkTreeIter iter; - if (!gtk_tree_selection_get_selected (selection, &model, &iter)) { - gtk_widget_set_sensitive (GTK_WIDGET (codecMoveUpButton), FALSE); - gtk_widget_set_sensitive (GTK_WIDGET (codecMoveDownButton), FALSE); + if (!gtk_tree_selection_get_selected(selection, &model, &iter)) { + gtk_widget_set_sensitive(GTK_WIDGET(codecMoveUpButton), FALSE); + gtk_widget_set_sensitive(GTK_WIDGET(codecMoveDownButton), FALSE); } else { - gtk_widget_set_sensitive (GTK_WIDGET (codecMoveUpButton), TRUE); - gtk_widget_set_sensitive (GTK_WIDGET (codecMoveDownButton), TRUE); + gtk_widget_set_sensitive(GTK_WIDGET(codecMoveUpButton), TRUE); + gtk_widget_set_sensitive(GTK_WIDGET(codecMoveDownButton), TRUE); } } @@ -493,56 +387,53 @@ select_codec (GtkTreeSelection *selection, GtkTreeModel *model) * and in configuration files */ static void -codec_active_toggled (GtkCellRendererToggle *renderer UNUSED, gchar *path, gpointer data) +codec_active_toggled(GtkCellRendererToggle *renderer UNUSED, gchar *path, gpointer data) { - GtkTreeIter iter; - GtkTreePath *treePath; - GtkTreeModel *model; - gboolean active; - char* name; - char* srate; - codec_t* codec; - account_t *acc; - // Get path of clicked codec active toggle box - treePath = gtk_tree_path_new_from_string (path); - model = gtk_tree_view_get_model (GTK_TREE_VIEW (codecTreeView)); - gtk_tree_model_get_iter (model, &iter, treePath); + GtkTreePath *treePath = gtk_tree_path_new_from_string(path); + GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(codecTreeView)); + GtkTreeIter iter; + gtk_tree_model_get_iter(model, &iter, treePath); // Retrieve userdata - acc = (account_t*) data; + account_t *acc = (account_t*) data; - if (!acc) - ERROR ("Aie, no account selected"); + if (!acc) { + ERROR("Aie, no account selected"); + return; + } // Get active value and name at iteration - gtk_tree_model_get (model, &iter, - COLUMN_CODEC_ACTIVE, &active, - COLUMN_CODEC_NAME, &name, - COLUMN_CODEC_FREQUENCY, &srate, - -1); - - printf ("%s, %s\n", name, srate); - printf ("%i\n", g_queue_get_length (acc->codecs)); - - if ( (g_strcasecmp (name,"speex") ==0) && (g_strcasecmp (srate,"8 kHz") ==0)) - codec = codec_list_get_by_payload ( (gconstpointer) 110, acc->codecs); - else if ( (g_strcasecmp (name,"speex") ==0) && (g_strcasecmp (srate,"16 kHz") ==0)) - codec = codec_list_get_by_payload ( (gconstpointer) 111, acc->codecs); - else if ( (g_strcasecmp (name,"speex") ==0) && (g_strcasecmp (srate,"32 kHz") ==0)) - codec = codec_list_get_by_payload ( (gconstpointer) 112, acc->codecs); + gboolean active; + gchar* name; + gchar* srate; + gtk_tree_model_get(model, &iter, COLUMN_CODEC_ACTIVE, &active, + COLUMN_CODEC_NAME, &name, COLUMN_CODEC_FREQUENCY, + &srate, -1); + + DEBUG("%s, %s\n", name, srate); + DEBUG("%i\n", g_queue_get_length(acc->codecs)); + + codec_t* codec; + + if ((g_strcasecmp(name,"speex") == 0) && (g_strcasecmp(srate,"8 kHz") == 0)) + codec = codec_list_get_by_payload((gconstpointer) 110, acc->codecs); + else if ((g_strcasecmp(name,"speex") ==0) && (g_strcasecmp(srate,"16 kHz") ==0)) + codec = codec_list_get_by_payload((gconstpointer) 111, acc->codecs); + else if ((g_strcasecmp(name,"speex") ==0) && (g_strcasecmp(srate,"32 kHz") ==0)) + codec = codec_list_get_by_payload((gconstpointer) 112, acc->codecs); else - codec = codec_list_get_by_name ( (gconstpointer) name, acc->codecs); + codec = codec_list_get_by_name((gconstpointer) name, acc->codecs); // Toggle active value active = !active; // Store value - gtk_list_store_set (GTK_LIST_STORE (model), &iter, - COLUMN_CODEC_ACTIVE, active, - -1); + gtk_list_store_set(GTK_LIST_STORE(model), &iter, + COLUMN_CODEC_ACTIVE, active, + -1); - gtk_tree_path_free (treePath); + gtk_tree_path_free(treePath); // Modify codec queue to represent change if (codec) @@ -553,184 +444,163 @@ codec_active_toggled (GtkCellRendererToggle *renderer UNUSED, gchar *path, gpoin * Move codec in list depending on direction and selected codec and * update changes in the daemon list and the configuration files */ -static void codec_move (gboolean moveUp, gpointer data) +static void codec_move(gboolean moveUp, gpointer data) { - - GtkTreeIter iter; - GtkTreeIter *iter2; - GtkTreeModel *model; - GtkTreeSelection *selection; - GtkTreePath *treePath; - gchar *path; - account_t *acc; - GQueue *acc_q; - // Get view, model and selection of codec store - model = gtk_tree_view_get_model (GTK_TREE_VIEW (codecTreeView)); - selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (codecTreeView)); - - // Retrieve the user data - acc = (account_t*) data; - - if (acc) - acc_q = acc->codecs; + GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(codecTreeView)); + GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(codecTreeView)); // Find selected iteration and create a copy - gtk_tree_selection_get_selected (GTK_TREE_SELECTION (selection), &model, &iter); - iter2 = gtk_tree_iter_copy (&iter); + GtkTreeIter iter; + gtk_tree_selection_get_selected(selection, &model, &iter); + GtkTreeIter *iter2 = gtk_tree_iter_copy(&iter); // Find path of iteration - path = gtk_tree_model_get_string_from_iter (GTK_TREE_MODEL (model), &iter); - treePath = gtk_tree_path_new_from_string (path); - gint *indices = gtk_tree_path_get_indices (treePath); + gchar *path = gtk_tree_model_get_string_from_iter(GTK_TREE_MODEL(model), &iter); + GtkTreePath *treePath = gtk_tree_path_new_from_string(path); + gint *indices = gtk_tree_path_get_indices(treePath); gint indice = indices[0]; // Depending on button direction get new path if (moveUp) - gtk_tree_path_prev (treePath); + gtk_tree_path_prev(treePath); else - gtk_tree_path_next (treePath); + gtk_tree_path_next(treePath); - gtk_tree_model_get_iter (model, &iter, treePath); + gtk_tree_model_get_iter(model, &iter, treePath); // Swap iterations if valid - if (gtk_list_store_iter_is_valid (GTK_LIST_STORE (model), &iter)) - gtk_list_store_swap (GTK_LIST_STORE (model), &iter, iter2); + if (gtk_list_store_iter_is_valid(GTK_LIST_STORE(model), &iter)) + gtk_list_store_swap(GTK_LIST_STORE(model), &iter, iter2); // Scroll to new position - gtk_tree_view_scroll_to_cell (GTK_TREE_VIEW (codecTreeView), treePath, NULL, FALSE, 0, 0); + gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(codecTreeView), treePath, NULL, FALSE, 0, 0); // Free resources - gtk_tree_path_free (treePath); - gtk_tree_iter_free (iter2); - g_free (path); - - // Perpetuate changes in codec queue - if (moveUp) - codec_list_move_codec_up (indice, &acc_q); - else - codec_list_move_codec_down (indice, &acc_q); + gtk_tree_path_free(treePath); + gtk_tree_iter_free(iter2); + g_free(path); + // Retrieve the user data + account_t *acc = (account_t*) data; + + if (acc) { + // propagate changes in codec queue + if (moveUp) + codec_list_move_codec_up(indice, &acc->codecs); + else + codec_list_move_codec_down(indice, &acc->codecs); + } } /** * Called from move up codec button signal */ -static void codec_move_up (GtkButton *button UNUSED, gpointer data) +static void codec_move_up(GtkButton *button UNUSED, gpointer data) { // Change tree view ordering and get indice changed - codec_move (TRUE, data); + codec_move(TRUE, data); } /** * Called from move down codec button signal */ -static void codec_move_down (GtkButton *button UNUSED, gpointer data) +static void codec_move_down(GtkButton *button UNUSED, gpointer data) { // Change tree view ordering and get indice changed - codec_move (FALSE, data); + codec_move(FALSE, data); } -GtkWidget* audiocodecs_box (account_t *a) +GtkWidget* audiocodecs_box(account_t *a) { - GtkWidget *ret; - GtkWidget *scrolledWindow; - GtkWidget *buttonBox; - - GtkListStore *codecStore; - GtkCellRenderer *renderer; - GtkTreeSelection *treeSelection; - GtkTreeViewColumn *treeViewColumn; - - ret = gtk_hbox_new (FALSE, 10); - gtk_container_set_border_width (GTK_CONTAINER (ret), 10); - - scrolledWindow = gtk_scrolled_window_new (NULL, NULL); - gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolledWindow), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); - gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolledWindow), GTK_SHADOW_IN); - - gtk_box_pack_start (GTK_BOX (ret), scrolledWindow, TRUE, TRUE, 0); - codecStore = gtk_list_store_new (CODEC_COLUMN_COUNT, - G_TYPE_BOOLEAN, // Active - G_TYPE_STRING, // Name - G_TYPE_STRING, // Frequency - G_TYPE_STRING, // Bit rate - G_TYPE_STRING // Bandwith - ); + GtkWidget *audiocodecs_hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10); + gtk_container_set_border_width(GTK_CONTAINER(audiocodecs_hbox), 10); + + GtkWidget *scrolledWindow = gtk_scrolled_window_new(NULL, NULL); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledWindow), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); + gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolledWindow), GTK_SHADOW_IN); + + gtk_box_pack_start(GTK_BOX(audiocodecs_hbox), scrolledWindow, TRUE, TRUE, 0); + GtkListStore *codecStore = gtk_list_store_new(CODEC_COLUMN_COUNT, + G_TYPE_BOOLEAN, /* Active */ + G_TYPE_STRING, /* Name */ + G_TYPE_STRING, /* Frequency */ + G_TYPE_STRING, /* Bit rate */ + G_TYPE_STRING /* Bandwith */); // Create codec tree view with list store - codecTreeView = gtk_tree_view_new_with_model (GTK_TREE_MODEL (codecStore)); + codecTreeView = gtk_tree_view_new_with_model(GTK_TREE_MODEL(codecStore)); // Get tree selection manager - treeSelection = gtk_tree_view_get_selection (GTK_TREE_VIEW (codecTreeView)); - g_signal_connect (G_OBJECT (treeSelection), "changed", - G_CALLBACK (select_codec), - codecStore); + GtkTreeSelection *treeSelection = gtk_tree_view_get_selection(GTK_TREE_VIEW(codecTreeView)); + g_signal_connect(G_OBJECT(treeSelection), "changed", + G_CALLBACK(select_codec), codecStore); // Active column - renderer = gtk_cell_renderer_toggle_new(); - treeViewColumn = gtk_tree_view_column_new_with_attributes ("", renderer, "active", COLUMN_CODEC_ACTIVE, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (codecTreeView), treeViewColumn); + GtkCellRenderer *renderer = gtk_cell_renderer_toggle_new(); + GtkTreeViewColumn *treeViewColumn = gtk_tree_view_column_new_with_attributes("", renderer, "active", COLUMN_CODEC_ACTIVE, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(codecTreeView), treeViewColumn); // Toggle codec active property on clicked - g_signal_connect (G_OBJECT (renderer), "toggled", G_CALLBACK (codec_active_toggled), (gpointer) a); + g_signal_connect(G_OBJECT(renderer), "toggled", G_CALLBACK(codec_active_toggled),(gpointer) a); // Name column renderer = gtk_cell_renderer_text_new(); - treeViewColumn = gtk_tree_view_column_new_with_attributes (_ ("Name"), renderer, "markup", COLUMN_CODEC_NAME, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (codecTreeView), treeViewColumn); + treeViewColumn = gtk_tree_view_column_new_with_attributes(_("Name"), renderer, "markup", COLUMN_CODEC_NAME, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(codecTreeView), treeViewColumn); // Bit rate column renderer = gtk_cell_renderer_text_new(); - treeViewColumn = gtk_tree_view_column_new_with_attributes (_ ("Frequency"), renderer, "text", COLUMN_CODEC_FREQUENCY, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (codecTreeView), treeViewColumn); + treeViewColumn = gtk_tree_view_column_new_with_attributes(_("Frequency"), renderer, "text", COLUMN_CODEC_FREQUENCY, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(codecTreeView), treeViewColumn); // Bandwith column renderer = gtk_cell_renderer_text_new(); - treeViewColumn = gtk_tree_view_column_new_with_attributes (_ ("Bitrate"), renderer, "text", COLUMN_CODEC_BITRATE, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (codecTreeView), treeViewColumn); + treeViewColumn = gtk_tree_view_column_new_with_attributes(_("Bitrate"), renderer, "text", COLUMN_CODEC_BITRATE, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(codecTreeView), treeViewColumn); - g_object_unref (G_OBJECT (codecStore)); - gtk_container_add (GTK_CONTAINER (scrolledWindow), codecTreeView); + g_object_unref(G_OBJECT(codecStore)); + gtk_container_add(GTK_CONTAINER(scrolledWindow), codecTreeView); // Create button box - buttonBox = gtk_vbox_new (FALSE, 0); - gtk_container_set_border_width (GTK_CONTAINER (buttonBox), 10); - gtk_box_pack_start (GTK_BOX (ret), buttonBox, FALSE, FALSE, 0); + GtkWidget *buttonBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + gtk_container_set_border_width(GTK_CONTAINER(buttonBox), 10); + gtk_box_pack_start(GTK_BOX(audiocodecs_hbox), buttonBox, FALSE, FALSE, 0); - codecMoveUpButton = gtk_button_new_from_stock (GTK_STOCK_GO_UP); - gtk_widget_set_sensitive (GTK_WIDGET (codecMoveUpButton), FALSE); - gtk_box_pack_start (GTK_BOX (buttonBox), codecMoveUpButton, FALSE, FALSE, 0); - g_signal_connect (G_OBJECT (codecMoveUpButton), "clicked", G_CALLBACK (codec_move_up), a); + codecMoveUpButton = gtk_button_new_from_stock(GTK_STOCK_GO_UP); + gtk_widget_set_sensitive(GTK_WIDGET(codecMoveUpButton), FALSE); + gtk_box_pack_start(GTK_BOX(buttonBox), codecMoveUpButton, FALSE, FALSE, 0); + g_signal_connect(G_OBJECT(codecMoveUpButton), "clicked", G_CALLBACK(codec_move_up), a); - codecMoveDownButton = gtk_button_new_from_stock (GTK_STOCK_GO_DOWN); - gtk_widget_set_sensitive (GTK_WIDGET (codecMoveDownButton), FALSE); - gtk_box_pack_start (GTK_BOX (buttonBox), codecMoveDownButton, FALSE, FALSE, 0); - g_signal_connect (G_OBJECT (codecMoveDownButton), "clicked", G_CALLBACK (codec_move_down), a); + codecMoveDownButton = gtk_button_new_from_stock(GTK_STOCK_GO_DOWN); + gtk_widget_set_sensitive(GTK_WIDGET(codecMoveDownButton), FALSE); + gtk_box_pack_start(GTK_BOX(buttonBox), codecMoveDownButton, FALSE, FALSE, 0); + g_signal_connect(G_OBJECT(codecMoveDownButton), "clicked", G_CALLBACK(codec_move_down), a); - preferences_dialog_fill_codec_list (a); + preferences_dialog_fill_codec_list(a); - return ret; + return audiocodecs_hbox; } void -select_audio_manager (void) +select_audio_manager(void) { - if (!must_show_alsa_conf() && !gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (pulse))) { - dbus_set_audio_manager (ALSA_API_STR); + if (!must_show_alsa_conf() && !gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(pulse))) { + dbus_set_audio_manager(ALSA_API_STR); alsabox = alsa_box(); - gtk_container_add (GTK_CONTAINER(alsa_conf), alsabox); + gtk_container_add(GTK_CONTAINER(alsa_conf), alsabox); gtk_widget_show(alsa_conf); - gtk_widget_set_sensitive (alsa_conf, TRUE); - gtk_action_set_sensitive (volumeToggle_, TRUE); - } else if (must_show_alsa_conf() && gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (pulse))) { - dbus_set_audio_manager (PULSEAUDIO_API_STR); - gtk_container_remove (GTK_CONTAINER (alsa_conf) , alsabox); + gtk_widget_set_sensitive(alsa_conf, TRUE); + gtk_action_set_sensitive(volumeToggle_, TRUE); + } else if (must_show_alsa_conf() && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(pulse))) { + dbus_set_audio_manager(PULSEAUDIO_API_STR); + gtk_container_remove(GTK_CONTAINER(alsa_conf) , alsabox); gtk_widget_hide(alsa_conf); + if (gtk_toggle_action_get_active(GTK_TOGGLE_ACTION(volumeToggle_))) { main_window_volume_controls(FALSE); eel_gconf_set_integer(SHOW_VOLUME_CONTROLS, FALSE); - gtk_toggle_action_set_active(GTK_TOGGLE_ACTION (volumeToggle_), FALSE); + gtk_toggle_action_set_active(GTK_TOGGLE_ACTION(volumeToggle_), FALSE); } gtk_action_set_sensitive(volumeToggle_, FALSE); @@ -738,316 +608,267 @@ select_audio_manager (void) } void -active_noise_suppress (void) +active_noise_suppress(void) { + gchar *state = dbus_get_noise_suppress_state(); - gchar *state; - gchar *newstate; - - state = dbus_get_noise_suppress_state(); - - if (g_strcmp0 (state, "enabled") == 0) { - newstate = "disabled"; - } else { - newstate = "enabled"; - } + if (g_strcmp0(state, "enabled") == 0) + dbus_set_noise_suppress_state("disabled"); + else + dbus_set_noise_suppress_state("enabled"); - dbus_set_noise_suppress_state (newstate); + g_free(state); } void active_echo_cancel(void) { - gchar *state; - gchar *newstate; + gchar *state = dbus_get_echo_cancel_state(); - state = dbus_get_echo_cancel_state(); - - if(g_strcmp0(state, "enabled") == 0) { - newstate = "disabled"; - } else { - newstate = "enabled"; - } + if (g_strcmp0(state, "enabled") == 0) + dbus_set_echo_cancel_state("disabled"); + else + dbus_set_echo_cancel_state("enabled"); - dbus_set_echo_cancel_state(newstate); + g_free(state); } void -echo_tail_length_changed(GtkRange *range, gpointer user_data) +echo_tail_length_changed(GtkRange *range, gpointer user_data UNUSED) { - (void) user_data; /* UNUSED */ - gint value; - value = (gint)gtk_range_get_value(range); - - dbus_set_echo_cancel_tail_length(value); + dbus_set_echo_cancel_tail_length(gtk_range_get_value(range)); } void -echo_delay_changed(GtkRange *range, gpointer user_data) +echo_delay_changed(GtkRange *range, gpointer user_data UNUSED) { - (void) user_data; /* UNUSED */ - gint value; - value = (gint)gtk_range_get_value(range); - - dbus_set_echo_cancel_delay(value); + dbus_set_echo_cancel_delay(gtk_range_get_value(range)); } void -active_is_always_recording (void) +active_is_always_recording(void) { - gboolean enabled = FALSE; - - enabled = dbus_get_is_always_recording(); - - if(enabled) { - enabled = FALSE; - } - else { - enabled = TRUE; - } - - dbus_set_is_always_recording(enabled); + dbus_set_is_always_recording(!dbus_get_is_always_recording()); } GtkWidget* alsa_box() { - GtkWidget *ret; - GtkWidget *table; - GtkWidget *item; - GtkWidget *info_bar; - GtkCellRenderer *renderer; - - ret = gtk_hbox_new (FALSE, 10); - gtk_widget_show (ret); + GtkWidget *alsa_hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10); + gtk_widget_show(alsa_hbox); - table = gtk_table_new (6, 3, FALSE); - gtk_table_set_col_spacing (GTK_TABLE (table), 0, 40); - gtk_box_pack_start (GTK_BOX (ret) , table , TRUE , TRUE , 1); - gtk_widget_show (table); + GtkWidget *table = gtk_table_new(6, 3, FALSE); + gtk_table_set_col_spacing(GTK_TABLE(table), 0, 40); + gtk_box_pack_start(GTK_BOX(alsa_hbox) , table , TRUE , TRUE , 1); + gtk_widget_show(table); gchar *message = "<small><i>default</i> plugin always uses internal sound card. Select <i>dmix/dsnoop</i> to use an alternate soundcard.</small>"; - gnome_info_bar (message, GTK_MESSAGE_INFO, &info_bar); - gtk_table_attach (GTK_TABLE (table), info_bar, 1, 3, 1, 2, GTK_FILL, GTK_SHRINK, 10, 10); - - DEBUG ("Audio: Configuration plugin"); - item = gtk_label_new (_ ("ALSA plugin")); - gtk_misc_set_alignment (GTK_MISC (item), 0, 0.5); - gtk_table_attach (GTK_TABLE (table), item, 1, 2, 2, 3, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); - gtk_widget_show (item); + GtkWidget *info_bar = gnome_info_bar(message, GTK_MESSAGE_INFO); + gtk_table_attach(GTK_TABLE(table), info_bar, 1, 3, 1, 2, GTK_FILL, GTK_SHRINK, 10, 10); + + DEBUG("Audio: Configuration plugin"); + GtkWidget *label = gtk_label_new(_("ALSA plugin")); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 1, 2, 2, 3, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); + gtk_widget_show(label); // Set choices of audio managers - pluginlist = gtk_list_store_new (1, G_TYPE_STRING); + pluginlist = gtk_list_store_new(1, G_TYPE_STRING); preferences_dialog_fill_audio_plugin_list(); - plugin = gtk_combo_box_new_with_model (GTK_TREE_MODEL (pluginlist)); + plugin = gtk_combo_box_new_with_model(GTK_TREE_MODEL(pluginlist)); select_active_output_audio_plugin(); - gtk_label_set_mnemonic_widget (GTK_LABEL (item), plugin); - g_signal_connect (G_OBJECT (plugin), "changed", G_CALLBACK (select_output_audio_plugin), plugin); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), plugin); + g_signal_connect(G_OBJECT(plugin), "changed", G_CALLBACK(select_output_audio_plugin), plugin); // Set rendering - renderer = gtk_cell_renderer_text_new(); - gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (plugin), renderer, TRUE); - gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (plugin), renderer, "text", 0, NULL); - gtk_table_attach (GTK_TABLE (table), plugin, 2, 3, 2, 3, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); - gtk_widget_show (plugin); + GtkCellRenderer *renderer = gtk_cell_renderer_text_new(); + gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(plugin), renderer, TRUE); + gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(plugin), renderer, "text", 0, NULL); + gtk_table_attach(GTK_TABLE(table), plugin, 2, 3, 2, 3, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); + gtk_widget_show(plugin); // Device : Output device // Create title label - DEBUG ("Audio: Configuration output"); - item = gtk_label_new (_ ("Output")); - gtk_misc_set_alignment (GTK_MISC (item), 0, 0.5); - gtk_table_attach (GTK_TABLE (table), item, 1, 2, 3, 4, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); - gtk_widget_show (item); + DEBUG("Audio: Configuration output"); + label = gtk_label_new(_("Output")); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 1, 2, 3, 4, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); + gtk_widget_show(label); // Set choices of output devices - outputlist = gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_INT); + outputlist = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_INT); preferences_dialog_fill_output_audio_device_list(); - output = gtk_combo_box_new_with_model (GTK_TREE_MODEL (outputlist)); + output = gtk_combo_box_new_with_model(GTK_TREE_MODEL(outputlist)); select_active_output_audio_device(); - gtk_label_set_mnemonic_widget (GTK_LABEL (item), output); - g_signal_connect (G_OBJECT (output), "changed", G_CALLBACK (select_audio_output_device), output); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), output); + g_signal_connect(G_OBJECT(output), "changed", G_CALLBACK(select_audio_output_device), output); // Set rendering renderer = gtk_cell_renderer_text_new(); - gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (output), renderer, TRUE); - gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (output), renderer, "text", 0, NULL); - gtk_table_attach (GTK_TABLE (table), output, 2, 3, 3, 4, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); - gtk_widget_show (output); + gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(output), renderer, TRUE); + gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(output), renderer, "text", 0, NULL); + gtk_table_attach(GTK_TABLE(table), output, 2, 3, 3, 4, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); + gtk_widget_show(output); // Device : Input device // Create title label - DEBUG ("Audio: Configuration input"); - item = gtk_label_new (_ ("Input")); - gtk_misc_set_alignment (GTK_MISC (item), 0, 0.5); - gtk_table_attach (GTK_TABLE (table), item, 1, 2, 4, 5, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); - gtk_widget_show (item); + DEBUG("Audio: Configuration input"); + label = gtk_label_new(_("Input")); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 1, 2, 4, 5, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); + gtk_widget_show(label); // Set choices of output devices - inputlist = gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_INT); + inputlist = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_INT); preferences_dialog_fill_input_audio_device_list(); - input = gtk_combo_box_new_with_model (GTK_TREE_MODEL (inputlist)); + input = gtk_combo_box_new_with_model(GTK_TREE_MODEL(inputlist)); select_active_input_audio_device(); - gtk_label_set_mnemonic_widget (GTK_LABEL (item), input); - g_signal_connect (G_OBJECT (input), "changed", G_CALLBACK (select_audio_input_device), input); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), input); + g_signal_connect(G_OBJECT(input), "changed", G_CALLBACK(select_audio_input_device), input); // Set rendering renderer = gtk_cell_renderer_text_new(); - gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (input), renderer, TRUE); - gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (input), renderer, "text", 0, NULL); - gtk_table_attach (GTK_TABLE (table), input, 2, 3, 4, 5, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); - gtk_widget_show (input); - - DEBUG ("Audio: Configuration rintgtone"); - item = gtk_label_new (_ ("Ringtone")); - gtk_misc_set_alignment (GTK_MISC (item), 0, 0.5); - gtk_table_attach (GTK_TABLE (table), item, 1, 2, 5, 6, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); - gtk_widget_show (item); + gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(input), renderer, TRUE); + gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(input), renderer, "text", 0, NULL); + gtk_table_attach(GTK_TABLE(table), input, 2, 3, 4, 5, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); + gtk_widget_show(input); + + DEBUG("Audio: Configuration rintgtone"); + label = gtk_label_new(_("Ringtone")); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 1, 2, 5, 6, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); + gtk_widget_show(label); // set choices of ringtone devices - ringtonelist = gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_INT); + ringtonelist = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_INT); preferences_dialog_fill_ringtone_audio_device_list(); - ringtone = gtk_combo_box_new_with_model (GTK_TREE_MODEL (ringtonelist)); + ringtone = gtk_combo_box_new_with_model(GTK_TREE_MODEL(ringtonelist)); select_active_ringtone_audio_device(); - gtk_label_set_mnemonic_widget (GTK_LABEL (item), output); - g_signal_connect (G_OBJECT (ringtone), "changed", G_CALLBACK (select_audio_ringtone_device), output); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), output); + g_signal_connect(G_OBJECT(ringtone), "changed", G_CALLBACK(select_audio_ringtone_device), output); // Set rendering renderer = gtk_cell_renderer_text_new(); - gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (ringtone), renderer, TRUE); - gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (ringtone), renderer, "text", 0, NULL); - gtk_table_attach (GTK_TABLE (table), ringtone, 2, 3, 5, 6, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); - gtk_widget_show (ringtone); + gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(ringtone), renderer, TRUE); + gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(ringtone), renderer, "text", 0, NULL); + gtk_table_attach(GTK_TABLE(table), ringtone, 2, 3, 5, 6, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0); + gtk_widget_show(ringtone); - gtk_widget_show_all (ret); + gtk_widget_show_all(alsa_hbox); // Update the combo box - update_device_widget (dbus_get_current_audio_output_plugin()); - return ret; + update_device_widget(dbus_get_current_audio_output_plugin()); + return alsa_hbox; } -static void record_path_changed (GtkFileChooser *chooser , GtkLabel *label UNUSED) +static void record_path_changed(GtkFileChooser *chooser , GtkLabel *label UNUSED) { - DEBUG ("record_path_changed"); - gchar* path; - path = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (chooser)); - DEBUG ("path2 %s", path); - dbus_set_record_path (path); + path = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(chooser)); + dbus_set_record_path(path); } GtkWidget* create_audio_configuration() { - // Main widget - GtkWidget *ret; - // Sub boxes - GtkWidget *frame; - GtkWidget *enableNoiseReduction; - GtkWidget *enableEchoCancel; - gboolean noisesuppressActive; - gboolean echoCancelActive; - gchar *state; + /* Main widget */ + GtkWidget *audio_vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); + gtk_container_set_border_width(GTK_CONTAINER(audio_vbox), 10); - ret = gtk_vbox_new (FALSE, 10); - gtk_container_set_border_width (GTK_CONTAINER (ret), 10); - - GtkWidget *alsa; + GtkWidget *frame; GtkWidget *table; - - gnome_main_section_new_with_table (_ ("Sound Manager"), &frame, &table, 1, 4); - gtk_box_pack_start (GTK_BOX (ret), frame, FALSE, FALSE, 0); + gnome_main_section_new_with_table(_("Sound Manager"), &frame, &table, 1, 4); + gtk_box_pack_start(GTK_BOX(audio_vbox), frame, FALSE, FALSE, 0); gchar *audio_manager = dbus_get_audio_manager(); gboolean pulse_audio = FALSE; if (g_strcmp0(audio_manager, PULSEAUDIO_API_STR) == 0) pulse_audio = TRUE; + g_free(audio_manager); - pulse = gtk_radio_button_new_with_mnemonic (NULL , _ ("_Pulseaudio")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (pulse), pulse_audio); - gtk_table_attach (GTK_TABLE (table), pulse, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + pulse = gtk_radio_button_new_with_mnemonic(NULL , _("_Pulseaudio")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(pulse), pulse_audio); + gtk_table_attach(GTK_TABLE(table), pulse, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - alsa = gtk_radio_button_new_with_mnemonic_from_widget (GTK_RADIO_BUTTON (pulse), _ ("_ALSA")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (alsa), !pulse_audio); - g_signal_connect (G_OBJECT (alsa), "clicked", G_CALLBACK (select_audio_manager), NULL); - gtk_table_attach (GTK_TABLE (table), alsa, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + GtkWidget *alsa = gtk_radio_button_new_with_mnemonic_from_widget(GTK_RADIO_BUTTON(pulse), _("_ALSA")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(alsa), !pulse_audio); + g_signal_connect(G_OBJECT(alsa), "clicked", G_CALLBACK(select_audio_manager), NULL); + gtk_table_attach(GTK_TABLE(table), alsa, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); // Box for the ALSA configuration - gnome_main_section_new (_ ("ALSA settings"), &alsa_conf); - gtk_box_pack_start (GTK_BOX (ret), alsa_conf, FALSE, FALSE, 0); - gtk_widget_show (alsa_conf); + alsa_conf = gnome_main_section_new(_("ALSA settings")); + gtk_box_pack_start(GTK_BOX(audio_vbox), alsa_conf, FALSE, FALSE, 0); + gtk_widget_show(alsa_conf); if (must_show_alsa_conf()) { // Box for the ALSA configuration alsabox = alsa_box(); - gtk_container_add (GTK_CONTAINER (alsa_conf) , alsabox); - gtk_widget_hide (alsa_conf); + gtk_container_add(GTK_CONTAINER(alsa_conf) , alsabox); + gtk_widget_hide(alsa_conf); } - // Recorded file saving path - GtkWidget *label; - GtkWidget *folderChooser; - gchar *dftPath; - - /* Get the path where to save audio files */ - dftPath = dbus_get_record_path (); - DEBUG ("AudioConf: Load recording path %s", dftPath); - - gnome_main_section_new_with_table (_ ("Recordings"), &frame, &table, 2, 3); - gtk_box_pack_start (GTK_BOX (ret), frame, FALSE, FALSE, 0); + gnome_main_section_new_with_table(_("Recordings"), &frame, &table, 2, 3); + gtk_box_pack_start(GTK_BOX(audio_vbox), frame, FALSE, FALSE, 0); // label - label = gtk_label_new (_ ("Destination folder")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); + GtkWidget *label = gtk_label_new(_("Destination folder")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); // folder chooser button - folderChooser = gtk_file_chooser_button_new (_ ("Select a folder"), GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER); - gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (folderChooser), dftPath); - g_signal_connect (G_OBJECT (folderChooser) , "selection_changed" , G_CALLBACK (record_path_changed) , NULL); - gtk_table_attach (GTK_TABLE (table), folderChooser, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); + GtkWidget *folderChooser = gtk_file_chooser_button_new(_("Select a folder"), GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER); + /* Get the path where to save audio files */ + gchar *recordingPath = dbus_get_record_path(); + DEBUG("AudioConf: Load recording path %s", recordingPath); + gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(folderChooser), recordingPath); + g_free(recordingPath); - // isAlwaysRecording functionality checkbox - GtkWidget *enableIsAlwaysRecording = NULL; - gboolean isAlwaysRecording = FALSE; + g_signal_connect(G_OBJECT(folderChooser) , "selection_changed" , G_CALLBACK(record_path_changed) , NULL); + gtk_table_attach(GTK_TABLE(table), folderChooser, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); - isAlwaysRecording = dbus_get_is_always_recording(); - enableIsAlwaysRecording = gtk_check_button_new_with_mnemonic(_("_Always recording")); + // isAlwaysRecording functionality checkbox + gboolean isAlwaysRecording = dbus_get_is_always_recording(); + GtkWidget *enableIsAlwaysRecording = gtk_check_button_new_with_mnemonic(_("_Always recording")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(enableIsAlwaysRecording), isAlwaysRecording); g_signal_connect(G_OBJECT(enableIsAlwaysRecording), "clicked", active_is_always_recording, NULL); gtk_table_attach(GTK_TABLE(table), enableIsAlwaysRecording, 0, 1, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); gtk_widget_show(GTK_WIDGET(enableIsAlwaysRecording)); // Box for the voice enhancement configuration - gnome_main_section_new_with_table (_ ("Voice enhancement settings"), &frame, &table, 2, 1); - gtk_box_pack_start (GTK_BOX (ret), frame, FALSE, FALSE, 0); - - enableNoiseReduction = gtk_check_button_new_with_mnemonic (_ ("_Noise Reduction")); - state = dbus_get_noise_suppress_state(); - noisesuppressActive = FALSE; - if (g_strcmp0 (state, "enabled") == 0) - noisesuppressActive = TRUE; + gnome_main_section_new_with_table(_("Voice enhancement settings"), &frame, &table, 2, 1); + gtk_box_pack_start(GTK_BOX(audio_vbox), frame, FALSE, FALSE, 0); + + GtkWidget *enableNoiseReduction = gtk_check_button_new_with_mnemonic(_("_Noise Reduction")); + gchar *state = dbus_get_noise_suppress_state(); + + if (g_strcmp0(state, "enabled") == 0) + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(enableNoiseReduction), TRUE); else - noisesuppressActive = FALSE; - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (enableNoiseReduction), noisesuppressActive); - g_signal_connect (G_OBJECT (enableNoiseReduction), "clicked", active_noise_suppress, NULL); - gtk_table_attach (GTK_TABLE (table), enableNoiseReduction, 0, 1, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(enableNoiseReduction), FALSE); + + g_free(state); + state = NULL; - enableEchoCancel = gtk_check_button_new_with_mnemonic(_("_Echo Cancellation")); + g_signal_connect(G_OBJECT(enableNoiseReduction), "clicked", active_noise_suppress, NULL); + gtk_table_attach(GTK_TABLE(table), enableNoiseReduction, 0, 1, 1, 2, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + + GtkWidget *enableEchoCancel = gtk_check_button_new_with_mnemonic(_("_Echo Cancellation")); state = dbus_get_echo_cancel_state(); - echoCancelActive = FALSE; + if (g_strcmp0(state, "enabled") == 0) - echoCancelActive = TRUE; + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(enableEchoCancel), TRUE); else - echoCancelActive = FALSE; + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(enableEchoCancel), FALSE); + + g_free(state); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(enableEchoCancel), echoCancelActive); g_signal_connect(G_OBJECT(enableEchoCancel), "clicked", active_echo_cancel, NULL); gtk_table_attach(GTK_TABLE(table), enableEchoCancel, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_show_all (ret); + gtk_widget_show_all(audio_vbox); if (!pulse_audio) - gtk_widget_show (alsa_conf); + gtk_widget_show(alsa_conf); else - gtk_widget_hide (alsa_conf); + gtk_widget_hide(alsa_conf); - return ret; + return audio_vbox; } /** Show/Hide the alsa configuration panel */ diff --git a/gnome/src/config/hooks-config.c b/gnome/src/config/hooks-config.c index d8a448560f4855710dc6e83df1e60c8ea94ee3ef..2b3e9e882cb9c9cb7de77567699b5008eb764aa4 100644 --- a/gnome/src/config/hooks-config.c +++ b/gnome/src/config/hooks-config.c @@ -29,22 +29,23 @@ */ #include "hooks-config.h" +#include "dbus.h" URLHook_Config *_urlhook_config; GtkWidget *field, *command, *prefix; -void hooks_load_parameters (URLHook_Config** settings) +void hooks_load_parameters(URLHook_Config** settings) { GHashTable *_params = NULL; URLHook_Config *_settings; // Allocate a struct - _settings = g_new0 (URLHook_Config, 1); + _settings = g_new0(URLHook_Config, 1); // Fetch the settings from D-Bus - _params = (GHashTable*) dbus_get_hook_settings (); + _params = (GHashTable*) dbus_get_hook_settings(); if (_params == NULL) { _settings->sip_field = DEFAULT_SIP_URL_FIELD; @@ -54,50 +55,50 @@ void hooks_load_parameters (URLHook_Config** settings) _settings->phone_number_enabled = "false"; _settings->phone_number_prefix = ""; } else { - _settings->sip_field = (gchar*) (g_hash_table_lookup (_params, URLHOOK_SIP_FIELD)); - _settings->command = (gchar*) (g_hash_table_lookup (_params, URLHOOK_COMMAND)); - _settings->sip_enabled = (gchar*) (g_hash_table_lookup (_params, URLHOOK_SIP_ENABLED)); - _settings->iax2_enabled = (gchar*) (g_hash_table_lookup (_params, URLHOOK_IAX2_ENABLED)); - _settings->phone_number_enabled = (gchar*) (g_hash_table_lookup (_params, PHONE_NUMBER_HOOK_ENABLED)); - _settings->phone_number_prefix = (gchar*) (g_hash_table_lookup (_params, PHONE_NUMBER_HOOK_ADD_PREFIX)); + _settings->sip_field = (gchar*)(g_hash_table_lookup(_params, URLHOOK_SIP_FIELD)); + _settings->command = (gchar*)(g_hash_table_lookup(_params, URLHOOK_COMMAND)); + _settings->sip_enabled = (gchar*)(g_hash_table_lookup(_params, URLHOOK_SIP_ENABLED)); + _settings->iax2_enabled = (gchar*)(g_hash_table_lookup(_params, URLHOOK_IAX2_ENABLED)); + _settings->phone_number_enabled = (gchar*)(g_hash_table_lookup(_params, PHONE_NUMBER_HOOK_ENABLED)); + _settings->phone_number_prefix = (gchar*)(g_hash_table_lookup(_params, PHONE_NUMBER_HOOK_ADD_PREFIX)); } *settings = _settings; } -void hooks_save_parameters (void) +void hooks_save_parameters(void) { GHashTable *params = NULL; - params = g_hash_table_new (NULL, g_str_equal); - g_hash_table_replace (params, (gpointer) URLHOOK_SIP_FIELD, - g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (field)))); - g_hash_table_replace (params, (gpointer) URLHOOK_COMMAND, - g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (command)))); - g_hash_table_replace (params, (gpointer) URLHOOK_SIP_ENABLED, - (gpointer) g_strdup (_urlhook_config->sip_enabled)); - g_hash_table_replace (params, (gpointer) URLHOOK_IAX2_ENABLED, - (gpointer) g_strdup (_urlhook_config->iax2_enabled)); - g_hash_table_replace (params, (gpointer) PHONE_NUMBER_HOOK_ENABLED, - (gpointer) g_strdup (_urlhook_config->phone_number_enabled)); - g_hash_table_replace (params, (gpointer) PHONE_NUMBER_HOOK_ADD_PREFIX, - g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (prefix)))); - - dbus_set_hook_settings (params); + params = g_hash_table_new(NULL, g_str_equal); + g_hash_table_replace(params, (gpointer) URLHOOK_SIP_FIELD, + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(field)))); + g_hash_table_replace(params, (gpointer) URLHOOK_COMMAND, + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(command)))); + g_hash_table_replace(params, (gpointer) URLHOOK_SIP_ENABLED, + (gpointer) g_strdup(_urlhook_config->sip_enabled)); + g_hash_table_replace(params, (gpointer) URLHOOK_IAX2_ENABLED, + (gpointer) g_strdup(_urlhook_config->iax2_enabled)); + g_hash_table_replace(params, (gpointer) PHONE_NUMBER_HOOK_ENABLED, + (gpointer) g_strdup(_urlhook_config->phone_number_enabled)); + g_hash_table_replace(params, (gpointer) PHONE_NUMBER_HOOK_ADD_PREFIX, + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(prefix)))); + + dbus_set_hook_settings(params); // Decrement the reference count - g_hash_table_unref (params); + g_hash_table_unref(params); } -static void sip_enabled_cb (GtkWidget *widget) +static void sip_enabled_cb(GtkWidget *widget) { guint check; - check = (guint) gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)); + check = (guint) gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)); if (check) _urlhook_config->sip_enabled="true"; @@ -105,12 +106,12 @@ static void sip_enabled_cb (GtkWidget *widget) _urlhook_config->sip_enabled="false"; } -static void iax2_enabled_cb (GtkWidget *widget) +static void iax2_enabled_cb(GtkWidget *widget) { guint check; - check = (guint) gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)); + check = (guint) gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)); if (check) _urlhook_config->iax2_enabled="true"; @@ -118,82 +119,81 @@ static void iax2_enabled_cb (GtkWidget *widget) _urlhook_config->iax2_enabled="false"; } -static void phone_number_enabled_cb (GtkWidget *widget) +static void phone_number_enabled_cb(GtkWidget *widget) { guint check; - check = (guint) gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)); + check = (guint) gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)); if (check) { _urlhook_config->phone_number_enabled="true"; - gtk_widget_set_sensitive (GTK_WIDGET (prefix), TRUE); + gtk_widget_set_sensitive(GTK_WIDGET(prefix), TRUE); } else { _urlhook_config->phone_number_enabled="false"; - gtk_widget_set_sensitive (GTK_WIDGET (prefix), FALSE); + gtk_widget_set_sensitive(GTK_WIDGET(prefix), FALSE); } } -GtkWidget* create_hooks_settings () +GtkWidget* create_hooks_settings() { - - GtkWidget *ret, *frame, *table, *label, *widg, *info_bar; + GtkWidget *ret, *frame, *table, *label, *widg; // Load the user value - hooks_load_parameters (&_urlhook_config); + hooks_load_parameters(&_urlhook_config); - ret = gtk_vbox_new (FALSE, 10); - gtk_container_set_border_width (GTK_CONTAINER (ret), 10); + ret = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); + gtk_container_set_border_width(GTK_CONTAINER(ret), 10); - gnome_main_section_new_with_table (_ ("URL Argument"), &frame, &table, 5, 2); - gtk_box_pack_start (GTK_BOX (ret), frame, FALSE, FALSE, 0); - gtk_widget_show (frame); + gnome_main_section_new_with_table(_("URL Argument"), &frame, &table, 5, 2); + gtk_box_pack_start(GTK_BOX(ret), frame, FALSE, FALSE, 0); + gtk_widget_show(frame); gchar *message = "<small>Custom commands on incoming calls with URL. %s will be replaced with the passed URL.</small>"; - gnome_info_bar (message, GTK_MESSAGE_INFO, &info_bar); - gtk_table_attach (GTK_TABLE (table), info_bar, 0, 2, 0, 1, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 10, 10); + GtkWidget *info_bar = gnome_info_bar(message, GTK_MESSAGE_INFO); + gtk_table_attach(GTK_TABLE(table), info_bar, 0, 2, 0, 1, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 10, 10); - widg = gtk_check_button_new_with_mnemonic (_ ("Trigger on specific _SIP header")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (widg), (g_strcasecmp (_urlhook_config->sip_enabled, "true") ==0) ?TRUE:FALSE); - g_signal_connect (G_OBJECT (widg) , "clicked" , G_CALLBACK (sip_enabled_cb), NULL); - gtk_table_attach (GTK_TABLE (table), widg, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + widg = gtk_check_button_new_with_mnemonic(_("Trigger on specific _SIP header")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widg), (g_strcasecmp(_urlhook_config->sip_enabled, "true") ==0) ?TRUE:FALSE); + g_signal_connect(G_OBJECT(widg) , "clicked" , G_CALLBACK(sip_enabled_cb), NULL); + gtk_table_attach(GTK_TABLE(table), widg, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - field = gtk_entry_new (); - gtk_entry_set_text (GTK_ENTRY (field), _urlhook_config->sip_field); - gtk_table_attach (GTK_TABLE (table), field, 1, 2, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + field = gtk_entry_new(); + gtk_entry_set_text(GTK_ENTRY(field), _urlhook_config->sip_field); + gtk_table_attach(GTK_TABLE(table), field, 1, 2, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - widg = gtk_check_button_new_with_mnemonic (_ ("Trigger on _IAX2 URL")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (widg), (g_strcasecmp (_urlhook_config->iax2_enabled, "true") ==0) ?TRUE:FALSE); - g_signal_connect (G_OBJECT (widg) , "clicked" , G_CALLBACK (iax2_enabled_cb), NULL); - gtk_table_attach (GTK_TABLE (table), widg, 0, 2, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + widg = gtk_check_button_new_with_mnemonic(_("Trigger on _IAX2 URL")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widg), (g_strcasecmp(_urlhook_config->iax2_enabled, "true") ==0) ?TRUE:FALSE); + g_signal_connect(G_OBJECT(widg) , "clicked" , G_CALLBACK(iax2_enabled_cb), NULL); + gtk_table_attach(GTK_TABLE(table), widg, 0, 2, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - label = gtk_label_new_with_mnemonic (_ ("Command to _run")); - gtk_misc_set_alignment (GTK_MISC (label), 0.05, 0.5); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 4, 5, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - command = gtk_entry_new (); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), command); - gtk_entry_set_text (GTK_ENTRY (command), _urlhook_config->command); - gtk_table_attach (GTK_TABLE (table), command, 1, 2, 4, 5, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 10); + label = gtk_label_new_with_mnemonic(_("Command to _run")); + gtk_misc_set_alignment(GTK_MISC(label), 0.05, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 4, 5, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + command = gtk_entry_new(); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), command); + gtk_entry_set_text(GTK_ENTRY(command), _urlhook_config->command); + gtk_table_attach(GTK_TABLE(table), command, 1, 2, 4, 5, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 10); - gnome_main_section_new_with_table (_ ("Phone number rewriting"), &frame, &table, 4, 2); - gtk_box_pack_start (GTK_BOX (ret), frame, FALSE, FALSE, 0); - gtk_widget_show (frame); + gnome_main_section_new_with_table(_("Phone number rewriting"), &frame, &table, 4, 2); + gtk_box_pack_start(GTK_BOX(ret), frame, FALSE, FALSE, 0); + gtk_widget_show(frame); - widg = gtk_check_button_new_with_mnemonic (_ ("_Prefix dialed numbers with")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (widg), (g_strcasecmp (_urlhook_config->phone_number_enabled, "true") ==0) ?TRUE:FALSE); - g_signal_connect (G_OBJECT (widg) , "clicked" , G_CALLBACK (phone_number_enabled_cb), NULL); - gtk_table_attach (GTK_TABLE (table), widg, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + widg = gtk_check_button_new_with_mnemonic(_("_Prefix dialed numbers with")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widg), (g_strcasecmp(_urlhook_config->phone_number_enabled, "true") ==0) ?TRUE:FALSE); + g_signal_connect(G_OBJECT(widg) , "clicked" , G_CALLBACK(phone_number_enabled_cb), NULL); + gtk_table_attach(GTK_TABLE(table), widg, 0, 1, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - prefix = gtk_entry_new (); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), prefix); - gtk_entry_set_text (GTK_ENTRY (prefix), _urlhook_config->phone_number_prefix); - gtk_widget_set_sensitive (GTK_WIDGET (prefix), gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widg))); - gtk_table_attach (GTK_TABLE (table), prefix, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 10); + prefix = gtk_entry_new(); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), prefix); + gtk_entry_set_text(GTK_ENTRY(prefix), _urlhook_config->phone_number_prefix); + gtk_widget_set_sensitive(GTK_WIDGET(prefix), gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widg))); + gtk_table_attach(GTK_TABLE(table), prefix, 1, 2, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 10); - gtk_widget_show_all (ret); + gtk_widget_show_all(ret); return ret; } diff --git a/gnome/src/config/preferencesdialog.c b/gnome/src/config/preferencesdialog.c index ad7b03781d3b0aa65fccc4c8867a5f683ecb1cc9..8a38ed761a3e81bc63534cbcfd9224782dceb3e5 100644 --- a/gnome/src/config/preferencesdialog.c +++ b/gnome/src/config/preferencesdialog.c @@ -36,39 +36,35 @@ #include <stdlib.h> #include <stdio.h> #include <string.h> -#include "eel-gconf-extensions.h" +#include <assert.h> +#include "eel-gconf-extensions.h" +#include "dbus.h" +#include "logger.h" +#include "statusicon.h" #include "addrbookfactory.h" #include "preferencesdialog.h" #include "addressbook-config.h" #include "shortcuts-config.h" -#include "audioconf.h" #include "hooks-config.h" #include "audioconf.h" #include "uimanager.h" +#include "unused.h" #include "mainwindow.h" /** * Local variables */ -gboolean accDialogOpen = FALSE; -gboolean dialogOpen = FALSE; -gboolean ringtoneEnabled = TRUE; - +static gboolean dialogOpen = FALSE; -GtkWidget * status; -GtkWidget * history_value; +static GtkWidget * history_value; -GtkWidget *starthidden; -GtkWidget *popupwindow; -GtkWidget *neverpopupwindow; +static GtkWidget *starthidden; +static GtkWidget *popupwindow; +static GtkWidget *neverpopupwindow; -GtkWidget *treeView; -GtkWidget *iconview; -GtkCellRenderer *renderer; -GtkTreeViewColumn *column; -GtkTreeSelection *selection; -GtkWidget * notebook; +static GtkWidget *iconview; +static GtkWidget * notebook; enum { @@ -77,12 +73,6 @@ enum { PAGE_NUMBER }; -typedef struct { - gchar* icon_descr; - gchar* icon_name; - gint page_number; -} browser_t; - // history preference parameters static int history_limit; static gboolean history_enabled = TRUE; @@ -91,284 +81,314 @@ static gboolean history_enabled = TRUE; static gboolean instant_messaging_enabled = TRUE; static void -start_hidden (void) +start_hidden(void) { - gboolean currentstate = eel_gconf_get_integer (START_HIDDEN); - eel_gconf_set_integer (START_HIDDEN, !currentstate); + gboolean currentstate = eel_gconf_get_integer(START_HIDDEN); + eel_gconf_set_integer(START_HIDDEN, !currentstate); } static void -set_popup_mode (GtkWidget *widget, gpointer *userdata UNUSED) +set_popup_mode(GtkWidget *widget, gpointer *userdata UNUSED) { - gboolean currentstate = eel_gconf_get_integer (POPUP_ON_CALL); + gboolean currentstate = eel_gconf_get_integer(POPUP_ON_CALL); - if (currentstate || gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget))) { - eel_gconf_set_integer (POPUP_ON_CALL, !currentstate); - } + if (currentstate || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget))) + eel_gconf_set_integer(POPUP_ON_CALL, !currentstate); } void -set_notif_level () +set_notif_level() { - gboolean current_state = eel_gconf_get_integer (NOTIFY_ALL); - eel_gconf_set_integer (NOTIFY_ALL, !current_state); + gboolean current_state = eel_gconf_get_integer(NOTIFY_ALL); + eel_gconf_set_integer(NOTIFY_ALL, !current_state); } static void -history_limit_cb (GtkSpinButton *button UNUSED, void *ptr) +history_limit_cb(GtkSpinButton *button UNUSED, void *ptr) { - history_limit = gtk_spin_button_get_value_as_int ( (GtkSpinButton *) (ptr)); + history_limit = gtk_spin_button_get_value_as_int((GtkSpinButton *)(ptr)); } static void -history_enabled_cb (GtkWidget *widget) +history_enabled_cb(GtkWidget *widget) { - history_enabled = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)); - gtk_widget_set_sensitive (GTK_WIDGET (history_value), history_enabled); + history_enabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)); + gtk_widget_set_sensitive(GTK_WIDGET(history_value), history_enabled); // Toggle it through D-Bus - eel_gconf_set_integer (HISTORY_ENABLED, !eel_gconf_get_integer (HISTORY_ENABLED)); + eel_gconf_set_integer(HISTORY_ENABLED, !eel_gconf_get_integer(HISTORY_ENABLED)); } static void -instant_messaging_enabled_cb (GtkWidget *widget) +instant_messaging_enabled_cb(GtkWidget *widget) { - instant_messaging_enabled = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)); - - eel_gconf_set_integer (INSTANT_MESSAGING_ENABLED, !eel_gconf_get_integer (INSTANT_MESSAGING_ENABLED)); + instant_messaging_enabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)); + eel_gconf_set_integer(INSTANT_MESSAGING_ENABLED, !eel_gconf_get_integer(INSTANT_MESSAGING_ENABLED)); } void -clean_history (void) +clean_history(void) { - calllist_clean_history (); + calllist_clean_history(); } -void showstatusicon_cb (GtkWidget *widget, gpointer data UNUSED) +void showstatusicon_cb(GtkWidget *widget, gpointer data UNUSED) { - - gboolean currentstatus = FALSE; - // data contains the previous value of dbus_is_status_icon_enabled () - ie before the click. - currentstatus = (gboolean) gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)); + gboolean currentstatus = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)); // Update the widget states - gtk_widget_set_sensitive (GTK_WIDGET (popupwindow), currentstatus); - gtk_widget_set_sensitive (GTK_WIDGET (neverpopupwindow), currentstatus); - gtk_widget_set_sensitive (GTK_WIDGET (starthidden), currentstatus); + gtk_widget_set_sensitive(GTK_WIDGET(popupwindow), currentstatus); + gtk_widget_set_sensitive(GTK_WIDGET(neverpopupwindow), currentstatus); + gtk_widget_set_sensitive(GTK_WIDGET(starthidden), currentstatus); - currentstatus ? show_status_icon () : hide_status_icon (); + currentstatus ? show_status_icon() : hide_status_icon(); // Update through D-Bus - eel_gconf_set_integer (SHOW_STATUSICON, currentstatus); + eel_gconf_set_integer(SHOW_STATUSICON, currentstatus); } GtkWidget* -create_general_settings () +create_general_settings() { - GtkWidget *ret, *notifAll, *frame, *checkBoxWidget, *label, *table, *showstatusicon; gboolean statusicon; // Load history configuration - history_load_configuration (); + history_load_configuration(); // Load instant messaging configuration instant_messaging_load_configuration(); // Main widget - ret = gtk_vbox_new (FALSE, 10); - gtk_container_set_border_width (GTK_CONTAINER (ret), 10); + ret = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); + gtk_container_set_border_width(GTK_CONTAINER(ret), 10); // Notifications Frame - gnome_main_section_new_with_table (_ ("Desktop Notifications"), &frame, - &table, 2, 1); - gtk_box_pack_start (GTK_BOX (ret), frame, FALSE, FALSE, 0); + gnome_main_section_new_with_table(_("Desktop Notifications"), &frame, + &table, 2, 1); + gtk_box_pack_start(GTK_BOX(ret), frame, FALSE, FALSE, 0); // Notification All - notifAll = gtk_check_button_new_with_mnemonic (_ ("_Enable notifications")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (notifAll), eel_gconf_get_integer (NOTIFY_ALL)); - g_signal_connect (G_OBJECT (notifAll) , "clicked" , G_CALLBACK (set_notif_level) , NULL); - gtk_table_attach (GTK_TABLE (table), notifAll, 0, 1, 0, 1, GTK_EXPAND - | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); + notifAll = gtk_check_button_new_with_mnemonic(_("_Enable notifications")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(notifAll), eel_gconf_get_integer(NOTIFY_ALL)); + g_signal_connect(G_OBJECT(notifAll) , "clicked" , G_CALLBACK(set_notif_level) , NULL); + gtk_table_attach(GTK_TABLE(table), notifAll, 0, 1, 0, 1, GTK_EXPAND + | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); // System Tray option frame - gnome_main_section_new_with_table (_ ("System Tray Icon"), &frame, &table, 4, - 1); - gtk_box_pack_start (GTK_BOX (ret), frame, FALSE, FALSE, 0); + gnome_main_section_new_with_table(_("System Tray Icon"), &frame, &table, 4, + 1); + gtk_box_pack_start(GTK_BOX(ret), frame, FALSE, FALSE, 0); // Whether or not displaying an icon in the system tray - statusicon = eel_gconf_get_integer (SHOW_STATUSICON); - - showstatusicon = gtk_check_button_new_with_mnemonic ( - _ ("Show SFLphone in the system tray")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (showstatusicon), statusicon); - g_signal_connect (G_OBJECT (showstatusicon) , "clicked" , G_CALLBACK (showstatusicon_cb), NULL); - gtk_table_attach (GTK_TABLE (table), showstatusicon, 0, 1, 0, 1, GTK_EXPAND - | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); - - popupwindow = gtk_radio_button_new_with_mnemonic (NULL, - _ ("_Popup main window on incoming call")); - g_signal_connect (G_OBJECT (popupwindow), "toggled", G_CALLBACK (set_popup_mode), NULL); - gtk_table_attach (GTK_TABLE (table), popupwindow, 0, 1, 1, 2, GTK_EXPAND - | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); - - neverpopupwindow = gtk_radio_button_new_with_mnemonic_from_widget ( - GTK_RADIO_BUTTON (popupwindow), _ ("Ne_ver popup main window")); - gtk_table_attach (GTK_TABLE (table), neverpopupwindow, 0, 1, 2, 3, GTK_EXPAND - | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); + statusicon = eel_gconf_get_integer(SHOW_STATUSICON); + + showstatusicon = gtk_check_button_new_with_mnemonic( + _("Show SFLphone in the system tray")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(showstatusicon), statusicon); + g_signal_connect(G_OBJECT(showstatusicon) , "clicked" , G_CALLBACK(showstatusicon_cb), NULL); + gtk_table_attach(GTK_TABLE(table), showstatusicon, 0, 1, 0, 1, GTK_EXPAND + | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); + + popupwindow = gtk_radio_button_new_with_mnemonic(NULL, + _("_Popup main window on incoming call")); + g_signal_connect(G_OBJECT(popupwindow), "toggled", G_CALLBACK(set_popup_mode), NULL); + gtk_table_attach(GTK_TABLE(table), popupwindow, 0, 1, 1, 2, GTK_EXPAND + | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); + + neverpopupwindow = gtk_radio_button_new_with_mnemonic_from_widget( + GTK_RADIO_BUTTON(popupwindow), _("Ne_ver popup main window")); + gtk_table_attach(GTK_TABLE(table), neverpopupwindow, 0, 1, 2, 3, GTK_EXPAND + | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); // Toggle according to the user configuration - eel_gconf_get_integer (POPUP_ON_CALL) ? gtk_toggle_button_set_active ( - GTK_TOGGLE_BUTTON (popupwindow), + eel_gconf_get_integer(POPUP_ON_CALL) ? gtk_toggle_button_set_active( + GTK_TOGGLE_BUTTON(popupwindow), TRUE) : - gtk_toggle_button_set_active ( - GTK_TOGGLE_BUTTON (neverpopupwindow), + gtk_toggle_button_set_active( + GTK_TOGGLE_BUTTON(neverpopupwindow), TRUE); - starthidden = gtk_check_button_new_with_mnemonic ( - _ ("Hide SFLphone window on _startup")); + starthidden = gtk_check_button_new_with_mnemonic( + _("Hide SFLphone window on _startup")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (starthidden), - eel_gconf_get_integer (START_HIDDEN)); - g_signal_connect (G_OBJECT (starthidden) , "clicked" , G_CALLBACK (start_hidden) , NULL); - gtk_table_attach (GTK_TABLE (table), starthidden, 0, 1, 3, 4, GTK_EXPAND - | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(starthidden), + eel_gconf_get_integer(START_HIDDEN)); + g_signal_connect(G_OBJECT(starthidden) , "clicked" , G_CALLBACK(start_hidden) , NULL); + gtk_table_attach(GTK_TABLE(table), starthidden, 0, 1, 3, 4, GTK_EXPAND + | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); // Update the widget states - gtk_widget_set_sensitive (GTK_WIDGET (popupwindow),statusicon); - gtk_widget_set_sensitive (GTK_WIDGET (neverpopupwindow),statusicon); - gtk_widget_set_sensitive (GTK_WIDGET (starthidden),statusicon); + gtk_widget_set_sensitive(GTK_WIDGET(popupwindow),statusicon); + gtk_widget_set_sensitive(GTK_WIDGET(neverpopupwindow),statusicon); + gtk_widget_set_sensitive(GTK_WIDGET(starthidden),statusicon); // HISTORY CONFIGURATION - gnome_main_section_new_with_table (_ ("Calls History"), &frame, &table, 3, 1); - gtk_box_pack_start (GTK_BOX (ret), frame, FALSE, FALSE, 0); - - checkBoxWidget = gtk_check_button_new_with_mnemonic ( - _ ("_Keep my history for at least")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (checkBoxWidget), - history_enabled); - g_signal_connect (G_OBJECT (checkBoxWidget) , "clicked" , G_CALLBACK (history_enabled_cb) , NULL); - gtk_table_attach (GTK_TABLE (table), checkBoxWidget, 0, 1, 0, 1, GTK_EXPAND - | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); - - history_value = gtk_spin_button_new_with_range (1, 99, 1); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (history_value), history_limit); - g_signal_connect (G_OBJECT (history_value) , "value-changed" , G_CALLBACK (history_limit_cb) , history_value); - gtk_widget_set_sensitive (GTK_WIDGET (history_value), - gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (checkBoxWidget))); - gtk_table_attach (GTK_TABLE (table), history_value, 1, 2, 0, 1, GTK_EXPAND - | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); - - label = gtk_label_new (_ ("days")); - gtk_table_attach (GTK_TABLE (table), label, 2, 3, 0, 1, GTK_EXPAND | GTK_FILL, - GTK_EXPAND | GTK_FILL, 0, 5); + gnome_main_section_new_with_table(_("Calls History"), &frame, &table, 3, 1); + gtk_box_pack_start(GTK_BOX(ret), frame, FALSE, FALSE, 0); + + checkBoxWidget = gtk_check_button_new_with_mnemonic( + _("_Keep my history for at least")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkBoxWidget), + history_enabled); + g_signal_connect(G_OBJECT(checkBoxWidget) , "clicked" , G_CALLBACK(history_enabled_cb) , NULL); + gtk_table_attach(GTK_TABLE(table), checkBoxWidget, 0, 1, 0, 1, GTK_EXPAND + | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); + + history_value = gtk_spin_button_new_with_range(1, 99, 1); + gtk_spin_button_set_value(GTK_SPIN_BUTTON(history_value), history_limit); + g_signal_connect(G_OBJECT(history_value) , "value-changed" , G_CALLBACK(history_limit_cb) , history_value); + gtk_widget_set_sensitive(GTK_WIDGET(history_value), + gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkBoxWidget))); + gtk_table_attach(GTK_TABLE(table), history_value, 1, 2, 0, 1, GTK_EXPAND + | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); + + label = gtk_label_new(_("days")); + gtk_table_attach(GTK_TABLE(table), label, 2, 3, 0, 1, GTK_EXPAND | GTK_FILL, + GTK_EXPAND | GTK_FILL, 0, 5); // INSTANT MESSAGING CONFIGURATION - gnome_main_section_new_with_table (_ ("Instant Messaging"), &frame, &table, 1, 1); - gtk_box_pack_start (GTK_BOX (ret), frame, FALSE, FALSE, 0); + gnome_main_section_new_with_table(_("Instant Messaging"), &frame, &table, 1, 1); + gtk_box_pack_start(GTK_BOX(ret), frame, FALSE, FALSE, 0); - checkBoxWidget = gtk_check_button_new_with_mnemonic ( - _ ("Enable instant messaging")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (checkBoxWidget), - instant_messaging_enabled); - g_signal_connect (G_OBJECT (checkBoxWidget) , "clicked" , G_CALLBACK (instant_messaging_enabled_cb) , NULL); - gtk_table_attach (GTK_TABLE (table), checkBoxWidget, 0, 1, 0, 1, GTK_EXPAND - | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); + checkBoxWidget = gtk_check_button_new_with_mnemonic( + _("Enable instant messaging")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkBoxWidget), + instant_messaging_enabled); + g_signal_connect(G_OBJECT(checkBoxWidget) , "clicked" , G_CALLBACK(instant_messaging_enabled_cb) , NULL); + gtk_table_attach(GTK_TABLE(table), checkBoxWidget, 0, 1, 0, 1, GTK_EXPAND + | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 5); - gtk_widget_show_all (ret); + gtk_widget_show_all(ret); return ret; } void -save_configuration_parameters (void) +save_configuration_parameters(void) { - if (addrbook) { - // Address book config - addressbook_config_save_parameters (); - } + if (addrbook) + addressbook_config_save_parameters(); - hooks_save_parameters (); + hooks_save_parameters(); // History config - dbus_set_history_limit (history_limit); - + dbus_set_history_limit(history_limit); } void -history_load_configuration () +history_load_configuration() { - history_limit = dbus_get_history_limit (); - history_enabled = eel_gconf_get_integer (HISTORY_ENABLED); + history_limit = dbus_get_history_limit(); + history_enabled = eel_gconf_get_integer(HISTORY_ENABLED); } void -instant_messaging_load_configuration () +instant_messaging_load_configuration() { - instant_messaging_enabled = eel_gconf_get_integer (INSTANT_MESSAGING_ENABLED); - + instant_messaging_enabled = eel_gconf_get_integer(INSTANT_MESSAGING_ENABLED); } void -selection_changed_cb (GtkIconView *view, gpointer user_data UNUSED) +selection_changed_cb(GtkIconView *view, gpointer user_data UNUSED) { - GtkTreeModel *model; GtkTreeIter iter; GList *list; gint page; - model = gtk_icon_view_get_model (view); - list = gtk_icon_view_get_selected_items (view); + model = gtk_icon_view_get_model(view); + list = gtk_icon_view_get_selected_items(view); if (list == NULL) return; - if (g_list_length (list) > 1) + if (g_list_length(list) > 1) return; - gtk_tree_model_get_iter (model, &iter, list->data); - gtk_tree_model_get (model, &iter, PAGE_NUMBER, &page, -1); + gtk_tree_model_get_iter(model, &iter, list->data); + gtk_tree_model_get(model, &iter, PAGE_NUMBER, &page, -1); - gtk_notebook_set_current_page (GTK_NOTEBOOK (notebook), page); - g_list_foreach (list, (GFunc) gtk_tree_path_free, NULL); - g_list_free (list); + gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook), page); + g_list_foreach(list, (GFunc) gtk_tree_path_free, NULL); + g_list_free(list); } +/* + * Get an 48x48 icon from the default theme or fallback to an application icon. + */ +static GdkPixbuf *get_icon(const gchar *name, GtkWidget *widget) +{ + GtkIconTheme *theme = gtk_icon_theme_get_default(); + GdkPixbuf *pixbuf = gtk_icon_theme_load_icon(theme, name, 48, 0, NULL); + if (!pixbuf) + pixbuf = gtk_widget_render_icon_pixbuf(widget, name, GTK_ICON_SIZE_DIALOG); + + return pixbuf; +} + +static GtkTreeModel* create_model(GtkWidget *widget) +{ + static const struct { + gchar* icon_descr; + gchar* icon_name; + gint page_number; + } browser_entries_full[] = { + {"General", GTK_STOCK_PREFERENCES, 0}, + {"Audio", GTK_STOCK_AUDIO_CARD, 1}, + {"Hooks", "applications-development", 2}, + {"Shortcuts", "preferences-desktop-keyboard", 3}, + {"Address Book", GTK_STOCK_ADDRESSBOOK, 4}, + }; + GdkPixbuf *pixbuf; + GtkTreeIter iter; + gint i, nb_entries; + + GtkListStore *store = gtk_list_store_new(3, GDK_TYPE_PIXBUF, G_TYPE_STRING, G_TYPE_INT); + nb_entries = sizeof(browser_entries_full) / sizeof(browser_entries_full[0]); + + for (i = 0; i < nb_entries; i++) { + gtk_list_store_append (store, &iter); + pixbuf = get_icon(browser_entries_full[i].icon_name, widget); + gtk_list_store_set(store, &iter, + PIXBUF_COL, pixbuf, + TEXT_COL, _(browser_entries_full[i].icon_descr), + PAGE_NUMBER, browser_entries_full[i].page_number, + -1); + if (pixbuf) + gdk_pixbuf_unref(pixbuf); + } + + return GTK_TREE_MODEL(store); +} /** * Show configuration window with tabs */ guint -show_preferences_dialog () +show_preferences_dialog() { - GtkDialog * dialog; - GtkWidget * hbox; - GtkWidget * tab; - guint result; - dialogOpen = TRUE; - - dialog = GTK_DIALOG (gtk_dialog_new_with_buttons (_ ("Preferences"), - GTK_WINDOW (get_main_window()), - GTK_DIALOG_DESTROY_WITH_PARENT, - GTK_STOCK_CLOSE, - GTK_RESPONSE_ACCEPT, - NULL)); + GtkDialog *dialog = GTK_DIALOG(gtk_dialog_new_with_buttons(_("Preferences"), + GTK_WINDOW(get_main_window()), + GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_STOCK_CLOSE, + GTK_RESPONSE_ACCEPT, + NULL)); // Set window properties - gtk_window_set_default_size (GTK_WINDOW (dialog), 600, 400); - gtk_container_set_border_width (GTK_CONTAINER (dialog), 0); + gtk_window_set_default_size(GTK_WINDOW(dialog), 600, 400); + gtk_container_set_border_width(GTK_CONTAINER(dialog), 0); - hbox = gtk_hbox_new (FALSE, 10); + GtkWidget *hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10); // Create tree view - iconview = gtk_icon_view_new_with_model (createModel ()); + iconview = gtk_icon_view_new_with_model(create_model(hbox)); g_object_set (iconview, "selection-mode", GTK_SELECTION_BROWSE, "text-column", TEXT_COL, @@ -376,106 +396,61 @@ show_preferences_dialog () "columns", 1, "margin", 10, NULL); + // Connect the callback when clicking on an item - g_signal_connect (G_OBJECT (iconview), "selection-changed", G_CALLBACK (selection_changed_cb), NULL); - gtk_box_pack_start (GTK_BOX (hbox), iconview, TRUE, TRUE, 0); + g_signal_connect(G_OBJECT(iconview), "selection-changed", G_CALLBACK(selection_changed_cb), NULL); + gtk_box_pack_start(GTK_BOX(hbox), iconview, TRUE, TRUE, 0); // Create tabs container - notebook = gtk_notebook_new (); - gtk_notebook_set_show_tabs (GTK_NOTEBOOK (notebook), FALSE); - gtk_box_pack_end (GTK_BOX (hbox), notebook, TRUE, TRUE, 0); + notebook = gtk_notebook_new(); + gtk_notebook_set_show_tabs(GTK_NOTEBOOK(notebook), FALSE); + gtk_box_pack_end(GTK_BOX(hbox), notebook, TRUE, TRUE, 0); GtkWidget *box = gtk_dialog_get_content_area(dialog); - gtk_box_pack_start (GTK_BOX (box), hbox, TRUE, TRUE, 0); - gtk_widget_show_all (box); - gtk_container_set_border_width (GTK_CONTAINER (notebook), 10); - gtk_widget_show (notebook); + gtk_box_pack_start(GTK_BOX(box), hbox, TRUE, TRUE, 0); + gtk_widget_show_all(box); + gtk_container_set_border_width(GTK_CONTAINER(notebook), 10); + gtk_widget_show(notebook); // General settings tab - tab = create_general_settings (); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), tab, gtk_label_new (_ ("General"))); - gtk_notebook_page_num (GTK_NOTEBOOK (notebook), tab); + GtkWidget *tab = create_general_settings(); + gtk_notebook_append_page(GTK_NOTEBOOK(notebook), tab, gtk_label_new(_("General"))); + gtk_notebook_page_num(GTK_NOTEBOOK(notebook), tab); // Audio tab - tab = create_audio_configuration (); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), tab, gtk_label_new (_ ("Audio"))); - gtk_notebook_page_num (GTK_NOTEBOOK (notebook), tab); + tab = create_audio_configuration(); + + gtk_notebook_append_page(GTK_NOTEBOOK(notebook), tab, gtk_label_new(_("Audio"))); + gtk_notebook_page_num(GTK_NOTEBOOK(notebook), tab); // Hooks tab - tab = create_hooks_settings (); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), tab, gtk_label_new (_ ("Hooks"))); - gtk_notebook_page_num (GTK_NOTEBOOK (notebook), tab); + tab = create_hooks_settings(); + gtk_notebook_append_page(GTK_NOTEBOOK(notebook), tab, gtk_label_new(_("Hooks"))); + gtk_notebook_page_num(GTK_NOTEBOOK(notebook), tab); // Shortcuts tab tab = create_shortcuts_settings(); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), tab, gtk_label_new (_ ("Shortcuts"))); - gtk_notebook_page_num (GTK_NOTEBOOK (notebook), tab); + gtk_notebook_append_page(GTK_NOTEBOOK(notebook), tab, gtk_label_new(_("Shortcuts"))); + gtk_notebook_page_num(GTK_NOTEBOOK(notebook), tab); - if(addrbook) { + if (addrbook) { // Addressbook tab - tab = create_addressbook_settings (); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), tab, gtk_label_new (_ ("Address Book"))); - gtk_notebook_page_num (GTK_NOTEBOOK (notebook), tab); + tab = create_addressbook_settings(); + gtk_notebook_append_page(GTK_NOTEBOOK(notebook), tab, gtk_label_new(_("Address Book"))); + gtk_notebook_page_num(GTK_NOTEBOOK(notebook), tab); } - + // By default, general settings - gtk_notebook_set_current_page (GTK_NOTEBOOK (notebook), 0); + gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook), 0); // Highlight the corresponding icon - gtk_icon_view_select_path (GTK_ICON_VIEW (iconview), gtk_tree_path_new_first ()); + gtk_icon_view_select_path(GTK_ICON_VIEW(iconview), gtk_tree_path_new_first()); - result = gtk_dialog_run (dialog); + guint result = gtk_dialog_run(dialog); - save_configuration_parameters (); - update_actions (); + save_configuration_parameters(); + update_actions(); dialogOpen = FALSE; - gtk_widget_destroy (GTK_WIDGET (dialog)); + gtk_widget_destroy(GTK_WIDGET(dialog)); return result; } - -#define NB_MAX_ENTRIES 5 - -GtkTreeModel* createModel() -{ - browser_t browser_entries_full[NB_MAX_ENTRIES] = { - {_ ("General"), "preferences-system", 0}, - {_ ("Audio"), "multimedia-volume-control", 1}, - {_ ("Hooks"), "gnome-globe", 2}, - {_ ("Shortcuts"), "preferences-desktop-keyboard", 3}, - {_ ("Address Book"), "address-book-new", 4}, - }; - - GdkPixbuf *pixbuf; - GtkTreeIter iter; - GtkListStore *store; - GError *error = NULL; - gint i, nb_entries; - - nb_entries = addrbook ? 5 : 4; - - store = gtk_list_store_new (3, GDK_TYPE_PIXBUF, G_TYPE_STRING, G_TYPE_INT); - GtkIconTheme* theme = gtk_icon_theme_get_default(); - - - for (i = 0; i < nb_entries; i++) { - - gtk_list_store_append (store, &iter); - - pixbuf = gtk_icon_theme_load_icon (theme, browser_entries_full[i].icon_name, 48, 0, &error); - - gtk_list_store_set (store, &iter, - PIXBUF_COL, pixbuf, - TEXT_COL, browser_entries_full[i].icon_descr, - PAGE_NUMBER, browser_entries_full[i].page_number, - -1); - - if (pixbuf != NULL) { - gdk_pixbuf_unref (pixbuf); - } else { - DEBUG ("Couldn't load icon: %s", error->message); - g_clear_error (&error); - } - } - - return GTK_TREE_MODEL (store); -} diff --git a/gnome/src/config/shortcuts-config.c b/gnome/src/config/shortcuts-config.c index 71d475b8ddf24955a043e53787a5d29d2b907065..caa354a22c2030d920c88ed846d61bc9a321ff08 100644 --- a/gnome/src/config/shortcuts-config.c +++ b/gnome/src/config/shortcuts-config.c @@ -28,132 +28,118 @@ * as that of the covered work. */ +#include <gdk/gdk.h> #include "shortcuts-config.h" #include "shortcuts.h" +#include "unused.h" +#include "logger.h" -#include <gdk/gdkx.h> static void -accel_cleared (GtkCellRendererAccel *renderer UNUSED, gchar *path, - GtkTreeView *treeview) +accel_cleared(GtkCellRendererAccel *renderer UNUSED, gchar *path, + GtkTreeView *treeview) { - DEBUG ("Accel cleared"); + // Update treeview + GtkTreeModel *model = gtk_tree_view_get_model(treeview); - GtkTreeModel *model; GtkTreeIter iter; - // Update treeview - model = gtk_tree_view_get_model (treeview); - - if (gtk_tree_model_get_iter_from_string (model, &iter, path)) - gtk_list_store_set (GTK_LIST_STORE (model), &iter, MASK, 0, VALUE, 0, -1); + if (gtk_tree_model_get_iter_from_string(model, &iter, path)) + gtk_list_store_set(GTK_LIST_STORE(model), &iter, MASK, 0, VALUE, 0, -1); // Update GDK bindings - shortcuts_update_bindings (atoi (path), 0, 0); + shortcuts_update_bindings(atoi(path), 0, 0); } static void -accel_edited (GtkCellRendererAccel *renderer UNUSED, gchar *path, guint accel_key, - GdkModifierType mask, guint hardware_keycode UNUSED, GtkTreeView *treeview) +accel_edited(GtkCellRendererAccel *renderer UNUSED, gchar *path, guint accel_key, + GdkModifierType mask, guint hardware_keycode UNUSED, GtkTreeView *treeview) { - DEBUG ("Accel edited"); - - GtkTreeModel *model; - GtkTreeIter iter; - - Accelerator* list = shortcuts_get_list (); - model = gtk_tree_view_get_model (treeview); - guint code = XKeysymToKeycode (GDK_DISPLAY(), accel_key); - // Disable existing binding if key already used - int i = 0; - gtk_tree_model_get_iter_first (model, &iter); + GtkTreeModel *model = gtk_tree_view_get_model(treeview); + GtkTreeIter iter; + gtk_tree_model_get_iter_first(model, &iter); - while (list[i].action != NULL) { + Accelerator* list = shortcuts_get_list(); + const guint code = XKeysymToKeycode(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()), accel_key); + for (guint i = 0; list[i].action != NULL; ++i) { if (list[i].key == code && list[i].mask == mask) { - gtk_list_store_set (GTK_LIST_STORE (model), &iter, MASK, 0, VALUE, 0, - -1); - WARN ("This key was already affected"); + gtk_list_store_set(GTK_LIST_STORE(model), &iter, MASK, 0, VALUE, 0, + -1); + WARN("This key was already affected"); } - gtk_tree_model_iter_next (model, &iter); - i++; + gtk_tree_model_iter_next(model, &iter); } // Update treeview - if (gtk_tree_model_get_iter_from_string (model, &iter, path)) - gtk_list_store_set (GTK_LIST_STORE (model), &iter, MASK, (gint) mask, - VALUE, accel_key, -1); + if (gtk_tree_model_get_iter_from_string(model, &iter, path)) + gtk_list_store_set(GTK_LIST_STORE(model), &iter, MASK, (gint) mask, + VALUE, accel_key, -1); // Update GDK bindings - shortcuts_update_bindings (atoi (path), code, mask); + shortcuts_update_bindings(atoi(path), code, mask); } /* - * Create a tree view with two columns. The first is an action and the + * Create a tree view with two columns. The first is an action and the * second is a keyboard accelerator. */ static void -setup_tree_view (GtkWidget *treeview) +setup_tree_view(GtkWidget *treeview) { - GtkCellRenderer *renderer; - GtkTreeViewColumn *column; - - renderer = gtk_cell_renderer_text_new (); - column = gtk_tree_view_column_new_with_attributes ("Action", renderer, - "text", ACTION, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column); - - renderer = gtk_cell_renderer_accel_new (); - g_object_set (renderer, "accel-mode", GTK_CELL_RENDERER_ACCEL_MODE_GTK, - "editable", TRUE, NULL); - column = gtk_tree_view_column_new_with_attributes ("Shortcut", renderer, + GtkCellRenderer *renderer = gtk_cell_renderer_text_new(); + GtkTreeViewColumn *column = gtk_tree_view_column_new_with_attributes("Action", renderer, + "text", ACTION, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(treeview), column); + + renderer = gtk_cell_renderer_accel_new(); + g_object_set(renderer, "accel-mode", GTK_CELL_RENDERER_ACCEL_MODE_GTK, + "editable", TRUE, NULL); + column = gtk_tree_view_column_new_with_attributes("Shortcut", renderer, "accel-mods", MASK, "accel-key", VALUE, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column); - g_signal_connect (G_OBJECT (renderer), "accel_edited", G_CALLBACK (accel_edited), (gpointer) treeview); - g_signal_connect (G_OBJECT (renderer), "accel_cleared", G_CALLBACK (accel_cleared), (gpointer) treeview); + gtk_tree_view_append_column(GTK_TREE_VIEW(treeview), column); + g_signal_connect(renderer, "accel_edited", G_CALLBACK(accel_edited), + (gpointer) treeview); + g_signal_connect(renderer, "accel_cleared", G_CALLBACK(accel_cleared), + (gpointer) treeview); } GtkWidget* -create_shortcuts_settings () +create_shortcuts_settings() { - GtkWidget *vbox, *result_frame, *treeview, *label; - - GtkTreeIter iter; - guint i = 0; - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 10); + GtkWidget *vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); + gtk_container_set_border_width(GTK_CONTAINER(vbox), 10); - gnome_main_section_new (_ ("General"), &result_frame); + GtkWidget * result_frame = gnome_main_section_new(_("General")); - label = gtk_label_new ( - _ ("Be careful: these shortcuts might override system-wide shortcuts.")); - treeview = gtk_tree_view_new (); - setup_tree_view (treeview); + GtkWidget *label = gtk_label_new(_("Be careful: these shortcuts might " + "override system-wide shortcuts.")); + GtkWidget *treeview = gtk_tree_view_new(); + setup_tree_view(treeview); - GtkListStore *store = gtk_list_store_new (COLUMNS, G_TYPE_STRING, G_TYPE_INT, + GtkListStore *store = gtk_list_store_new(COLUMNS, G_TYPE_STRING, G_TYPE_INT, G_TYPE_UINT); - Accelerator* list = shortcuts_get_list (); + Accelerator* list = shortcuts_get_list(); - while (list[i].action != NULL) { - gtk_list_store_append (store, &iter); - gtk_list_store_set (store, &iter, ACTION, _ (list[i].action), MASK, - (gint) list[i].mask, VALUE, XKeycodeToKeysym (GDK_DISPLAY(), - list[i].key, 0), -1); - i++; + for (guint i = 0; list[i].action != NULL; ++i) { + GtkTreeIter iter; + gtk_list_store_append(store, &iter); + gtk_list_store_set(store, &iter, ACTION, _(list[i].action), MASK, + (gint) list[i].mask, VALUE, + XKeycodeToKeysym(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()), list[i].key, 0), -1); } - gtk_tree_view_set_model (GTK_TREE_VIEW (treeview), GTK_TREE_MODEL (store)); - g_object_unref (store); + gtk_tree_view_set_model(GTK_TREE_VIEW(treeview), GTK_TREE_MODEL(store)); + g_object_unref(store); - gtk_container_add (GTK_CONTAINER (result_frame), treeview); - gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 0); - gtk_box_pack_start (GTK_BOX (vbox), result_frame, FALSE, FALSE, 0); + gtk_container_add(GTK_CONTAINER(result_frame), treeview); + gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(vbox), result_frame, FALSE, FALSE, 0); - gtk_widget_show_all (vbox); + gtk_widget_show_all(vbox); return vbox; } diff --git a/gnome/src/config/tlsadvanceddialog.c b/gnome/src/config/tlsadvanceddialog.c index 8e929819a7506b5fe77c8f705c76beb38a7dc035..3d6c11860099d0647afb3b88f35b97dc07e37d99 100644 --- a/gnome/src/config/tlsadvanceddialog.c +++ b/gnome/src/config/tlsadvanceddialog.c @@ -36,40 +36,40 @@ #include <gtk/gtk.h> #include <math.h> -void show_advanced_tls_options (GHashTable * properties) +void show_advanced_tls_options(GHashTable * properties) { - GtkDialog *tlsDialog = GTK_DIALOG (gtk_dialog_new_with_buttons (_ ("Advanced options for TLS"), - GTK_WINDOW (get_main_window()), - GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, - GTK_STOCK_CANCEL, - GTK_RESPONSE_CANCEL, - GTK_STOCK_SAVE, - GTK_RESPONSE_ACCEPT, - NULL)); - - gtk_window_set_resizable(GTK_WINDOW (tlsDialog), FALSE); - gtk_container_set_border_width (GTK_CONTAINER (tlsDialog), 0); - - GtkWidget *ret = gtk_vbox_new (FALSE, 10); - gtk_container_set_border_width (GTK_CONTAINER (ret), 10); - gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area(tlsDialog)), ret, FALSE, FALSE, 0); + GtkDialog *tlsDialog = GTK_DIALOG(gtk_dialog_new_with_buttons(_("Advanced options for TLS"), + GTK_WINDOW(get_main_window()), + GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_STOCK_CANCEL, + GTK_RESPONSE_CANCEL, + GTK_STOCK_SAVE, + GTK_RESPONSE_ACCEPT, + NULL)); + + gtk_window_set_resizable(GTK_WINDOW(tlsDialog), FALSE); + gtk_container_set_border_width(GTK_CONTAINER(tlsDialog), 0); + + GtkWidget *ret = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); + gtk_container_set_border_width(GTK_CONTAINER(ret), 10); + gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(tlsDialog)), ret, FALSE, FALSE, 0); GtkWidget *frame, *table; - gnome_main_section_new_with_table (_ ("TLS transport"), &frame, &table, 3, 13); - gtk_container_set_border_width (GTK_CONTAINER (table), 10); - gtk_box_pack_start (GTK_BOX (ret), frame, FALSE, FALSE, 0); + gnome_main_section_new_with_table(_("TLS transport"), &frame, &table, 3, 13); + gtk_container_set_border_width(GTK_CONTAINER(table), 10); + gtk_box_pack_start(GTK_BOX(ret), frame, FALSE, FALSE, 0); - gchar * description = g_markup_printf_escaped (_ ("TLS transport can be used along with UDP for those calls that would\n"\ + gchar * description = g_markup_printf_escaped(_("TLS transport can be used along with UDP for those calls that would\n"\ "require secure sip transactions (aka SIPS). You can configure a different\n"\ "TLS transport for each account. However, each of them will run on a dedicated\n"\ "port, different one from each other\n")); - GtkWidget * label = gtk_label_new (NULL); - gtk_widget_set_size_request (label, 600, 70); - gtk_label_set_line_wrap (GTK_LABEL (label), TRUE); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); - gtk_label_set_markup (GTK_LABEL (label), description); - gtk_table_attach (GTK_TABLE (table), label, 0, 3, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + GtkWidget * label = gtk_label_new(NULL); + gtk_widget_set_size_request(label, 600, 70); + gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + gtk_label_set_markup(GTK_LABEL(label), description); + gtk_table_attach(GTK_TABLE(table), label, 0, 3, 0, 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); gchar * account_id = NULL; gchar * tls_listener_port = NULL; @@ -88,235 +88,234 @@ void show_advanced_tls_options (GHashTable * properties) if (properties != NULL) { - account_id = g_hash_table_lookup (properties, ACCOUNT_ID); - tls_listener_port = g_hash_table_lookup (properties, TLS_LISTENER_PORT); - tls_ca_list_file = g_hash_table_lookup (properties, TLS_CA_LIST_FILE); - tls_certificate_file = g_hash_table_lookup (properties, TLS_CERTIFICATE_FILE); - tls_private_key_file = g_hash_table_lookup (properties, TLS_PRIVATE_KEY_FILE); - tls_password = g_hash_table_lookup (properties, TLS_PASSWORD); - tls_method = g_hash_table_lookup (properties, TLS_METHOD); - tls_ciphers = g_hash_table_lookup (properties, TLS_CIPHERS); - tls_server_name = g_hash_table_lookup (properties, TLS_SERVER_NAME); - verify_server = g_hash_table_lookup (properties, TLS_VERIFY_SERVER); - verify_client = g_hash_table_lookup (properties, TLS_VERIFY_CLIENT); - require_client_certificate = g_hash_table_lookup (properties, TLS_REQUIRE_CLIENT_CERTIFICATE); - negotiation_timeout_sec = g_hash_table_lookup (properties, TLS_NEGOTIATION_TIMEOUT_SEC); - negotiation_timeout_msec = g_hash_table_lookup (properties, TLS_NEGOTIATION_TIMEOUT_MSEC); + account_id = g_hash_table_lookup(properties, ACCOUNT_ID); + tls_listener_port = g_hash_table_lookup(properties, TLS_LISTENER_PORT); + tls_ca_list_file = g_hash_table_lookup(properties, TLS_CA_LIST_FILE); + tls_certificate_file = g_hash_table_lookup(properties, TLS_CERTIFICATE_FILE); + tls_private_key_file = g_hash_table_lookup(properties, TLS_PRIVATE_KEY_FILE); + tls_password = g_hash_table_lookup(properties, TLS_PASSWORD); + tls_method = g_hash_table_lookup(properties, TLS_METHOD); + tls_ciphers = g_hash_table_lookup(properties, TLS_CIPHERS); + tls_server_name = g_hash_table_lookup(properties, TLS_SERVER_NAME); + verify_server = g_hash_table_lookup(properties, TLS_VERIFY_SERVER); + verify_client = g_hash_table_lookup(properties, TLS_VERIFY_CLIENT); + require_client_certificate = g_hash_table_lookup(properties, TLS_REQUIRE_CLIENT_CERTIFICATE); + negotiation_timeout_sec = g_hash_table_lookup(properties, TLS_NEGOTIATION_TIMEOUT_SEC); + negotiation_timeout_msec = g_hash_table_lookup(properties, TLS_NEGOTIATION_TIMEOUT_MSEC); } - label = gtk_label_new (_ ("Global TLS listener (all accounts)")); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - GtkWidget * hbox = gtk_hbox_new (FALSE, 10); - gtk_table_attach (GTK_TABLE (table), hbox, 1, 2, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - GtkWidget *tlsListenerPort = gtk_spin_button_new_with_range (0, 65535, 1); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), tlsListenerPort); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (tlsListenerPort), g_ascii_strtod (tls_listener_port, NULL)); - gtk_box_pack_start(GTK_BOX (hbox), tlsListenerPort, TRUE, TRUE, 0); + label = gtk_label_new(_("Global TLS listener (all accounts)")); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + GtkWidget * hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10); + gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + GtkWidget *tlsListenerPort = gtk_spin_button_new_with_range(0, 65535, 1); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), tlsListenerPort); + gtk_spin_button_set_value(GTK_SPIN_BUTTON(tlsListenerPort), g_ascii_strtod(tls_listener_port, NULL)); + gtk_box_pack_start(GTK_BOX(hbox), tlsListenerPort, TRUE, TRUE, 0); - if (g_strcmp0 (account_id, IP2IP_PROFILE) != 0) { - gtk_widget_set_sensitive (tlsListenerPort, FALSE); + if (g_strcmp0(account_id, IP2IP_PROFILE) != 0) { + gtk_widget_set_sensitive(tlsListenerPort, FALSE); } - label = gtk_label_new (_ ("Certificate of Authority list")); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - GtkWidget * caListFileChooser = gtk_file_chooser_button_new (_ ("Choose a CA list file (optional)"), GTK_FILE_CHOOSER_ACTION_OPEN); - gtk_table_attach (GTK_TABLE (table), caListFileChooser, 1, 2, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + label = gtk_label_new(_("Certificate of Authority list")); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + GtkWidget * caListFileChooser = gtk_file_chooser_button_new(_("Choose a CA list file (optional)"), GTK_FILE_CHOOSER_ACTION_OPEN); + gtk_table_attach(GTK_TABLE(table), caListFileChooser, 1, 2, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); if (!tls_ca_list_file || !*tls_ca_list_file) { - gtk_file_chooser_unselect_all (GTK_FILE_CHOOSER (caListFileChooser)); + gtk_file_chooser_unselect_all(GTK_FILE_CHOOSER(caListFileChooser)); } else { - GFile *file = g_file_new_for_path (tls_ca_list_file); - gtk_file_chooser_set_file (GTK_FILE_CHOOSER (caListFileChooser), file, NULL); - g_object_unref (file); + GFile *file = g_file_new_for_path(tls_ca_list_file); + gtk_file_chooser_set_file(GTK_FILE_CHOOSER(caListFileChooser), file, NULL); + g_object_unref(file); } - label = gtk_label_new (_ ("Public endpoint certificate file")); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 4, 5, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - GtkWidget * certificateFileChooser = gtk_file_chooser_button_new (_ ("Choose a public endpoint certificate (optional)"), GTK_FILE_CHOOSER_ACTION_OPEN); - gtk_table_attach (GTK_TABLE (table), certificateFileChooser, 1, 2, 4, 5, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + label = gtk_label_new(_("Public endpoint certificate file")); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 4, 5, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + GtkWidget * certificateFileChooser = gtk_file_chooser_button_new(_("Choose a public endpoint certificate (optional)"), GTK_FILE_CHOOSER_ACTION_OPEN); + gtk_table_attach(GTK_TABLE(table), certificateFileChooser, 1, 2, 4, 5, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); if (!tls_certificate_file) { - gtk_file_chooser_unselect_all (GTK_FILE_CHOOSER (caListFileChooser)); + gtk_file_chooser_unselect_all(GTK_FILE_CHOOSER(caListFileChooser)); } else { if (!*tls_certificate_file) { - gtk_file_chooser_unselect_all (GTK_FILE_CHOOSER (certificateFileChooser)); + gtk_file_chooser_unselect_all(GTK_FILE_CHOOSER(certificateFileChooser)); } else { - GFile * file = g_file_new_for_path (tls_certificate_file); - gtk_file_chooser_set_file (GTK_FILE_CHOOSER (certificateFileChooser), file, NULL); - g_object_unref (file); + GFile * file = g_file_new_for_path(tls_certificate_file); + gtk_file_chooser_set_file(GTK_FILE_CHOOSER(certificateFileChooser), file, NULL); + g_object_unref(file); } } - label = gtk_label_new ( ("Private key file")); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - GtkWidget *privateKeyFileChooser = gtk_file_chooser_button_new (_ ("Choose a private key file (optional)"), GTK_FILE_CHOOSER_ACTION_OPEN); - gtk_table_attach (GTK_TABLE (table), privateKeyFileChooser, 1, 2, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + label = gtk_label_new(("Private key file")); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + GtkWidget *privateKeyFileChooser = gtk_file_chooser_button_new(_("Choose a private key file (optional)"), GTK_FILE_CHOOSER_ACTION_OPEN); + gtk_table_attach(GTK_TABLE(table), privateKeyFileChooser, 1, 2, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); if (!tls_private_key_file) { - gtk_file_chooser_unselect_all (GTK_FILE_CHOOSER (caListFileChooser)); + gtk_file_chooser_unselect_all(GTK_FILE_CHOOSER(caListFileChooser)); } else { if (!*tls_private_key_file) { - gtk_file_chooser_unselect_all (GTK_FILE_CHOOSER (privateKeyFileChooser)); + gtk_file_chooser_unselect_all(GTK_FILE_CHOOSER(privateKeyFileChooser)); } else { - GFile * file = g_file_new_for_path (tls_private_key_file); - gtk_file_chooser_set_file (GTK_FILE_CHOOSER (privateKeyFileChooser), file, NULL); - g_object_unref (file); + GFile * file = g_file_new_for_path(tls_private_key_file); + gtk_file_chooser_set_file(GTK_FILE_CHOOSER(privateKeyFileChooser), file, NULL); + g_object_unref(file); } } - label = gtk_label_new_with_mnemonic (_ ("Password for the private key")); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 6, 7, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + label = gtk_label_new_with_mnemonic(_("Password for the private key")); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 6, 7, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); GtkWidget * privateKeyPasswordEntry; privateKeyPasswordEntry = gtk_entry_new(); - gtk_entry_set_icon_from_stock (GTK_ENTRY (privateKeyPasswordEntry), GTK_ENTRY_ICON_PRIMARY, GTK_STOCK_DIALOG_AUTHENTICATION); - gtk_entry_set_visibility (GTK_ENTRY (privateKeyPasswordEntry), FALSE); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), privateKeyPasswordEntry); - gtk_entry_set_text (GTK_ENTRY (privateKeyPasswordEntry), tls_password); - gtk_table_attach (GTK_TABLE (table), privateKeyPasswordEntry, 1, 2, 6, 7, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_entry_set_icon_from_stock(GTK_ENTRY(privateKeyPasswordEntry), GTK_ENTRY_ICON_PRIMARY, GTK_STOCK_DIALOG_AUTHENTICATION); + gtk_entry_set_visibility(GTK_ENTRY(privateKeyPasswordEntry), FALSE); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), privateKeyPasswordEntry); + gtk_entry_set_text(GTK_ENTRY(privateKeyPasswordEntry), tls_password); + gtk_table_attach(GTK_TABLE(table), privateKeyPasswordEntry, 1, 2, 6, 7, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); /* TLS protocol methods */ GtkTreeIter iter; - GtkListStore * tlsProtocolMethodListStore = gtk_list_store_new (1, G_TYPE_STRING); - label = gtk_label_new_with_mnemonic (_ ("TLS protocol method")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 7, 8, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + GtkListStore * tlsProtocolMethodListStore = gtk_list_store_new(1, G_TYPE_STRING); + label = gtk_label_new_with_mnemonic(_("TLS protocol method")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 7, 8, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); gchar** supported_tls_method = dbus_get_supported_tls_method(); - GtkTreeIter supported_tls_method_iter = iter; + GtkTreeIter supported_tls_method_iter; for (char **supported_tls_method_ptr = supported_tls_method; supported_tls_method_ptr && *supported_tls_method_ptr; supported_tls_method_ptr++) { - gtk_list_store_append (tlsProtocolMethodListStore, &iter); - gtk_list_store_set (tlsProtocolMethodListStore, &iter, 0, *supported_tls_method_ptr, -1); + gtk_list_store_append(tlsProtocolMethodListStore, &iter); + gtk_list_store_set(tlsProtocolMethodListStore, &iter, 0, *supported_tls_method_ptr, -1); - if (g_strcmp0 (*supported_tls_method_ptr, tls_method) == 0) + if (g_strcmp0(*supported_tls_method_ptr, tls_method) == 0) supported_tls_method_iter = iter; } - GtkWidget *tlsProtocolMethodCombo = gtk_combo_box_new_with_model (GTK_TREE_MODEL (tlsProtocolMethodListStore)); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), tlsProtocolMethodCombo); - gtk_table_attach (GTK_TABLE (table), tlsProtocolMethodCombo, 1, 2, 7, 8, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - g_object_unref (G_OBJECT (tlsProtocolMethodListStore)); + GtkWidget *tlsProtocolMethodCombo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(tlsProtocolMethodListStore)); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), tlsProtocolMethodCombo); + gtk_table_attach(GTK_TABLE(table), tlsProtocolMethodCombo, 1, 2, 7, 8, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + g_object_unref(G_OBJECT(tlsProtocolMethodListStore)); GtkCellRenderer *tlsProtocolMethodCellRenderer; tlsProtocolMethodCellRenderer = gtk_cell_renderer_text_new(); - gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (tlsProtocolMethodCombo), tlsProtocolMethodCellRenderer, TRUE); - gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (tlsProtocolMethodCombo), tlsProtocolMethodCellRenderer, "text", 0, NULL); - gtk_combo_box_set_active_iter (GTK_COMBO_BOX (tlsProtocolMethodCombo), &supported_tls_method_iter); + gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(tlsProtocolMethodCombo), tlsProtocolMethodCellRenderer, TRUE); + gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(tlsProtocolMethodCombo), tlsProtocolMethodCellRenderer, "text", 0, NULL); + gtk_combo_box_set_active_iter(GTK_COMBO_BOX(tlsProtocolMethodCombo), &supported_tls_method_iter); /* Cipher list */ GtkWidget * cipherListEntry; - label = gtk_label_new_with_mnemonic (_ ("TLS cipher list")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 8, 9, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + label = gtk_label_new_with_mnemonic(_("TLS cipher list")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 8, 9, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); cipherListEntry = gtk_entry_new(); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), cipherListEntry); - gtk_entry_set_text (GTK_ENTRY (cipherListEntry), tls_ciphers); - gtk_table_attach (GTK_TABLE (table), cipherListEntry, 1, 2, 8, 9, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), cipherListEntry); + gtk_entry_set_text(GTK_ENTRY(cipherListEntry), tls_ciphers); + gtk_table_attach(GTK_TABLE(table), cipherListEntry, 1, 2, 8, 9, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); GtkWidget * serverNameInstance; - label = gtk_label_new_with_mnemonic (_ ("Server name instance for outgoing TLS connection")); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 9, 10, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + label = gtk_label_new_with_mnemonic(_("Server name instance for outgoing TLS connection")); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 9, 10, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); serverNameInstance = gtk_entry_new(); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), serverNameInstance); - gtk_entry_set_text (GTK_ENTRY (serverNameInstance), tls_server_name); - gtk_table_attach (GTK_TABLE (table), serverNameInstance, 1, 2, 9, 10, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), serverNameInstance); + gtk_entry_set_text(GTK_ENTRY(serverNameInstance), tls_server_name); + gtk_table_attach(GTK_TABLE(table), serverNameInstance, 1, 2, 9, 10, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - label = gtk_label_new (_ ("Negotiation timeout (sec:msec)")); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 10, 11, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + label = gtk_label_new(_("Negotiation timeout (sec:msec)")); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 10, 11, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); GtkWidget * tlsTimeOutSec; - hbox = gtk_hbox_new (FALSE, 10); - gtk_table_attach (GTK_TABLE (table), hbox, 1, 2, 10, 11, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - tlsTimeOutSec = gtk_spin_button_new_with_range (0, pow (2,sizeof (long)), 1); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), tlsTimeOutSec); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (tlsTimeOutSec), g_ascii_strtod (negotiation_timeout_sec, NULL)); - gtk_box_pack_start(GTK_BOX (hbox), tlsTimeOutSec, TRUE, TRUE, 0); + hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10); + gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 10, 11, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + tlsTimeOutSec = gtk_spin_button_new_with_range(0, pow(2,sizeof(long)), 1); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), tlsTimeOutSec); + gtk_spin_button_set_value(GTK_SPIN_BUTTON(tlsTimeOutSec), g_ascii_strtod(negotiation_timeout_sec, NULL)); + gtk_box_pack_start(GTK_BOX(hbox), tlsTimeOutSec, TRUE, TRUE, 0); GtkWidget * tlsTimeOutMSec; - tlsTimeOutMSec = gtk_spin_button_new_with_range (0, pow (2,sizeof (long)), 1); - gtk_label_set_mnemonic_widget (GTK_LABEL (label), tlsTimeOutMSec); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (tlsTimeOutMSec), g_ascii_strtod (negotiation_timeout_msec, NULL)); - gtk_box_pack_start(GTK_BOX (hbox), tlsTimeOutMSec, TRUE, TRUE, 0); + tlsTimeOutMSec = gtk_spin_button_new_with_range(0, pow(2,sizeof(long)), 1); + gtk_label_set_mnemonic_widget(GTK_LABEL(label), tlsTimeOutMSec); + gtk_spin_button_set_value(GTK_SPIN_BUTTON(tlsTimeOutMSec), g_ascii_strtod(negotiation_timeout_msec, NULL)); + gtk_box_pack_start(GTK_BOX(hbox), tlsTimeOutMSec, TRUE, TRUE, 0); GtkWidget * verifyCertificateServer; - verifyCertificateServer = gtk_check_button_new_with_mnemonic (_ ("Verify incoming certificates, as a server")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (verifyCertificateServer), - g_strcasecmp (verify_server,"true") == 0 ? TRUE: FALSE); - gtk_table_attach (GTK_TABLE (table), verifyCertificateServer, 0, 1, 11, 12, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + verifyCertificateServer = gtk_check_button_new_with_mnemonic(_("Verify incoming certificates, as a server")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(verifyCertificateServer), + g_strcasecmp(verify_server,"true") == 0 ? TRUE: FALSE); + gtk_table_attach(GTK_TABLE(table), verifyCertificateServer, 0, 1, 11, 12, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); GtkWidget * verifyCertificateClient; - verifyCertificateClient = gtk_check_button_new_with_mnemonic (_ ("Verify certificates from answer, as a client")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (verifyCertificateClient), - g_strcasecmp (verify_client,"true") == 0 ? TRUE: FALSE); - gtk_table_attach (GTK_TABLE (table), verifyCertificateClient, 0, 1, 12, 13, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + verifyCertificateClient = gtk_check_button_new_with_mnemonic(_("Verify certificates from answer, as a client")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(verifyCertificateClient), + g_strcasecmp(verify_client,"true") == 0 ? TRUE: FALSE); + gtk_table_attach(GTK_TABLE(table), verifyCertificateClient, 0, 1, 12, 13, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); GtkWidget * requireCertificate; - requireCertificate = gtk_check_button_new_with_mnemonic (_ ("Require certificate for incoming tls connections")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (requireCertificate), - g_strcasecmp (require_client_certificate,"true") == 0 ? TRUE: FALSE); - gtk_table_attach (GTK_TABLE (table), requireCertificate, 0, 1, 13, 14, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + requireCertificate = gtk_check_button_new_with_mnemonic(_("Require certificate for incoming tls connections")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(requireCertificate), + g_strcasecmp(require_client_certificate,"true") == 0 ? TRUE: FALSE); + gtk_table_attach(GTK_TABLE(table), requireCertificate, 0, 1, 13, 14, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_show_all (ret); + gtk_widget_show_all(ret); - if (gtk_dialog_run (GTK_DIALOG (tlsDialog)) == GTK_RESPONSE_ACCEPT) { + if (gtk_dialog_run(GTK_DIALOG(tlsDialog)) == GTK_RESPONSE_ACCEPT) { + g_hash_table_replace(properties, + g_strdup(TLS_LISTENER_PORT), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(tlsListenerPort)))); + g_hash_table_replace(properties, + g_strdup(TLS_CA_LIST_FILE), g_strdup(gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(caListFileChooser)))); - g_hash_table_replace (properties, - g_strdup (TLS_LISTENER_PORT), - g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (tlsListenerPort)))); - g_hash_table_replace (properties, - g_strdup (TLS_CA_LIST_FILE), g_strdup (gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (caListFileChooser)))); + g_hash_table_replace(properties, + g_strdup(TLS_CERTIFICATE_FILE), g_strdup(gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(certificateFileChooser)))); - g_hash_table_replace (properties, - g_strdup (TLS_CERTIFICATE_FILE), g_strdup (gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (certificateFileChooser)))); + g_hash_table_replace(properties, + g_strdup(TLS_PRIVATE_KEY_FILE), g_strdup(gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(privateKeyFileChooser)))); - g_hash_table_replace (properties, - g_strdup (TLS_PRIVATE_KEY_FILE), g_strdup (gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (privateKeyFileChooser)))); + g_hash_table_replace(properties, + g_strdup(TLS_PASSWORD), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(privateKeyPasswordEntry)))); - g_hash_table_replace (properties, - g_strdup (TLS_PASSWORD), - g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (privateKeyPasswordEntry)))); + g_hash_table_replace(properties, + g_strdup(TLS_METHOD), + g_strdup((gchar *) gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(tlsProtocolMethodCombo)))); - g_hash_table_replace (properties, - g_strdup (TLS_METHOD), - g_strdup ( (gchar *) gtk_combo_box_get_active_text (GTK_COMBO_BOX (tlsProtocolMethodCombo)))); + g_hash_table_replace(properties, + g_strdup(TLS_CIPHERS), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(cipherListEntry)))); - g_hash_table_replace (properties, - g_strdup (TLS_CIPHERS), - g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (cipherListEntry)))); + g_hash_table_replace(properties, + g_strdup(TLS_SERVER_NAME), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(serverNameInstance)))); - g_hash_table_replace (properties, - g_strdup (TLS_SERVER_NAME), - g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (serverNameInstance)))); + g_hash_table_replace(properties, + g_strdup(TLS_VERIFY_SERVER), + g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(verifyCertificateServer)) ? "true": "false")); - g_hash_table_replace (properties, - g_strdup (TLS_VERIFY_SERVER), - g_strdup (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (verifyCertificateServer)) ? "true": "false")); + g_hash_table_replace(properties, + g_strdup(TLS_VERIFY_CLIENT), + g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(verifyCertificateClient)) ? "true": "false")); - g_hash_table_replace (properties, - g_strdup (TLS_VERIFY_CLIENT), - g_strdup (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (verifyCertificateClient)) ? "true": "false")); + g_hash_table_replace(properties, + g_strdup(TLS_REQUIRE_CLIENT_CERTIFICATE), + g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(requireCertificate)) ? "true": "false")); - g_hash_table_replace (properties, - g_strdup (TLS_REQUIRE_CLIENT_CERTIFICATE), - g_strdup (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (requireCertificate)) ? "true": "false")); + g_hash_table_replace(properties, + g_strdup(TLS_NEGOTIATION_TIMEOUT_SEC), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(tlsTimeOutSec)))); - g_hash_table_replace (properties, - g_strdup (TLS_NEGOTIATION_TIMEOUT_SEC), - g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (tlsTimeOutSec)))); - - g_hash_table_replace (properties, - g_strdup (TLS_NEGOTIATION_TIMEOUT_MSEC), - g_strdup ( (gchar *) gtk_entry_get_text (GTK_ENTRY (tlsTimeOutMSec)))); + g_hash_table_replace(properties, + g_strdup(TLS_NEGOTIATION_TIMEOUT_MSEC), + g_strdup((gchar *) gtk_entry_get_text(GTK_ENTRY(tlsTimeOutMSec)))); } - gtk_widget_destroy (GTK_WIDGET (tlsDialog)); + gtk_widget_destroy(GTK_WIDGET(tlsDialog)); } diff --git a/gnome/src/config/utils.c b/gnome/src/config/utils.c index 23f438b11b9d96b9d375f6a97d27dac67bb3b3ae..4329b035bbfa13f5fa7bc414b0492f970e69501a 100644 --- a/gnome/src/config/utils.c +++ b/gnome/src/config/utils.c @@ -29,108 +29,65 @@ */ #include "utils.h" -#include <sflphone_const.h> +#include "sflphone_const.h" -void gnome_main_section_new_with_table (gchar *title, GtkWidget **frame, GtkWidget **table, gint nb_col, gint nb_row) +void gnome_main_section_new_with_table(gchar *title, GtkWidget **frame, GtkWidget **table, gint nb_col, gint nb_row) { - GtkWidget *_frame, *_table, *label, *align; - PangoAttrList *attrs = NULL; - PangoAttribute *attr = NULL; - - attrs = pango_attr_list_new (); - attr = pango_attr_weight_new (PANGO_WEIGHT_BOLD); + PangoAttrList *attrs = pango_attr_list_new(); + PangoAttribute *attr = pango_attr_weight_new(PANGO_WEIGHT_BOLD); attr->start_index = 0; attr->end_index = -1; - pango_attr_list_insert (attrs, attr); - - _frame = gtk_frame_new (title); - gtk_frame_set_shadow_type (GTK_FRAME (_frame), GTK_SHADOW_NONE); - gtk_container_set_border_width (GTK_CONTAINER (_frame), 2); + pango_attr_list_insert(attrs, attr); - label = gtk_frame_get_label_widget (GTK_FRAME (_frame)); - gtk_label_set_attributes (GTK_LABEL (label), attrs); - pango_attr_list_unref (attrs); + *frame = gtk_frame_new(title); + gtk_frame_set_shadow_type(GTK_FRAME(*frame), GTK_SHADOW_NONE); + gtk_container_set_border_width(GTK_CONTAINER(*frame), 2); - align = gtk_alignment_new (0.08, 0.2, 0.1, 0.1); - gtk_container_add (GTK_CONTAINER (_frame), align); + GtkWidget *label = gtk_frame_get_label_widget(GTK_FRAME(*frame)); + gtk_label_set_attributes(GTK_LABEL(label), attrs); + pango_attr_list_unref(attrs); - _table = gtk_table_new (nb_col, nb_row, FALSE); - gtk_table_set_row_spacings (GTK_TABLE (_table), 2); - gtk_table_set_col_spacings (GTK_TABLE (_table), 2); - gtk_widget_show (_table); - gtk_container_add (GTK_CONTAINER (align), _table); + GtkWidget *align = gtk_alignment_new(0.08, 0.2, 0.1, 0.1); + gtk_container_add(GTK_CONTAINER(*frame), align); - *table = _table; - *frame = _frame; + *table = gtk_table_new(nb_col, nb_row, FALSE); + gtk_table_set_row_spacings(GTK_TABLE(*table), 2); + gtk_table_set_col_spacings(GTK_TABLE(*table), 2); + gtk_widget_show(*table); + gtk_container_add(GTK_CONTAINER(align), *table); } -void gnome_main_section_new_with_vbox (gchar *title, GtkWidget **frame, GtkWidget **vbox, gint nb_row UNUSED) -{ - GtkWidget *_frame, *_vbox, *label, *align; - PangoAttrList *attrs = NULL; - PangoAttribute *attr = NULL; - - attrs = pango_attr_list_new (); - attr = pango_attr_weight_new (PANGO_WEIGHT_BOLD); - attr->start_index = 0; - attr->end_index = -1; - pango_attr_list_insert (attrs, attr); - - _frame = gtk_frame_new (title); - gtk_frame_set_shadow_type (GTK_FRAME (_frame), GTK_SHADOW_NONE); - gtk_container_set_border_width (GTK_CONTAINER (_frame), 2); - - label = gtk_frame_get_label_widget (GTK_FRAME (_frame)); - gtk_label_set_attributes (GTK_LABEL (label), attrs); - pango_attr_list_unref (attrs); - align = gtk_alignment_new (0.08, 0.2, 0.1, 0.1); - gtk_container_add (GTK_CONTAINER (_frame), align); - - _vbox = gtk_vbox_new (FALSE, 10); - gtk_widget_show (_vbox); - gtk_container_add (GTK_CONTAINER (align), _vbox); - - *vbox = _vbox; - *frame = _frame; -} - -void gnome_main_section_new (gchar *title, GtkWidget **frame) +GtkWidget *gnome_main_section_new(const gchar * const title) { - GtkWidget *_frame, *label; - PangoAttrList *attrs = NULL; - PangoAttribute *attr = NULL; - - attrs = pango_attr_list_new (); - attr = pango_attr_weight_new (PANGO_WEIGHT_BOLD); + PangoAttrList *attrs = pango_attr_list_new(); + PangoAttribute *attr = pango_attr_weight_new(PANGO_WEIGHT_BOLD); attr->start_index = 0; attr->end_index = -1; - pango_attr_list_insert (attrs, attr); + pango_attr_list_insert(attrs, attr); - _frame = gtk_frame_new (title); - gtk_frame_set_shadow_type (GTK_FRAME (_frame), GTK_SHADOW_NONE); - gtk_container_set_border_width (GTK_CONTAINER (_frame), 2); + GtkWidget *frame = gtk_frame_new(title); + gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); + gtk_container_set_border_width(GTK_CONTAINER(frame), 2); - label = gtk_frame_get_label_widget (GTK_FRAME (_frame)); - gtk_label_set_attributes (GTK_LABEL (label), attrs); - pango_attr_list_unref (attrs); + GtkWidget *label = gtk_frame_get_label_widget(GTK_FRAME(frame)); + gtk_label_set_attributes(GTK_LABEL(label), attrs); + pango_attr_list_unref(attrs); - *frame = _frame; + return frame; } -void gnome_info_bar (gchar *message, GtkMessageType type, GtkWidget **info_bar) +GtkWidget *gnome_info_bar(gchar *message, GtkMessageType type) { - GtkWidget *_info_bar, *message_label, *content_area; - - _info_bar = gtk_info_bar_new(); - gtk_widget_set_no_show_all (_info_bar, TRUE); - message_label = gtk_label_new (NULL); - gtk_widget_show (message_label); - content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (_info_bar)); - gtk_container_add (GTK_CONTAINER (content_area), message_label); - gtk_label_set_markup (GTK_LABEL (message_label), message); //message); - gtk_info_bar_set_message_type (GTK_INFO_BAR (_info_bar), type); - gtk_widget_show (_info_bar); - - *info_bar = _info_bar; + GtkWidget *info_bar = gtk_info_bar_new(); + gtk_widget_set_no_show_all(info_bar, TRUE); + GtkWidget *message_label = gtk_label_new(NULL); + gtk_widget_show(message_label); + GtkWidget *content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(info_bar)); + gtk_container_add(GTK_CONTAINER(content_area), message_label); + gtk_label_set_markup(GTK_LABEL(message_label), message); + gtk_info_bar_set_message_type(GTK_INFO_BAR(info_bar), type); + gtk_widget_show(info_bar); + + return info_bar; } diff --git a/gnome/src/config/utils.h b/gnome/src/config/utils.h index 2a932f6bc208c6f5f1837f82b81c32fea4cea1a4..8f084f2f3735fcceeddcae01c2d4fbb2f946447b 100644 --- a/gnome/src/config/utils.h +++ b/gnome/src/config/utils.h @@ -35,10 +35,9 @@ G_BEGIN_DECLS -void gnome_main_section_new (gchar *title, GtkWidget**); +GtkWidget *gnome_main_section_new(const gchar * const title); void gnome_main_section_new_with_table (gchar *title, GtkWidget**, GtkWidget**, gint nb_col, gint nb_row); -void gnome_main_section_new_with_vbox (gchar *title, GtkWidget **frame, GtkWidget **vbox, gint nb_row); -void gnome_info_bar (gchar *message, GtkMessageType type, GtkWidget **info_bar); +GtkWidget *gnome_info_bar (gchar *message, GtkMessageType type); G_END_DECLS diff --git a/gnome/src/config/zrtpadvanceddialog.c b/gnome/src/config/zrtpadvanceddialog.c index 3f9140788f39151efb599208a17cb1d00a3c94c4..e50898a7be8b2b3bd5edd21ddfa1d9a866ef1636 100644 --- a/gnome/src/config/zrtpadvanceddialog.c +++ b/gnome/src/config/zrtpadvanceddialog.c @@ -34,7 +34,7 @@ #include <gtk/gtk.h> -void show_advanced_zrtp_options (GHashTable * properties) +void show_advanced_zrtp_options(GHashTable * properties) { gboolean curSasConfirm = TRUE; gboolean curHelloEnabled = TRUE; @@ -48,110 +48,111 @@ void show_advanced_zrtp_options (GHashTable * properties) curDisplaySasOnce = !g_strcasecmp(g_hash_table_lookup(properties, ACCOUNT_DISPLAY_SAS_ONCE), "true"); } - GtkDialog *securityDialog = GTK_DIALOG (gtk_dialog_new_with_buttons (_ ("ZRTP Options"), - GTK_WINDOW (get_main_window()), - GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, - GTK_STOCK_CANCEL, - GTK_RESPONSE_CANCEL, - GTK_STOCK_SAVE, - GTK_RESPONSE_ACCEPT, - NULL) - ); - gtk_window_set_resizable(GTK_WINDOW (securityDialog), FALSE); - gtk_container_set_border_width (GTK_CONTAINER (securityDialog), 0); - - - GtkWidget *tableZrtp = gtk_table_new (4, 2 , FALSE/* homogeneous */); - gtk_table_set_row_spacings (GTK_TABLE (tableZrtp), 10); - gtk_table_set_col_spacings (GTK_TABLE (tableZrtp), 10); - gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area(securityDialog)), tableZrtp, FALSE, FALSE, 0); - gtk_widget_show (tableZrtp); - - GtkWidget *enableHelloHash = gtk_check_button_new_with_mnemonic (_ ("Send Hello Hash in S_DP")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (enableHelloHash), curHelloEnabled); - gtk_table_attach (GTK_TABLE (tableZrtp), enableHelloHash, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_set_sensitive (GTK_WIDGET (enableHelloHash) , TRUE); - - GtkWidget *enableSASConfirm = gtk_check_button_new_with_mnemonic (_ ("Ask User to Confirm SAS")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (enableSASConfirm), curSasConfirm); - gtk_table_attach (GTK_TABLE (tableZrtp), enableSASConfirm, 0, 1, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_set_sensitive (GTK_WIDGET (enableSASConfirm) , TRUE); - - GtkWidget *enableZrtpNotSuppOther = gtk_check_button_new_with_mnemonic (_ ("_Warn if ZRTP not supported")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (enableZrtpNotSuppOther), curZrtpNotSuppOther); - gtk_table_attach (GTK_TABLE (tableZrtp), enableZrtpNotSuppOther, 0, 1, 4, 5, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_set_sensitive (GTK_WIDGET (enableZrtpNotSuppOther) , TRUE); - - GtkWidget *displaySasOnce = gtk_check_button_new_with_mnemonic (_ ("Display SAS once for hold events")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (displaySasOnce), curDisplaySasOnce); - gtk_table_attach (GTK_TABLE (tableZrtp), displaySasOnce, 0, 1, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_set_sensitive (GTK_WIDGET (displaySasOnce) , TRUE); - - gtk_widget_show_all (tableZrtp); - - gtk_container_set_border_width (GTK_CONTAINER (tableZrtp), 10); - - if (gtk_dialog_run (GTK_DIALOG (securityDialog)) == GTK_RESPONSE_ACCEPT) { - g_hash_table_replace (properties, - g_strdup (ACCOUNT_ZRTP_DISPLAY_SAS), - g_strdup (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (enableSASConfirm)) ? "true": "false")); - - g_hash_table_replace (properties, - g_strdup (ACCOUNT_DISPLAY_SAS_ONCE), - g_strdup (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (displaySasOnce)) ? "true": "false")); - - g_hash_table_replace (properties, - g_strdup (ACCOUNT_ZRTP_HELLO_HASH), - g_strdup (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (enableHelloHash)) ? "true": "false")); - - g_hash_table_replace (properties, - g_strdup (ACCOUNT_ZRTP_NOT_SUPP_WARNING), - g_strdup (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (enableZrtpNotSuppOther)) ? "true": "false")); + GtkDialog *securityDialog = GTK_DIALOG(gtk_dialog_new_with_buttons(_("ZRTP Options"), + GTK_WINDOW(get_main_window()), + GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_STOCK_CANCEL, + GTK_RESPONSE_CANCEL, + GTK_STOCK_SAVE, + GTK_RESPONSE_ACCEPT, + NULL) + ); + gtk_window_set_resizable(GTK_WINDOW(securityDialog), FALSE); + gtk_container_set_border_width(GTK_CONTAINER(securityDialog), 0); + + + GtkWidget *tableZrtp = gtk_table_new(4, 2 , FALSE/* homogeneous */); + gtk_table_set_row_spacings(GTK_TABLE(tableZrtp), 10); + gtk_table_set_col_spacings(GTK_TABLE(tableZrtp), 10); + gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(securityDialog)), tableZrtp, FALSE, FALSE, 0); + gtk_widget_show(tableZrtp); + + GtkWidget *enableHelloHash = gtk_check_button_new_with_mnemonic(_("Send Hello Hash in S_DP")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(enableHelloHash), curHelloEnabled); + gtk_table_attach(GTK_TABLE(tableZrtp), enableHelloHash, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_widget_set_sensitive(GTK_WIDGET(enableHelloHash) , TRUE); + + GtkWidget *enableSASConfirm = gtk_check_button_new_with_mnemonic(_("Ask User to Confirm SAS")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(enableSASConfirm), curSasConfirm); + gtk_table_attach(GTK_TABLE(tableZrtp), enableSASConfirm, 0, 1, 3, 4, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_widget_set_sensitive(GTK_WIDGET(enableSASConfirm) , TRUE); + + GtkWidget *enableZrtpNotSuppOther = gtk_check_button_new_with_mnemonic(_("_Warn if ZRTP not supported")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(enableZrtpNotSuppOther), curZrtpNotSuppOther); + gtk_table_attach(GTK_TABLE(tableZrtp), enableZrtpNotSuppOther, 0, 1, 4, 5, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_widget_set_sensitive(GTK_WIDGET(enableZrtpNotSuppOther) , TRUE); + + GtkWidget *displaySasOnce = gtk_check_button_new_with_mnemonic(_("Display SAS once for hold events")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(displaySasOnce), curDisplaySasOnce); + gtk_table_attach(GTK_TABLE(tableZrtp), displaySasOnce, 0, 1, 5, 6, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_widget_set_sensitive(GTK_WIDGET(displaySasOnce) , TRUE); + + gtk_widget_show_all(tableZrtp); + + gtk_container_set_border_width(GTK_CONTAINER(tableZrtp), 10); + + if (gtk_dialog_run(GTK_DIALOG(securityDialog)) == GTK_RESPONSE_ACCEPT) { + g_hash_table_replace(properties, + g_strdup(ACCOUNT_ZRTP_DISPLAY_SAS), + g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(enableSASConfirm)) ? "true": "false")); + + g_hash_table_replace(properties, + g_strdup(ACCOUNT_DISPLAY_SAS_ONCE), + g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(displaySasOnce)) ? "true": "false")); + + g_hash_table_replace(properties, + g_strdup(ACCOUNT_ZRTP_HELLO_HASH), + g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(enableHelloHash)) ? "true": "false")); + + g_hash_table_replace(properties, + g_strdup(ACCOUNT_ZRTP_NOT_SUPP_WARNING), + g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(enableZrtpNotSuppOther)) ? "true": "false")); } - gtk_widget_destroy (GTK_WIDGET (securityDialog)); + gtk_widget_destroy(GTK_WIDGET(securityDialog)); } -void show_advanced_sdes_options (GHashTable * properties) +void show_advanced_sdes_options(GHashTable * properties) { gboolean rtpFallback = FALSE; + if (properties != NULL) { - rtpFallback = !g_strcasecmp(g_hash_table_lookup (properties, ACCOUNT_SRTP_RTP_FALLBACK), "true"); + rtpFallback = !g_strcasecmp(g_hash_table_lookup(properties, ACCOUNT_SRTP_RTP_FALLBACK), "true"); } - GtkDialog *securityDialog = GTK_DIALOG(gtk_dialog_new_with_buttons (_ ("SDES Options"), - GTK_WINDOW (get_main_window()), - GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, - GTK_STOCK_CANCEL, - GTK_RESPONSE_CANCEL, - GTK_STOCK_SAVE, - GTK_RESPONSE_ACCEPT, - NULL)); - - gtk_window_set_resizable(GTK_WINDOW (securityDialog), FALSE); - gtk_container_set_border_width (GTK_CONTAINER (securityDialog), 0); - - GtkWidget *sdesTable = gtk_table_new (1, 2 , FALSE/* homogeneous */); - gtk_table_set_row_spacings (GTK_TABLE (sdesTable), 10); - gtk_table_set_col_spacings (GTK_TABLE (sdesTable), 10); - gtk_box_pack_start (GTK_BOX(gtk_dialog_get_content_area(securityDialog)), sdesTable, FALSE, FALSE, 0); - gtk_widget_show (sdesTable); - - GtkWidget *enableRtpFallback = gtk_check_button_new_with_mnemonic (_ ("Fallback on RTP on SDES failure")); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (enableRtpFallback), rtpFallback); - gtk_table_attach (GTK_TABLE (sdesTable), enableRtpFallback, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); - gtk_widget_set_sensitive (GTK_WIDGET (enableRtpFallback) , TRUE); - - gtk_widget_show_all (sdesTable); - - gtk_container_set_border_width (GTK_CONTAINER (sdesTable), 10); - - if (gtk_dialog_run (GTK_DIALOG (securityDialog)) == GTK_RESPONSE_ACCEPT) { - g_hash_table_replace (properties, - g_strdup (ACCOUNT_SRTP_RTP_FALLBACK), - g_strdup (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (enableRtpFallback)) ? "true": "false")); + GtkDialog *securityDialog = GTK_DIALOG(gtk_dialog_new_with_buttons(_("SDES Options"), + GTK_WINDOW(get_main_window()), + GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_STOCK_CANCEL, + GTK_RESPONSE_CANCEL, + GTK_STOCK_SAVE, + GTK_RESPONSE_ACCEPT, + NULL)); + + gtk_window_set_resizable(GTK_WINDOW(securityDialog), FALSE); + gtk_container_set_border_width(GTK_CONTAINER(securityDialog), 0); + + GtkWidget *sdesTable = gtk_table_new(1, 2 , FALSE/* homogeneous */); + gtk_table_set_row_spacings(GTK_TABLE(sdesTable), 10); + gtk_table_set_col_spacings(GTK_TABLE(sdesTable), 10); + gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(securityDialog)), sdesTable, FALSE, FALSE, 0); + gtk_widget_show(sdesTable); + + GtkWidget *enableRtpFallback = gtk_check_button_new_with_mnemonic(_("Fallback on RTP on SDES failure")); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(enableRtpFallback), rtpFallback); + gtk_table_attach(GTK_TABLE(sdesTable), enableRtpFallback, 0, 1, 2, 3, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); + gtk_widget_set_sensitive(GTK_WIDGET(enableRtpFallback) , TRUE); + + gtk_widget_show_all(sdesTable); + + gtk_container_set_border_width(GTK_CONTAINER(sdesTable), 10); + + if (gtk_dialog_run(GTK_DIALOG(securityDialog)) == GTK_RESPONSE_ACCEPT) { + g_hash_table_replace(properties, + g_strdup(ACCOUNT_SRTP_RTP_FALLBACK), + g_strdup(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(enableRtpFallback)) ? "true": "false")); } - gtk_widget_destroy (GTK_WIDGET (securityDialog)); + gtk_widget_destroy(GTK_WIDGET(securityDialog)); } diff --git a/gnome/src/contacts/Makefile.am b/gnome/src/contacts/Makefile.am index b6fc155e2d235066265732629dd4c3622680360d..9c2343de99e5c356e2308252924acd41dcdd3ebd 100644 --- a/gnome/src/contacts/Makefile.am +++ b/gnome/src/contacts/Makefile.am @@ -20,9 +20,7 @@ libcontacts_la_SOURCES = \ searchbar.h libcontacts_la_LDFLAGS = $(DBUSGLIB_LDFLAGS) $(LIBNOTIFY_LDFLAGS) \ - $(GTK_LDFLAGS) $(GLIB_LDFLAGS) $(WEBKIT_LDFLAGS) $(LIBGNOMEUI_LDFLAGS) \ - $(GNOMEDOCUTILS_LDFLAGS) + $(GTK_LDFLAGS) $(GLIB_LDFLAGS) $(WEBKIT_LDFLAGS) libcontacts_la_CFLAGS = $(DBUSGLIB_CFLAGS) $(LIBNOTIFY_CFLAGS) \ - $(GTK_CFLAGS) $(GLIB_CFLAGS) $(WEBKIT_CFLAGS) $(LIBGNOMEUI_CFLAGS) \ - $(GNOMEDOCUTILS_CFLAGS) + $(GTK_CFLAGS) $(GLIB_CFLAGS) $(WEBKIT_CFLAGS) $(GCONF_CFLAGS) diff --git a/gnome/src/contacts/addrbookfactory.c b/gnome/src/contacts/addrbookfactory.c index 5348f209773e8ff1ba1194c20ab33dae1fff5789..3db2562ffcbaa58fe557f69a28c800107b780d47 100644 --- a/gnome/src/contacts/addrbookfactory.c +++ b/gnome/src/contacts/addrbookfactory.c @@ -30,7 +30,7 @@ #include "addrbookfactory.h" #include "addressbook-config.h" - +#include "logger.h" #include "calltab.h" #include "calltree.h" @@ -44,54 +44,55 @@ AddrBookHandle *addrbook = NULL; * Callback called after all book have been processed */ static void -handler_async_search (GList *hits, gpointer user_data) +handler_async_search(GList *hits, gpointer user_data) { AddressBook_Config *addressbook_config = user_data; - gtk_tree_store_clear (contacts->store); - calllist_reset (contacts); + gtk_tree_store_clear(contacts_tab->store); + calllist_reset(contacts_tab); for (GList *i = hits; i != NULL; i = i->next) { GdkPixbuf *photo = NULL; Hit *entry = i->data; + if (!entry) - continue; + continue; - if (addressbook_display (addressbook_config, - ADDRESSBOOK_DISPLAY_CONTACT_PHOTO)) + if (addressbook_display(addressbook_config, + ADDRESSBOOK_DISPLAY_CONTACT_PHOTO)) photo = entry->photo; - if (addressbook_display (addressbook_config, - ADDRESSBOOK_DISPLAY_PHONE_BUSINESS)) - calllist_add_contact (entry->name, entry->phone_business, - CONTACT_PHONE_BUSINESS, photo); - - if (addressbook_display (addressbook_config, - ADDRESSBOOK_DISPLAY_PHONE_HOME)) - calllist_add_contact (entry->name, entry->phone_home, - CONTACT_PHONE_HOME, photo); - - if (addressbook_display (addressbook_config, - ADDRESSBOOK_DISPLAY_PHONE_MOBILE)) - calllist_add_contact (entry->name, entry->phone_mobile, - CONTACT_PHONE_MOBILE, photo); - - g_free (entry->name); - g_free (entry->phone_business); - g_free (entry->phone_home); - g_free (entry->phone_mobile); - g_free (entry); + if (addressbook_display(addressbook_config, + ADDRESSBOOK_DISPLAY_PHONE_BUSINESS)) + calllist_add_contact(entry->name, entry->phone_business, + CONTACT_PHONE_BUSINESS, photo); + + if (addressbook_display(addressbook_config, + ADDRESSBOOK_DISPLAY_PHONE_HOME)) + calllist_add_contact(entry->name, entry->phone_home, + CONTACT_PHONE_HOME, photo); + + if (addressbook_display(addressbook_config, + ADDRESSBOOK_DISPLAY_PHONE_MOBILE)) + calllist_add_contact(entry->name, entry->phone_mobile, + CONTACT_PHONE_MOBILE, photo); + + g_free(entry->name); + g_free(entry->phone_business); + g_free(entry->phone_home); + g_free(entry->phone_mobile); + g_free(entry); } - g_list_free (hits); - gtk_widget_grab_focus(GTK_WIDGET (contacts->view)); + g_list_free(hits); + gtk_widget_grab_focus(GTK_WIDGET(contacts_tab->view)); } void abook_init() { void *handle = dlopen(PLUGINS_DIR"/libevladdrbook.so", RTLD_LAZY); - if(handle == NULL) { + if (handle == NULL) { ERROR("Addressbook: Error: Could not load addressbook"); return; } diff --git a/gnome/src/contacts/calllist.c b/gnome/src/contacts/calllist.c index 61aead2161651f6c29a68fd6ee27768021556733..75b0727f8c03104ee93158e47a74a58b8df8ad0c 100644 --- a/gnome/src/contacts/calllist.c +++ b/gnome/src/contacts/calllist.c @@ -29,54 +29,58 @@ */ #include "calllist.h" +#include "calltab.h" #include "calltree.h" -#include "contacts/searchbar.h" +#include "unused.h" +#include "logger.h" #include "eel-gconf-extensions.h" static gint is_callID_callstruct(gconstpointer a, gconstpointer b) { const QueueElement *c = a; - if(c == NULL || c->type != HIST_CALL) - return 1; + + if (c == NULL || c->type != HIST_CALL) + return 1; return g_strcasecmp(c->elem.call->_callID, (const gchar *) b); } -// TODO : sflphoneGTK : try to do this more generic -void calllist_add_contact (gchar *contact_name, gchar *contact_phone, contact_type_t type, GdkPixbuf *photo) +// TODO : try to do this more generically +void calllist_add_contact(gchar *contact_name, gchar *contact_phone, contact_type_t type, GdkPixbuf *photo) { /* Check if the information is valid */ if (!contact_phone) return; - callable_obj_t *new_call = create_new_call (CONTACT, CALL_STATE_DIALING, "", "", contact_name, contact_phone); + callable_obj_t *new_call = create_new_call(CONTACT, CALL_STATE_DIALING, "", "", contact_name, contact_phone); // Attach a pixbuf to a contact - if (photo) { - new_call->_contact_thumbnail = gdk_pixbuf_copy (photo); - } else { + if (photo) + new_call->_contact_thumbnail = gdk_pixbuf_copy(photo); + else { GdkPixbuf *pixbuf; + switch (type) { case CONTACT_PHONE_BUSINESS: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/users.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/users.svg", NULL); break; case CONTACT_PHONE_HOME: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/home.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/home.svg", NULL); break; case CONTACT_PHONE_MOBILE: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/phone.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/phone.svg", NULL); break; default: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/contact_default.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/contact_default.svg", NULL); break; } new_call->_contact_thumbnail = pixbuf; } - calllist_add_call (contacts, new_call); - calltree_add_call (contacts, new_call, NULL); + calllist_add_call(contacts_tab, new_call); + calltree_add_call(contacts_tab, new_call, NULL); } /* @@ -86,51 +90,29 @@ static void calllist_free_element(gpointer data, gpointer user_data UNUSED) { QueueElement *element = data; - if (element->type == HIST_CONFERENCE) - free_conference_obj_t (element->elem.conf); - else /* HIST_CALL */ - free_callable_obj_t (element->elem.call); - g_free (element); + + g_assert(element->type == HIST_CALL); + free_callable_obj_t(element->elem.call); + + g_free(element); } void -calllist_clean (calltab_t* tab) +calllist_clean(calltab_t* tab) { - g_queue_foreach (tab->callQueue, calllist_free_element, NULL); - g_queue_free (tab->callQueue); + g_queue_foreach(tab->callQueue, calllist_free_element, NULL); + g_queue_free(tab->callQueue); } void -calllist_reset (calltab_t* tab) +calllist_reset(calltab_t* tab) { - calllist_clean (tab); + calllist_clean(tab); tab->callQueue = g_queue_new(); } -void calllist_add_history_call (callable_obj_t *obj) -{ - if (eel_gconf_get_integer (HISTORY_ENABLED)) { - QueueElement *element = g_new0(QueueElement, 1); - element->type = HIST_CALL; - element->elem.call = obj; - g_queue_push_tail (history->callQueue, (gpointer) element); - calltree_add_call (history, obj, NULL); - } -} - -void calllist_add_history_conference(conference_obj_t *obj) -{ - if(eel_gconf_get_integer (HISTORY_ENABLED)) { - QueueElement *element = g_new0(QueueElement, 1); - element->type = HIST_CONFERENCE; - element->elem.conf = obj; - g_queue_push_tail (history->callQueue, (gpointer) element); - calltree_add_conference (history, obj); - } -} - void -calllist_add_call (calltab_t* tab, callable_obj_t * c) +calllist_add_call(calltab_t* tab, callable_obj_t * c) { QueueElement *element = g_new0(QueueElement, 1); element->type = HIST_CALL; @@ -139,36 +121,37 @@ calllist_add_call (calltab_t* tab, callable_obj_t * c) } void -calllist_clean_history (void) +calllist_clean_history(void) { - guint size = calllist_get_size (history); + guint size = calllist_get_size(history_tab); + for (guint i = 0; i < size; i++) { - QueueElement* c = calllist_get_nth(history, i); + QueueElement* c = calllist_get_nth(history_tab, i); + if (c->type == HIST_CALL) - calltree_remove_call (history, c->elem.call, NULL); - else if(c->type == HIST_CONFERENCE) - calltree_remove_conference (history, c->elem.conf, NULL); + calltree_remove_call(history_tab, c->elem.call); } - calllist_reset (history); + calllist_reset(history_tab); } void -calllist_remove_from_history (callable_obj_t* c) +calllist_remove_from_history(callable_obj_t* c) { - calllist_remove_call(history, c->_callID); - calltree_remove_call(history, c, NULL); + calllist_remove_call(history_tab, c->_callID); + calltree_remove_call(history_tab, c); } void -calllist_remove_call (calltab_t* tab, const gchar * callID) +calllist_remove_call(calltab_t* tab, const gchar * callID) { - GList *c = g_queue_find_custom (tab->callQueue, callID, is_callID_callstruct); - if (c == NULL) { - return; - } + GList *c = g_queue_find_custom(tab->callQueue, callID, is_callID_callstruct); + + if (c == NULL) + return; QueueElement *element = (QueueElement *)c->data; + if (element->type != HIST_CALL) { ERROR("CallList: Error: Element %s is not a call", callID); return; @@ -176,8 +159,8 @@ calllist_remove_call (calltab_t* tab, const gchar * callID) g_queue_remove(tab->callQueue, element); - calllist_add_call(history, element->elem.call); - calltree_add_call(history, element->elem.call, NULL); + calllist_add_call(history_tab, element->elem.call); + calltree_add_history_entry(element->elem.call); } @@ -189,27 +172,29 @@ calllist_get_by_state(calltab_t* tab, call_state_t state) } guint -calllist_get_size (calltab_t* tab) +calllist_get_size(calltab_t* tab) { - return g_queue_get_length (tab->callQueue); + return g_queue_get_length(tab->callQueue); } QueueElement * -calllist_get_nth (calltab_t* tab, guint n) +calllist_get_nth(calltab_t* tab, guint n) { - return g_queue_peek_nth (tab->callQueue, n); + return g_queue_peek_nth(tab->callQueue, n); } callable_obj_t * -calllist_get_call (calltab_t* tab, const gchar * callID) +calllist_get_call(calltab_t* tab, const gchar * callID) { - GList * c = g_queue_find_custom (tab->callQueue, callID, is_callID_callstruct); + GList * c = g_queue_find_custom(tab->callQueue, callID, is_callID_callstruct); + if (c == NULL) { ERROR("CallList: Error: Could not find call %s", callID); return NULL; } QueueElement *element = c->data; + if (element->type != HIST_CALL) { ERROR("CallList: Error: Element %s is not a call", callID); return NULL; diff --git a/gnome/src/contacts/calllist.h b/gnome/src/contacts/calllist.h index 288162457bfe439843e2c1ed4a1ae30343b4e5af..66d793f5627f598d5c792b8a480c0f893b8e94f7 100644 --- a/gnome/src/contacts/calllist.h +++ b/gnome/src/contacts/calllist.h @@ -31,15 +31,15 @@ #ifndef __CALLLIST_H__ #define __CALLLIST_H__ -#include <callable_obj.h> -#include <conference_obj.h> #include <gtk/gtk.h> +#include "callable_obj.h" +#include "conference_obj.h" /** @file calllist.h * @brief A list to hold calls. */ -typedef enum { HIST_CONFERENCE, HIST_CALL } ElementType; +typedef enum { HIST_CALL } ElementType; typedef union { callable_obj_t *call; @@ -69,10 +69,6 @@ typedef struct { void calllist_add_contact (gchar *, gchar *, contact_type_t, GdkPixbuf *); -void calllist_add_history_call (callable_obj_t *obj); - -void calllist_add_history_conference (conference_obj_t *obj); - /** This function empty and free the call list. */ void calllist_clean (calltab_t* tab); diff --git a/gnome/src/contacts/calltab.c b/gnome/src/contacts/calltab.c index 0df4e7dda1b3b00564ae3a7b5fb46ea6e13d33e6..fcf0d85009f6333cddaeef6884bf57bb991c2def 100644 --- a/gnome/src/contacts/calltab.c +++ b/gnome/src/contacts/calltab.c @@ -28,28 +28,30 @@ * as that of the covered work. */ -#include <calltab.h> +#include "calltab.h" #include <gtk/gtk.h> #include <stdlib.h> -#include <calltree.h> -#include <contacts/searchbar.h> +#include "calltree.h" +#include "contacts/searchbar.h" +#include "logger.h" -calltab_t* calltab_init (gboolean searchbar_type, gchar *name) +calltab_t* calltab_init(gboolean searchbar_type, const gchar * const name) { - calltab_t* ret = calloc (1, sizeof (calltab_t)); - ret->_name = g_strdup (name); + calltab_t* ret = calloc(1, sizeof(calltab_t)); + ret->_name = g_strdup(name); - calltree_create (ret, searchbar_type); + calltree_create(ret, searchbar_type); - ret->callQueue = g_queue_new (); + ret->callQueue = g_queue_new(); ret->selectedCall = NULL; return ret; } void -calltab_select_call (calltab_t* tab, callable_obj_t * c) +calltab_select_call(calltab_t* tab, callable_obj_t * c) { + g_assert(tab); DEBUG("CallTab: Select call %s", c ? c->_callID : ""); tab->selectedType = A_CALL; @@ -59,8 +61,9 @@ calltab_select_call (calltab_t* tab, callable_obj_t * c) void -calltab_select_conf (calltab_t *tab, conference_obj_t * c) +calltab_select_conf(calltab_t *tab, conference_obj_t * c) { + g_assert(tab); DEBUG("CallTab: Selected conf %s", c ? c->_confID : ""); tab->selectedType = A_CONFERENCE; @@ -69,33 +72,35 @@ calltab_select_conf (calltab_t *tab, conference_obj_t * c) } gint -calltab_get_selected_type (calltab_t* tab) +calltab_get_selected_type(calltab_t* tab) { + g_assert(tab); return tab->selectedType; } callable_obj_t * -calltab_get_selected_call (calltab_t *tab) +calltab_get_selected_call(calltab_t *tab) { + g_assert(tab); return tab->selectedCall; } conference_obj_t* -calltab_get_selected_conf (calltab_t *tab) +calltab_get_selected_conf(calltab_t *tab) { + g_assert(tab); return tab->selectedConf; } void -calltab_create_searchbar (calltab_t* tab) +calltab_create_searchbar(calltab_t* tab) { - if (g_strcasecmp (tab->_name, HISTORY) == 0) { - tab->searchbar = history_searchbar_new (); - } - else if (g_strcasecmp (tab->_name, CONTACTS) == 0) { - tab->searchbar = contacts_searchbar_new (); - } - else { - ERROR ("Current calls tab does not need a searchbar\n"); - } + g_assert(tab); + + if (g_strcasecmp(tab->_name, HISTORY) == 0) + tab->searchbar = history_searchbar_new(); + else if (g_strcasecmp(tab->_name, CONTACTS) == 0) + tab->searchbar = contacts_searchbar_new(); + else + ERROR("Current calls tab does not need a searchbar\n"); } diff --git a/gnome/src/contacts/calltab.h b/gnome/src/contacts/calltab.h index e9d0e70b1afe2da2044954a62d158dcc9b33f0ea..4b2edca9c8c0f8d97798088cfd51d7e233f4c338 100644 --- a/gnome/src/contacts/calltab.h +++ b/gnome/src/contacts/calltab.h @@ -31,18 +31,16 @@ #ifndef __CALLTAB_H__ #define __CALLTAB_H__ -#include <calllist.h> -#include <conferencelist.h> +#include "calllist.h" +#include "conferencelist.h" #include <gtk/gtk.h> -calltab_t* active_calltree; -calltab_t* current_calls; -calltab_t* history; -calltab_t* contacts; - -calltab_t* calltab_init (gboolean, gchar *); - +calltab_t* active_calltree_tab; +calltab_t* current_calls_tab; +calltab_t* history_tab; +calltab_t* contacts_tab; +calltab_t* calltab_init (gboolean, const gchar * const); /** Mark a call as selected. There can be only one selected call. This call * is the currently highlighted one in the list. diff --git a/gnome/src/contacts/calltree.c b/gnome/src/contacts/calltree.c index b6ef5fe73ee66107f88443b23fc0a2fad1b97456..2e70bc5e929f1f9ac609cb3f26abc69403c8e93d 100644 --- a/gnome/src/contacts/calltree.c +++ b/gnome/src/contacts/calltree.c @@ -30,13 +30,16 @@ * as that of the covered work. */ -#include <calltree.h> +#include "calllist.h" +#include "calltree.h" #include <stdlib.h> #include <glib/gprintf.h> -#include <eel-gconf-extensions.h> +#include "eel-gconf-extensions.h" +#include "unused.h" #include "dbus.h" -#include "calllist.h" +#include "calltab.h" +#include "logger.h" #include "conferencelist.h" #include "mainwindow.h" #include "history.h" @@ -47,8 +50,8 @@ #include "searchbar.h" // Messages used in menu item -#define SFL_CREATE_CONFERENCE "Create conference" -#define SFL_TRANSFER_CALL "Transfer call to" +static const gchar * const SFL_CREATE_CONFERENCE = "Create conference"; +static const gchar * const SFL_TRANSFER_CALL = "Transfer call to"; static GtkWidget *calltree_sw = NULL; static GtkCellRenderer *calltree_rend = NULL; @@ -61,11 +64,10 @@ static GtkWidget *calltree_menu_items = NULL; static CallType calltree_dragged_type = A_INVALID; static CallType calltree_selected_type = A_INVALID; -static gchar *calltree_dragged_call_id = NULL; -static gchar *calltree_selected_call_id; - -static gchar *calltree_dragged_path = NULL; -static gchar *calltree_selected_path = NULL; +static const gchar *calltree_dragged_call_id = NULL; +static const gchar *calltree_selected_call_id = NULL; +static const gchar *calltree_dragged_path = NULL; +static const gchar *calltree_selected_path = NULL; static gint calltree_dragged_path_depth = -1; static gint calltree_selected_path_depth = -1; @@ -76,18 +78,15 @@ static callable_obj_t *calltree_selected_call = NULL; static conference_obj_t *calltree_dragged_conf = NULL; static conference_obj_t *calltree_selected_conf = NULL; -static void calltree_add_history_conference(conference_obj_t *); - -static void drag_end_cb (GtkWidget *, GdkDragContext *, gpointer); -static void drag_data_received_cb (GtkWidget *, GdkDragContext *, gint, gint, GtkSelectionData *, guint, guint, gpointer); -static void drag_history_received_cb (GtkWidget *, GdkDragContext *, gint, gint, GtkSelectionData *, guint, guint, gpointer); -static void menuitem_response (gchar *); -static void calltree_create_conf_from_participant_list (GSList *); +static void drag_end_cb(GtkWidget *, GdkDragContext *, gpointer); +static void drag_data_received_cb(GtkWidget *, GdkDragContext *, gint, gint, GtkSelectionData *, guint, guint, gpointer); +static void drag_history_received_cb(GtkWidget *, GdkDragContext *, gint, gint, GtkSelectionData *, guint, guint, gpointer); +static void menuitem_response(gchar *); enum { - COLUMN_ACCOUNT_STATE = 0, + COLUMN_ACCOUNT_PIXBUF = 0, COLUMN_ACCOUNT_DESC, - COLUMN_ACCOUNT_SECURITY, + COLUMN_ACCOUNT_SECURITY_PIXBUF, COLUMN_ACCOUNT_PTR }; @@ -95,116 +94,108 @@ enum { * Show popup menu */ static gboolean -popup_menu (GtkWidget *widget, - gpointer user_data UNUSED) +popup_menu(GtkWidget *widget, + gpointer user_data UNUSED) { - show_popup_menu (widget, NULL); + show_popup_menu(widget, NULL); return TRUE; } /* Call back when the user click on a call in the list */ static void -call_selected_cb (GtkTreeSelection *sel, void* data UNUSED) +call_selected_cb(GtkTreeSelection *sel, void* data UNUSED) { - DEBUG ("CallTree: Selection callback"); + DEBUG("CallTree: Selection callback"); + GtkTreeModel *model = GTK_TREE_MODEL(active_calltree_tab->store); GtkTreeIter iter; - GtkTreeModel *model = (GtkTreeModel*) active_calltree->store; - if (!gtk_tree_selection_get_selected (sel, &model, &iter)) + if (!gtk_tree_selection_get_selected(sel, &model, &iter)) return; - if (active_calltree == history) + if (active_calltree_tab == history_tab) DEBUG("CallTree: Current call tree is history"); - else if(active_calltree == current_calls) + else if (active_calltree_tab == current_calls_tab) DEBUG("CallTree: Current call tree is current calls"); // store info for dragndrop - GtkTreePath *path = gtk_tree_model_get_path (model, &iter); - gchar *string_path = gtk_tree_path_to_string (path); - calltree_selected_path_depth = gtk_tree_path_get_depth (path); - - GValue val; - if (gtk_tree_model_iter_has_child (GTK_TREE_MODEL (model), &iter)) { + GtkTreePath *path = gtk_tree_model_get_path(model, &iter); + gchar *string_path = gtk_tree_path_to_string(path); + calltree_selected_path_depth = gtk_tree_path_get_depth(path); - DEBUG ("CallTree: Selected a conference"); + if (gtk_tree_model_iter_has_child(model, &iter)) { + DEBUG("CallTree: Selected a conference"); calltree_selected_type = A_CONFERENCE; + GValue val; val.g_type = 0; - gtk_tree_model_get_value (model, &iter, COLUMN_ACCOUNT_PTR, &val); + gtk_tree_model_get_value(model, &iter, COLUMN_ACCOUNT_PTR, &val); - calltab_select_conf ( active_calltree, (conference_obj_t*) g_value_get_pointer (&val)); - - calltree_selected_conf = (conference_obj_t*) g_value_get_pointer (&val); + calltree_selected_conf = (conference_obj_t*) g_value_get_pointer(&val); + g_value_unset(&val); if (calltree_selected_conf) { - + calltab_select_conf(active_calltree_tab, calltree_selected_conf); calltree_selected_call_id = calltree_selected_conf->_confID; calltree_selected_path = string_path; calltree_selected_call = NULL; if (calltree_selected_conf->_im_widget) - im_window_show_tab (calltree_selected_conf->_im_widget); - } - - DEBUG ("CallTree: selected_path %s, selected_conf_id %s, selected_path_depth %d", - calltree_selected_path, calltree_selected_call_id, calltree_selected_path_depth); + im_window_show_tab(calltree_selected_conf->_im_widget); + DEBUG("CallTree: selected_path %s, selected_conf_id %s, selected_path_depth %d", + calltree_selected_path, calltree_selected_call_id, calltree_selected_path_depth); + } } else { - - DEBUG ("CallTree: Selected a call"); + DEBUG("CallTree: Selected a call"); calltree_selected_type = A_CALL; + GValue val; val.g_type = 0; - gtk_tree_model_get_value (model, &iter, COLUMN_ACCOUNT_PTR, &val); - - calltab_select_call (active_calltree, (callable_obj_t*) g_value_get_pointer (&val)); + gtk_tree_model_get_value(model, &iter, COLUMN_ACCOUNT_PTR, &val); - calltree_selected_call = (callable_obj_t*) g_value_get_pointer (&val); + calltree_selected_call = g_value_get_pointer(&val); + g_value_unset(&val); if (calltree_selected_call) { - + calltab_select_call(active_calltree_tab, calltree_selected_call); calltree_selected_call_id = calltree_selected_call->_callID; calltree_selected_path = string_path; calltree_selected_conf = NULL; if (calltree_selected_call->_im_widget) - im_window_show_tab (calltree_selected_call->_im_widget); - } + im_window_show_tab(calltree_selected_call->_im_widget); - DEBUG ("CallTree: selected_path %s, selected_call_id %s, selected_path_depth %d", - calltree_selected_path, calltree_selected_call_id, calltree_selected_path_depth); + DEBUG("CallTree: selected_path %s, selected_call_id %s, selected_path_depth %d", + calltree_selected_path, calltree_selected_call_id, calltree_selected_path_depth); + } } - g_value_unset (&val); update_actions(); } /* A row is activated when it is double clicked */ void -row_activated (GtkTreeView *tree_view UNUSED, - GtkTreePath *path UNUSED, - GtkTreeViewColumn *column UNUSED, - void * data UNUSED) +row_activated(GtkTreeView *tree_view UNUSED, + GtkTreePath *path UNUSED, + GtkTreeViewColumn *column UNUSED, + void * data UNUSED) { - DEBUG ("CallTree: Double click action"); - - if (calltab_get_selected_type (active_calltree) == A_CALL) { + DEBUG("CallTree: Double click action"); + if (calltab_get_selected_type(active_calltree_tab) == A_CALL) { DEBUG("CallTree: Selected a call"); - - callable_obj_t *selectedCall = calltab_get_selected_call (active_calltree); + callable_obj_t *selectedCall = calltab_get_selected_call(active_calltree_tab); if (selectedCall) { // Get the right event from the right calltree - if (active_calltree == current_calls) { - + if (active_calltree_tab == current_calls_tab) { switch (selectedCall->_state) { case CALL_STATE_INCOMING: - dbus_accept (selectedCall); + dbus_accept(selectedCall); break; case CALL_STATE_HOLD: - dbus_unhold (selectedCall); + dbus_unhold(selectedCall); break; case CALL_STATE_RINGING: case CALL_STATE_CURRENT: @@ -212,191 +203,145 @@ row_activated (GtkTreeView *tree_view UNUSED, case CALL_STATE_FAILURE: break; case CALL_STATE_DIALING: - sflphone_place_call (selectedCall); + sflphone_place_call(selectedCall); break; default: - WARN ("Row activated - Should not happen!"); + WARN("Row activated - Should not happen!"); break; } } else { // If history or contact: double click action places a new call - callable_obj_t* new_call = create_new_call (CALL, CALL_STATE_DIALING, "", selectedCall->_accountID, selectedCall->_peer_name, selectedCall->_peer_number); + callable_obj_t* new_call = create_new_call(CALL, CALL_STATE_DIALING, "", selectedCall->_accountID, selectedCall->_peer_name, selectedCall->_peer_number); - calllist_add_call(current_calls, new_call); - calltree_add_call (current_calls, new_call, NULL); + calllist_add_call(current_calls_tab, new_call); + calltree_add_call(current_calls_tab, new_call, NULL); // Function sflphone_place_call (new_call) is processed in process_dialing sflphone_place_call(new_call); - calltree_display (current_calls); + calltree_display(current_calls_tab); } } - } else if (calltab_get_selected_type (active_calltree) == A_CONFERENCE) { + } else if (calltab_get_selected_type(active_calltree_tab) == A_CONFERENCE) { + DEBUG("CallTree: Selected a conference"); - DEBUG("CallTree: Seleceted a conference"); + if (active_calltree_tab == current_calls_tab) { + conference_obj_t * selectedConf = calltab_get_selected_conf(current_calls_tab); - if (active_calltree == current_calls) { - conference_obj_t * selectedConf = calltab_get_selected_conf (current_calls); if (selectedConf) { switch (selectedConf->_state) { case CONFERENCE_STATE_ACTIVE_DETACHED: case CONFERENCE_STATE_ACTIVE_DETACHED_RECORD: - sflphone_add_main_participant (selectedConf); + sflphone_add_main_participant(selectedConf); break; case CONFERENCE_STATE_HOLD: case CONFERENCE_STATE_HOLD_RECORD: - sflphone_conference_off_hold (selectedConf); + dbus_unhold_conference(selectedConf); break; - case CONFERENCE_STATE_ACTIVE_ATACHED: + case CONFERENCE_STATE_ACTIVE_ATTACHED: case CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD: default: break; } } - } - else if (active_calltree == history) { - conference_obj_t* selectedConf = calltab_get_selected_conf(history); - if (selectedConf == NULL) { - ERROR("CallTree: Error: Could not get selected conference from history"); - return; - } - - calltree_create_conf_from_participant_list(selectedConf->participant_list); - calltree_display(current_calls); - } + } else + WARN("CallTree: Selected a conference in history, should not be possible"); } } -static void -calltree_create_conf_from_participant_list(GSList *list) -{ - gchar **participant_list; - gint list_length = g_slist_length(list); - - DEBUG("CallTree: Create conference from participant list"); - - participant_list = (void *) malloc(sizeof(void*)); - - // concatenate - gint i, c; - for(i = 0, c = 0; i < list_length; i++, c++) { - gchar *number; - gchar *participant_id = g_slist_nth_data(list, i); - callable_obj_t *call = calllist_get_call(history, participant_id); - - if (c != 0) - participant_list = (void *) realloc(participant_list, (c+1) * sizeof(void *)); - - // allocate memory for the participant number - number = g_strconcat(call->_peer_number, ",", call->_accountID, NULL); - - *(participant_list + c) = number; - } - - participant_list = (void *) realloc(participant_list, (c+1) *sizeof(void*)); - *(participant_list+c) = NULL; - - dbus_create_conf_from_participant_list((const gchar **)participant_list); -} - /* Catch cursor-activated signal. That is, when the entry is single clicked */ static void -row_single_click (GtkTreeView *tree_view UNUSED, void * data UNUSED) +row_single_click(GtkTreeView *tree_view UNUSED, void * data UNUSED) { - callable_obj_t * selectedCall = NULL; - conference_obj_t *selectedConf = NULL; gchar * displaySasOnce = NULL; - DEBUG ("CallTree: Single click action"); + DEBUG("CallTree: Single click action"); - selectedCall = calltab_get_selected_call (active_calltree); - selectedConf = calltab_get_selected_conf (active_calltree); + callable_obj_t *selectedCall = calltab_get_selected_call(active_calltree_tab); + conference_obj_t *selectedConf = calltab_get_selected_conf(active_calltree_tab); - if (active_calltree == current_calls) + if (active_calltree_tab == current_calls_tab) DEBUG("CallTree: Active calltree is current_calls"); - else if (active_calltree == history) + else if (active_calltree_tab == history_tab) DEBUG("CallTree: Active calltree is history"); - if(calltab_get_selected_type(active_calltree) == A_CALL) { - + if (calltab_get_selected_type(active_calltree_tab) == A_CALL) { DEBUG("CallTree: Selected a call"); if (selectedCall) { - account_t *account_details = account_list_get_by_id (selectedCall->_accountID); - DEBUG ("AccountID %s", selectedCall->_accountID); + account_t *account_details = account_list_get_by_id(selectedCall->_accountID); + DEBUG("AccountID %s", selectedCall->_accountID); if (account_details != NULL) { - displaySasOnce = g_hash_table_lookup (account_details->properties, ACCOUNT_DISPLAY_SAS_ONCE); - DEBUG ("Display SAS once %s", displaySasOnce); + displaySasOnce = g_hash_table_lookup(account_details->properties, ACCOUNT_DISPLAY_SAS_ONCE); + DEBUG("Display SAS once %s", displaySasOnce); } else { GHashTable *properties = sflphone_get_ip2ip_properties(); + if (properties != NULL) { - displaySasOnce = g_hash_table_lookup (properties, ACCOUNT_DISPLAY_SAS_ONCE); - DEBUG ("IP2IP displaysasonce %s", displaySasOnce); + displaySasOnce = g_hash_table_lookup(properties, ACCOUNT_DISPLAY_SAS_ONCE); + DEBUG("IP2IP displaysasonce %s", displaySasOnce); } } /* Make sure that we are not in the history tab since * nothing is defined for it yet */ - if (active_calltree == current_calls) { + if (active_calltree_tab == current_calls_tab) { switch (selectedCall->_srtp_state) { case SRTP_STATE_ZRTP_SAS_UNCONFIRMED: selectedCall->_srtp_state = SRTP_STATE_ZRTP_SAS_CONFIRMED; - if (g_strcasecmp (displaySasOnce, "true") == 0) + if (g_strcasecmp(displaySasOnce, "true") == 0) selectedCall->_zrtp_confirmed = TRUE; - dbus_confirm_sas (selectedCall); - calltree_update_call (current_calls, selectedCall, NULL); + dbus_confirm_sas(selectedCall); + calltree_update_call(current_calls_tab, selectedCall); break; case SRTP_STATE_ZRTP_SAS_CONFIRMED: selectedCall->_srtp_state = SRTP_STATE_ZRTP_SAS_UNCONFIRMED; - dbus_reset_sas (selectedCall); - calltree_update_call (current_calls, selectedCall, NULL); + dbus_reset_sas(selectedCall); + calltree_update_call(current_calls_tab, selectedCall); break; default: - DEBUG ("Single click but no action"); + DEBUG("Single click but no action"); break; } } } - } - else if(calltab_get_selected_type(active_calltree) == A_CONFERENCE) { + } else if (calltab_get_selected_type(active_calltree_tab) == A_CONFERENCE) { DEBUG("CallTree: Selected a conference"); - if (selectedConf) DEBUG("CallTree: There is actually a selected conf"); - } - else - WARN("CallTree: Warning: Unknow selection type"); + } else + WARN("CallTree: Warning: Unknown selection type"); } static gboolean -button_pressed (GtkWidget* widget, GdkEventButton *event, gpointer user_data UNUSED) +button_pressed(GtkWidget* widget, GdkEventButton *event, gpointer user_data UNUSED) { if (event->button != 3 || event->type != GDK_BUTTON_PRESS) return FALSE; - if (active_calltree == current_calls) - show_popup_menu (widget, event); - else if (active_calltree == history) - show_popup_menu_history (widget, event); + if (active_calltree_tab == current_calls_tab) + show_popup_menu(widget, event); + else if (active_calltree_tab == history_tab) + show_popup_menu_history(widget, event); else - show_popup_menu_contacts (widget, event); + show_popup_menu_contacts(widget, event); return TRUE; } static gchar * -calltree_display_call_info (callable_obj_t * c, CallDisplayType display_type, const gchar *const audio_codec) +calltree_display_call_info(callable_obj_t * c, CallDisplayType display_type, const gchar *const audio_codec) { gchar display_number[strlen(c->_peer_number) + 1]; strcpy(display_number, c->_peer_number); if (c->_type != CALL || c->_history_state != OUTGOING) { // Get the hostname for this call (NULL if not existent) - gchar * hostname = g_strrstr (c->_peer_number, "@"); + gchar * hostname = g_strrstr(c->_peer_number, "@"); // Test if we are dialing a new number if (*c->_peer_number && hostname) @@ -405,6 +350,7 @@ calltree_display_call_info (callable_obj_t * c, CallDisplayType display_type, co // Different display depending on type const gchar *name, *details = NULL; + if (*c->_peer_name) { name = c->_peer_name; details = display_number; @@ -413,31 +359,33 @@ calltree_display_call_info (callable_obj_t * c, CallDisplayType display_type, co details = ""; } - gchar *desc = g_markup_printf_escaped ("<b>%s</b> <i>%s</i> ", name, details); + gchar *desc = g_markup_printf_escaped("<b>%s</b> <i>%s</i> ", name, details); gchar *suffix = NULL; switch (display_type) { - case DISPLAY_TYPE_CALL: - if (c->_state_code) - suffix = g_markup_printf_escaped ("\n<i>%s (%d)</i>", c->_state_code_description, c->_state_code); - break; - case DISPLAY_TYPE_STATE_CODE : - if (c->_state_code) - suffix = g_markup_printf_escaped ("\n<i>%s (%d)</i> <i>%s</i>", - c->_state_code_description, c->_state_code, - audio_codec); - else - suffix = g_markup_printf_escaped ("\n<i>%s</i>", audio_codec); - break; - case DISPLAY_TYPE_CALL_TRANSFER: - suffix = g_markup_printf_escaped ("\n<i>Transfer to:%s</i> ", c->_trsft_to); - break; - case DISPLAY_TYPE_SAS: - suffix = g_markup_printf_escaped ("\n<i>Confirm SAS <b>%s</b> ?</i>", c->_sas); - break; - case DISPLAY_TYPE_HISTORY : - default: - break; + case DISPLAY_TYPE_CALL: + if (c->_state_code) + suffix = g_markup_printf_escaped("\n<i>%s (%d)</i>", c->_state_code_description, c->_state_code); + break; + case DISPLAY_TYPE_STATE_CODE : + + if (c->_state_code) + suffix = g_markup_printf_escaped("\n<i>%s (%d)</i> <i>%s</i>", + c->_state_code_description, c->_state_code, + audio_codec); + else + suffix = g_markup_printf_escaped("\n<i>%s</i>", audio_codec); + + break; + case DISPLAY_TYPE_CALL_TRANSFER: + suffix = g_markup_printf_escaped("\n<i>Transfer to:%s</i> ", c->_trsft_to); + break; + case DISPLAY_TYPE_SAS: + suffix = g_markup_printf_escaped("\n<i>Confirm SAS <b>%s</b> ?</i>", c->_sas); + break; + case DISPLAY_TYPE_HISTORY : + default: + break; } gchar *msg = g_strconcat(desc, suffix, NULL); @@ -447,159 +395,163 @@ calltree_display_call_info (callable_obj_t * c, CallDisplayType display_type, co } void -calltree_create (calltab_t* tab, gboolean searchbar_type) +calltree_create(calltab_t* tab, int searchbar_type) { - gchar *conference = SFL_CREATE_CONFERENCE; - gchar *transfer = SFL_TRANSFER_CALL; - - tab->tree = gtk_vbox_new (FALSE, 10); + tab->tree = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); // Fix bug #708 (resize) - gtk_widget_set_size_request (tab->tree,100,80); + gtk_widget_set_size_request(tab->tree,100,80); - gtk_container_set_border_width (GTK_CONTAINER (tab->tree), 0); + gtk_container_set_border_width(GTK_CONTAINER(tab->tree), 0); - calltree_sw = gtk_scrolled_window_new (NULL, NULL); - gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (calltree_sw), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); - gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (calltree_sw), GTK_SHADOW_IN); + calltree_sw = gtk_scrolled_window_new(NULL, NULL); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(calltree_sw), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); + gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(calltree_sw), GTK_SHADOW_IN); + tab->store = gtk_tree_store_new(4, + GDK_TYPE_PIXBUF, /* Icon */ + G_TYPE_STRING, /* Description */ + GDK_TYPE_PIXBUF, /* Security Icon */ + G_TYPE_POINTER /* Pointer to the Object */ + ); - tab->store = gtk_tree_store_new (4, - GDK_TYPE_PIXBUF,// Icon - G_TYPE_STRING, // Description - GDK_TYPE_PIXBUF, // Security Icon - G_TYPE_POINTER // Pointer to the Object - ); + tab->view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(tab->store)); + gtk_tree_view_set_enable_search(GTK_TREE_VIEW(tab->view), FALSE); + gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tab->view), FALSE); + g_signal_connect(G_OBJECT(tab->view), "row-activated", + G_CALLBACK(row_activated), + NULL); - tab->view = gtk_tree_view_new_with_model (GTK_TREE_MODEL (tab->store)); - gtk_tree_view_set_enable_search (GTK_TREE_VIEW (tab->view), FALSE); - gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (tab->view), FALSE); - g_signal_connect (G_OBJECT (tab->view), "row-activated", - G_CALLBACK (row_activated), - NULL); + gtk_widget_set_can_focus(calltree_sw, TRUE); + gtk_widget_grab_focus(calltree_sw); - gtk_widget_set_can_focus (calltree_sw, TRUE); - gtk_widget_grab_focus (calltree_sw); - - g_signal_connect (G_OBJECT (tab->view), "cursor-changed", - G_CALLBACK (row_single_click), - NULL); + g_signal_connect(G_OBJECT(tab->view), "cursor-changed", + G_CALLBACK(row_single_click), + NULL); // Connect the popup menu - g_signal_connect (G_OBJECT (tab->view), "popup-menu", - G_CALLBACK (popup_menu), - NULL); - g_signal_connect (G_OBJECT (tab->view), "button-press-event", - G_CALLBACK (button_pressed), - NULL); - - if (tab != history && tab!=contacts) { - + g_signal_connect(G_OBJECT(tab->view), "popup-menu", + G_CALLBACK(popup_menu), + NULL); + g_signal_connect(G_OBJECT(tab->view), "button-press-event", + G_CALLBACK(button_pressed), + NULL); + + if (tab != history_tab && tab != contacts_tab) { // Make calltree reordable for drag n drop - gtk_tree_view_set_reorderable (GTK_TREE_VIEW (tab->view), TRUE); + gtk_tree_view_set_reorderable(GTK_TREE_VIEW(tab->view), TRUE); // source widget drag n drop signals - g_signal_connect (G_OBJECT (tab->view), "drag_end", G_CALLBACK (drag_end_cb), NULL); + g_signal_connect(G_OBJECT(tab->view), "drag_end", G_CALLBACK(drag_end_cb), NULL); // destination widget drag n drop signals - g_signal_connect (G_OBJECT (tab->view), "drag_data_received", G_CALLBACK (drag_data_received_cb), NULL); - - calltree_popupmenu = gtk_menu_new (); - - calltree_menu_items = gtk_menu_item_new_with_label (transfer); - g_signal_connect_swapped (calltree_menu_items, "activate", - G_CALLBACK (menuitem_response), (gpointer) g_strdup (transfer)); - gtk_menu_shell_append (GTK_MENU_SHELL (calltree_popupmenu), calltree_menu_items); - gtk_widget_show (calltree_menu_items); - - calltree_menu_items = gtk_menu_item_new_with_label (conference); - g_signal_connect_swapped (calltree_menu_items, "activate", - G_CALLBACK (menuitem_response), (gpointer) g_strdup (conference)); - gtk_menu_shell_append (GTK_MENU_SHELL (calltree_popupmenu), calltree_menu_items); - gtk_widget_show (calltree_menu_items); - } - - if (tab == history) { + g_signal_connect(G_OBJECT(tab->view), "drag_data_received", G_CALLBACK(drag_data_received_cb), NULL); + + calltree_popupmenu = gtk_menu_new(); + + calltree_menu_items = gtk_menu_item_new_with_label(SFL_TRANSFER_CALL); + g_signal_connect_swapped(calltree_menu_items, "activate", + G_CALLBACK(menuitem_response), (gpointer) g_strdup(SFL_TRANSFER_CALL)); + gtk_menu_shell_append(GTK_MENU_SHELL(calltree_popupmenu), calltree_menu_items); + gtk_widget_show(calltree_menu_items); + + calltree_menu_items = gtk_menu_item_new_with_label(SFL_CREATE_CONFERENCE); + g_signal_connect_swapped(calltree_menu_items, "activate", + G_CALLBACK(menuitem_response), (gpointer) g_strdup(SFL_CREATE_CONFERENCE)); + gtk_menu_shell_append(GTK_MENU_SHELL(calltree_popupmenu), calltree_menu_items); + gtk_widget_show(calltree_menu_items); + } else if (tab == history_tab) { gtk_tree_view_set_show_expanders(GTK_TREE_VIEW(tab->view), TRUE); - g_signal_connect (G_OBJECT (tab->view), "drag_data_received", G_CALLBACK (drag_history_received_cb), NULL); + g_signal_connect(G_OBJECT(tab->view), "drag_data_received", G_CALLBACK(drag_history_received_cb), NULL); } - gtk_widget_grab_focus (GTK_WIDGET (tab->view)); + gtk_widget_grab_focus(GTK_WIDGET(tab->view)); calltree_rend = gtk_cell_renderer_pixbuf_new(); - calltree_col = gtk_tree_view_column_new_with_attributes ("Icon", calltree_rend, "pixbuf", 0, - NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (tab->view), calltree_col); + calltree_col = gtk_tree_view_column_new_with_attributes("Icon", calltree_rend, "pixbuf", COLUMN_ACCOUNT_PIXBUF, + NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(tab->view), calltree_col); calltree_rend = gtk_cell_renderer_text_new(); - calltree_col = gtk_tree_view_column_new_with_attributes ("Description", calltree_rend, - "markup", COLUMN_ACCOUNT_DESC, - NULL); - g_object_set (calltree_rend, "wrap-mode", (PangoWrapMode) PANGO_WRAP_WORD_CHAR, NULL); - g_object_set (calltree_rend, "wrap-width", (gint) CALLTREE_TEXT_WIDTH, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (tab->view), calltree_col); + calltree_col = gtk_tree_view_column_new_with_attributes("Description", calltree_rend, + "markup", COLUMN_ACCOUNT_DESC, + NULL); + g_object_set(calltree_rend, "wrap-mode", (PangoWrapMode) PANGO_WRAP_WORD_CHAR, NULL); + + static const gint SFLPHONE_HIG_MARGIN = 10; + static const gint CALLTREE_CALL_ICON_WIDTH = 24; + static const gint CALLTREE_SECURITY_ICON_WIDTH = 24; + gint CALLTREE_TEXT_WIDTH = (MAIN_WINDOW_WIDTH - + CALLTREE_SECURITY_ICON_WIDTH - + CALLTREE_CALL_ICON_WIDTH - (2 * SFLPHONE_HIG_MARGIN)); + g_object_set(calltree_rend, "wrap-width", CALLTREE_TEXT_WIDTH, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(tab->view), calltree_col); /* Security icon */ calltree_rend = gtk_cell_renderer_pixbuf_new(); - calltree_col = gtk_tree_view_column_new_with_attributes ("Icon", - calltree_rend, - "pixbuf", COLUMN_ACCOUNT_SECURITY, - NULL); - g_object_set (calltree_rend, "xalign", (gfloat) 1.0, NULL); - g_object_set (calltree_rend, "yalign", (gfloat) 0.0, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (tab->view), calltree_col); + calltree_col = gtk_tree_view_column_new_with_attributes("Icon", + calltree_rend, + "pixbuf", COLUMN_ACCOUNT_SECURITY_PIXBUF, + NULL); + g_object_set(calltree_rend, "xalign", (gfloat) 1.0, NULL); + g_object_set(calltree_rend, "yalign", (gfloat) 0.0, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(tab->view), calltree_col); - g_object_unref (G_OBJECT (tab->store)); - gtk_container_add (GTK_CONTAINER (calltree_sw), tab->view); + g_object_unref(G_OBJECT(tab->store)); + gtk_container_add(GTK_CONTAINER(calltree_sw), tab->view); - calltree_sel = gtk_tree_view_get_selection (GTK_TREE_VIEW (tab->view)); - g_signal_connect (G_OBJECT (calltree_sel), "changed", - G_CALLBACK (call_selected_cb), - NULL); + calltree_sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tab->view)); + g_signal_connect(G_OBJECT(calltree_sel), "changed", + G_CALLBACK(call_selected_cb), + NULL); - gtk_box_pack_start (GTK_BOX (tab->tree), calltree_sw, TRUE, TRUE, 0); + gtk_box_pack_start(GTK_BOX(tab->tree), calltree_sw, TRUE, TRUE, 0); // search bar if tab is either "history" or "addressbook" if (searchbar_type) { - calltab_create_searchbar (tab); - if(tab->searchbar != NULL) - gtk_box_pack_start (GTK_BOX (tab->tree), tab->searchbar, FALSE, TRUE, 0); + calltab_create_searchbar(tab); + + if (tab->searchbar != NULL) + gtk_box_pack_start(GTK_BOX(tab->tree), tab->searchbar, FALSE, TRUE, 0); } - gtk_widget_show (tab->tree); + gtk_widget_show(tab->tree); } -void -calltree_remove_call (calltab_t* tab, callable_obj_t * c, GtkTreeIter *parent) +static void +calltree_remove_call_recursive(calltab_t* tab, callable_obj_t * callable, GtkTreeIter *parent) { - GtkTreeIter iter; - GtkTreeStore* store = tab->store; + GtkTreeStore *store = tab->store; + GtkTreeModel *model = GTK_TREE_MODEL(store); - if (!c) - ERROR ("CallTree: Error: Not a valid call"); + if (!callable) + ERROR("CallTree: Error: Not a valid call"); - DEBUG ("CallTree: Remove call %s", c->_callID); + DEBUG("CallTree: Remove call %s", callable->_callID); + + int nbChild = gtk_tree_model_iter_n_children(GTK_TREE_MODEL(store), parent); - int nbChild = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (store), parent); for (int i = 0; i < nbChild; i++) { - if (gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (store), &iter, parent, i)) { - if (gtk_tree_model_iter_has_child (GTK_TREE_MODEL (store), &iter)) - calltree_remove_call (tab, c, &iter); + GtkTreeIter child; + + if (gtk_tree_model_iter_nth_child(model, &child, parent, i)) { + if (gtk_tree_model_iter_has_child(model, &child)) + calltree_remove_call_recursive(tab, callable, &child); GValue val = { .g_type = 0 }; - gtk_tree_model_get_value (GTK_TREE_MODEL (store), &iter, COLUMN_ACCOUNT_PTR, &val); + gtk_tree_model_get_value(model, &child, COLUMN_ACCOUNT_PTR, &val); - callable_obj_t * iterCall = g_value_get_pointer (&val); - g_value_unset (&val); + callable_obj_t * iterCall = g_value_get_pointer(&val); + g_value_unset(&val); - if (iterCall == c) - gtk_tree_store_remove (store, &iter); + if (iterCall == callable) + gtk_tree_store_remove(store, &child); } } - if (calltab_get_selected_call (tab) == c) - calltab_select_call (tab, NULL); + if (calltab_get_selected_call(tab) == callable) + calltab_select_call(tab, NULL); update_actions(); @@ -607,7 +559,13 @@ calltree_remove_call (calltab_t* tab, callable_obj_t * c, GtkTreeIter *parent) } void -calltree_update_call (calltab_t* tab, callable_obj_t * c, GtkTreeIter *parent) +calltree_remove_call(calltab_t* tab, callable_obj_t * c) +{ + calltree_remove_call_recursive(tab, c, NULL); +} + +static void +calltree_update_call_recursive(calltab_t* tab, callable_obj_t * c, GtkTreeIter *parent) { GdkPixbuf *pixbuf = NULL; GdkPixbuf *pixbuf_security = NULL; @@ -619,187 +577,177 @@ calltree_update_call (calltab_t* tab, callable_obj_t * c, GtkTreeIter *parent) gboolean display_sas = TRUE; account_t* account_details=NULL; - int nbChild = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (store), parent); - int i; + int nbChild = gtk_tree_model_iter_n_children(GTK_TREE_MODEL(store), parent); if (c) { - account_details = account_list_get_by_id (c->_accountID); + account_details = account_list_get_by_id(c->_accountID); if (account_details != NULL) { - srtp_enabled = g_hash_table_lookup (account_details->properties, ACCOUNT_SRTP_ENABLED); + srtp_enabled = g_hash_table_lookup(account_details->properties, ACCOUNT_SRTP_ENABLED); - if (g_strcasecmp (g_hash_table_lookup (account_details->properties, ACCOUNT_ZRTP_DISPLAY_SAS),"false") == 0) + if (g_strcasecmp(g_hash_table_lookup(account_details->properties, ACCOUNT_ZRTP_DISPLAY_SAS),"false") == 0) display_sas = FALSE; } else { GHashTable * properties = sflphone_get_ip2ip_properties(); if (properties != NULL) { - srtp_enabled = g_hash_table_lookup (properties, ACCOUNT_SRTP_ENABLED); + srtp_enabled = g_hash_table_lookup(properties, ACCOUNT_SRTP_ENABLED); - if (g_strcasecmp (g_hash_table_lookup (properties, ACCOUNT_ZRTP_DISPLAY_SAS),"false") == 0) + if (g_strcasecmp(g_hash_table_lookup(properties, ACCOUNT_ZRTP_DISPLAY_SAS),"false") == 0) display_sas = FALSE; } } } - for (i = 0; i < nbChild; i++) { + for (gint i = 0; i < nbChild; i++) { - if (gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (store), &iter, parent, i)) { + if (gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(store), &iter, parent, i)) { - if (gtk_tree_model_iter_has_child (GTK_TREE_MODEL (store), &iter)) - calltree_update_call (tab, c, &iter); + if (gtk_tree_model_iter_has_child(GTK_TREE_MODEL(store), &iter)) + calltree_update_call_recursive(tab, c, &iter); val.g_type = 0; - gtk_tree_model_get_value (GTK_TREE_MODEL (store), &iter, COLUMN_ACCOUNT_PTR, &val); + gtk_tree_model_get_value(GTK_TREE_MODEL(store), &iter, COLUMN_ACCOUNT_PTR, &val); - callable_obj_t * iterCall = (callable_obj_t*) g_value_get_pointer (&val); - g_value_unset (&val); + callable_obj_t * iterCall = (callable_obj_t*) g_value_get_pointer(&val); + g_value_unset(&val); if (iterCall != c) continue; /* Update text */ gchar * description = NULL; - gchar * audio_codec = call_get_audio_codec (c); + gchar * audio_codec = call_get_audio_codec(c); if (c->_state == CALL_STATE_TRANSFER) - description = calltree_display_call_info (c, DISPLAY_TYPE_CALL_TRANSFER, ""); - else { + description = calltree_display_call_info(c, DISPLAY_TYPE_CALL_TRANSFER, ""); + else if (c->_sas && display_sas && c->_srtp_state == SRTP_STATE_ZRTP_SAS_UNCONFIRMED && !c->_zrtp_confirmed) - description = calltree_display_call_info (c, DISPLAY_TYPE_SAS, ""); + description = calltree_display_call_info(c, DISPLAY_TYPE_SAS, ""); else - description = calltree_display_call_info (c, DISPLAY_TYPE_STATE_CODE, audio_codec); - } + description = calltree_display_call_info(c, DISPLAY_TYPE_STATE_CODE, audio_codec); - g_free (audio_codec); + g_free(audio_codec); /* Update icons */ - if (tab == current_calls) { - DEBUG ("Receiving in state %d", c->_state); + if (tab == current_calls_tab) { + DEBUG("Receiving in state %d", c->_state); switch (c->_state) { case CALL_STATE_HOLD: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/hold.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/hold.svg", NULL); break; case CALL_STATE_INCOMING: case CALL_STATE_RINGING: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/ring.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/ring.svg", NULL); break; case CALL_STATE_CURRENT: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/current.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/current.svg", NULL); break; case CALL_STATE_DIALING: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/dial.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/dial.svg", NULL); break; case CALL_STATE_FAILURE: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/fail.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/fail.svg", NULL); break; case CALL_STATE_BUSY: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/busy.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/busy.svg", NULL); break; case CALL_STATE_TRANSFER: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/transfer.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/transfer.svg", NULL); break; case CALL_STATE_RECORD: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/icon_rec.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/icon_rec.svg", NULL); break; default: - WARN ("Update calltree - Should not happen!"); + WARN("Update calltree - Should not happen!"); } switch (c->_srtp_state) { case SRTP_STATE_SDES_SUCCESS: - DEBUG ("SDES negotiation succes"); - pixbuf_security = gdk_pixbuf_new_from_file (ICONS_DIR "/lock_confirmed.svg", NULL); + pixbuf_security = gdk_pixbuf_new_from_file(ICONS_DIR "/lock_confirmed.svg", NULL); break; case SRTP_STATE_ZRTP_SAS_UNCONFIRMED: - DEBUG ("Secure is ON"); - pixbuf_security = gdk_pixbuf_new_from_file (ICONS_DIR "/lock_unconfirmed.svg", NULL); - if (c->_sas != NULL) { - DEBUG ("SAS is ready with value %s", c->_sas); - } + pixbuf_security = gdk_pixbuf_new_from_file(ICONS_DIR "/lock_unconfirmed.svg", NULL); + if (c->_sas != NULL) + DEBUG("SAS is ready with value %s", c->_sas); break; case SRTP_STATE_ZRTP_SAS_CONFIRMED: - DEBUG ("SAS is confirmed"); - pixbuf_security = gdk_pixbuf_new_from_file (ICONS_DIR "/lock_confirmed.svg", NULL); + pixbuf_security = gdk_pixbuf_new_from_file(ICONS_DIR "/lock_confirmed.svg", NULL); break; case SRTP_STATE_ZRTP_SAS_SIGNED: - DEBUG ("Secure is ON with SAS signed and verified"); - pixbuf_security = gdk_pixbuf_new_from_file (ICONS_DIR "/lock_certified.svg", NULL); + pixbuf_security = gdk_pixbuf_new_from_file(ICONS_DIR "/lock_certified.svg", NULL); break; case SRTP_STATE_UNLOCKED: - DEBUG ("Secure is off calltree %d", c->_state); - - if (g_strcasecmp (srtp_enabled,"true") == 0) - pixbuf_security = gdk_pixbuf_new_from_file (ICONS_DIR "/lock_off.svg", NULL); + if (g_strcasecmp(srtp_enabled,"true") == 0) + pixbuf_security = gdk_pixbuf_new_from_file(ICONS_DIR "/lock_off.svg", NULL); break; default: - WARN ("Update calltree srtp state #%d- Should not happen!", c->_srtp_state); - - if (g_strcasecmp (srtp_enabled, "true") == 0) - pixbuf_security = gdk_pixbuf_new_from_file (ICONS_DIR "/lock_off.svg", NULL); + WARN("Update calltree srtp state #%d- Should not happen!", c->_srtp_state); + if (g_strcasecmp(srtp_enabled, "true") == 0) + pixbuf_security = gdk_pixbuf_new_from_file(ICONS_DIR "/lock_off.svg", NULL); } - } else if (tab == history) { + } else if (tab == history_tab) { if (parent == NULL) { // parent is NULL this is not a conference participant switch (c->_history_state) { case INCOMING: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/incoming.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/incoming.svg", NULL); break; case OUTGOING: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/outgoing.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/outgoing.svg", NULL); break; case MISSED: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/missed.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/missed.svg", NULL); break; default: - WARN ("History - Should not happen!"); + WARN("History - Should not happen!"); } - } - else // parent is not NULL this is a conference participant + } else // parent is not NULL this is a conference participant pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/current.svg", NULL); + g_free(description); + description = calltree_display_call_info(c, DISPLAY_TYPE_HISTORY, ""); + gchar * date = get_formatted_start_timestamp(c->_time_start); + gchar *duration = get_call_duration(c); + gchar *full_duration = g_strconcat(date , duration , NULL); + g_free(date); + g_free(duration); + gchar *old_description = description; - g_free (old_description); - - description = calltree_display_call_info (c, DISPLAY_TYPE_HISTORY, ""); - gchar * date = get_formatted_start_timestamp (c->_time_start); - gchar *duration = get_call_duration (c); - gchar *full_duration = g_strconcat (date , duration , NULL); - g_free (date); - g_free (duration); - - old_description = description; - description = g_strconcat (old_description , full_duration, NULL); - g_free (full_duration); - g_free (old_description); + description = g_strconcat(old_description , full_duration, NULL); + g_free(full_duration); + g_free(old_description); } - gtk_tree_store_set (store, &iter, - 0, pixbuf, // Icon - 1, description, // Description - 2, pixbuf_security, - 3, c, - -1); + gtk_tree_store_set(store, &iter, + COLUMN_ACCOUNT_PIXBUF, pixbuf, + COLUMN_ACCOUNT_DESC, description, + COLUMN_ACCOUNT_SECURITY_PIXBUF, pixbuf_security, + COLUMN_ACCOUNT_PTR, c, + -1); - g_free (description); + g_free(description); if (pixbuf != NULL) - g_object_unref (G_OBJECT (pixbuf)); + g_object_unref(G_OBJECT(pixbuf)); + if (pixbuf_security != NULL) + g_object_unref(G_OBJECT(pixbuf_security)); } } update_actions(); } +void calltree_update_call(calltab_t* tab, callable_obj_t * c) +{ + return calltree_update_call_recursive(tab, c, NULL); +} -void calltree_add_call (calltab_t* tab, callable_obj_t * c, GtkTreeIter *parent) +void calltree_add_call(calltab_t* tab, callable_obj_t * c, GtkTreeIter *parent) { - if (tab == history) { - calltree_add_history_entry (c, parent); - return; - } + g_assert(tab != history_tab); account_t* account_details = NULL; @@ -811,492 +759,394 @@ void calltree_add_call (calltab_t* tab, callable_obj_t * c, GtkTreeIter *parent) // New call in the list - gchar *description = calltree_display_call_info (c, DISPLAY_TYPE_CALL, ""); + gchar *description = calltree_display_call_info(c, DISPLAY_TYPE_CALL, ""); - gtk_tree_store_prepend (tab->store, &iter, parent); + gtk_tree_store_prepend(tab->store, &iter, parent); if (c) { - account_details = account_list_get_by_id (c->_accountID); + account_details = account_list_get_by_id(c->_accountID); + if (account_details) { - srtp_enabled = g_hash_table_lookup (account_details->properties, ACCOUNT_SRTP_ENABLED); - key_exchange = g_hash_table_lookup (account_details->properties, ACCOUNT_KEY_EXCHANGE); + srtp_enabled = g_hash_table_lookup(account_details->properties, ACCOUNT_SRTP_ENABLED); + key_exchange = g_hash_table_lookup(account_details->properties, ACCOUNT_KEY_EXCHANGE); } } - DEBUG ("Added call key exchange is %s", key_exchange); + DEBUG("Added call key exchange is %s", key_exchange); - if (tab == current_calls) { + if (tab == current_calls_tab) { switch (c->_state) { case CALL_STATE_INCOMING: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/ring.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/ring.svg", NULL); break; case CALL_STATE_DIALING: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/dial.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/dial.svg", NULL); break; case CALL_STATE_RINGING: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/ring.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/ring.svg", NULL); break; case CALL_STATE_CURRENT: // If the call has been initiated by a another client and, when we start, it is already current - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/current.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/current.svg", NULL); break; case CALL_STATE_HOLD: // If the call has been initiated by a another client and, when we start, it is already current - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/hold.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/hold.svg", NULL); break; case CALL_STATE_RECORD: pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/icon_rec.svg", NULL); break; case CALL_STATE_FAILURE: // If the call has been initiated by a another client and, when we start, it is already current - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/fail.svg", NULL); + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/fail.svg", NULL); break; default: - WARN ("Update calltree add - Should not happen!"); + WARN("Update calltree add - Should not happen!"); } - if (srtp_enabled && g_strcasecmp (srtp_enabled, "true") == 0) - pixbuf_security = gdk_pixbuf_new_from_file (ICONS_DIR "/secure_off.svg", NULL); - } else if (tab == contacts) { + if (srtp_enabled && g_strcasecmp(srtp_enabled, "true") == 0) + pixbuf_security = gdk_pixbuf_new_from_file(ICONS_DIR "/secure_off.svg", NULL); + + } else if (tab == contacts_tab) pixbuf = c->_contact_thumbnail; - } else { - WARN ("CallTree: This widget doesn't exist - This is a bug in the application."); - } + else + WARN("CallTree: This widget doesn't exist - This is a bug in the application."); //Resize it - if (pixbuf) - if (gdk_pixbuf_get_width (pixbuf) > 32 || gdk_pixbuf_get_height (pixbuf) > 32) { - GdkPixbuf *new = gdk_pixbuf_scale_simple (pixbuf, 32, 32, GDK_INTERP_BILINEAR); - g_object_unref(pixbuf); - pixbuf = new; - } + if (pixbuf && (gdk_pixbuf_get_width(pixbuf) > 32 || gdk_pixbuf_get_height(pixbuf) > 32)) { + GdkPixbuf *new = gdk_pixbuf_scale_simple(pixbuf, 32, 32, GDK_INTERP_BILINEAR); + g_object_unref(pixbuf); + pixbuf = new; + } - if (pixbuf_security) - if (gdk_pixbuf_get_width (pixbuf_security) > 32 || gdk_pixbuf_get_height (pixbuf_security) > 32) { - GdkPixbuf *new = gdk_pixbuf_scale_simple (pixbuf_security, 32, 32, GDK_INTERP_BILINEAR); - g_object_unref(pixbuf_security); - pixbuf_security = new; - } + if (pixbuf_security && (gdk_pixbuf_get_width(pixbuf_security) > 32 || gdk_pixbuf_get_height(pixbuf_security) > 32)) { + GdkPixbuf *new = gdk_pixbuf_scale_simple(pixbuf_security, 32, 32, GDK_INTERP_BILINEAR); + g_object_unref(pixbuf_security); + pixbuf_security = new; + } - gtk_tree_store_set (tab->store, &iter, - 0, pixbuf, // Icon - 1, description, // Description - 2, pixbuf_security, // Informs user about the state of security - 3, c, // Pointer - -1); + gtk_tree_store_set(tab->store, &iter, + COLUMN_ACCOUNT_PIXBUF, pixbuf, + COLUMN_ACCOUNT_DESC, description, + COLUMN_ACCOUNT_SECURITY_PIXBUF, pixbuf_security, + COLUMN_ACCOUNT_PTR, c, + -1); g_free(description); if (pixbuf != NULL) - g_object_unref (G_OBJECT (pixbuf)); + g_object_unref(G_OBJECT(pixbuf)); if (pixbuf_security != NULL) - g_object_unref (G_OBJECT (pixbuf)); - - gtk_tree_view_set_model (GTK_TREE_VIEW (history->view), GTK_TREE_MODEL (history->store)); + g_object_unref(G_OBJECT(pixbuf)); - gtk_tree_selection_select_iter (gtk_tree_view_get_selection (GTK_TREE_VIEW (tab->view)), &iter); + gtk_tree_view_set_model(GTK_TREE_VIEW(history_tab->view), GTK_TREE_MODEL(history_tab->store)); - //history_init(); + gtk_tree_selection_select_iter(gtk_tree_view_get_selection(GTK_TREE_VIEW(tab->view)), &iter); } -void calltree_add_history_entry (callable_obj_t *c, GtkTreeIter *parent) +void calltree_add_history_entry(callable_obj_t *c) { - if (!eel_gconf_get_integer (HISTORY_ENABLED)) + if (!eel_gconf_get_integer(HISTORY_ENABLED)) return; - GdkPixbuf *pixbuf = NULL; - GtkTreeIter iter; - // New call in the list - gchar *date = NULL; - gchar *duration = NULL; + gchar * description = calltree_display_call_info(c, DISPLAY_TYPE_HISTORY, ""); - gchar * description = calltree_display_call_info (c, DISPLAY_TYPE_HISTORY, ""); + GtkTreeIter iter; + gtk_tree_store_prepend(history_tab->store, &iter, NULL); - gtk_tree_store_prepend (history->store, &iter, parent); + GdkPixbuf *pixbuf = NULL; - if (parent == NULL) { - // this is a first level call not participating to a conference - switch (c->_history_state) { - case INCOMING: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/incoming.svg", NULL); - break; - case OUTGOING: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/outgoing.svg", NULL); - break; - case MISSED: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/missed.svg", NULL); - break; - default: - WARN ("History - Should not happen!"); - } - } - else { - // participant to a conference - pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/current.svg", NULL); + switch (c->_history_state) { + case INCOMING: + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/incoming.svg", NULL); + break; + case OUTGOING: + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/outgoing.svg", NULL); + break; + case MISSED: + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/missed.svg", NULL); + break; + default: + WARN("History - Should not happen!"); } - date = get_formatted_start_timestamp (c->_time_start); - duration = get_call_duration (c); - gchar * full_duration = g_strconcat (date , duration , NULL); - g_free (date); - g_free (duration); - gchar * full_description = g_strconcat (description , full_duration, NULL); - g_free (description); - g_free (full_duration); + gchar *date = get_formatted_start_timestamp(c->_time_start); + gchar *duration = get_call_duration(c); + gchar * full_duration = g_strconcat(date, duration, NULL); + g_free(date); + g_free(duration); + gchar * full_description = g_strconcat(description, full_duration, NULL); + g_free(description); + g_free(full_duration); //Resize it - if (pixbuf) - if (gdk_pixbuf_get_width (pixbuf) > 32 || gdk_pixbuf_get_height (pixbuf) > 32) { - GdkPixbuf *new = gdk_pixbuf_scale_simple (pixbuf, 32, 32, GDK_INTERP_BILINEAR); - g_object_unref(pixbuf); - pixbuf = new; - } + if (pixbuf && (gdk_pixbuf_get_width(pixbuf) > 32 || gdk_pixbuf_get_height(pixbuf) > 32)) { + GdkPixbuf *new = gdk_pixbuf_scale_simple(pixbuf, 32, 32, GDK_INTERP_BILINEAR); + g_object_unref(pixbuf); + pixbuf = new; + } - gtk_tree_store_set (history->store, &iter, - 0, pixbuf, // Icon - 1, full_description, // Description - 2, NULL, // Icon - 3, c, // Pointer - -1); + gtk_tree_store_set(history_tab->store, &iter, + COLUMN_ACCOUNT_PIXBUF, pixbuf, + COLUMN_ACCOUNT_DESC, full_description, + COLUMN_ACCOUNT_SECURITY_PIXBUF, NULL, + COLUMN_ACCOUNT_PTR, c, + -1); - g_free (full_description); + g_free(full_description); if (pixbuf != NULL) - g_object_unref (G_OBJECT (pixbuf)); + g_object_unref(G_OBJECT(pixbuf)); - gtk_tree_view_set_model (GTK_TREE_VIEW (history->view), GTK_TREE_MODEL (history->store)); + gtk_tree_view_set_model(GTK_TREE_VIEW(history_tab->view), GTK_TREE_MODEL(history_tab->store)); history_search(); } -void calltree_add_conference (calltab_t* tab, conference_obj_t* conf) +void calltree_add_conference_to_current_calls(conference_obj_t* conf) { - GdkPixbuf *pixbuf = NULL; - GdkPixbuf *pixbuf_security = NULL; - GtkTreeIter iter; - GtkTreePath *path; - GtkTreeModel *model = (GtkTreeModel*) tab->store; - GSList *conference_participant; - gchar *call_id; - callable_obj_t *call; account_t *account_details = NULL; - gchar *srtp_enabled = ""; - // New call in the list - gchar * description; if (!conf) { - ERROR ("Calltree: Error: Conference is null"); + ERROR("Calltree: Error: Conference is null"); return; } - DEBUG ("Calltree: Add conference %s", conf->_confID); + DEBUG("Calltree: Add conference %s", conf->_confID); - if(tab == history) { - calltree_add_history_conference(conf); - return; - } - - description = g_markup_printf_escaped ("<b>%s</b>", ""); + GtkTreeIter iter; + gtk_tree_store_append(current_calls_tab->store, &iter, NULL); - gtk_tree_store_append (tab->store, &iter, NULL); + GdkPixbuf *pixbuf = NULL; - if (tab == current_calls) { - switch (conf->_state) { - case CONFERENCE_STATE_ACTIVE_ATACHED: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/usersAttached.svg", NULL); - break; - case CONFERENCE_STATE_ACTIVE_DETACHED: - case CONFERENCE_STATE_HOLD: - case CONFERENCE_STATE_HOLD_RECORD: - pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/usersDetached.svg", NULL); - break; - case CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD: - pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/usersAttachedRec.svg", NULL); - break; - case CONFERENCE_STATE_ACTIVE_DETACHED_RECORD: - pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/usersDetachedRec.svg", NULL); - break; - default: - WARN ("Update conference add - Should not happen!"); - } + switch (conf->_state) { + case CONFERENCE_STATE_ACTIVE_ATTACHED: + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/usersAttached.svg", NULL); + break; + case CONFERENCE_STATE_ACTIVE_DETACHED: + case CONFERENCE_STATE_HOLD: + case CONFERENCE_STATE_HOLD_RECORD: + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/usersDetached.svg", NULL); + break; + case CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD: + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/usersAttachedRec.svg", NULL); + break; + case CONFERENCE_STATE_ACTIVE_DETACHED_RECORD: + pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/usersDetachedRec.svg", NULL); + break; + default: + WARN("Update conference add - Should not happen!"); } - else if (tab == history) - pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/usersAttached.svg", NULL); //Resize it if (pixbuf) { - if (gdk_pixbuf_get_width (pixbuf) > 32 || gdk_pixbuf_get_height (pixbuf) > 32) { - GdkPixbuf *new = gdk_pixbuf_scale_simple (pixbuf, 32, 32, GDK_INTERP_BILINEAR); + if (gdk_pixbuf_get_width(pixbuf) > 32 || gdk_pixbuf_get_height(pixbuf) > 32) { + GdkPixbuf *new = gdk_pixbuf_scale_simple(pixbuf, 32, 32, GDK_INTERP_BILINEAR); g_object_unref(pixbuf); pixbuf = new; } } else - DEBUG ("Error no pixbuff for conference from %s", ICONS_DIR); + DEBUG("Error no pixbuff for conference from %s", ICONS_DIR); - if (tab == current_calls) { - - // Used to determine if at least one participant use a security feature - // If true (at least on call use a security feature) we need to display security icons - conf->_conf_srtp_enabled = FALSE; + GdkPixbuf *pixbuf_security = NULL; - // Used to determine if the conference is secured - // Every participant to a conference must be secured, the conference is not secured elsewhere - conf->_conference_secured = TRUE; + // Used to determine if at least one participant use a security feature + // If true (at least on call use a security feature) we need to display security icons + conf->_conf_srtp_enabled = FALSE; - conference_participant = conf->participant_list; - if (conference_participant) { + // Used to determine if the conference is secured + // Every participant to a conference must be secured, the conference is not secured elsewhere + conf->_conference_secured = TRUE; - DEBUG ("Calltree: Determine if at least one participant uses SRTP"); + if (conf->participant_list) { + DEBUG("Calltree: Determine if at least one participant uses SRTP"); - while (conference_participant) { - call_id = (gchar*) (conference_participant->data); - call = calllist_get_call(tab, call_id); - if (call == NULL) { - ERROR("Calltree: Error: Could not find call %s in call list", call_id); - } else { - account_details = account_list_get_by_id (call->_accountID); - if (!account_details) - ERROR("Calltree: Error: Could not find account %s in account list", call->_accountID); - else - srtp_enabled = g_hash_table_lookup (account_details->properties, ACCOUNT_SRTP_ENABLED); - - if (g_strcasecmp (srtp_enabled, "true") == 0) { - DEBUG ("Calltree: SRTP enabled for participant %s", call_id); - conf->_conf_srtp_enabled = TRUE; - break; - } - else - DEBUG ("Calltree: SRTP is not enabled for participant %s", call_id); - } + for (GSList *part = conf->participant_list; part; part = g_slist_next(part)) { + const gchar * const call_id = (gchar *) part->data; + callable_obj_t *call = calllist_get_call(current_calls_tab, call_id); - conference_participant = conference_next_participant (conference_participant); - } + if (call == NULL) + ERROR("Calltree: Error: Could not find call %s in call list", call_id); + else { + account_details = account_list_get_by_id(call->_accountID); + gchar *srtp_enabled = ""; - DEBUG ("Calltree: Determine if all conference participant are secured"); + if (!account_details) + ERROR("Calltree: Error: Could not find account %s in account list", call->_accountID); + else + srtp_enabled = g_hash_table_lookup(account_details->properties, ACCOUNT_SRTP_ENABLED); - if (conf->_conf_srtp_enabled) { - conference_participant = conf->participant_list; + if (g_strcasecmp(srtp_enabled, "true") == 0) { + DEBUG("Calltree: SRTP enabled for participant %s", call_id); + conf->_conf_srtp_enabled = TRUE; + break; + } else + DEBUG("Calltree: SRTP is not enabled for participant %s", call_id); + } + } - while (conference_participant) { - call_id = (gchar*) (conference_participant->data); - call = calllist_get_call(tab, call_id); + DEBUG("Calltree: Determine if all conference participants are secured"); - if (call) { - if (call->_srtp_state == SRTP_STATE_UNLOCKED) { - DEBUG ("Calltree: Participant %s is not secured", call_id); - conf->_conference_secured = FALSE; - break; - } - else - DEBUG ("Calltree: Participant %s is secured", call_id); - } - - conference_participant = conference_next_participant (conference_participant); + if (conf->_conf_srtp_enabled) { + for (GSList *part = conf->participant_list; part; part = g_slist_next(part)) { + const gchar * const call_id = (gchar *) part->data; + callable_obj_t *call = calllist_get_call(current_calls_tab, call_id); + + if (call) { + if (call->_srtp_state == SRTP_STATE_UNLOCKED) { + DEBUG("Calltree: Participant %s is not secured", call_id); + conf->_conference_secured = FALSE; + break; + } else + DEBUG("Calltree: Participant %s is secured", call_id); } } } + } - if (conf->_conf_srtp_enabled) { - if (conf->_conference_secured) { - DEBUG ("Calltree: Conference is secured"); - pixbuf_security = gdk_pixbuf_new_from_file (ICONS_DIR "/lock_confirmed.svg", NULL); - } else { - DEBUG ("Calltree: Conference is not secured"); - pixbuf_security = gdk_pixbuf_new_from_file (ICONS_DIR "/lock_off.svg", NULL); - } + if (conf->_conf_srtp_enabled) { + if (conf->_conference_secured) { + DEBUG("Calltree: Conference is secured"); + pixbuf_security = gdk_pixbuf_new_from_file(ICONS_DIR "/lock_confirmed.svg", NULL); + } else { + DEBUG("Calltree: Conference is not secured"); + pixbuf_security = gdk_pixbuf_new_from_file(ICONS_DIR "/lock_off.svg", NULL); } } - DEBUG ("Calltree: Add conference to tree store"); + DEBUG("Calltree: Add conference to tree store"); - gtk_tree_store_set (tab->store, &iter, - 0, pixbuf, // Icon - 1, description, // Description - 2, pixbuf_security, - 3, conf, // Pointer - -1); + gchar *description = g_markup_printf_escaped("<b>%s</b>", ""); + gtk_tree_store_set(current_calls_tab->store, &iter, + COLUMN_ACCOUNT_PIXBUF, pixbuf, + COLUMN_ACCOUNT_DESC, description, + COLUMN_ACCOUNT_SECURITY_PIXBUF, pixbuf_security, + COLUMN_ACCOUNT_PTR, conf, + -1); + g_free(description); if (pixbuf) - g_object_unref (G_OBJECT (pixbuf)); - - conference_participant = conf->participant_list; + g_object_unref(pixbuf); - while (conference_participant) { - call_id = (gchar*) (conference_participant->data); - call = calllist_get_call(tab, call_id); + if (pixbuf_security) + g_object_unref(pixbuf_security); - calltree_remove_call (tab, call, NULL); - calltree_add_call (tab, call, &iter); + for (GSList *part = conf->participant_list; part; part = g_slist_next(part)) { + const gchar * const call_id = (gchar *) part->data; + callable_obj_t *call = calllist_get_call(current_calls_tab, call_id); - conference_participant = conference_next_participant (conference_participant); + calltree_remove_call(current_calls_tab, call); + calltree_add_call(current_calls_tab, call, &iter); } - gtk_tree_view_set_model (GTK_TREE_VIEW (tab->view), GTK_TREE_MODEL (tab->store)); + gtk_tree_view_set_model(GTK_TREE_VIEW(current_calls_tab->view), + GTK_TREE_MODEL(current_calls_tab->store)); - path = gtk_tree_model_get_path (model, &iter); + GtkTreePath *path = gtk_tree_model_get_path(GTK_TREE_MODEL(current_calls_tab->store), &iter); - gtk_tree_view_expand_row (GTK_TREE_VIEW (tab->view), path, FALSE); + gtk_tree_view_expand_row(GTK_TREE_VIEW(current_calls_tab->view), path, FALSE); update_actions(); } -void calltree_update_conference (calltab_t* tab, const conference_obj_t* conf) +static +void calltree_remove_conference_recursive(calltab_t* tab, const conference_obj_t* conf, GtkTreeIter *parent) { - DEBUG ("CallTree: Update conference %s", conf->_confID); - - calltree_remove_conference(tab, conf, NULL); - calltree_add_conference (tab, (conference_obj_t *)conf); -} + GtkTreeModel *model = GTK_TREE_MODEL(tab->store); + int nbChildren = gtk_tree_model_iter_n_children(model, parent); + for (int i = 0; i < nbChildren; i++) { + GtkTreeIter iter_parent; -void calltree_remove_conference (calltab_t* tab, const conference_obj_t* conf, GtkTreeIter *parent) -{ - GtkTreeIter iter_parent; - GtkTreeIter iter_child; - GValue confval; - GValue callval; - conference_obj_t *tempconf = NULL; - GtkTreeStore* store = tab->store; - int nbParticipant; + /* if the nth child of parent has one or more children */ + if (gtk_tree_model_iter_nth_child(model, &iter_parent, parent, i)) { + /* RECURSION! */ + if (gtk_tree_model_iter_has_child(model, &iter_parent)) + calltree_remove_conference_recursive(tab, conf, &iter_parent); - DEBUG ("CallTree: Remove conference %s", conf->_confID); + GValue confval; + confval.g_type = 0; + gtk_tree_model_get_value(model, &iter_parent, COLUMN_ACCOUNT_PTR, &confval); - int nbChild = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (store), parent); + conference_obj_t *tempconf = (conference_obj_t*) g_value_get_pointer(&confval); + g_value_unset(&confval); - for (int i = 0; i < nbChild; i++) { - if (!gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (store), &iter_parent, parent, i)) - continue; - if (!gtk_tree_model_iter_has_child (GTK_TREE_MODEL (store), &iter_parent)) - continue; + /* if this is the conference we want to remove */ + if (tempconf == conf) { + int nbParticipants = gtk_tree_model_iter_n_children(model, &iter_parent); + DEBUG("CallTree: nbParticipants: %d", nbParticipants); - calltree_remove_conference (tab, conf, &iter_parent); + for (int j = 0; j < nbParticipants; j++) { + GtkTreeIter iter_child; - confval.g_type = 0; - gtk_tree_model_get_value (GTK_TREE_MODEL (store), &iter_parent, COLUMN_ACCOUNT_PTR, &confval); + if (gtk_tree_model_iter_nth_child(model, &iter_child, &iter_parent, j)) { + GValue callval; + callval.g_type = 0; + gtk_tree_model_get_value(model, &iter_child, COLUMN_ACCOUNT_PTR, &callval); - tempconf = (conference_obj_t*) g_value_get_pointer (&confval); - g_value_unset (&confval); + callable_obj_t *call = g_value_get_pointer(&callval); + g_value_unset(&callval); - if (tempconf != conf) - continue; - - nbParticipant = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (store), &iter_parent); - DEBUG ("CallTree: nbParticipant: %d", nbParticipant); - - for (int j = 0; j < nbParticipant; j++) { - if (!gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (store), &iter_child, &iter_parent, j)) - continue; - - callval.g_type = 0; - gtk_tree_model_get_value (GTK_TREE_MODEL (store), &iter_child, COLUMN_ACCOUNT_PTR, &callval); - - callable_obj_t *call = g_value_get_pointer (&callval); - g_value_unset (&callval); + // do not add back call in history calltree when cleaning it + if (call && tab != history_tab) + calltree_add_call(tab, call, NULL); + } + } - // do not add back call in history calltree when cleaning it - if (call && tab != history) - calltree_add_call (tab, call, NULL); + DEBUG("CallTree: Remove conference %s", conf->_confID); + gtk_tree_store_remove(tab->store, &iter_parent); + } } - - gtk_tree_store_remove (store, &iter_parent); } + if (calltab_get_selected_conf(tab) == conf) + calltab_select_conf(tab, NULL); + update_actions(); } -void calltree_add_history_conference(conference_obj_t *conf) +void calltree_remove_conference(calltab_t* tab, const conference_obj_t* conf) { - GdkPixbuf *pixbuf = NULL; - const gchar *description = "Conference: \n"; - GtkTreeIter iter; - GSList *conference_participant; - - if (!conf) - ERROR("CallTree: Error conference is NULL"); - - DEBUG("CallTree: Add conference %s to history", conf->_confID); - - gtk_tree_store_prepend(history->store, &iter, NULL); - - pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/usersAttached.svg", NULL); - - if (pixbuf) - if (gdk_pixbuf_get_width(pixbuf) > 32 || gdk_pixbuf_get_height(pixbuf) > 32) { - GdkPixbuf *new = gdk_pixbuf_scale_simple(pixbuf, 32, 32, GDK_INTERP_BILINEAR); - g_object_unref(pixbuf); - pixbuf = new; - } - - const gchar * const date = get_formatted_start_timestamp(conf->_time_start); - description = g_strconcat(description, date, NULL); - gtk_tree_store_set(history->store, &iter, 0, pixbuf, 1, description, 2, NULL, 3, conf, -1); - - conference_participant = conf->participant_list; - while (conference_participant) { - const gchar * const call_id = (gchar *)(conference_participant->data); - callable_obj_t *call = calllist_get_call(history, call_id); - if (call) - calltree_add_history_entry(call, &iter); - else - ERROR("ConferenceList: Error: Could not find call \"%s\"", call_id); - - conference_participant = conference_next_participant(conference_participant); - } - - if(pixbuf != NULL) - g_object_unref(G_OBJECT(pixbuf)); + DEBUG("CallTree: Remove conference %s", conf->_confID); + calltree_remove_conference_recursive(tab, conf, NULL); + DEBUG("CallTree: Finished Removing conference"); } - -void calltree_display (calltab_t *tab) +void calltree_display(calltab_t *tab) { - GtkTreeSelection *sel; - /* If we already are displaying the specified calltree */ - if (active_calltree == tab) + if (active_calltree_tab == tab) return; - /* case 1: we want to display the main calltree */ - if (tab==current_calls) { - DEBUG ("CallTree: Display main tab"); - - if (active_calltree==contacts) - gtk_toggle_tool_button_set_active ( (GtkToggleToolButton*) contactButton_, FALSE); + if (tab == current_calls_tab) { + if (active_calltree_tab == contacts_tab) + gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(contactButton_), FALSE); else - gtk_toggle_tool_button_set_active ( (GtkToggleToolButton*) historyButton_, FALSE); - } - - /* case 2: we want to display the history */ - else if (tab == history) { - DEBUG ("ConferenceList: Display history tab"); - if (active_calltree == contacts) - gtk_toggle_tool_button_set_active((GtkToggleToolButton*) contactButton_, FALSE); - - gtk_toggle_tool_button_set_active((GtkToggleToolButton*) historyButton_, TRUE); - } - else if (tab==contacts) { - DEBUG ("CallTree: Display contact tab"); - - if (active_calltree == history) - gtk_toggle_tool_button_set_active((GtkToggleToolButton*) historyButton_, FALSE); + gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(historyButton_), FALSE); + } else if (tab == history_tab) { + if (active_calltree_tab == contacts_tab) + gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(contactButton_), FALSE); - gtk_toggle_tool_button_set_active((GtkToggleToolButton*) contactButton_, TRUE); + gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(historyButton_), TRUE); + } else if (tab == contacts_tab) { + if (active_calltree_tab == history_tab) + gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(historyButton_), FALSE); + gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(contactButton_), TRUE); set_focus_on_addressbook_searchbar(); - } - else - ERROR ("CallTree: Error: Not a valid call tab (%d, %s)", __LINE__, __FILE__); + } else + ERROR("CallTree: Error: Not a valid call tab (%d, %s)", __LINE__, __FILE__); - gtk_widget_hide (active_calltree->tree); - active_calltree = tab; - gtk_widget_show (active_calltree->tree); + gtk_widget_hide(active_calltree_tab->tree); + active_calltree_tab = tab; + gtk_widget_show(active_calltree_tab->tree); - sel = gtk_tree_view_get_selection (GTK_TREE_VIEW (active_calltree->view)); - DEBUG ("CallTree: Emit signal changed from calltree_display"); - g_signal_emit_by_name (sel, "changed"); + GtkTreeSelection *sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(active_calltree_tab->view)); + DEBUG("CallTree: Emit signal changed from calltree_display"); + g_signal_emit_by_name(sel, "changed"); update_actions(); } @@ -1306,56 +1156,57 @@ gboolean calltree_update_clock(gpointer data UNUSED) char timestr[20]; const gchar *msg = ""; long duration; - callable_obj_t *c = calltab_get_selected_call (current_calls); + callable_obj_t *c = calltab_get_selected_call(current_calls_tab); if (c) switch (c->_state) { - case CALL_STATE_INVALID: - case CALL_STATE_INCOMING: - case CALL_STATE_RINGING: - case CALL_STATE_FAILURE: - case CALL_STATE_DIALING: - case CALL_STATE_BUSY: - break; - default: - duration = difftime (time(NULL), c->_time_start); - if (duration < 0) - duration = 0; - g_snprintf (timestr, sizeof(timestr), "%.2ld:%.2ld", duration / 60, duration % 60); - msg = timestr; + case CALL_STATE_INVALID: + case CALL_STATE_INCOMING: + case CALL_STATE_RINGING: + case CALL_STATE_FAILURE: + case CALL_STATE_DIALING: + case CALL_STATE_BUSY: + break; + default: + duration = difftime(time(NULL), c->_time_start); + + if (duration < 0) + duration = 0; + + g_snprintf(timestr, sizeof(timestr), "%.2ld:%.2ld", duration / 60, duration % 60); + msg = timestr; + break; } - statusbar_update_clock (msg); + statusbar_update_clock(msg); return TRUE; } -static void drag_end_cb (GtkWidget * widget UNUSED, GdkDragContext * context UNUSED, gpointer data UNUSED) +static void drag_end_cb(GtkWidget * widget UNUSED, GdkDragContext * context UNUSED, gpointer data UNUSED) { - if(active_calltree == history) + if (active_calltree_tab == history_tab) return; - DEBUG ("CallTree: Drag end callback"); - DEBUG ("CallTree: selected_path %s, selected_call_id %s, selected_path_depth %d", - calltree_selected_path, calltree_selected_call_id, calltree_selected_path_depth); - DEBUG ("CallTree: dragged path %s, dragged_call_id %s, dragged_path_depth %d", - calltree_dragged_path, calltree_dragged_call_id, calltree_dragged_path_depth); + DEBUG("CallTree: Drag end callback"); + DEBUG("CallTree: selected_path %s, selected_call_id %s, selected_path_depth %d", + calltree_selected_path, calltree_selected_call_id, calltree_selected_path_depth); + DEBUG("CallTree: dragged path %s, dragged_call_id %s, dragged_path_depth %d", + calltree_dragged_path, calltree_dragged_call_id, calltree_dragged_path_depth); - GtkTreeModel *model = (GtkTreeModel*) current_calls->store; - GtkTreePath *path = gtk_tree_path_new_from_string (calltree_dragged_path); - GtkTreePath *dpath = gtk_tree_path_new_from_string (calltree_dragged_path); - GtkTreePath *spath = gtk_tree_path_new_from_string (calltree_selected_path); + GtkTreeModel *model = (GtkTreeModel*) current_calls_tab->store; + GtkTreePath *path = gtk_tree_path_new_from_string(calltree_dragged_path); + GtkTreePath *dpath = gtk_tree_path_new_from_string(calltree_dragged_path); + GtkTreePath *spath = gtk_tree_path_new_from_string(calltree_selected_path); GtkTreeIter iter; GtkTreeIter parent_conference; // conference for which this call is attached GValue val; - conference_obj_t* conf; - // Make sure drag n drop does not imply a dialing call for either selected and dragged call if (calltree_selected_call && (calltree_selected_type == A_CALL)) { - DEBUG ("CallTree: Selected a call"); + DEBUG("CallTree: Selected a call"); if (calltree_selected_call->_state == CALL_STATE_DIALING || calltree_selected_call->_state == CALL_STATE_INVALID || @@ -1363,10 +1214,10 @@ static void drag_end_cb (GtkWidget * widget UNUSED, GdkDragContext * context UNU calltree_selected_call->_state == CALL_STATE_BUSY || calltree_selected_call->_state == CALL_STATE_TRANSFER) { - DEBUG ("CallTree: Selected an invalid call"); + DEBUG("CallTree: Selected an invalid call"); - calltree_remove_call (current_calls, calltree_selected_call, NULL); - calltree_add_call (current_calls, calltree_selected_call, NULL); + calltree_remove_call(current_calls_tab, calltree_selected_call); + calltree_add_call(current_calls_tab, calltree_selected_call, NULL); calltree_dragged_call = NULL; return; @@ -1375,7 +1226,7 @@ static void drag_end_cb (GtkWidget * widget UNUSED, GdkDragContext * context UNU if (calltree_dragged_call && (calltree_dragged_type == A_CALL)) { - DEBUG ("CallTree: Dragged on a call"); + DEBUG("CallTree: Dragged on a call"); if (calltree_dragged_call->_state == CALL_STATE_DIALING || calltree_dragged_call->_state == CALL_STATE_INVALID || @@ -1383,18 +1234,18 @@ static void drag_end_cb (GtkWidget * widget UNUSED, GdkDragContext * context UNU calltree_dragged_call->_state == CALL_STATE_BUSY || calltree_dragged_call->_state == CALL_STATE_TRANSFER) { - DEBUG ("CallTree: Dragged on an invalid call"); + DEBUG("CallTree: Dragged on an invalid call"); - calltree_remove_call (current_calls, calltree_selected_call, NULL); + calltree_remove_call(current_calls_tab, calltree_selected_call); if (calltree_selected_call->_confID) { - gtk_tree_path_up (spath); - gtk_tree_model_get_iter (GTK_TREE_MODEL (model), &parent_conference, spath); + gtk_tree_path_up(spath); + gtk_tree_model_get_iter(GTK_TREE_MODEL(model), &parent_conference, spath); - calltree_add_call (current_calls, calltree_selected_call, &parent_conference); + calltree_add_call(current_calls_tab, calltree_selected_call, &parent_conference); } else - calltree_add_call (current_calls, calltree_selected_call, NULL); + calltree_add_call(current_calls_tab, calltree_selected_call, NULL); calltree_dragged_call = NULL; return; @@ -1405,16 +1256,15 @@ static void drag_end_cb (GtkWidget * widget UNUSED, GdkDragContext * context UNU // Make sure a conference is only dragged on another conference if (calltree_selected_conf && (calltree_selected_type == A_CONFERENCE)) { - DEBUG ("CallTree: Selected a conference"); + DEBUG("CallTree: Selected a conference"); if (!calltree_dragged_conf && (calltree_dragged_type == A_CALL)) { - DEBUG ("CallTree: Dragged on a call"); + DEBUG("CallTree: Dragged on a call"); + conference_obj_t* conf = calltree_selected_conf; - conf = calltree_selected_conf; - - calltree_remove_conference (current_calls, conf, NULL); - calltree_add_conference (current_calls, conf); + calltree_remove_conference(current_calls_tab, conf); + calltree_add_conference_to_current_calls(conf); calltree_dragged_call = NULL; return; @@ -1425,59 +1275,59 @@ static void drag_end_cb (GtkWidget * widget UNUSED, GdkDragContext * context UNU if (calltree_selected_path_depth == 1) { if (calltree_dragged_path_depth == 1) { if (calltree_selected_type == A_CALL && calltree_dragged_type == A_CALL) { - if (gtk_tree_path_compare (dpath, spath) != 0) { + if (gtk_tree_path_compare(dpath, spath) != 0) { // dragged a single call on a single call if (calltree_selected_call != NULL && calltree_dragged_call != NULL) { - calltree_remove_call (current_calls, calltree_selected_call, NULL); - calltree_add_call (current_calls, calltree_selected_call, NULL); - gtk_menu_popup (GTK_MENU (calltree_popupmenu), NULL, NULL, NULL, NULL, - 0, 0); + calltree_remove_call(current_calls_tab, calltree_selected_call); + calltree_add_call(current_calls_tab, calltree_selected_call, NULL); + gtk_menu_popup(GTK_MENU(calltree_popupmenu), NULL, NULL, NULL, NULL, + 0, 0); } } } else if (calltree_selected_type == A_CALL && calltree_dragged_type == A_CONFERENCE) { // dragged a single call on a conference if (!calltree_selected_call) { - DEBUG ("Error: call dragged on a conference is null"); + DEBUG("Error: call dragged on a conference is null"); return; } - g_free (calltree_selected_call->_confID); - calltree_selected_call->_confID = g_strdup (calltree_dragged_call_id); + g_free(calltree_selected_call->_confID); + calltree_selected_call->_confID = g_strdup(calltree_dragged_call_id); - g_free (calltree_selected_call->_historyConfID); + g_free(calltree_selected_call->_historyConfID); calltree_selected_call->_historyConfID = g_strdup(calltree_dragged_call_id); - sflphone_add_participant (calltree_selected_call_id, calltree_dragged_call_id); + sflphone_add_participant(calltree_selected_call_id, calltree_dragged_call_id); } else if (calltree_selected_type == A_CONFERENCE && calltree_dragged_type == A_CALL) { // dragged a conference on a single call - conf = calltree_selected_conf; + conference_obj_t* conf = calltree_selected_conf; - calltree_remove_conference (current_calls, conf, NULL); - calltree_add_conference (current_calls, conf); + calltree_remove_conference(current_calls_tab, conf); + calltree_add_conference_to_current_calls(conf); } else if (calltree_selected_type == A_CONFERENCE && calltree_dragged_type == A_CONFERENCE) { // dragged a conference on a conference - if (gtk_tree_path_compare (dpath, spath) == 0) { + if (gtk_tree_path_compare(dpath, spath) == 0) { - if (!current_calls) { - DEBUG ("Error while joining the same conference\n"); + if (!current_calls_tab) { + DEBUG("Error while joining the same conference\n"); return; } - DEBUG ("Joined the same conference!\n"); - gtk_tree_view_expand_row (GTK_TREE_VIEW (current_calls->view), path, FALSE); + DEBUG("Joined the same conference!\n"); + gtk_tree_view_expand_row(GTK_TREE_VIEW(current_calls_tab->view), path, FALSE); } else { if (!calltree_selected_conf) - DEBUG ("Error: selected conference is null while joining 2 conference"); + DEBUG("Error: selected conference is null while joining 2 conference"); if (!calltree_dragged_conf) - DEBUG ("Error: dragged conference is null while joining 2 conference"); + DEBUG("Error: dragged conference is null while joining 2 conference"); - DEBUG ("Joined two conference %s, %s!\n", calltree_dragged_path, calltree_selected_path); - sflphone_join_conference (calltree_selected_conf->_confID, calltree_dragged_conf->_confID); + DEBUG("Joined conferences %s and %s!\n", calltree_dragged_path, calltree_selected_path); + dbus_join_conference(calltree_selected_conf->_confID, calltree_dragged_conf->_confID); } } @@ -1488,13 +1338,13 @@ static void drag_end_cb (GtkWidget * widget UNUSED, GdkDragContext * context UNU // dragged_path_depth == 2 if (calltree_selected_type == A_CALL && calltree_dragged_type == A_CALL) { // TODO: dragged a call on a conference call - calltree_remove_call (current_calls, calltree_selected_call, NULL); - calltree_add_call (current_calls, calltree_selected_call, NULL); + calltree_remove_call(current_calls_tab, calltree_selected_call); + calltree_add_call(current_calls_tab, calltree_selected_call, NULL); } else if (calltree_selected_type == A_CONFERENCE && calltree_dragged_type == A_CALL) { // TODO: dragged a conference on a conference call - calltree_remove_conference (current_calls, calltree_selected_conf, NULL); - calltree_add_conference (current_calls, calltree_selected_conf); + calltree_remove_conference(current_calls_tab, calltree_selected_conf); + calltree_add_conference_to_current_calls(calltree_selected_conf); } // TODO: dragged a single call on a NULL element @@ -1503,75 +1353,66 @@ static void drag_end_cb (GtkWidget * widget UNUSED, GdkDragContext * context UNU } else { if (calltree_dragged_path_depth == 1) { - if (calltree_selected_type == A_CALL && calltree_dragged_type == A_CALL) { // dragged a conference call on a call - sflphone_detach_participant (calltree_selected_call_id); + sflphone_detach_participant(calltree_selected_call_id); if (calltree_selected_call && calltree_dragged_call) - gtk_menu_popup (GTK_MENU (calltree_popupmenu), NULL, NULL, NULL, NULL, - 0, 0); + gtk_menu_popup(GTK_MENU(calltree_popupmenu), NULL, NULL, NULL, NULL, + 0, 0); } else if (calltree_selected_type == A_CALL && calltree_dragged_type == A_CONFERENCE) { // dragged a conference call on a conference - sflphone_detach_participant (calltree_selected_call_id); + sflphone_detach_participant(calltree_selected_call_id); if (calltree_selected_call && calltree_dragged_conf) { - DEBUG ("Adding a participant, since dragged call on a conference"); - sflphone_add_participant (calltree_selected_call_id, calltree_dragged_call_id); + DEBUG("Adding a participant, since dragged call on a conference"); + sflphone_add_participant(calltree_selected_call_id, calltree_dragged_call_id); } } else { // dragged a conference call on a NULL element - sflphone_detach_participant (calltree_selected_call_id); + sflphone_detach_participant(calltree_selected_call_id); } } else { - // dragged_path_depth == 2 // dragged a conference call on another conference call (same conference) // TODO: dragged a conference call on another conference call (different conference) - gtk_tree_path_up (path); - - gtk_tree_model_get_iter (GTK_TREE_MODEL (model), &parent_conference, path); + gtk_tree_path_up(path); + gtk_tree_model_get_iter(GTK_TREE_MODEL(model), &parent_conference, path); - gtk_tree_path_up (dpath); - gtk_tree_path_up (spath); + gtk_tree_path_up(dpath); + gtk_tree_path_up(spath); - if (gtk_tree_path_compare (dpath, spath) == 0) { + if (gtk_tree_path_compare(dpath, spath) == 0) { - DEBUG ("Dragged a call in the same conference"); - calltree_remove_call (current_calls, calltree_selected_call, NULL); - calltree_add_call (current_calls, calltree_selected_call, &parent_conference); + DEBUG("Dragged a call in the same conference"); + calltree_remove_call(current_calls_tab, calltree_selected_call); + calltree_add_call(current_calls_tab, calltree_selected_call, &parent_conference); gtk_widget_hide(calltree_menu_items); - gtk_menu_popup (GTK_MENU (calltree_popupmenu), NULL, NULL, NULL, NULL, - 0, 0); + gtk_menu_popup(GTK_MENU(calltree_popupmenu), NULL, NULL, NULL, NULL, + 0, 0); } else { - DEBUG ("Dragged a conference call onto another conference call %s, %s", gtk_tree_path_to_string (dpath), gtk_tree_path_to_string (spath)); - - conf = NULL; + DEBUG("Dragged a conference call onto another conference call %s, %s", gtk_tree_path_to_string(dpath), gtk_tree_path_to_string(spath)); + conference_obj_t *conf = NULL; val.g_type = 0; - if (gtk_tree_model_get_iter (model, &iter, dpath)) { - - DEBUG ("we got an iter!"); - gtk_tree_model_get_value (model, &iter, COLUMN_ACCOUNT_PTR, &val); - - conf = (conference_obj_t*) g_value_get_pointer (&val); + if (gtk_tree_model_get_iter(model, &iter, dpath)) { + gtk_tree_model_get_value(model, &iter, COLUMN_ACCOUNT_PTR, &val); + conf = (conference_obj_t*) g_value_get_pointer(&val); } - g_value_unset (&val); + g_value_unset(&val); - sflphone_detach_participant (calltree_selected_call_id); + sflphone_detach_participant(calltree_selected_call_id); - if (conf) { - DEBUG ("we got a conf!"); - sflphone_add_participant (calltree_selected_call_id, conf->_confID); - } + if (conf) + sflphone_add_participant(calltree_selected_call_id, conf->_confID); else - DEBUG ("didn't find a conf!"); + DEBUG("didn't find a conf!"); } // TODO: dragged a conference call on another conference call (different conference) @@ -1581,42 +1422,42 @@ static void drag_end_cb (GtkWidget * widget UNUSED, GdkDragContext * context UNU } } -void drag_history_received_cb (GtkWidget *widget, GdkDragContext *context UNUSED, gint x UNUSED, gint y UNUSED, GtkSelectionData *selection_data UNUSED, guint info UNUSED, guint t UNUSED, gpointer data UNUSED) +void drag_history_received_cb(GtkWidget *widget, GdkDragContext *context UNUSED, gint x UNUSED, gint y UNUSED, GtkSelectionData *selection_data UNUSED, guint info UNUSED, guint t UNUSED, gpointer data UNUSED) { - g_signal_stop_emission_by_name(G_OBJECT(widget), "drag_data_received"); + g_signal_stop_emission_by_name(G_OBJECT(widget), "drag_data_received"); } -void drag_data_received_cb (GtkWidget *widget, GdkDragContext *context UNUSED, gint x UNUSED, gint y UNUSED, GtkSelectionData *selection_data UNUSED, guint info UNUSED, guint t UNUSED, gpointer data UNUSED) +void drag_data_received_cb(GtkWidget *widget, GdkDragContext *context UNUSED, gint x UNUSED, gint y UNUSED, GtkSelectionData *selection_data UNUSED, guint info UNUSED, guint t UNUSED, gpointer data UNUSED) { - GtkTreeView *tree_view = GTK_TREE_VIEW (widget); + GtkTreeView *tree_view = GTK_TREE_VIEW(widget); GtkTreePath *drop_path; GtkTreeViewDropPosition position; GValue val; - if(active_calltree == history) { + if (active_calltree_tab == history_tab) { g_signal_stop_emission_by_name(G_OBJECT(widget), "drag_data_received"); return; } - GtkTreeModel* tree_model = gtk_tree_view_get_model (tree_view); + GtkTreeModel* tree_model = gtk_tree_view_get_model(tree_view); GtkTreeIter iter; val.g_type = 0; - gtk_tree_view_get_drag_dest_row (tree_view, &drop_path, &position); + gtk_tree_view_get_drag_dest_row(tree_view, &drop_path, &position); if (drop_path) { - gtk_tree_model_get_iter (tree_model, &iter, drop_path); - gtk_tree_model_get_value (tree_model, &iter, COLUMN_ACCOUNT_PTR, &val); + gtk_tree_model_get_iter(tree_model, &iter, drop_path); + gtk_tree_model_get_value(tree_model, &iter, COLUMN_ACCOUNT_PTR, &val); - if (gtk_tree_model_iter_has_child (tree_model, &iter)) { - DEBUG ("CallTree: Dragging on a conference"); + if (gtk_tree_model_iter_has_child(tree_model, &iter)) { + DEBUG("CallTree: Dragging on a conference"); calltree_dragged_type = A_CONFERENCE; calltree_dragged_call = NULL; } else { - DEBUG ("CallTree: Dragging on a call"); + DEBUG("CallTree: Dragging on a call"); calltree_dragged_type = A_CALL; calltree_dragged_conf = NULL; } @@ -1624,105 +1465,79 @@ void drag_data_received_cb (GtkWidget *widget, GdkDragContext *context UNUSED, g switch (position) { case GTK_TREE_VIEW_DROP_AFTER: - DEBUG ("CallTree: GTK_TREE_VIEW_DROP_AFTER"); - calltree_dragged_path = gtk_tree_path_to_string (drop_path); - calltree_dragged_path_depth = gtk_tree_path_get_depth (drop_path); + DEBUG("CallTree: GTK_TREE_VIEW_DROP_AFTER"); + calltree_dragged_path = gtk_tree_path_to_string(drop_path); + calltree_dragged_path_depth = gtk_tree_path_get_depth(drop_path); calltree_dragged_call_id = "NULL"; calltree_dragged_call = NULL; calltree_dragged_conf = NULL; break; case GTK_TREE_VIEW_DROP_INTO_OR_AFTER: - DEBUG ("CallTree: GTK_TREE_VIEW_DROP_INTO_OR_AFTER"); - calltree_dragged_path = gtk_tree_path_to_string (drop_path); - calltree_dragged_path_depth = gtk_tree_path_get_depth (drop_path); + DEBUG("CallTree: GTK_TREE_VIEW_DROP_INTO_OR_AFTER"); + calltree_dragged_path = gtk_tree_path_to_string(drop_path); + calltree_dragged_path_depth = gtk_tree_path_get_depth(drop_path); if (calltree_dragged_type == A_CALL) { - calltree_dragged_call_id = ( (callable_obj_t*) g_value_get_pointer (&val))->_callID; - calltree_dragged_call = (callable_obj_t*) g_value_get_pointer (&val); + calltree_dragged_call_id = ((callable_obj_t*) g_value_get_pointer(&val))->_callID; + calltree_dragged_call = (callable_obj_t*) g_value_get_pointer(&val); } else { - calltree_dragged_call_id = ( (conference_obj_t*) g_value_get_pointer (&val))->_confID; - calltree_dragged_conf = (conference_obj_t*) g_value_get_pointer (&val); + calltree_dragged_call_id = ((conference_obj_t*) g_value_get_pointer(&val))->_confID; + calltree_dragged_conf = (conference_obj_t*) g_value_get_pointer(&val); } break; case GTK_TREE_VIEW_DROP_BEFORE: - DEBUG ("CallTree: GTK_TREE_VIEW_DROP_BEFORE"); - calltree_dragged_path = gtk_tree_path_to_string (drop_path); - calltree_dragged_path_depth = gtk_tree_path_get_depth (drop_path); + DEBUG("CallTree: GTK_TREE_VIEW_DROP_BEFORE"); + calltree_dragged_path = gtk_tree_path_to_string(drop_path); + calltree_dragged_path_depth = gtk_tree_path_get_depth(drop_path); calltree_dragged_call_id = "NULL"; calltree_dragged_call = NULL; calltree_dragged_conf = NULL; break; case GTK_TREE_VIEW_DROP_INTO_OR_BEFORE: - DEBUG ("CallTree: GTK_TREE_VIEW_DROP_INTO_OR_BEFORE"); - calltree_dragged_path = gtk_tree_path_to_string (drop_path); - calltree_dragged_path_depth = gtk_tree_path_get_depth (drop_path); + DEBUG("CallTree: GTK_TREE_VIEW_DROP_INTO_OR_BEFORE"); + calltree_dragged_path = gtk_tree_path_to_string(drop_path); + calltree_dragged_path_depth = gtk_tree_path_get_depth(drop_path); if (calltree_dragged_type == A_CALL) { - calltree_dragged_call_id = ( (callable_obj_t*) g_value_get_pointer (&val))->_callID; - calltree_dragged_call = (callable_obj_t*) g_value_get_pointer (&val); + calltree_dragged_call_id = ((callable_obj_t*) g_value_get_pointer(&val))->_callID; + calltree_dragged_call = (callable_obj_t*) g_value_get_pointer(&val); } else { - calltree_dragged_call_id = ( (conference_obj_t*) g_value_get_pointer (&val))->_confID; - calltree_dragged_conf = (conference_obj_t*) g_value_get_pointer (&val); + calltree_dragged_call_id = ((conference_obj_t*) g_value_get_pointer(&val))->_confID; + calltree_dragged_conf = (conference_obj_t*) g_value_get_pointer(&val); } break; default: - return; + break; } } } /* Print a string when a menu item is selected */ -static void menuitem_response( gchar *string ) +static void menuitem_response(gchar *string) { if (g_strcmp0(string, SFL_CREATE_CONFERENCE) == 0) - sflphone_join_participant (calltree_selected_call->_callID, - calltree_dragged_call->_callID); + dbus_join_participant(calltree_selected_call->_callID, + calltree_dragged_call->_callID); else if (g_strcmp0(string, SFL_TRANSFER_CALL) == 0) { DEBUG("Calltree: Transfering call %s, to %s", calltree_selected_call->_peer_number, calltree_dragged_call->_peer_number); dbus_attended_transfer(calltree_selected_call, calltree_dragged_call); - calltree_remove_call(current_calls, calltree_selected_call, NULL); - } - else + calltree_remove_call(current_calls_tab, calltree_selected_call); + } else DEBUG("CallTree: Error unknown option selected in menu %s", string); // Make sure the create conference opetion will appear next time the menu pops // The create conference option will hide if tow call from the same conference are draged on each other gtk_widget_show(calltree_menu_items); - printf("%s\n", string); + DEBUG("%s", string); } -GtkTreeIter calltree_get_gtkiter_from_id(calltab_t *tab, gchar *id) -{ - GtkTreeIter iter; - GtkTreeModel *tree_model = GTK_TREE_MODEL(tab->store); - - gtk_tree_model_get_iter_first(tree_model, &iter); - - while(gtk_tree_model_iter_next(tree_model, &iter)) { - GValue val = { .g_type = 0 }; - gtk_tree_model_get_value (tree_model, &iter, COLUMN_ACCOUNT_PTR, &val); - - if(gtk_tree_model_iter_has_child(tree_model, &iter)) { - conference_obj_t *conf = (conference_obj_t *) g_value_get_pointer (&val); - if(g_strcmp0(conf->_confID, id) == 0) - return iter; - } - else { - callable_obj_t *call = (callable_obj_t *) g_value_get_pointer(&val); - if(g_strcmp0(call->_callID, id) == 0) - return iter; - } - } - - return iter; -} diff --git a/gnome/src/contacts/calltree.h b/gnome/src/contacts/calltree.h index 770f3da966d3e10267b448b360efa181b8f99499..4f4fde48c77f3ba7d6acc2de617bf0dd07a49efc 100644 --- a/gnome/src/contacts/calltree.h +++ b/gnome/src/contacts/calltree.h @@ -32,15 +32,6 @@ #ifndef __CALLTREE_H__ #define __CALLTREE_H__ -#include <gtk/gtk.h> -#include <calltab.h> -#include <mainwindow.h> - -#define SFLPHONE_HIG_MARGIN 10 -#define CALLTREE_CALL_ICON_WIDTH 24 -#define CALLTREE_SECURITY_ICON_WIDTH 24 -#define CALLTREE_TEXT_WIDTH (MAIN_WINDOW_WIDTH - CALLTREE_SECURITY_ICON_WIDTH - CALLTREE_CALL_ICON_WIDTH - (2*SFLPHONE_HIG_MARGIN)) - /** @file calltree.h * @brief The GtkTreeView that list calls in the main window. */ @@ -51,7 +42,6 @@ typedef enum { A_INVALID } CallType; - /** * Tags used to identify display type in calltree */ @@ -63,33 +53,37 @@ typedef enum { DISPLAY_TYPE_HISTORY } CallDisplayType; +struct calltab_t; +struct callable_obj_t; +struct conference_obj_t; + /** * Create a new widget calltree * @return GtkWidget* A new widget */ void -calltree_create (calltab_t* tab, gboolean searchbar_type); +calltree_create (calltab_t *, int searchbar_type); /** * Add a call in the calltree * @param c The call to add */ void -calltree_add_call (calltab_t* ct, callable_obj_t * c, GtkTreeIter *parent); +calltree_add_call (calltab_t *, callable_obj_t *, GtkTreeIter *); /* * Update the call tree if the call state changes * @param c The call to update */ void -calltree_update_call (calltab_t* ct, callable_obj_t * c, GtkTreeIter *parent); +calltree_update_call (calltab_t *, callable_obj_t *); /** * Remove a call from the call tree * @param c The call to remove */ void -calltree_remove_call (calltab_t* ct, callable_obj_t * c, GtkTreeIter *parent); +calltree_remove_call(calltab_t *, callable_obj_t *); /** * Add a callable object to history treeview @@ -97,19 +91,16 @@ calltree_remove_call (calltab_t* ct, callable_obj_t * c, GtkTreeIter *parent); * @param The parent item in case of a conference, should be NULL in case of a normal call */ void -calltree_add_history_entry (callable_obj_t *, GtkTreeIter *); +calltree_add_history_entry(callable_obj_t *); void -calltree_add_conference (calltab_t* tab, conference_obj_t* conf); +calltree_add_conference_to_current_calls(conference_obj_t *); void -calltree_update_conference (calltab_t* tab, const conference_obj_t* conf); +calltree_remove_conference(calltab_t *, const conference_obj_t *); void -calltree_remove_conference (calltab_t* tab, const conference_obj_t* conf, GtkTreeIter *parent); - -void -calltree_display (calltab_t *tab); +calltree_display (calltab_t *); void row_activated (GtkTreeView *, GtkTreePath *, GtkTreeViewColumn *, void *); @@ -121,12 +112,11 @@ gboolean calltree_update_clock(gpointer); /** - * Get the iter to a row provided the callID/confID * @param The calltab (current_calls, history, contacts) + * @param The call * @param The callID/confID - * @return The */ -GtkTreeIter -calltree_get_gtkiter_from_id(calltab_t *, gchar *); +void +calltree_(calltab_t *, callable_obj_t *, const gchar * const); #endif diff --git a/gnome/src/contacts/conferencelist.c b/gnome/src/contacts/conferencelist.c index ad29dbc26e99ee6d9f3543bd4bc6bff8ca22770f..3d4c68f8e1f04fbc347f7653fb0e4422e39dce31 100644 --- a/gnome/src/contacts/conferencelist.c +++ b/gnome/src/contacts/conferencelist.c @@ -28,144 +28,107 @@ * as that of the covered work. */ +#include "calltab.h" +#include "callable_obj.h" #include "calltree.h" #include "conferencelist.h" #include "logger.h" -static gint is_confID_confstruct(gconstpointer, gconstpointer); - -static gint is_confID_confstruct (gconstpointer a, gconstpointer b) +static gint is_confID_confstruct(gconstpointer a, gconstpointer b) { conference_obj_t * c = (conference_obj_t*) a; - - if (g_strcasecmp (c->_confID, (const gchar*) b) == 0) { - return 0; - } else { - return 1; - } + return g_strcasecmp(c->_confID, (const gchar*) b); } void conferencelist_init(calltab_t *tab) { - if(tab == NULL) { - ERROR("ConferenceList: Error: Call tab is NULL"); - return; + if (tab == NULL) { + ERROR("ConferenceList: Error: Call tab is NULL"); + return; } - tab->conferenceQueue = g_queue_new (); + tab->conferenceQueue = g_queue_new(); } void conferencelist_clean(calltab_t *tab) { - if(tab == NULL) { - ERROR("ConferenceList: Error: Calltab tab is NULL"); - return; - } - - g_queue_free (tab->conferenceQueue); -} - -void -conferencelist_clean_history(void) -{ - conference_obj_t *conf; - guint size = conferencelist_get_size(history); - - DEBUG("ConferenceList: clean history"); - - while(size > 0) { - conf = conferencelist_pop_head(history); - if(conf) { - calltree_remove_conference(history, conf, NULL); - } - else { - ERROR("ConferenceList: Conference pointer is NULL"); - } - size = conferencelist_get_size(history); + if (tab == NULL) { + ERROR("ConferenceList: Error: Calltab tab is NULL"); + return; } - // g_queue_free(history->conferenceQueue); - + g_queue_free(tab->conferenceQueue); } - void conferencelist_reset(calltab_t *tab) { - if(tab == NULL) { + if (tab == NULL) { ERROR("ConferenceList: Error: Calltab tab is NULL"); return; } - g_queue_free (tab->conferenceQueue); + g_queue_free(tab->conferenceQueue); tab->conferenceQueue = g_queue_new(); } -void conferencelist_add (calltab_t *tab, const conference_obj_t* conf) +void conferencelist_add(calltab_t *tab, const conference_obj_t* conf) { - gchar* c; - - if(conf == NULL) { + if (conf == NULL) { ERROR("ConferenceList: Error: Conference is NULL"); - return; + return; } - if(tab == NULL) { - ERROR("ConferenceList: Error: Tab is NULL"); - return; + if (tab == NULL) { + ERROR("ConferenceList: Error: Tab is NULL"); + return; } - c = (gchar*) conferencelist_get (tab, conf->_confID); + conference_obj_t *c = conferencelist_get(tab, conf->_confID); - if (!c) { - // only add conference into the list if not already inserted - g_queue_push_tail (tab->conferenceQueue, (gpointer) conf); - } + // only add conference into the list if not already inserted + if (c == NULL) + g_queue_push_tail(tab->conferenceQueue, (gpointer) conf); } -void conferencelist_remove (calltab_t *tab, const gchar* conf) +void conferencelist_remove(calltab_t *tab, const gchar* const conf) { - gchar* c; - DEBUG("ConferenceList: Remove conference %s", conf); - if(conf == NULL) { - ERROR("ConferenceList: Error: Conf id is NULL"); - return; + if (conf == NULL) { + ERROR("ConferenceList: Error: Conf id is NULL"); + return; } - if(tab == NULL) { - ERROR("ConferenceList: Error: Calltab is NULL"); - return; + if (tab == NULL) { + ERROR("ConferenceList: Error: Calltab is NULL"); + return; } - c = (gchar*) conferencelist_get (tab, conf); + gchar *c = (gchar*) conferencelist_get(tab, conf); - if(c == NULL) { + if (c == NULL) { ERROR("ConferenceList: Error: Could not find conference %s", conf); - return; + return; } - g_queue_remove (tab->conferenceQueue, c); + g_queue_remove(tab->conferenceQueue, c); } -conference_obj_t* conferencelist_get (calltab_t *tab, const gchar* conf_id) +conference_obj_t* conferencelist_get(calltab_t *tab, const gchar* const conf_id) { - - GList* c; - DEBUG("ConferenceList: Conference list get %s", conf_id); - if(tab == NULL) { - ERROR("ConferenceList: Error: Calltab is NULL"); - return NULL; - } + if (tab == NULL) { + ERROR("ConferenceList: Error: Calltab is NULL"); + return NULL; + } - c = g_queue_find_custom (tab->conferenceQueue, conf_id, is_confID_confstruct); + GList *c = g_queue_find_custom(tab->conferenceQueue, conf_id, is_confID_confstruct); - if(c == NULL) { + if (c == NULL) { ERROR("ConferenceList: Error: Could not find conference %s", conf_id); return NULL; } @@ -173,21 +136,18 @@ conference_obj_t* conferencelist_get (calltab_t *tab, const gchar* conf_id) return (conference_obj_t*) c->data; } - -conference_obj_t* conferencelist_get_nth (calltab_t *tab, guint n) +conference_obj_t* conferencelist_get_nth(calltab_t *tab, guint n) { - conference_obj_t *c; - - if(tab == NULL) { + if (tab == NULL) { ERROR("ConferenceList: Error: Calltab is NULL"); - return NULL; + return NULL; } - c = g_queue_peek_nth (tab->conferenceQueue, n); + conference_obj_t *c = g_queue_peek_nth(tab->conferenceQueue, n); - if(c == NULL) { - ERROR("ConferenceList: Error: Could not fetch conference %d", n); - return NULL; + if (c == NULL) { + ERROR("ConferenceList: Error: Could not fetch conference %d", n); + return NULL; } return c; @@ -195,20 +155,20 @@ conference_obj_t* conferencelist_get_nth (calltab_t *tab, guint n) conference_obj_t *conferencelist_pop_head(calltab_t *tab) { - if(tab == NULL) { - ERROR("ConferenceList: Error: Tab is NULL"); - return NULL; + if (tab == NULL) { + ERROR("ConferenceList: Error: Tab is NULL"); + return NULL; } return g_queue_pop_head(tab->conferenceQueue); } -guint conferencelist_get_size (calltab_t *tab) +guint conferencelist_get_size(calltab_t *tab) { - if(tab == NULL) { + if (tab == NULL) { ERROR("ConferenceList: Error: Calltab is NULL"); - return 0; + return 0; } - return g_queue_get_length (tab->conferenceQueue); + return g_queue_get_length(tab->conferenceQueue); } diff --git a/gnome/src/contacts/conferencelist.h b/gnome/src/contacts/conferencelist.h index a66f4168ebfd961882e3e9deafb9028096495cea..2d864673066ff7a1c3fa5b21e412bf963e51b5cb 100644 --- a/gnome/src/contacts/conferencelist.h +++ b/gnome/src/contacts/conferencelist.h @@ -31,63 +31,43 @@ #ifndef __CONFERENCELIST_H__ #define __CONFERENCELIST_H__ -#include <gtk/gtk.h> - -#include "conference_obj.h" -#include "calllist.h" - /** @file conferencelist.h * @brief A list to store conferences. */ -// GQueue* conferenceQueue; - /** This function initialize a conference list. */ -void -conferencelist_init (calltab_t *); +void conferencelist_init (calltab_t *); /** This function empty and free the conference list. */ -void -conferencelist_clean (calltab_t *); - -/** This function empty and free the history conference list */ -void -conferencelist_clean_history (void); +void conferencelist_clean (calltab_t *); /** This function empty, free the conference list and allocate a new one. */ -void -conferencelist_reset (calltab_t *); +void conferencelist_reset (calltab_t *); /** This function append a conference to the list. * @param conf The conference you want to add * */ -void -conferencelist_add (calltab_t *, const conference_obj_t *); +void conferencelist_add (calltab_t *, const conference_obj_t *); /** This function remove a conference from list. * @param callID The callID of the conference you want to remove */ -void -conferencelist_remove (calltab_t *, const gchar *); +void conferencelist_remove (calltab_t *, const gchar * const conf_id); /** Return the number of calls in the list * @return The number of calls in the list */ -guint -conferencelist_get_size (calltab_t *); +guint conferencelist_get_size (calltab_t *); /** Return the call at the nth position in the list * @param n The position of the call you want * @return A call or NULL */ -conference_obj_t* -conferencelist_get_nth (calltab_t *, guint); +conference_obj_t* conferencelist_get_nth (calltab_t *, guint); /** Return the call corresponding to the callID * @param n The callID of the call want * @return A call or NULL */ -conference_obj_t* -conferencelist_get (calltab_t *, const gchar *); +conference_obj_t* conferencelist_get(calltab_t *, const gchar const *); -conference_obj_t* -conferencelist_pop_head(calltab_t *); +conference_obj_t* conferencelist_pop_head(calltab_t *); #endif diff --git a/gnome/src/contacts/history.c b/gnome/src/contacts/history.c index 7eb9b6629ed4888e79af9dd9d1978f084f249775..36cd0a2ac4ad1d72e2b8c7cb1b097683739d5889 100644 --- a/gnome/src/contacts/history.c +++ b/gnome/src/contacts/history.c @@ -28,15 +28,16 @@ * as that of the covered work. */ -#include <history.h> #include <string.h> -#include <searchbar.h> -#include <calltab.h> +#include "history.h" +#include "searchbar.h" +#include "calltab.h" +#include "unused.h" static GtkTreeModel *history_filter; static GtkEntry *history_searchbar_widget; -static gboolean history_is_visible (GtkTreeModel* model, GtkTreeIter* iter, gpointer data UNUSED) +static gboolean history_is_visible(GtkTreeModel* model, GtkTreeIter* iter, gpointer data UNUSED) { gboolean ret = TRUE; callable_obj_t *history_entry = NULL; @@ -45,25 +46,27 @@ static gboolean history_is_visible (GtkTreeModel* model, GtkTreeIter* iter, gpoi // Fetch the call description GValue val; memset(&val, 0, sizeof val); - gtk_tree_model_get_value (GTK_TREE_MODEL (model), iter, 1, &val); + gtk_tree_model_get_value(GTK_TREE_MODEL(model), iter, 1, &val); - if (G_VALUE_HOLDS_STRING (&val)) - text = (gchar *) g_value_get_string (&val); + if (G_VALUE_HOLDS_STRING(&val)) + text = (gchar *) g_value_get_string(&val); // Fetch the call type GValue obj; memset(&obj, 0, sizeof obj); - gtk_tree_model_get_value (GTK_TREE_MODEL (model), iter, 3, &obj); + gtk_tree_model_get_value(GTK_TREE_MODEL(model), iter, 3, &obj); - if (G_VALUE_HOLDS_POINTER (&obj)) - history_entry = (gpointer) g_value_get_pointer (&obj); + if (G_VALUE_HOLDS_POINTER(&obj)) + history_entry = (gpointer) g_value_get_pointer(&obj); if (text && history_entry) { // Filter according to the type of call // MISSED, INCOMING, OUTGOING, ALL - const gchar* search = gtk_entry_get_text (history_searchbar_widget); + const gchar* search = gtk_entry_get_text(history_searchbar_widget); + if (!search || !*search) goto end; + SearchType search_type = get_current_history_search_type(); ret = g_regex_match_simple(search, text, G_REGEX_CASELESS, 0); @@ -78,26 +81,26 @@ end: return ret; } -static GtkTreeModel* history_create_filter (GtkTreeModel* child) +static GtkTreeModel* history_create_filter(GtkTreeModel* child) { - GtkTreeModel* ret = gtk_tree_model_filter_new (child, NULL); - gtk_tree_model_filter_set_visible_func (GTK_TREE_MODEL_FILTER (ret), history_is_visible, NULL, NULL); - return GTK_TREE_MODEL (ret); + GtkTreeModel* ret = gtk_tree_model_filter_new(child, NULL); + gtk_tree_model_filter_set_visible_func(GTK_TREE_MODEL_FILTER(ret), history_is_visible, NULL, NULL); + return GTK_TREE_MODEL(ret); } -void history_search (void) +void history_search(void) { if (history_filter != NULL) - gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (history_filter)); + gtk_tree_model_filter_refilter(GTK_TREE_MODEL_FILTER(history_filter)); } -void history_search_init (void) +void history_search_init(void) { - history_filter = history_create_filter(GTK_TREE_MODEL (history->store)); - gtk_tree_view_set_model(GTK_TREE_VIEW (history->view), GTK_TREE_MODEL (history_filter)); + history_filter = history_create_filter(GTK_TREE_MODEL(history_tab->store)); + gtk_tree_view_set_model(GTK_TREE_VIEW(history_tab->view), GTK_TREE_MODEL(history_filter)); } -void history_set_searchbar_widget (GtkWidget *searchbar) +void history_set_searchbar_widget(GtkWidget *searchbar) { history_searchbar_widget = GTK_ENTRY(searchbar); } diff --git a/gnome/src/contacts/searchbar.c b/gnome/src/contacts/searchbar.c index 1dda95581e3b4657c9a3e07c7555cecb337f1033..e48efafbc3a67d32932bc230df4de868c34de642 100644 --- a/gnome/src/contacts/searchbar.c +++ b/gnome/src/contacts/searchbar.c @@ -31,68 +31,80 @@ * as that of the covered work. */ -#include <searchbar.h> -#include <calltree.h> -#include <config/addressbook-config.h> -#include <contacts/addressbook.h> -// #include <contacts/addressbook/eds.h> -#include <contacts/addrbookfactory.h> +#include "searchbar.h" +#include "calltree.h" +#include "calltab.h" +#include "dbus.h" +#include "logger.h" +#include "unused.h" +#include "config/addressbook-config.h" +#include "contacts/addressbook.h" +#include "contacts/addrbookfactory.h" -GtkWidget * searchbox; -GtkWidget * addressbookentry; +static GtkWidget * searchbox; +static GtkWidget * addressbookentry; -GtkWidget * cbox; -GtkListStore * liststore = NULL; +static GtkWidget * cbox; +static GtkListStore * liststore = NULL; -gint cboxSignalId; +static gint cboxSignalId; static GtkWidget *menu = NULL; /** * Searchbar icons */ -GdkPixbuf *incoming_pixbuf = NULL; -GdkPixbuf *outgoing_pixbuf = NULL; -GdkPixbuf *missed_pixbuf = NULL; +static GdkPixbuf *incoming_pixbuf = NULL; +static GdkPixbuf *outgoing_pixbuf = NULL; +static GdkPixbuf *missed_pixbuf = NULL; - -void searchbar_addressbook_activated (GtkEntry *entry, gchar *arg1 UNUSED, gpointer data UNUSED) +void searchbar_addressbook_activated(GtkEntry *entry, gchar *arg1 UNUSED, gpointer data UNUSED) { - if(addrbook) + if (addrbook) addrbook->search(addrbook->search_cb, entry, addressbook_config_load_parameters()); } -void searchbar_entry_changed (GtkEntry* entry UNUSED, gchar* arg1 UNUSED, gpointer data UNUSED) +void searchbar_entry_changed(GtkEntry* entry UNUSED, gchar* arg1 UNUSED, gpointer data UNUSED) { - DEBUG ("Searchbar: Entry changed"); - - if (active_calltree == contacts) { - // Search made only when text entry is activated - // addressbook_search (entry); - } else if (active_calltree == history) { + DEBUG("Searchbar: Entry changed"); + if (active_calltree_tab == history_tab) history_search(); - } } -static void cbox_changed_cb (GtkWidget *widget, gpointer user_data UNUSED) +static gchar *get_combobox_active_text(GtkWidget *widget) { - if(!addrbook) + GtkTreeIter iter; + gtk_combo_box_get_active_iter(GTK_COMBO_BOX(widget), &iter); + GtkTreeModel *model = gtk_combo_box_get_model(GTK_COMBO_BOX(widget)); + gchar *string = NULL; + /* this will return a strdup'd string of the text for the active + * entry, which must be freed */ + gtk_tree_model_get(model, &iter, 0, &string, -1); + return string; +} + +static void cbox_changed_cb(GtkWidget *widget, gpointer user_data UNUSED) +{ + if (!addrbook) return; - addrbook->set_current_book (gtk_combo_box_get_active_text (GTK_COMBO_BOX (widget))); + gchar *string = get_combobox_active_text(widget); + if (string) { + addrbook->set_current_book(string); + g_free(string); + } AddressBook_Config *addressbook_config = addressbook_config_load_parameters(); addrbook->search(addrbook->search_cb, GTK_ENTRY(addressbookentry), addressbook_config); } -void set_focus_on_addressbook_searchbar () +void set_focus_on_addressbook_searchbar() { - gtk_widget_grab_focus (addressbookentry); + gtk_widget_grab_focus(addressbookentry); } void update_searchbar_addressbook_list() { GtkTreeIter iter, activeIter; - gchar *activeText; GSList *book_list_iterator; book_data_t *book_data; GSList *books_data = NULL; @@ -100,23 +112,23 @@ void update_searchbar_addressbook_list() if (addrbook) books_data = addrbook->get_books_data(dbus_get_addressbook_list()); - if(books_data == NULL) { + if (books_data == NULL) { ERROR("Searchbar: No books data found"); - return; + return; } - DEBUG ("Searchbar: Update addressbook list"); - // we must disconnect signal from teh cbox while updating its content - gtk_signal_disconnect (cbox, cboxSignalId); + DEBUG("Searchbar: Update addressbook list"); + + // we must disconnect signal from the cbox while updating its content + g_signal_handler_disconnect(cbox, cboxSignalId); // store the current active text - activeText = g_strdup (gtk_combo_box_get_active_text (GTK_COMBO_BOX (cbox))); - if(activeText == NULL) { + gchar *activeText = get_combobox_active_text(cbox); - activeText = g_strdup (""); - } + if (activeText == NULL) + activeText = g_strdup(""); - gtk_list_store_clear (liststore); + gtk_list_store_clear(liststore); // Populate menu gboolean activeIsSet = FALSE; @@ -127,271 +139,254 @@ void update_searchbar_addressbook_list() if (book_data && book_data->active) { + gtk_list_store_append(liststore, &iter); + gtk_list_store_set(liststore, &iter, 0, book_data->name, -1); - gtk_list_store_append (liststore, &iter); - gtk_list_store_set (liststore, &iter, 0, book_data->name, -1); - - if (g_strcmp0 (book_data->name, activeText) == 0) { + if (g_strcmp0(book_data->name, activeText) == 0) { activeIter = iter; activeIsSet = TRUE; } } } - if(addrbook) { + if (addrbook) { if (activeIsSet) { - gtk_combo_box_set_active_iter (GTK_COMBO_BOX (cbox), &activeIter); + gtk_combo_box_set_active_iter(GTK_COMBO_BOX(cbox), &activeIter); addrbook->set_current_book(activeText); - } - else { - gtk_combo_box_set_active (GTK_COMBO_BOX (cbox), 0); - gtk_combo_box_get_active_text(GTK_COMBO_BOX(cbox)); - addrbook->set_current_book(gtk_combo_box_get_active_text(GTK_COMBO_BOX(cbox))); + } else { + gtk_combo_box_set_active(GTK_COMBO_BOX(cbox), 0); + addrbook->set_current_book(get_combobox_active_text(cbox)); } } - g_free (activeText); - cboxSignalId = gtk_signal_connect (GTK_OBJECT (cbox), "changed", G_CALLBACK (cbox_changed_cb), NULL); + g_free(activeText); + cboxSignalId = g_signal_connect(G_OBJECT(cbox), "changed", G_CALLBACK(cbox_changed_cb), NULL); } -static void select_search_type (GtkWidget *item, GtkEntry *entry UNUSED) +static void select_search_type(GtkWidget *item, GtkEntry *entry UNUSED) { - - if(addrbook) { - DEBUG ("Searchbar: %s", gtk_menu_item_get_label (GTK_MENU_ITEM (item))); + if (addrbook) { + DEBUG("Searchbar: %s", gtk_menu_item_get_label(GTK_MENU_ITEM(item))); - gtk_entry_set_icon_tooltip_text (GTK_ENTRY (addressbookentry), GTK_ENTRY_ICON_PRIMARY, - gtk_menu_item_get_label (GTK_MENU_ITEM (item))); + gtk_entry_set_icon_tooltip_text(GTK_ENTRY(addressbookentry), GTK_ENTRY_ICON_PRIMARY, + gtk_menu_item_get_label(GTK_MENU_ITEM(item))); - if (g_strcmp0 ("Search is", gtk_menu_item_get_label (GTK_MENU_ITEM (item))) == 0) { + if (g_strcmp0("Search is", gtk_menu_item_get_label(GTK_MENU_ITEM(item))) == 0) { addrbook->set_search_type(ABOOK_QUERY_IS); - } - else if (g_strcmp0 ("Search begins with", gtk_menu_item_get_label (GTK_MENU_ITEM (item))) == 0) { + } else if (g_strcmp0("Search begins with", gtk_menu_item_get_label(GTK_MENU_ITEM(item))) == 0) { addrbook->set_search_type(ABOOK_QUERY_BEGINS_WITH); - } - else if (g_strcmp0 ("Search contains", gtk_menu_item_get_label (GTK_MENU_ITEM (item))) == 0) { + } else if (g_strcmp0("Search contains", gtk_menu_item_get_label(GTK_MENU_ITEM(item))) == 0) { addrbook->set_search_type(ABOOK_QUERY_CONTAINS); } - + AddressBook_Config *addressbook_config = addressbook_config_load_parameters(); - addrbook->search (addrbook->search_cb, GTK_ENTRY (addressbookentry), addressbook_config); + addrbook->search(addrbook->search_cb, GTK_ENTRY(addressbookentry), addressbook_config); } + AddressBook_Config *addressbook_config = addressbook_config_load_parameters(); + addrbook->search (addrbook->search_cb, GTK_ENTRY (addressbookentry), addressbook_config); } -static void search_all (GtkWidget *item UNUSED, GtkEntry *entry) +static void search_all(GtkWidget *item UNUSED, GtkEntry *entry) { HistorySearchType = SEARCH_ALL; - gtk_entry_set_icon_from_stock (entry, GTK_ENTRY_ICON_PRIMARY, GTK_STOCK_FIND); - gchar *markup = g_markup_printf_escaped ("%s\n%s", - _ ("Search all"), - _ ("Click here to change the search type")); - gtk_entry_set_icon_tooltip_text (entry, GTK_ENTRY_ICON_PRIMARY, markup); + gtk_entry_set_icon_from_stock(entry, GTK_ENTRY_ICON_PRIMARY, GTK_STOCK_FIND); + gchar *markup = g_markup_printf_escaped("%s\n%s", + _("Search all"), + _("Click here to change the search type")); + gtk_entry_set_icon_tooltip_text(entry, GTK_ENTRY_ICON_PRIMARY, markup); g_free(markup); history_search(); } -static void search_by_missed (GtkWidget *item UNUSED, GtkEntry *entry) +static void search_by_missed(GtkWidget *item UNUSED, GtkEntry *entry) { HistorySearchType = SEARCH_MISSED; - gtk_entry_set_icon_from_pixbuf (entry, GTK_ENTRY_ICON_PRIMARY, missed_pixbuf); - gtk_entry_set_icon_tooltip_text (entry, GTK_ENTRY_ICON_PRIMARY, - g_markup_printf_escaped ("%s\n%s", - _ ("Search by missed call"), - _ ("Click here to change the search type"))); + gtk_entry_set_icon_from_pixbuf(entry, GTK_ENTRY_ICON_PRIMARY, missed_pixbuf); + gtk_entry_set_icon_tooltip_text(entry, GTK_ENTRY_ICON_PRIMARY, + g_markup_printf_escaped("%s\n%s", + _("Search by missed call"), + _("Click here to change the search type"))); history_search(); } -static void search_by_incoming (GtkWidget *item UNUSED, GtkEntry *entry) +static void search_by_incoming(GtkWidget *item UNUSED, GtkEntry *entry) { HistorySearchType = SEARCH_INCOMING; - gtk_entry_set_icon_from_pixbuf (entry, GTK_ENTRY_ICON_PRIMARY, incoming_pixbuf); - gtk_entry_set_icon_tooltip_text (entry, GTK_ENTRY_ICON_PRIMARY, - g_markup_printf_escaped ("%s\n%s", - _ ("Search by incoming call"), - _ ("Click here to change the search type"))); + gtk_entry_set_icon_from_pixbuf(entry, GTK_ENTRY_ICON_PRIMARY, incoming_pixbuf); + gtk_entry_set_icon_tooltip_text(entry, GTK_ENTRY_ICON_PRIMARY, + g_markup_printf_escaped("%s\n%s", + _("Search by incoming call"), + _("Click here to change the search type"))); history_search(); } -static void search_by_outgoing (GtkWidget *item UNUSED, GtkEntry *entry) +static void search_by_outgoing(GtkWidget *item UNUSED, GtkEntry *entry) { HistorySearchType = SEARCH_OUTGOING; - gtk_entry_set_icon_from_pixbuf (entry, GTK_ENTRY_ICON_PRIMARY, outgoing_pixbuf); - gtk_entry_set_icon_tooltip_text (entry, GTK_ENTRY_ICON_PRIMARY, - g_markup_printf_escaped ("%s\n%s", - _ ("Search by outgoing call"), - _ ("Click here to change the search type"))); + gtk_entry_set_icon_from_pixbuf(entry, GTK_ENTRY_ICON_PRIMARY, outgoing_pixbuf); + gtk_entry_set_icon_tooltip_text(entry, GTK_ENTRY_ICON_PRIMARY, + g_markup_printf_escaped("%s\n%s", + _("Search by outgoing call"), + _("Click here to change the search type"))); history_search(); } -static void icon_press_cb (GtkEntry *entry, gint position, GdkEventButton *event, gpointer data UNUSED) +static void icon_press_cb(GtkEntry *entry, gint position, GdkEventButton *event, gpointer data UNUSED) { - DEBUG ("Searchbar: Icon pressed"); + DEBUG("Searchbar: Icon pressed"); - if (position == GTK_ENTRY_ICON_PRIMARY && active_calltree == history) - gtk_menu_popup (GTK_MENU (menu), NULL, NULL, NULL, NULL, - event->button, event->time); - else if (position == GTK_ENTRY_ICON_PRIMARY && active_calltree == contacts) { + if (position == GTK_ENTRY_ICON_PRIMARY && active_calltree_tab == history_tab) + gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL, + event->button, event->time); + else if (position == GTK_ENTRY_ICON_PRIMARY && active_calltree_tab == contacts_tab) { GtkWidget *addrbook_menu = addressbook_menu_new(); - gtk_menu_popup (GTK_MENU (addrbook_menu), NULL, NULL, NULL, NULL, - event->button, event->time); + gtk_menu_popup(GTK_MENU(addrbook_menu), NULL, NULL, NULL, NULL, + event->button, event->time); } else - gtk_entry_set_text (entry, ""); + gtk_entry_set_text(entry, ""); } -static void text_changed_cb (GtkEntry *entry, GParamSpec *pspec UNUSED) +static void text_changed_cb(GtkEntry *entry, GParamSpec *pspec UNUSED) { gboolean has_text; - has_text = gtk_entry_get_text_length (entry) > 0; - gtk_entry_set_icon_sensitive (entry, GTK_ENTRY_ICON_SECONDARY, has_text); + has_text = gtk_entry_get_text_length(entry) > 0; + gtk_entry_set_icon_sensitive(entry, GTK_ENTRY_ICON_SECONDARY, has_text); } -GtkWidget *addressbook_menu_new (void) +GtkWidget *addressbook_menu_new(void) { - - GtkWidget *menu, *item; - // Create the menu - menu = gtk_menu_new (); - gtk_menu_attach_to_widget (GTK_MENU (menu), contacts->searchbar, NULL); + GtkWidget *menu_widget = gtk_menu_new(); + gtk_menu_attach_to_widget(GTK_MENU(menu_widget), contacts_tab->searchbar, NULL); // Populate menu - item = gtk_menu_item_new_with_label ("Search is"); - g_signal_connect (item, "activate", G_CALLBACK (select_search_type), searchbox); - gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); + GtkWidget *item = gtk_menu_item_new_with_label("Search is"); + g_signal_connect(item, "activate", G_CALLBACK(select_search_type), searchbox); + gtk_menu_shell_append(GTK_MENU_SHELL(menu_widget), item); - item = gtk_menu_item_new_with_label ("Search begins with"); - g_signal_connect (item, "activate", G_CALLBACK (select_search_type), searchbox); - gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); + item = gtk_menu_item_new_with_label("Search begins with"); + g_signal_connect(item, "activate", G_CALLBACK(select_search_type), searchbox); + gtk_menu_shell_append(GTK_MENU_SHELL(menu_widget), item); - item = gtk_menu_item_new_with_label ("Search contains"); - g_signal_connect (item, "activate", G_CALLBACK (select_search_type), searchbox); - gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); + item = gtk_menu_item_new_with_label("Search contains"); + g_signal_connect(item, "activate", G_CALLBACK(select_search_type), searchbox); + gtk_menu_shell_append(GTK_MENU_SHELL(menu_widget), item); - gtk_widget_show_all (menu); + gtk_widget_show_all(menu_widget); - return menu; + return menu_widget; } -GtkWidget* history_searchbar_new (void) +GtkWidget* history_searchbar_new(void) { - GtkWidget *ret, *item, *image; - - ret = gtk_hbox_new (FALSE, 0); + GtkWidget *ret = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); searchbox = gtk_entry_new(); - gtk_entry_set_icon_from_stock (GTK_ENTRY (searchbox), GTK_ENTRY_ICON_SECONDARY, GTK_STOCK_CLEAR); + gtk_entry_set_icon_from_stock(GTK_ENTRY(searchbox), GTK_ENTRY_ICON_SECONDARY, GTK_STOCK_CLEAR); - missed_pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/missed.svg", NULL); - incoming_pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/incoming.svg", NULL); - outgoing_pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/outgoing.svg", NULL); + missed_pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/missed.svg", NULL); + incoming_pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/incoming.svg", NULL); + outgoing_pixbuf = gdk_pixbuf_new_from_file(ICONS_DIR "/outgoing.svg", NULL); // Set the clean insensitive - text_changed_cb (GTK_ENTRY (searchbox), NULL); + text_changed_cb(GTK_ENTRY(searchbox), NULL); - g_signal_connect (searchbox, "icon-press", G_CALLBACK (icon_press_cb), NULL); - g_signal_connect (searchbox, "notify::text", G_CALLBACK (text_changed_cb), NULL); + g_signal_connect(searchbox, "icon-press", G_CALLBACK(icon_press_cb), NULL); + g_signal_connect(searchbox, "notify::text", G_CALLBACK(text_changed_cb), NULL); //g_signal_connect (searchbox, "activate", G_CALLBACK (activate_cb), NULL); // Set up the search icon - search_all (NULL, GTK_ENTRY (searchbox)); + search_all(NULL, GTK_ENTRY(searchbox)); // Create the menu - menu = gtk_menu_new (); - gtk_menu_attach_to_widget (GTK_MENU (menu), searchbox, NULL); - - image = gtk_image_new_from_stock (GTK_STOCK_FIND, GTK_ICON_SIZE_MENU); - item = gtk_image_menu_item_new_with_label ("Search all"); - gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image); - g_signal_connect (item, "activate", G_CALLBACK (search_all), searchbox); - gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); - - item = gtk_image_menu_item_new_with_label ("Search by missed call"); - image = gtk_image_new_from_file (ICONS_DIR "/missed.svg"); - gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image); - g_signal_connect (item, "activate", G_CALLBACK (search_by_missed), searchbox); - gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); - - item = gtk_image_menu_item_new_with_label ("Search by incoming call"); - image = gtk_image_new_from_file (ICONS_DIR "/incoming.svg"); - gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image); - g_signal_connect (item, "activate", G_CALLBACK (search_by_incoming), searchbox); - gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); - - item = gtk_image_menu_item_new_with_label ("Search by outgoing call"); - image = gtk_image_new_from_file (ICONS_DIR "/outgoing.svg"); - gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (item), image); - g_signal_connect (item, "activate", G_CALLBACK (search_by_outgoing), searchbox); - gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); - - gtk_widget_show_all (menu); - - g_signal_connect_after (GTK_ENTRY (searchbox), "changed", G_CALLBACK (searchbar_entry_changed), NULL); - g_signal_connect_after (G_OBJECT (searchbox), "focus-in-event", - G_CALLBACK (focus_on_searchbar_in), NULL); - g_signal_connect_after (G_OBJECT (searchbox), "focus-out-event", - G_CALLBACK (focus_on_searchbar_out), NULL); - - gtk_box_pack_start (GTK_BOX (ret), searchbox, TRUE, TRUE, 0); - history_set_searchbar_widget (searchbox); + menu = gtk_menu_new(); + gtk_menu_attach_to_widget(GTK_MENU(menu), searchbox, NULL); + + GtkWidget *image = gtk_image_new_from_stock(GTK_STOCK_FIND, GTK_ICON_SIZE_MENU); + GtkWidget *item = gtk_image_menu_item_new_with_label("Search all"); + gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(item), image); + g_signal_connect(item, "activate", G_CALLBACK(search_all), searchbox); + gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); + + item = gtk_image_menu_item_new_with_label("Search by missed call"); + image = gtk_image_new_from_file(ICONS_DIR "/missed.svg"); + gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(item), image); + g_signal_connect(item, "activate", G_CALLBACK(search_by_missed), searchbox); + gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); + + item = gtk_image_menu_item_new_with_label("Search by incoming call"); + image = gtk_image_new_from_file(ICONS_DIR "/incoming.svg"); + gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(item), image); + g_signal_connect(item, "activate", G_CALLBACK(search_by_incoming), searchbox); + gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); + + item = gtk_image_menu_item_new_with_label("Search by outgoing call"); + image = gtk_image_new_from_file(ICONS_DIR "/outgoing.svg"); + gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(item), image); + g_signal_connect(item, "activate", G_CALLBACK(search_by_outgoing), searchbox); + gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); + + gtk_widget_show_all(menu); + + g_signal_connect_after(GTK_ENTRY(searchbox), "changed", G_CALLBACK(searchbar_entry_changed), NULL); + g_signal_connect_after(G_OBJECT(searchbox), "focus-in-event", + G_CALLBACK(focus_on_searchbar_in), NULL); + g_signal_connect_after(G_OBJECT(searchbox), "focus-out-event", + G_CALLBACK(focus_on_searchbar_out), NULL); + + gtk_box_pack_start(GTK_BOX(ret), searchbox, TRUE, TRUE, 0); + history_set_searchbar_widget(searchbox); return ret; } -GtkWidget* contacts_searchbar_new () +GtkWidget* contacts_searchbar_new() { - - GtkWidget *ret; - GtkWidget *align; - int count, cbox_height, cbox_width; GtkTreeIter iter, activeIter; GtkCellRenderer *cell; - gchar **book_list; - // gchar *current_addressbook = NULL; - - DEBUG ("Addressbook: Create addressbook search bar"); - ret = gtk_hbox_new (FALSE, 0); + GtkWidget *ret = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); - liststore = gtk_list_store_new (1,G_TYPE_STRING); + liststore = gtk_list_store_new(1,G_TYPE_STRING); // Create combo box to select current addressbook - if(!addrbook) - return NULL; + if (!addrbook) + return NULL; - book_list = dbus_get_addressbook_list(); + gchar **book_list = dbus_get_addressbook_list(); addrbook->init(book_list); GSList *book_list_iterator; book_data_t *book_data; GSList *books_data = addrbook->get_books_data(book_list); - + // Populate menu - count = 0; + int count = 0; gboolean activeIsSet = FALSE; for (book_list_iterator = books_data; book_list_iterator != NULL; - book_list_iterator = book_list_iterator->next) { + book_list_iterator = book_list_iterator->next) { book_data = (book_data_t *) book_list_iterator->data; DEBUG("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ %s", book_data->name); if (book_data->active) { - gtk_list_store_append (liststore, &iter); + gtk_list_store_append(liststore, &iter); - gtk_list_store_set (liststore, &iter, 0, book_data->name, -1); + gtk_list_store_set(liststore, &iter, 0, book_data->name, -1); if (book_data->isdefault) { activeIter = iter; @@ -402,81 +397,65 @@ GtkWidget* contacts_searchbar_new () } } - // current_addressbook = get_current_addressbook(); - - cbox = gtk_combo_box_new_with_model ( (GtkTreeModel *) liststore); + cbox = gtk_combo_box_new_with_model((GtkTreeModel *) liststore); if (activeIsSet) - gtk_combo_box_set_active_iter (GTK_COMBO_BOX (cbox), &activeIter); + gtk_combo_box_set_active_iter(GTK_COMBO_BOX(cbox), &activeIter); else - gtk_combo_box_set_active (GTK_COMBO_BOX (cbox), 0); + gtk_combo_box_set_active(GTK_COMBO_BOX(cbox), 0); - align = gtk_alignment_new (0.0, 0.0, 1.0, 1.0); - gtk_alignment_set_padding (GTK_ALIGNMENT (align), 0, 2, 6, 6); - gtk_container_add (GTK_CONTAINER (align), cbox); + GtkWidget *align = gtk_alignment_new(0.0, 0.0, 1.0, 1.0); + gtk_alignment_set_padding(GTK_ALIGNMENT(align), 0, 2, 6, 6); + gtk_container_add(GTK_CONTAINER(align), cbox); - gtk_widget_get_size_request (GTK_WIDGET (cbox), &cbox_width, &cbox_height); - gtk_widget_set_size_request (GTK_WIDGET (cbox), cbox_width, 26); + gint cbox_width, cbox_height; + gtk_widget_get_size_request(GTK_WIDGET(cbox), &cbox_width, &cbox_height); + gtk_widget_set_size_request(GTK_WIDGET(cbox), cbox_width, 26); - cboxSignalId = gtk_signal_connect (GTK_OBJECT (cbox), "changed", G_CALLBACK (cbox_changed_cb), NULL); - // cbox_changed_cb (GTK_WIDGET (cbox), NULL); + cboxSignalId = g_signal_connect(G_OBJECT(cbox), "changed", G_CALLBACK(cbox_changed_cb), NULL); cell = gtk_cell_renderer_text_new(); - gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (cbox), cell, TRUE); - gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (cbox), cell, "text", 0, NULL); + gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(cbox), cell, TRUE); + gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(cbox), cell, "text", 0, NULL); // GdkPixbuf *pixbuf; - gchar *tooltip_text = g_strdup ("Search is"); + gchar *tooltip_text = g_strdup("Search is"); addressbookentry = gtk_entry_new(); - gtk_entry_set_icon_from_stock (GTK_ENTRY (addressbookentry), GTK_ENTRY_ICON_SECONDARY, GTK_STOCK_CLEAR); + gtk_entry_set_icon_from_stock(GTK_ENTRY(addressbookentry), GTK_ENTRY_ICON_SECONDARY, GTK_STOCK_CLEAR); // pixbuf = gdk_pixbuf_new_from_file (ICONS_DIR "/stock_person.svg", NULL); - gtk_entry_set_icon_from_stock (GTK_ENTRY (addressbookentry), GTK_ENTRY_ICON_PRIMARY, GTK_STOCK_FIND); - gtk_entry_set_icon_tooltip_text (GTK_ENTRY (addressbookentry), GTK_ENTRY_ICON_PRIMARY, - tooltip_text); - + gtk_entry_set_icon_from_stock(GTK_ENTRY(addressbookentry), GTK_ENTRY_ICON_PRIMARY, GTK_STOCK_FIND); + gtk_entry_set_icon_tooltip_text(GTK_ENTRY(addressbookentry), GTK_ENTRY_ICON_PRIMARY, + tooltip_text); // Set the clean insensitive - text_changed_cb (GTK_ENTRY (addressbookentry), NULL); - - g_signal_connect (addressbookentry, "notify::text", G_CALLBACK (text_changed_cb), NULL); - g_signal_connect (addressbookentry, "icon-press", G_CALLBACK (icon_press_cb), NULL); + text_changed_cb(GTK_ENTRY(addressbookentry), NULL); - gtk_entry_set_activates_default (GTK_ENTRY (addressbookentry), TRUE); - g_signal_connect_after (GTK_ENTRY (addressbookentry), "activate", G_CALLBACK (searchbar_addressbook_activated), NULL); + g_signal_connect(addressbookentry, "notify::text", G_CALLBACK(text_changed_cb), NULL); + g_signal_connect(addressbookentry, "icon-press", G_CALLBACK(icon_press_cb), NULL); - g_signal_connect_after (GTK_ENTRY (addressbookentry), "changed", G_CALLBACK (searchbar_entry_changed), NULL); + gtk_entry_set_activates_default(GTK_ENTRY(addressbookentry), TRUE); + g_signal_connect_after(GTK_ENTRY(addressbookentry), "activate", G_CALLBACK(searchbar_addressbook_activated), NULL); - g_signal_connect_after (G_OBJECT (addressbookentry), "focus-in-event", - G_CALLBACK (focus_on_searchbar_in), NULL); - g_signal_connect_after (G_OBJECT (addressbookentry), "focus-out-event", - G_CALLBACK (focus_on_searchbar_out), NULL); + g_signal_connect_after(GTK_ENTRY(addressbookentry), "changed", G_CALLBACK(searchbar_entry_changed), NULL); + g_signal_connect_after(G_OBJECT(addressbookentry), "focus-in-event", + G_CALLBACK(focus_on_searchbar_in), NULL); + g_signal_connect_after(G_OBJECT(addressbookentry), "focus-out-event", + G_CALLBACK(focus_on_searchbar_out), NULL); - gtk_box_pack_start (GTK_BOX (ret), align, TRUE, TRUE, 0); - gtk_box_pack_start (GTK_BOX (ret), addressbookentry, TRUE, TRUE, 0); - g_free (tooltip_text); - g_strfreev (book_list); + gtk_box_pack_start(GTK_BOX(ret), align, TRUE, TRUE, 0); + gtk_box_pack_start(GTK_BOX(ret), addressbookentry, TRUE, TRUE, 0); - // current_addressbook = gtk_combo_box_get_active_text (GTK_COMBO_BOX (cbox)); - // set_current_addressbook (current_addressbook); + g_free(tooltip_text); + g_strfreev(book_list); return ret; } -void activateWaitingLayer() -{ - gtk_widget_show (waitingLayer); -} - -void deactivateWaitingLayer() -{ - gtk_widget_hide (waitingLayer); -} - SearchType get_current_history_search_type (void) { return HistorySearchType; diff --git a/gnome/src/dbus/Makefile.am b/gnome/src/dbus/Makefile.am index c9fa5b156f89c82f446802678c8fd0c07570f22d..4c5ce7683b9290ca6b56a7207e8e16819d272797 100644 --- a/gnome/src/dbus/Makefile.am +++ b/gnome/src/dbus/Makefile.am @@ -26,15 +26,13 @@ libdbus_la_SOURCES= \ $(BUILT_SOURCES) libdbus_la_LDFLAGS= $(DBUSGLIB_LDFLAGS) $(LIBNOTIFY_LDFLAGS) \ - $(GTK_LDFLAGS) $(GLIB_LDFLAGS) $(WEBKIT_LDFLAGS) $(LIBGNOMEUI_LDFLAGS) \ - $(GNOMEDOCUTILS_LDFLAGS) + $(GTK_LDFLAGS) $(GLIB_LDFLAGS) $(WEBKIT_LDFLAGS) \ + $(GCONF_LDFLAGS) libdbus_la_CFLAGS= $(DBUSGLIB_CFLAGS) $(LIBNOTIFY_CFLAGS) \ - $(GTK_CFLAGS) $(GLIB_CFLAGS) $(WEBKIT_CFLAGS) $(LIBGNOMEUI_CFLAGS) \ - $(GNOMEDOCUTILS_CFLAGS) + $(GTK_CFLAGS) $(GLIB_CFLAGS) $(WEBKIT_CFLAGS) \ + $(GCONF_CFLAGS) -EXTRA_DIST= \ - marshaller.list +EXTRA_DIST= marshaller.list -CLEANFILES= \ - $(BUILT_SOURCES) +CLEANFILES= $(BUILT_SOURCES) diff --git a/gnome/src/dbus/callmanager-introspec.xml b/gnome/src/dbus/callmanager-introspec.xml index 8b23a3f68dc04fecfce79a233b5669f4882bc7b8..46cec40068df52b9d16a50324c3947821ed7f443 100644 --- a/gnome/src/dbus/callmanager-introspec.xml +++ b/gnome/src/dbus/callmanager-introspec.xml @@ -289,7 +289,7 @@ A map containing the ID of the conferences and their states: <ul> - <li>ACTIVE_ATACHED</li> + <li>ACTIVE_ATTACHED</li> <li>ACTIVE_DETACHED</li> <li>HOLD</li> </ul> diff --git a/gnome/src/dbus/configurationmanager-introspec.xml b/gnome/src/dbus/configurationmanager-introspec.xml old mode 100755 new mode 100644 index 603f40d0380741c8a0e4f24f5a2dc9668e2338a6..21493d0a003e6dc6c04833ed202416b36867d7bf --- a/gnome/src/dbus/configurationmanager-introspec.xml +++ b/gnome/src/dbus/configurationmanager-introspec.xml @@ -85,11 +85,11 @@ <method name="setCredentials" tp:name-for-bindings="setCredentials"> <tp:docstring> </tp:docstring> - <annotation name="com.trolltech.QtDBus.QtTypeName.In2" value="MapStringString"/> <arg type="s" name="accountID" direction="in"> <tp:docstring> </tp:docstring> </arg> + <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="VectorMapStringString"/> <arg type="aa{ss}" name="credentialInformation" direction="in" tp:type="String_String_Map"> <tp:docstring> </tp:docstring> @@ -137,11 +137,11 @@ <method name="getCredentials" tp:name-for-bindings="getCredentials"> <tp:docstring> </tp:docstring> - <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="MapStringString"/> <arg type="s" name="accountID" direction="in"> <tp:docstring> </tp:docstring> </arg> + <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="VectorMapStringString"/> <arg type="aa{ss}" name="credentialInformation" direction="out"> <tp:docstring> </tp:docstring> @@ -284,7 +284,7 @@ <method name="getAudioCodecList" tp:name-for-bindings="getAudioCodecList"> <tp:docstring> </tp:docstring> - <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="VectorString"/> + <annotation name="com.trolltech.QtDBus.QtTypeName.Out0" value="VectorInt"/> <arg type="ai" name="list" direction="out"> <tp:docstring> </tp:docstring> diff --git a/gnome/src/dbus/dbus.c b/gnome/src/dbus/dbus.c index 853614787dadca49b9c38f38ccf3aa803d253788..5c3cbfc55d42b17dac3ec1fc5f0f97af50098cc4 100644 --- a/gnome/src/dbus/dbus.c +++ b/gnome/src/dbus/dbus.c @@ -29,109 +29,112 @@ * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ -#include <config.h> - -#include <calltab.h> -#include <callmanager-glue.h> -#include <configurationmanager-glue.h> -#include <instance-glue.h> -#include <preferencesdialog.h> -#include <accountlistconfigdialog.h> -#include <mainwindow.h> -#include <marshaller.h> -#include <sliders.h> -#include <statusicon.h> -#include <assistant.h> - -#include <dbus.h> -#include <actions.h> -#include <string.h> - -#include <widget/imwidget.h> - -#include <eel-gconf-extensions.h> -#include <mainwindow.h> - -#define DEFAULT_DBUS_TIMEOUT 30000 +#include "config.h" + +#include "logger.h" +#include "calltab.h" +#include "callmanager-glue.h" +#include "configurationmanager-glue.h" +#include "instance-glue.h" +#include "preferencesdialog.h" +#include "accountlistconfigdialog.h" +#include "mainwindow.h" +#include "marshaller.h" +#include "sliders.h" +#include "statusicon.h" +#include "assistant.h" + +#include "dbus.h" +#include "actions.h" +#include "unused.h" + +#include "widget/imwidget.h" + +#include "eel-gconf-extensions.h" +#include "mainwindow.h" static DBusGProxy *callManagerProxy, *configurationManagerProxy, *instanceProxy; static void -new_call_created_cb (DBusGProxy *proxy UNUSED, const gchar *accountID, - const gchar *callID, const gchar *to, void *foo UNUSED) +new_call_created_cb(DBusGProxy *proxy UNUSED, const gchar *accountID, + const gchar *callID, const gchar *to, void *foo UNUSED) { callable_obj_t *c = create_new_call(CALL, CALL_STATE_RINGING, callID, accountID, to, to); - calllist_add_call(current_calls, c); - calltree_add_call(current_calls, c, NULL); + calllist_add_call(current_calls_tab, c); + calltree_add_call(current_calls_tab, c, NULL); update_actions(); - calltree_display(current_calls); + calltree_display(current_calls_tab); } static void -incoming_call_cb (DBusGProxy *proxy UNUSED, const gchar* accountID, - const gchar* callID, const gchar* from, void * foo UNUSED) +incoming_call_cb(DBusGProxy *proxy UNUSED, const gchar* accountID, + const gchar* callID, const gchar* from, void * foo UNUSED) { // We receive the from field under a formatted way. We want to extract the number and the name of the caller - gchar *peer_name = call_get_peer_name (from); - gchar *peer_number = call_get_peer_number (from); + gchar *peer_name = call_get_peer_name(from); + gchar *peer_number = call_get_peer_number(from); - callable_obj_t *c = create_new_call (CALL, CALL_STATE_INCOMING, callID, accountID, peer_name, peer_number); + callable_obj_t *c = create_new_call(CALL, CALL_STATE_INCOMING, callID, accountID, peer_name, peer_number); g_free(peer_number); g_free(peer_name); - status_tray_icon_blink (TRUE); + status_tray_icon_blink(TRUE); popup_main_window(); - notify_incoming_call (c); - sflphone_incoming_call (c); + notify_incoming_call(c); + sflphone_incoming_call(c); } static void -zrtp_negotiation_failed_cb (DBusGProxy *proxy UNUSED, const gchar* callID, - const gchar* reason, const gchar* severity, void * foo UNUSED) +zrtp_negotiation_failed_cb(DBusGProxy *proxy UNUSED, const gchar* callID, + const gchar* reason, const gchar* severity, void * foo UNUSED) { - main_window_zrtp_negotiation_failed (callID, reason, severity); - callable_obj_t *c = calllist_get_call (current_calls, callID); + main_window_zrtp_negotiation_failed(callID, reason, severity); + callable_obj_t *c = calllist_get_call(current_calls_tab, callID); + if (c) - notify_zrtp_negotiation_failed (c); + notify_zrtp_negotiation_failed(c); } static void -volume_changed_cb (DBusGProxy *proxy UNUSED, const gchar* device, const gdouble value, - void * foo UNUSED) +volume_changed_cb(DBusGProxy *proxy UNUSED, const gchar* device, const gdouble value, + void * foo UNUSED) { - set_slider (device, value); + set_slider(device, value); } static void -voice_mail_cb (DBusGProxy *proxy UNUSED, const gchar* accountID, const guint nb, - void * foo UNUSED) +voice_mail_cb(DBusGProxy *proxy UNUSED, const gchar* accountID, const guint nb, + void * foo UNUSED) { - sflphone_notify_voice_mail (accountID, nb); + sflphone_notify_voice_mail(accountID, nb); } static void -incoming_message_cb (DBusGProxy *proxy UNUSED, const gchar* callID UNUSED, const gchar *from, const gchar* msg, void * foo UNUSED) +incoming_message_cb(DBusGProxy *proxy UNUSED, const gchar* callID UNUSED, const gchar *from, const gchar* msg, void * foo UNUSED) { // do not display message if instant messaging is disabled - if (eel_gconf_key_exists (INSTANT_MESSAGING_ENABLED) && !eel_gconf_get_integer (INSTANT_MESSAGING_ENABLED)) + if (eel_gconf_key_exists(INSTANT_MESSAGING_ENABLED) && !eel_gconf_get_integer(INSTANT_MESSAGING_ENABLED)) return; GtkWidget **widget; gchar *id; - callable_obj_t *call = calllist_get_call (current_calls, callID); + callable_obj_t *call = calllist_get_call(current_calls_tab, callID); + if (call) { widget = &call->_im_widget; id = call->_callID; } else { - conference_obj_t *conf = conferencelist_get (current_calls, callID); + conference_obj_t *conf = conferencelist_get(current_calls_tab, callID); + if (!conf) { - ERROR ("Message received, but no recipient found"); + ERROR("Message received, but no recipient found"); return; } + widget = &conf->_im_widget; id = conf->_confID; } @@ -139,39 +142,41 @@ incoming_message_cb (DBusGProxy *proxy UNUSED, const gchar* callID UNUSED, const if (!*widget) *widget = im_widget_display(id); - im_widget_add_message (IM_WIDGET(*widget), from, msg, 0); + im_widget_add_message(IM_WIDGET(*widget), from, msg, 0); } static void -call_state_cb (DBusGProxy *proxy UNUSED, const gchar* callID, const gchar* state, - void * foo UNUSED) +call_state_cb(DBusGProxy *proxy UNUSED, const gchar* callID, const gchar* state, + void * foo UNUSED) { - callable_obj_t *c = calllist_get_call (current_calls, callID); + callable_obj_t *c = calllist_get_call(current_calls_tab, callID); + if (c) { - if (g_strcmp0 (state, "HUNGUP") == 0) { + if (g_strcmp0(state, "HUNGUP") == 0) { if (c->_state == CALL_STATE_CURRENT) { time(&c->_time_stop); - calltree_update_call (history, c, NULL); + calltree_update_call(history_tab, c); } - calltree_update_call (history, c, NULL); + + calltree_update_call(history_tab, c); status_bar_display_account(); - sflphone_hung_up (c); - } else if (g_strcmp0 (state, "UNHOLD_CURRENT") == 0) { - sflphone_current (c); - } else if (g_strcmp0 (state, "UNHOLD_RECORD") == 0) { - sflphone_record (c); - } else if (g_strcmp0 (state, "HOLD") == 0) { - sflphone_hold (c); - } else if (g_strcmp0 (state, "RINGING") == 0) { - sflphone_ringing (c); - } else if (g_strcmp0 (state, "CURRENT") == 0) { - sflphone_current (c); - } else if (g_strcmp0 (state, "RECORD") == 0) { - sflphone_record (c); - } else if (g_strcmp0 (state, "FAILURE") == 0) { - sflphone_fail (c); - } else if (g_strcmp0 (state, "BUSY") == 0) { - sflphone_busy (c); + sflphone_hung_up(c); + } else if (g_strcmp0(state, "UNHOLD_CURRENT") == 0) { + sflphone_current(c); + } else if (g_strcmp0(state, "UNHOLD_RECORD") == 0) { + sflphone_record(c); + } else if (g_strcmp0(state, "HOLD") == 0) { + sflphone_hold(c); + } else if (g_strcmp0(state, "RINGING") == 0) { + sflphone_ringing(c); + } else if (g_strcmp0(state, "CURRENT") == 0) { + sflphone_current(c); + } else if (g_strcmp0(state, "RECORD") == 0) { + sflphone_record(c); + } else if (g_strcmp0(state, "FAILURE") == 0) { + sflphone_fail(c); + } else if (g_strcmp0(state, "BUSY") == 0) { + sflphone_busy(c); } } else { ERROR("DBUS: Error: Call is NULL in %s", __func__); @@ -179,69 +184,68 @@ call_state_cb (DBusGProxy *proxy UNUSED, const gchar* callID, const gchar* state // The callID is unknow, threat it like a new call // If it were an incoming call, we won't be here // It means that a new call has been initiated with an other client (cli for instance) - if ((g_strcmp0 (state, "RINGING")) == 0 || - (g_strcmp0 (state, "CURRENT")) == 0 || - (g_strcmp0 (state, "RECORD"))) { + if ((g_strcmp0(state, "RINGING")) == 0 || + (g_strcmp0(state, "CURRENT")) == 0 || + (g_strcmp0(state, "RECORD"))) { - DEBUG ("DBUS: New ringing call! accountID: %s", callID); + DEBUG("DBUS: New ringing call! accountID: %s", callID); // We fetch the details associated to the specified call - GHashTable *call_details = dbus_get_call_details (callID); - callable_obj_t *new_call = create_new_call_from_details (callID, call_details); + GHashTable *call_details = dbus_get_call_details(callID); + callable_obj_t *new_call = create_new_call_from_details(callID, call_details); - new_call->_history_state = (g_strcasecmp (g_hash_table_lookup (call_details, "CALL_TYPE"), "0") == 0) - ? INCOMING : OUTGOING; + new_call->_history_state = (g_strcasecmp(g_hash_table_lookup(call_details, "CALL_TYPE"), "0") == 0) + ? INCOMING : OUTGOING; - calllist_add_call (current_calls, new_call); - calltree_add_call (current_calls, new_call, NULL); + calllist_add_call(current_calls_tab, new_call); + calltree_add_call(current_calls_tab, new_call, NULL); update_actions(); - calltree_display (current_calls); + calltree_display(current_calls_tab); } } } static void toggle_im(conference_obj_t *conf, gboolean activate) { - for (GSList *part = conf->participant_list; part; part = g_slist_next (part)) { - callable_obj_t *call = calllist_get_call (current_calls, part->data); + for (GSList *part = conf->participant_list; part; part = g_slist_next(part)) { + callable_obj_t *call = calllist_get_call(current_calls_tab, part->data); + if (call) - im_widget_update_state (IM_WIDGET (call->_im_widget), activate); + im_widget_update_state(IM_WIDGET(call->_im_widget), activate); } } static void -conference_changed_cb (DBusGProxy *proxy UNUSED, const gchar* confID, - const gchar* state, void * foo UNUSED) +conference_changed_cb(DBusGProxy *proxy UNUSED, const gchar* confID, + const gchar* state, void * foo UNUSED) { - DEBUG ("DBUS: Conference state changed: %s\n", state); + DEBUG("DBUS: Conference state changed: %s\n", state); - // sflphone_display_transfer_status("Transfer successfull"); - conference_obj_t* changed_conf = conferencelist_get (current_calls, confID); + conference_obj_t* changed_conf = conferencelist_get(current_calls_tab, confID); - if(changed_conf == NULL) { - ERROR("DBUS: Conference is NULL in conference state changed"); - return; + if (changed_conf == NULL) { + ERROR("DBUS: Conference is NULL in conference state changed"); + return; } // remove old conference from calltree - calltree_remove_conference (current_calls, changed_conf, NULL); + calltree_remove_conference(current_calls_tab, changed_conf); // update conference state - if (g_strcmp0 (state, "ACTIVE_ATACHED") == 0) { - changed_conf->_state = CONFERENCE_STATE_ACTIVE_ATACHED; - } else if (g_strcmp0 (state, "ACTIVE_DETACHED") == 0) { + if (g_strcmp0(state, "ACTIVE_ATTACHED") == 0) + changed_conf->_state = CONFERENCE_STATE_ACTIVE_ATTACHED; + else if (g_strcmp0(state, "ACTIVE_DETACHED") == 0) changed_conf->_state = CONFERENCE_STATE_ACTIVE_DETACHED; - } else if (g_strcmp0 (state, "ACTIVE_ATTACHED_REC") == 0) { + else if (g_strcmp0(state, "ACTIVE_ATTACHED_REC") == 0) changed_conf->_state = CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD; - } else if (g_strcmp0(state, "ACTIVE_DETACHED_REC") == 0) { + else if (g_strcmp0(state, "ACTIVE_DETACHED_REC") == 0) changed_conf->_state = CONFERENCE_STATE_ACTIVE_DETACHED_RECORD; - } else if (g_strcmp0 (state, "HOLD") == 0) { + else if (g_strcmp0(state, "HOLD") == 0) changed_conf->_state = CONFERENCE_STATE_HOLD; - } else if (g_strcmp0(state, "HOLD_REC") == 0) { + else if (g_strcmp0(state, "HOLD_REC") == 0) changed_conf->_state = CONFERENCE_STATE_HOLD_RECORD; - } else { - DEBUG ("Error: conference state not recognized"); - } + else + DEBUG("Error: conference state not recognized"); // reactivate instant messaging window for these calls toggle_im(changed_conf, TRUE); @@ -252,81 +256,77 @@ conference_changed_cb (DBusGProxy *proxy UNUSED, const gchar* confID, // deactivate instant messaging window for new participants toggle_im(changed_conf, FALSE); - - calltree_add_conference (current_calls, changed_conf); + calltree_add_conference_to_current_calls(changed_conf); } static void -conference_created_cb (DBusGProxy *proxy UNUSED, const gchar* confID, void * foo UNUSED) +conference_created_cb(DBusGProxy *proxy UNUSED, const gchar* confID, void * foo UNUSED) { - DEBUG ("DBUS: Conference %s added", confID); + DEBUG("DBUS: Conference %s added", confID); - conference_obj_t *new_conf = create_new_conference (CONFERENCE_STATE_ACTIVE_ATACHED, confID); + conference_obj_t *new_conf = create_new_conference(CONFERENCE_STATE_ACTIVE_ATTACHED, confID); - gchar **participants = dbus_get_participant_list (new_conf->_confID); + gchar **participants = dbus_get_participant_list(new_conf->_confID); // Update conference list - conference_participant_list_update (participants, new_conf); + conference_participant_list_update(participants, new_conf); // Add conference ID in in each calls - for (gchar **part = participants; *part; part++) { - callable_obj_t *call = calllist_get_call (current_calls, *part); + for (gchar **part = participants; part && *part; ++part) { + callable_obj_t *call = calllist_get_call(current_calls_tab, *part); - // set when this call have been added to the conference + /* set when this call has been added to the conference */ time(&call->_time_added); - im_widget_update_state (IM_WIDGET (call->_im_widget), FALSE); + im_widget_update_state(IM_WIDGET(call->_im_widget), FALSE); // if one of these participant is currently recording, the whole conference will be recorded - if(call->_state == CALL_STATE_RECORD) + if (call->_state == CALL_STATE_RECORD) new_conf->_state = CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD; - call->_confID = g_strdup (confID); - call->_historyConfID = g_strdup (confID); + call->_confID = g_strdup(confID); + call->_historyConfID = g_strdup(confID); } g_strfreev(participants); time(&new_conf->_time_start); - conferencelist_add (current_calls, new_conf); - conferencelist_add (history, new_conf); - calltree_add_conference (current_calls, new_conf); - calltree_add_conference (history, new_conf); + conferencelist_add(current_calls_tab, new_conf); + calltree_add_conference_to_current_calls(new_conf); } static void -conference_removed_cb (DBusGProxy *proxy UNUSED, const gchar* confID, void * foo UNUSED) +conference_removed_cb(DBusGProxy *proxy UNUSED, const gchar* confID, void * foo UNUSED) { - DEBUG ("DBUS: Conference removed %s", confID); + DEBUG("DBUS: Conference removed %s", confID); - conference_obj_t * c = conferencelist_get (current_calls, confID); - calltree_remove_conference (current_calls, c, NULL); + conference_obj_t * c = conferencelist_get(current_calls_tab, confID); + calltree_remove_conference(current_calls_tab, c); - im_widget_update_state (IM_WIDGET (c->_im_widget), FALSE); + im_widget_update_state(IM_WIDGET(c->_im_widget), FALSE); - // remove all participant for this conference - for (GSList *p = c->participant_list; p; p = conference_next_participant (p)) { + // remove all participants for this conference + for (GSList *p = c->participant_list; p; p = g_slist_next(p)) { + callable_obj_t *call = calllist_get_call(current_calls_tab, p->data); - callable_obj_t *call = calllist_get_call (current_calls, p->data); if (call) { - g_free (call->_confID); + g_free(call->_confID); call->_confID = NULL; - - im_widget_update_state(IM_WIDGET (call->_im_widget), TRUE); + im_widget_update_state(IM_WIDGET(call->_im_widget), TRUE); } } - conferencelist_remove (current_calls, c->_confID); + conferencelist_remove(current_calls_tab, c->_confID); } static void -record_playback_filepath_cb (DBusGProxy *proxy UNUSED, const gchar *id, const gchar *filepath) +record_playback_filepath_cb(DBusGProxy *proxy UNUSED, const gchar *id, const gchar *filepath) { DEBUG("DBUS: Filepath for %s: %s", id, filepath); - callable_obj_t *call = calllist_get_call(current_calls, id); - conference_obj_t *conf = conferencelist_get(current_calls, id); + callable_obj_t *call = calllist_get_call(current_calls_tab, id); + conference_obj_t *conf = conferencelist_get(current_calls_tab, id); if (call && conf) { ERROR("DBUS: Two objects for this callid"); @@ -338,157 +338,158 @@ record_playback_filepath_cb (DBusGProxy *proxy UNUSED, const gchar *id, const gc return; } - if(call && call->_recordfile == NULL) + if (call && call->_recordfile == NULL) call->_recordfile = g_strdup(filepath); - else if(conf && conf->_recordfile == NULL) + else if (conf && conf->_recordfile == NULL) conf->_recordfile = g_strdup(filepath); } static void -record_playback_stopped_cb (DBusGProxy *proxy UNUSED, const gchar *filepath) +record_playback_stopped_cb(DBusGProxy *proxy UNUSED, const gchar *filepath) { DEBUG("DBUS: Playback stopped for %s", filepath); - const gint calllist_size = calllist_get_size(history); + const gint calllist_size = calllist_get_size(history_tab); + for (gint i = 0; i < calllist_size; i++) { - QueueElement *element = calllist_get_nth(history, i); + QueueElement *element = calllist_get_nth(history_tab, i); + if (element == NULL) { ERROR("DBUS: ERROR: Could not find %dth call", i); break; } else if (element->type == HIST_CALL && - g_strcmp0(element->elem.call->_recordfile, filepath) == 0) + g_strcmp0(element->elem.call->_recordfile, filepath) == 0) element->elem.call->_record_is_playing = FALSE; } - const gint conflist_size = conferencelist_get_size(history); - for (gint i = 0; i < conflist_size; i++) { - conference_obj_t *conf = conferencelist_get_nth(history, i); - if (conf == NULL) { - ERROR("DBUS: ERROR: Could not find %dth conf", i); - break; - } else if (g_strcmp0(conf->_recordfile, filepath) == 0) - conf->_record_is_playing = FALSE; - } - update_actions(); } static void -accounts_changed_cb (DBusGProxy *proxy UNUSED, void * foo UNUSED) +accounts_changed_cb(DBusGProxy *proxy UNUSED, void * foo UNUSED) { - DEBUG ("DBUS: Accounts changed"); + DEBUG("DBUS: Accounts changed"); sflphone_fill_account_list(); sflphone_fill_ip2ip_profile(); account_list_config_dialog_fill(); status_bar_display_account(); - statusicon_set_tooltip (); + statusicon_set_tooltip(); } static void -transfer_succeded_cb (DBusGProxy *proxy UNUSED, void * foo UNUSED) +transfer_succeded_cb(DBusGProxy *proxy UNUSED, void * foo UNUSED) { - DEBUG ("DBUS: Transfer succeded"); - sflphone_display_transfer_status ("Transfer successfull"); + DEBUG("DBUS: Transfer succeded"); + sflphone_display_transfer_status("Transfer successfull"); } static void -transfer_failed_cb (DBusGProxy *proxy UNUSED, void * foo UNUSED) +transfer_failed_cb(DBusGProxy *proxy UNUSED, void * foo UNUSED) { - DEBUG ("DBUS: Transfer failed"); - sflphone_display_transfer_status ("Transfer failed"); + DEBUG("DBUS: Transfer failed"); + sflphone_display_transfer_status("Transfer failed"); } static void -secure_sdes_on_cb (DBusGProxy *proxy UNUSED, const gchar *callID, void *foo UNUSED) +secure_sdes_on_cb(DBusGProxy *proxy UNUSED, const gchar *callID, void *foo UNUSED) { - DEBUG ("DBUS: SRTP using SDES is on"); - callable_obj_t *c = calllist_get_call (current_calls, callID); + DEBUG("DBUS: SRTP using SDES is on"); + callable_obj_t *c = calllist_get_call(current_calls_tab, callID); + if (c) { - sflphone_srtp_sdes_on (c); - notify_secure_on (c); + sflphone_srtp_sdes_on(c); + notify_secure_on(c); } } static void -secure_sdes_off_cb (DBusGProxy *proxy UNUSED, const gchar *callID, void *foo UNUSED) +secure_sdes_off_cb(DBusGProxy *proxy UNUSED, const gchar *callID, void *foo UNUSED) { - DEBUG ("DBUS: SRTP using SDES is off"); - callable_obj_t *c = calllist_get_call (current_calls, callID); + DEBUG("DBUS: SRTP using SDES is off"); + callable_obj_t *c = calllist_get_call(current_calls_tab, callID); + if (c) { - sflphone_srtp_sdes_off (c); - notify_secure_off (c); + sflphone_srtp_sdes_off(c); + notify_secure_off(c); } } static void -secure_zrtp_on_cb (DBusGProxy *proxy UNUSED, const gchar* callID, const gchar* cipher, - void * foo UNUSED) +secure_zrtp_on_cb(DBusGProxy *proxy UNUSED, const gchar* callID, const gchar* cipher, + void * foo UNUSED) { - DEBUG ("DBUS: SRTP using ZRTP is ON secure_on_cb"); - callable_obj_t *c = calllist_get_call (current_calls, callID); + DEBUG("DBUS: SRTP using ZRTP is ON secure_on_cb"); + callable_obj_t *c = calllist_get_call(current_calls_tab, callID); + if (c) { - c->_srtp_cipher = g_strdup (cipher); - sflphone_srtp_zrtp_on (c); - notify_secure_on (c); + c->_srtp_cipher = g_strdup(cipher); + sflphone_srtp_zrtp_on(c); + notify_secure_on(c); } } static void -secure_zrtp_off_cb (DBusGProxy *proxy UNUSED, const gchar* callID, void * foo UNUSED) +secure_zrtp_off_cb(DBusGProxy *proxy UNUSED, const gchar* callID, void * foo UNUSED) { - DEBUG ("DBUS: SRTP using ZRTP is OFF"); - callable_obj_t *c = calllist_get_call (current_calls, callID); + DEBUG("DBUS: SRTP using ZRTP is OFF"); + callable_obj_t *c = calllist_get_call(current_calls_tab, callID); + if (c) { - sflphone_srtp_zrtp_off (c); - notify_secure_off (c); + sflphone_srtp_zrtp_off(c); + notify_secure_off(c); } } static void -show_zrtp_sas_cb (DBusGProxy *proxy UNUSED, const gchar* callID, const gchar* sas, - const gboolean verified, void * foo UNUSED) +show_zrtp_sas_cb(DBusGProxy *proxy UNUSED, const gchar* callID, const gchar* sas, + const gboolean verified, void * foo UNUSED) { - DEBUG ("DBUS: Showing SAS"); - callable_obj_t * c = calllist_get_call (current_calls, callID); + DEBUG("DBUS: Showing SAS"); + callable_obj_t * c = calllist_get_call(current_calls_tab, callID); + if (c) - sflphone_srtp_zrtp_show_sas (c, sas, verified); + sflphone_srtp_zrtp_show_sas(c, sas, verified); } static void -confirm_go_clear_cb (DBusGProxy *proxy UNUSED, const gchar* callID, void * foo UNUSED) +confirm_go_clear_cb(DBusGProxy *proxy UNUSED, const gchar* callID, void * foo UNUSED) { - DEBUG ("DBUS: Confirm Go Clear request"); - callable_obj_t * c = calllist_get_call (current_calls, callID); + DEBUG("DBUS: Confirm Go Clear request"); + callable_obj_t * c = calllist_get_call(current_calls_tab, callID); + if (c) - main_window_confirm_go_clear (c); + main_window_confirm_go_clear(c); } static void -zrtp_not_supported_cb (DBusGProxy *proxy UNUSED, const gchar* callID, void * foo UNUSED) +zrtp_not_supported_cb(DBusGProxy *proxy UNUSED, const gchar* callID, void * foo UNUSED) { - DEBUG ("ZRTP not supported on the other end"); - callable_obj_t * c = calllist_get_call (current_calls, callID); + DEBUG("ZRTP not supported on the other end"); + callable_obj_t * c = calllist_get_call(current_calls_tab, callID); + if (c) { - main_window_zrtp_not_supported (c); - notify_zrtp_not_supported (c); + main_window_zrtp_not_supported(c); + notify_zrtp_not_supported(c); } } static void -sip_call_state_cb (DBusGProxy *proxy UNUSED, const gchar* callID, - const gchar* description, const guint code, void * foo UNUSED) +sip_call_state_cb(DBusGProxy *proxy UNUSED, const gchar* callID, + const gchar* description, const guint code, void * foo UNUSED) { DEBUG("DBUS: Sip call state changed %s", callID); - callable_obj_t *c = calllist_get_call (current_calls, callID); + callable_obj_t *c = calllist_get_call(current_calls_tab, callID); + if (c) - sflphone_call_state_changed (c, description, code); + sflphone_call_state_changed(c, description, code); } static void -error_alert (DBusGProxy *proxy UNUSED, int err, void * foo UNUSED) +error_alert(DBusGProxy *proxy UNUSED, int err, void * foo UNUSED) { const gchar *msg; + switch (err) { case ALSA_PLAYBACK_DEVICE: msg = _("ALSA notification\n\nError while opening playback device"); @@ -507,203 +508,205 @@ error_alert (DBusGProxy *proxy UNUSED, int err, void * foo UNUSED) } GtkWidget * dialog = gtk_message_dialog_new( - GTK_WINDOW (get_main_window()), + GTK_WINDOW(get_main_window()), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", msg); - gtk_window_set_title (GTK_WINDOW (dialog), _ ("SFLphone Error")); + gtk_window_set_title(GTK_WINDOW(dialog), _("SFLphone Error")); - g_signal_connect(dialog, "response", G_CALLBACK (gtk_widget_destroy), NULL); + g_signal_connect(dialog, "response", G_CALLBACK(gtk_widget_destroy), NULL); gtk_widget_show(dialog); } gboolean -dbus_connect (GError **error) +dbus_connect(GError **error) { g_type_init(); - DBusGConnection *connection = dbus_g_bus_get (DBUS_BUS_SESSION, error); + DBusGConnection *connection = dbus_g_bus_get(DBUS_BUS_SESSION, error); + if (connection == NULL) return FALSE; /* Create a proxy object for the "bus driver" (name "org.freedesktop.DBus") */ - instanceProxy = dbus_g_proxy_new_for_name (connection, + instanceProxy = dbus_g_proxy_new_for_name(connection, "org.sflphone.SFLphone", "/org/sflphone/SFLphone/Instance", "org.sflphone.SFLphone.Instance"); if (instanceProxy == NULL) { - ERROR ("Failed to get proxy to Instance"); + ERROR("Failed to get proxy to Instance"); return FALSE; } - DEBUG ("DBus connected to Instance"); + DEBUG("DBus connected to Instance"); - callManagerProxy = dbus_g_proxy_new_for_name (connection, + callManagerProxy = dbus_g_proxy_new_for_name(connection, "org.sflphone.SFLphone", "/org/sflphone/SFLphone/CallManager", "org.sflphone.SFLphone.CallManager"); - g_assert (callManagerProxy != NULL); + g_assert(callManagerProxy != NULL); - DEBUG ("DBus connected to CallManager"); + DEBUG("DBus connected to CallManager"); /* STRING STRING STRING Marshaller */ /* Incoming call */ - dbus_g_object_register_marshaller ( + dbus_g_object_register_marshaller( g_cclosure_user_marshal_VOID__STRING_STRING_STRING, G_TYPE_NONE, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INVALID); - dbus_g_proxy_add_signal (callManagerProxy, "newCallCreated", G_TYPE_STRING, - G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "newCallCreated", - G_CALLBACK (new_call_created_cb), NULL, NULL); - dbus_g_proxy_add_signal (callManagerProxy, "incomingCall", G_TYPE_STRING, - G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "incomingCall", - G_CALLBACK (incoming_call_cb), NULL, NULL); - - dbus_g_proxy_add_signal (callManagerProxy, "zrtpNegotiationFailed", - G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "zrtpNegotiationFailed", - G_CALLBACK (zrtp_negotiation_failed_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "newCallCreated", G_TYPE_STRING, + G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "newCallCreated", + G_CALLBACK(new_call_created_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "incomingCall", G_TYPE_STRING, + G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "incomingCall", + G_CALLBACK(incoming_call_cb), NULL, NULL); + + dbus_g_proxy_add_signal(callManagerProxy, "zrtpNegotiationFailed", + G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "zrtpNegotiationFailed", + G_CALLBACK(zrtp_negotiation_failed_cb), NULL, NULL); /* Register a marshaller for STRING,STRING */ - dbus_g_object_register_marshaller ( + dbus_g_object_register_marshaller( g_cclosure_user_marshal_VOID__STRING_STRING, G_TYPE_NONE, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INVALID); - dbus_g_proxy_add_signal (callManagerProxy, "callStateChanged", G_TYPE_STRING, - G_TYPE_STRING, G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "callStateChanged", - G_CALLBACK (call_state_cb), NULL, NULL); - - dbus_g_object_register_marshaller (g_cclosure_user_marshal_VOID__STRING_INT, - G_TYPE_NONE, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INVALID); - dbus_g_proxy_add_signal (callManagerProxy, "voiceMailNotify", G_TYPE_STRING, - G_TYPE_INT, G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "voiceMailNotify", - G_CALLBACK (voice_mail_cb), NULL, NULL); - - dbus_g_proxy_add_signal (callManagerProxy, "incomingMessage", G_TYPE_STRING, - G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "incomingMessage", - G_CALLBACK (incoming_message_cb), NULL, NULL); - - dbus_g_object_register_marshaller ( + dbus_g_proxy_add_signal(callManagerProxy, "callStateChanged", G_TYPE_STRING, + G_TYPE_STRING, G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "callStateChanged", + G_CALLBACK(call_state_cb), NULL, NULL); + + dbus_g_object_register_marshaller(g_cclosure_user_marshal_VOID__STRING_INT, + G_TYPE_NONE, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INVALID); + dbus_g_proxy_add_signal(callManagerProxy, "voiceMailNotify", G_TYPE_STRING, + G_TYPE_INT, G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "voiceMailNotify", + G_CALLBACK(voice_mail_cb), NULL, NULL); + + dbus_g_proxy_add_signal(callManagerProxy, "incomingMessage", G_TYPE_STRING, + G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "incomingMessage", + G_CALLBACK(incoming_message_cb), NULL, NULL); + + dbus_g_object_register_marshaller( g_cclosure_user_marshal_VOID__STRING_DOUBLE, G_TYPE_NONE, G_TYPE_STRING, G_TYPE_DOUBLE, G_TYPE_INVALID); - dbus_g_proxy_add_signal (callManagerProxy, "volumeChanged", G_TYPE_STRING, - G_TYPE_DOUBLE, G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "volumeChanged", - G_CALLBACK (volume_changed_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "volumeChanged", G_TYPE_STRING, + G_TYPE_DOUBLE, G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "volumeChanged", + G_CALLBACK(volume_changed_cb), NULL, NULL); - dbus_g_proxy_add_signal (callManagerProxy, "transferSucceded", G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "transferSucceded", - G_CALLBACK (transfer_succeded_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "transferSucceded", G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "transferSucceded", + G_CALLBACK(transfer_succeded_cb), NULL, NULL); - dbus_g_proxy_add_signal (callManagerProxy, "transferFailed", G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "transferFailed", - G_CALLBACK (transfer_failed_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "transferFailed", G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "transferFailed", + G_CALLBACK(transfer_failed_cb), NULL, NULL); /* Conference related callback */ - dbus_g_object_register_marshaller (g_cclosure_user_marshal_VOID__STRING, - G_TYPE_NONE, G_TYPE_STRING, G_TYPE_INVALID); - dbus_g_proxy_add_signal (callManagerProxy, "conferenceChanged", G_TYPE_STRING, - G_TYPE_STRING, G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "conferenceChanged", - G_CALLBACK (conference_changed_cb), NULL, NULL); + dbus_g_object_register_marshaller(g_cclosure_user_marshal_VOID__STRING, + G_TYPE_NONE, G_TYPE_STRING, G_TYPE_INVALID); + dbus_g_proxy_add_signal(callManagerProxy, "conferenceChanged", G_TYPE_STRING, + G_TYPE_STRING, G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "conferenceChanged", + G_CALLBACK(conference_changed_cb), NULL, NULL); - dbus_g_proxy_add_signal (callManagerProxy, "conferenceCreated", G_TYPE_STRING, - G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "conferenceCreated", - G_CALLBACK (conference_created_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "conferenceCreated", G_TYPE_STRING, + G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "conferenceCreated", + G_CALLBACK(conference_created_cb), NULL, NULL); - dbus_g_proxy_add_signal (callManagerProxy, "conferenceRemoved", G_TYPE_STRING, - G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "conferenceRemoved", - G_CALLBACK (conference_removed_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "conferenceRemoved", G_TYPE_STRING, + G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "conferenceRemoved", + G_CALLBACK(conference_removed_cb), NULL, NULL); /* Playback related signals */ - dbus_g_proxy_add_signal (callManagerProxy, "recordPlaybackFilepath", G_TYPE_STRING, - G_TYPE_STRING, G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "recordPlaybackFilepath", - G_CALLBACK (record_playback_filepath_cb), NULL, NULL); - dbus_g_proxy_add_signal (callManagerProxy, "recordPlaybackStopped", G_TYPE_STRING, G_TYPE_INVALID); + dbus_g_proxy_add_signal(callManagerProxy, "recordPlaybackFilepath", G_TYPE_STRING, + G_TYPE_STRING, G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "recordPlaybackFilepath", + G_CALLBACK(record_playback_filepath_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "recordPlaybackStopped", G_TYPE_STRING, G_TYPE_INVALID); dbus_g_proxy_connect_signal(callManagerProxy, "recordPlaybackStopped", - G_CALLBACK (record_playback_stopped_cb), NULL, NULL); + G_CALLBACK(record_playback_stopped_cb), NULL, NULL); /* Security related callbacks */ - dbus_g_proxy_add_signal (callManagerProxy, "secureSdesOn", G_TYPE_STRING, - G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "secureSdesOn", - G_CALLBACK (secure_sdes_on_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "secureSdesOn", G_TYPE_STRING, + G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "secureSdesOn", + G_CALLBACK(secure_sdes_on_cb), NULL, NULL); - dbus_g_proxy_add_signal (callManagerProxy, "secureSdesOff", G_TYPE_STRING, - G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "secureSdesOff", - G_CALLBACK (secure_sdes_off_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "secureSdesOff", G_TYPE_STRING, + G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "secureSdesOff", + G_CALLBACK(secure_sdes_off_cb), NULL, NULL); /* Register a marshaller for STRING,STRING,BOOL */ - dbus_g_object_register_marshaller ( + dbus_g_object_register_marshaller( g_cclosure_user_marshal_VOID__STRING_STRING_BOOL, G_TYPE_NONE, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_BOOLEAN, G_TYPE_INVALID); - dbus_g_proxy_add_signal (callManagerProxy, "showSAS", G_TYPE_STRING, - G_TYPE_STRING, G_TYPE_BOOLEAN, G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "showSAS", - G_CALLBACK (show_zrtp_sas_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "showSAS", G_TYPE_STRING, + G_TYPE_STRING, G_TYPE_BOOLEAN, G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "showSAS", + G_CALLBACK(show_zrtp_sas_cb), NULL, NULL); - dbus_g_proxy_add_signal (callManagerProxy, "secureZrtpOn", G_TYPE_STRING, - G_TYPE_STRING, G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "secureZrtpOn", - G_CALLBACK (secure_zrtp_on_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "secureZrtpOn", G_TYPE_STRING, + G_TYPE_STRING, G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "secureZrtpOn", + G_CALLBACK(secure_zrtp_on_cb), NULL, NULL); /* Register a marshaller for STRING*/ - dbus_g_object_register_marshaller (g_cclosure_user_marshal_VOID__STRING, - G_TYPE_NONE, G_TYPE_STRING, G_TYPE_INVALID); - dbus_g_proxy_add_signal (callManagerProxy, "secureZrtpOff", G_TYPE_STRING, - G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "secureZrtpOff", - G_CALLBACK (secure_zrtp_off_cb), NULL, NULL); - dbus_g_proxy_add_signal (callManagerProxy, "zrtpNotSuppOther", G_TYPE_STRING, - G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "zrtpNotSuppOther", - G_CALLBACK (zrtp_not_supported_cb), NULL, NULL); - dbus_g_proxy_add_signal (callManagerProxy, "confirmGoClear", G_TYPE_STRING, - G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "confirmGoClear", - G_CALLBACK (confirm_go_clear_cb), NULL, NULL); + dbus_g_object_register_marshaller(g_cclosure_user_marshal_VOID__STRING, + G_TYPE_NONE, G_TYPE_STRING, G_TYPE_INVALID); + dbus_g_proxy_add_signal(callManagerProxy, "secureZrtpOff", G_TYPE_STRING, + G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "secureZrtpOff", + G_CALLBACK(secure_zrtp_off_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "zrtpNotSuppOther", G_TYPE_STRING, + G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "zrtpNotSuppOther", + G_CALLBACK(zrtp_not_supported_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "confirmGoClear", G_TYPE_STRING, + G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "confirmGoClear", + G_CALLBACK(confirm_go_clear_cb), NULL, NULL); /* VOID STRING STRING INT */ - dbus_g_object_register_marshaller ( + dbus_g_object_register_marshaller( g_cclosure_user_marshal_VOID__STRING_STRING_INT, G_TYPE_NONE, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INVALID); - dbus_g_proxy_add_signal (callManagerProxy, "sipCallStateChanged", - G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INVALID); - dbus_g_proxy_connect_signal (callManagerProxy, "sipCallStateChanged", - G_CALLBACK (sip_call_state_cb), NULL, NULL); + dbus_g_proxy_add_signal(callManagerProxy, "sipCallStateChanged", + G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INVALID); + dbus_g_proxy_connect_signal(callManagerProxy, "sipCallStateChanged", + G_CALLBACK(sip_call_state_cb), NULL, NULL); - configurationManagerProxy = dbus_g_proxy_new_for_name (connection, + configurationManagerProxy = dbus_g_proxy_new_for_name(connection, "org.sflphone.SFLphone", "/org/sflphone/SFLphone/ConfigurationManager", "org.sflphone.SFLphone.ConfigurationManager"); - g_assert (configurationManagerProxy != NULL); + g_assert(configurationManagerProxy != NULL); - DEBUG ("DBus connected to ConfigurationManager"); - dbus_g_proxy_add_signal (configurationManagerProxy, "accountsChanged", - G_TYPE_INVALID); - dbus_g_proxy_connect_signal (configurationManagerProxy, "accountsChanged", - G_CALLBACK (accounts_changed_cb), NULL, NULL); + DEBUG("DBus connected to ConfigurationManager"); + dbus_g_proxy_add_signal(configurationManagerProxy, "accountsChanged", + G_TYPE_INVALID); + dbus_g_proxy_connect_signal(configurationManagerProxy, "accountsChanged", + G_CALLBACK(accounts_changed_cb), NULL, NULL); - dbus_g_object_register_marshaller (g_cclosure_user_marshal_VOID__INT, - G_TYPE_NONE, G_TYPE_INT, G_TYPE_INVALID); - dbus_g_proxy_add_signal (configurationManagerProxy, "errorAlert", G_TYPE_INT, - G_TYPE_INVALID); - dbus_g_proxy_connect_signal (configurationManagerProxy, "errorAlert", - G_CALLBACK (error_alert), NULL, NULL); + dbus_g_object_register_marshaller(g_cclosure_user_marshal_VOID__INT, + G_TYPE_NONE, G_TYPE_INT, G_TYPE_INVALID); + dbus_g_proxy_add_signal(configurationManagerProxy, "errorAlert", G_TYPE_INT, + G_TYPE_INVALID); + dbus_g_proxy_connect_signal(configurationManagerProxy, "errorAlert", + G_CALLBACK(error_alert), NULL, NULL); /* Defines a default timeout for the proxies */ #if HAVE_DBUS_G_PROXY_SET_DEFAULT_TIMEOUT - dbus_g_proxy_set_default_timeout (callManagerProxy, DEFAULT_DBUS_TIMEOUT); - dbus_g_proxy_set_default_timeout (instanceProxy, DEFAULT_DBUS_TIMEOUT); - dbus_g_proxy_set_default_timeout (configurationManagerProxy, DEFAULT_DBUS_TIMEOUT); + static const int DEFAULT_DBUS_TIMEOUT = 30000; + dbus_g_proxy_set_default_timeout(callManagerProxy, DEFAULT_DBUS_TIMEOUT); + dbus_g_proxy_set_default_timeout(instanceProxy, DEFAULT_DBUS_TIMEOUT); + dbus_g_proxy_set_default_timeout(configurationManagerProxy, DEFAULT_DBUS_TIMEOUT); #endif return TRUE; @@ -712,56 +715,56 @@ dbus_connect (GError **error) void dbus_clean() { - g_object_unref (callManagerProxy); - g_object_unref (configurationManagerProxy); - g_object_unref (instanceProxy); + g_object_unref(callManagerProxy); + g_object_unref(configurationManagerProxy); + g_object_unref(instanceProxy); } void -dbus_hold (const callable_obj_t * c) +dbus_hold(const callable_obj_t * c) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_hold (callManagerProxy, c->_callID, &error); + org_sflphone_SFLphone_CallManager_hold(callManagerProxy, c->_callID, &error); if (error) { - ERROR ("Failed to call hold() on CallManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call hold() on CallManager: %s", error->message); + g_error_free(error); } } void -dbus_unhold (const callable_obj_t * c) +dbus_unhold(const callable_obj_t * c) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_unhold (callManagerProxy, c->_callID, &error); + org_sflphone_SFLphone_CallManager_unhold(callManagerProxy, c->_callID, &error); if (error) { - ERROR ("Failed to call unhold() on CallManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call unhold() on CallManager: %s", error->message); + g_error_free(error); } } void -dbus_hold_conference (const conference_obj_t * c) +dbus_hold_conference(const conference_obj_t * c) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_hold_conference (callManagerProxy, c->_confID, &error); + org_sflphone_SFLphone_CallManager_hold_conference(callManagerProxy, c->_confID, &error); if (error) { - ERROR ("Failed to call hold() on CallManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call hold() on CallManager: %s", error->message); + g_error_free(error); } } void -dbus_unhold_conference (const conference_obj_t * c) +dbus_unhold_conference(const conference_obj_t * c) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_unhold_conference (callManagerProxy, c->_confID, &error); + org_sflphone_SFLphone_CallManager_unhold_conference(callManagerProxy, c->_confID, &error); if (error) { - ERROR ("Failed to call unhold() on CallManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call unhold() on CallManager: %s", error->message); + g_error_free(error); } } @@ -772,7 +775,7 @@ dbus_start_recorded_file_playback(const gchar *filepath) gboolean result; org_sflphone_SFLphone_CallManager_start_recorded_file_playback(callManagerProxy, - filepath, &result, &error); + filepath, &result, &error); if (error) { ERROR("Failed to call recorded file playback: %s", error->message); @@ -787,7 +790,7 @@ dbus_stop_recorded_file_playback(const gchar *filepath) { GError *error = NULL; org_sflphone_SFLphone_CallManager_stop_recorded_file_playback(callManagerProxy, - filepath, &error); + filepath, &error); if (error) { ERROR("Failed to call stop recorded file playback: %s", error->message); @@ -796,46 +799,46 @@ dbus_stop_recorded_file_playback(const gchar *filepath) } void -dbus_hang_up (const callable_obj_t * c) +dbus_hang_up(const callable_obj_t * c) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_hang_up (callManagerProxy, c->_callID, &error); + org_sflphone_SFLphone_CallManager_hang_up(callManagerProxy, c->_callID, &error); if (error) { - ERROR ("Failed to call hang_up() on CallManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call hang_up() on CallManager: %s", error->message); + g_error_free(error); } } void -dbus_hang_up_conference (const conference_obj_t * c) +dbus_hang_up_conference(const conference_obj_t * c) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_hang_up_conference (callManagerProxy, c->_confID, &error); + org_sflphone_SFLphone_CallManager_hang_up_conference(callManagerProxy, c->_confID, &error); if (error) { - ERROR ("Failed to call hang_up() on CallManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call hang_up() on CallManager: %s", error->message); + g_error_free(error); } } void -dbus_transfer (const callable_obj_t * c) +dbus_transfer(const callable_obj_t * c) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_transfer (callManagerProxy, c->_callID, c->_trsft_to, &error); + org_sflphone_SFLphone_CallManager_transfer(callManagerProxy, c->_callID, c->_trsft_to, &error); if (error) { - ERROR ("Failed to call transfer() on CallManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call transfer() on CallManager: %s", error->message); + g_error_free(error); } } void -dbus_attended_transfer (const callable_obj_t *transfer, const callable_obj_t *target) +dbus_attended_transfer(const callable_obj_t *transfer, const callable_obj_t *target) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_attended_transfer (callManagerProxy, transfer->_callID, target->_callID, &error); + org_sflphone_SFLphone_CallManager_attended_transfer(callManagerProxy, transfer->_callID, target->_callID, &error); if (error) { ERROR("Failed to call transfer() on CallManager: %s", error->message); @@ -844,43 +847,43 @@ dbus_attended_transfer (const callable_obj_t *transfer, const callable_obj_t *ta } void -dbus_accept (const callable_obj_t * c) +dbus_accept(const callable_obj_t * c) { - status_tray_icon_blink (FALSE); + status_tray_icon_blink(FALSE); GError *error = NULL; - org_sflphone_SFLphone_CallManager_accept (callManagerProxy, c->_callID, &error); + org_sflphone_SFLphone_CallManager_accept(callManagerProxy, c->_callID, &error); if (error) { - ERROR ("Failed to call accept(%s) on CallManager: %s", c->_callID, error->message); - g_error_free (error); + ERROR("Failed to call accept(%s) on CallManager: %s", c->_callID, error->message); + g_error_free(error); } } void -dbus_refuse (const callable_obj_t * c) +dbus_refuse(const callable_obj_t * c) { - status_tray_icon_blink (FALSE); + status_tray_icon_blink(FALSE); GError *error = NULL; - org_sflphone_SFLphone_CallManager_refuse (callManagerProxy, c->_callID, &error); + org_sflphone_SFLphone_CallManager_refuse(callManagerProxy, c->_callID, &error); if (error) { - ERROR ("Failed to call refuse() on CallManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call refuse() on CallManager: %s", error->message); + g_error_free(error); } } void -dbus_place_call (const callable_obj_t * c) +dbus_place_call(const callable_obj_t * c) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_place_call (callManagerProxy, c->_accountID, + org_sflphone_SFLphone_CallManager_place_call(callManagerProxy, c->_accountID, c->_callID, c->_peer_number, &error); if (error) { - ERROR ("Failed to call placeCall() on CallManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call placeCall() on CallManager: %s", error->message); + g_error_free(error); } } @@ -890,227 +893,230 @@ dbus_account_list() GError *error = NULL; char ** array = NULL; - if (!org_sflphone_SFLphone_ConfigurationManager_get_account_list ( + if (!org_sflphone_SFLphone_ConfigurationManager_get_account_list( configurationManagerProxy, &array, &error)) { if (error->domain == DBUS_GERROR && error->code == DBUS_GERROR_REMOTE_EXCEPTION) - ERROR ("Caught remote method (get_account_list) exception %s: %s", dbus_g_error_get_name (error), error->message); + ERROR("Caught remote method (get_account_list) exception %s: %s", dbus_g_error_get_name(error), error->message); else - ERROR ("Error while calling get_account_list: %s", error->message); + ERROR("Error while calling get_account_list: %s", error->message); - g_error_free (error); + g_error_free(error); } else - DEBUG ("DBus called get_account_list() on ConfigurationManager"); + DEBUG("DBus called get_account_list() on ConfigurationManager"); return array; } GHashTable* -dbus_get_account_details (gchar * accountID) +dbus_get_account_details(gchar * accountID) { GError *error = NULL; GHashTable * details = NULL; - if (!org_sflphone_SFLphone_ConfigurationManager_get_account_details ( + if (!org_sflphone_SFLphone_ConfigurationManager_get_account_details( configurationManagerProxy, accountID, &details, &error)) { if (error->domain == DBUS_GERROR && error->code == DBUS_GERROR_REMOTE_EXCEPTION) { - ERROR ("Caught remote method (get_account_details) exception %s: %s", dbus_g_error_get_name (error), error->message); + ERROR("Caught remote method (get_account_details) exception %s: %s", dbus_g_error_get_name(error), error->message); } else { - ERROR ("Error while calling get_account_details: %s", error->message); + ERROR("Error while calling get_account_details: %s", error->message); } - g_error_free (error); + g_error_free(error); } + return details; } void -dbus_set_credentials (account_t *a) +dbus_set_credentials(account_t *a) { - DEBUG ("DBUS: Sending credentials to server"); + DEBUG("DBUS: Sending credentials to server"); GError *error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_credentials ( + org_sflphone_SFLphone_ConfigurationManager_set_credentials( configurationManagerProxy, a->accountID, a->credential_information, &error); if (error) { - ERROR ("Failed to call set_credential() on ConfigurationManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call set_credential() on ConfigurationManager: %s", + error->message); + g_error_free(error); } } void -dbus_get_credentials (account_t *a) +dbus_get_credentials(account_t *a) { GError *error = NULL; - if (org_sflphone_SFLphone_ConfigurationManager_get_credentials ( + + if (org_sflphone_SFLphone_ConfigurationManager_get_credentials( configurationManagerProxy, a->accountID, &a->credential_information, &error)) return; if (error->domain == DBUS_GERROR && error->code == DBUS_GERROR_REMOTE_EXCEPTION) - ERROR ("Caught remote method (get_account_details) exception %s: %s", dbus_g_error_get_name (error), error->message); + ERROR("Caught remote method (get_account_details) exception %s: %s", dbus_g_error_get_name(error), error->message); else - ERROR ("Error while calling get_account_details: %s", error->message); + ERROR("Error while calling get_account_details: %s", error->message); - g_error_free (error); + g_error_free(error); } GHashTable* -dbus_get_ip2_ip_details (void) +dbus_get_ip2_ip_details(void) { GError *error = NULL; GHashTable * details = NULL; - if (!org_sflphone_SFLphone_ConfigurationManager_get_ip2_ip_details ( + if (!org_sflphone_SFLphone_ConfigurationManager_get_ip2_ip_details( configurationManagerProxy, &details, &error)) { if (error->domain == DBUS_GERROR && error->code == DBUS_GERROR_REMOTE_EXCEPTION) - ERROR ("Caught remote method (get_ip2_ip_details) exception %s: %s", dbus_g_error_get_name (error), error->message); + ERROR("Caught remote method (get_ip2_ip_details) exception %s: %s", dbus_g_error_get_name(error), error->message); else - ERROR ("Error while calling get_ip2_ip_details: %s", error->message); + ERROR("Error while calling get_ip2_ip_details: %s", error->message); - g_error_free (error); + g_error_free(error); } + return details; } void -dbus_send_register (gchar* accountID, const guint enable) +dbus_send_register(gchar* accountID, const guint enable) { GError *error = NULL; - org_sflphone_SFLphone_ConfigurationManager_send_register ( + org_sflphone_SFLphone_ConfigurationManager_send_register( configurationManagerProxy, accountID, enable, &error); if (error) { - ERROR ("Failed to call send_register() on ConfigurationManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call send_register() on ConfigurationManager: %s", + error->message); + g_error_free(error); } } void -dbus_remove_account (gchar * accountID) +dbus_remove_account(gchar * accountID) { GError *error = NULL; - org_sflphone_SFLphone_ConfigurationManager_remove_account ( + org_sflphone_SFLphone_ConfigurationManager_remove_account( configurationManagerProxy, accountID, &error); if (error) { - ERROR ("Failed to call remove_account() on ConfigurationManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call remove_account() on ConfigurationManager: %s", + error->message); + g_error_free(error); } } void -dbus_set_account_details (account_t *a) +dbus_set_account_details(account_t *a) { GError *error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_account_details ( + org_sflphone_SFLphone_ConfigurationManager_set_account_details( configurationManagerProxy, a->accountID, a->properties, &error); if (error) { - ERROR ("Failed to call set_account_details() on ConfigurationManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call set_account_details() on ConfigurationManager: %s", + error->message); + g_error_free(error); } } void -dbus_add_account (account_t *a) +dbus_add_account(account_t *a) { GError *error = NULL; g_free(a->accountID); - org_sflphone_SFLphone_ConfigurationManager_add_account ( + org_sflphone_SFLphone_ConfigurationManager_add_account( configurationManagerProxy, a->properties, &a->accountID, &error); if (error) { - ERROR ("Failed to call add_account() on ConfigurationManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call add_account() on ConfigurationManager: %s", + error->message); + g_error_free(error); } } void -dbus_set_volume (const gchar * device, gdouble value) +dbus_set_volume(const gchar * device, gdouble value) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_set_volume (callManagerProxy, device, value, + org_sflphone_SFLphone_CallManager_set_volume(callManagerProxy, device, value, &error); if (error) { - ERROR ("Failed to call set_volume() on callManagerProxy: %s", - error->message); - g_error_free (error); + ERROR("Failed to call set_volume() on callManagerProxy: %s", + error->message); + g_error_free(error); } } gdouble -dbus_get_volume (const gchar * device) +dbus_get_volume(const gchar * device) { gdouble value; GError *error = NULL; - org_sflphone_SFLphone_CallManager_get_volume (callManagerProxy, device, + org_sflphone_SFLphone_CallManager_get_volume(callManagerProxy, device, &value, &error); if (error) { - ERROR ("Failed to call get_volume() on callManagerProxy: %s", - error->message); - g_error_free (error); + ERROR("Failed to call get_volume() on callManagerProxy: %s", + error->message); + g_error_free(error); } return value; } void -dbus_play_dtmf (const gchar * key) +dbus_play_dtmf(const gchar * key) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_play_dt_mf (callManagerProxy, key, &error); + org_sflphone_SFLphone_CallManager_play_dt_mf(callManagerProxy, key, &error); if (error) { - ERROR ("Failed to call playDTMF() on callManagerProxy: %s", - error->message); - g_error_free (error); + ERROR("Failed to call playDTMF() on callManagerProxy: %s", + error->message); + g_error_free(error); } } void -dbus_start_tone (const int start, const guint type) +dbus_start_tone(const int start, const guint type) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_start_tone (callManagerProxy, start, type, + org_sflphone_SFLphone_CallManager_start_tone(callManagerProxy, start, type, &error); if (error) { - ERROR ("Failed to call startTone() on callManagerProxy: %s", - error->message); - g_error_free (error); + ERROR("Failed to call startTone() on callManagerProxy: %s", + error->message); + g_error_free(error); } } gboolean -dbus_register (int pid, gchar *name, GError **error) +dbus_register(int pid, gchar *name, GError **error) { - return org_sflphone_SFLphone_Instance_register (instanceProxy, pid, name, error); + return org_sflphone_SFLphone_Instance_register(instanceProxy, pid, name, error); } void -dbus_unregister (int pid) +dbus_unregister(int pid) { GError *error = NULL; - org_sflphone_SFLphone_Instance_unregister (instanceProxy, pid, &error); + org_sflphone_SFLphone_Instance_unregister(instanceProxy, pid, &error); if (error) { - ERROR ("Failed to call unregister() on instanceProxy: %s", - error->message); - g_error_free (error); + ERROR("Failed to call unregister() on instanceProxy: %s", + error->message); + g_error_free(error); } } @@ -1119,85 +1125,85 @@ dbus_audio_codec_list() { GError *error = NULL; GArray * array = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_audio_codec_list ( + org_sflphone_SFLphone_ConfigurationManager_get_audio_codec_list( configurationManagerProxy, &array, &error); if (error) { - ERROR ("Failed to call get_audio_codec_list() on ConfigurationManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call get_audio_codec_list() on ConfigurationManager: %s", + error->message); + g_error_free(error); } return array; } gchar** -dbus_audio_codec_details (int payload) +dbus_audio_codec_details(int payload) { GError *error = NULL; gchar ** array; - org_sflphone_SFLphone_ConfigurationManager_get_audio_codec_details ( + org_sflphone_SFLphone_ConfigurationManager_get_audio_codec_details( configurationManagerProxy, payload, &array, &error); if (error) { - ERROR ("Failed to call get_audio_codec_details() on ConfigurationManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call get_audio_codec_details() on ConfigurationManager: %s", + error->message); + g_error_free(error); } return array; } gchar* -dbus_get_current_audio_codec_name (const callable_obj_t * c) +dbus_get_current_audio_codec_name(const callable_obj_t * c) { gchar* codecName = NULL; GError* error = NULL; - org_sflphone_SFLphone_CallManager_get_current_audio_codec_name (callManagerProxy, + org_sflphone_SFLphone_CallManager_get_current_audio_codec_name(callManagerProxy, c->_callID, &codecName, &error); if (error) { - g_error_free (error); - g_free (codecName); + g_error_free(error); + g_free(codecName); codecName = g_strdup(""); } - DEBUG ("%s: codecName : %s", __PRETTY_FUNCTION__, codecName); + DEBUG("%s: codecName : %s", __PRETTY_FUNCTION__, codecName); return codecName; } GArray * -dbus_get_active_audio_codec_list (gchar *accountID) +dbus_get_active_audio_codec_list(gchar *accountID) { - GArray * array = NULL; + GArray * array = NULL; GError *error = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_active_audio_codec_list ( + org_sflphone_SFLphone_ConfigurationManager_get_active_audio_codec_list( configurationManagerProxy, accountID, &array, &error); if (error) { - ERROR ("Failed to call get_active_audio_codec_list() on ConfigurationManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call get_active_audio_codec_list() on ConfigurationManager: %s", + error->message); + g_error_free(error); } return array; } void -dbus_set_active_audio_codec_list (const gchar** list, const gchar *accountID) +dbus_set_active_audio_codec_list(const gchar** list, const gchar *accountID) { GError *error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_active_audio_codec_list ( + org_sflphone_SFLphone_ConfigurationManager_set_active_audio_codec_list( configurationManagerProxy, list, accountID, &error); if (error) { - ERROR ("Failed to call set_active_audio_codec_list() on ConfigurationManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call set_active_audio_codec_list() on ConfigurationManager: %s", + error->message); + g_error_free(error); } } @@ -1210,29 +1216,30 @@ dbus_get_audio_plugin_list() gchar** array = NULL; GError* error = NULL; - if (!org_sflphone_SFLphone_ConfigurationManager_get_audio_plugin_list ( + if (!org_sflphone_SFLphone_ConfigurationManager_get_audio_plugin_list( configurationManagerProxy, &array, &error)) { if (error->domain == DBUS_GERROR && error->code == DBUS_GERROR_REMOTE_EXCEPTION) - ERROR ("Caught remote method (get_output_plugin_list) exception %s: %s", dbus_g_error_get_name (error), error->message); + ERROR("Caught remote method (get_output_plugin_list) exception %s: %s", dbus_g_error_get_name(error), error->message); else - ERROR ("Error while calling get_out_plugin_list: %s", error->message); + ERROR("Error while calling get_out_plugin_list: %s", error->message); - g_error_free (error); + g_error_free(error); } + return array; } void -dbus_set_audio_plugin (gchar* audioPlugin) +dbus_set_audio_plugin(gchar* audioPlugin) { GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_audio_plugin ( + org_sflphone_SFLphone_ConfigurationManager_set_audio_plugin( configurationManagerProxy, audioPlugin, &error); if (error) { - ERROR ("Failed to call set_audio_plugin() on ConfigurationManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call set_audio_plugin() on ConfigurationManager: %s", error->message); + g_error_free(error); } } @@ -1244,12 +1251,12 @@ dbus_get_audio_output_device_list() { gchar** array = NULL; GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_audio_output_device_list ( + org_sflphone_SFLphone_ConfigurationManager_get_audio_output_device_list( configurationManagerProxy, &array, &error); if (error) { - ERROR ("Failed to call get_audio_output_device_list() on ConfigurationManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call get_audio_output_device_list() on ConfigurationManager: %s", error->message); + g_error_free(error); } return array; @@ -1259,15 +1266,15 @@ dbus_get_audio_output_device_list() * Set audio output device from its index */ void -dbus_set_audio_output_device (const int index) +dbus_set_audio_output_device(const int device) { GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_audio_output_device ( - configurationManagerProxy, index, &error); + org_sflphone_SFLphone_ConfigurationManager_set_audio_output_device( + configurationManagerProxy, device, &error); if (error) { - ERROR ("Failed to call set_audio_output_device() on ConfigurationManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call set_audio_output_device() on ConfigurationManager: %s", error->message); + g_error_free(error); } } @@ -1275,15 +1282,15 @@ dbus_set_audio_output_device (const int index) * Set audio input device from its index */ void -dbus_set_audio_input_device (const int index) +dbus_set_audio_input_device(const int device) { GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_audio_input_device ( - configurationManagerProxy, index, &error); + org_sflphone_SFLphone_ConfigurationManager_set_audio_input_device( + configurationManagerProxy, device, &error); if (error) { - ERROR ("Failed to call set_audio_input_device() on ConfigurationManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call set_audio_input_device() on ConfigurationManager: %s", error->message); + g_error_free(error); } } @@ -1291,15 +1298,15 @@ dbus_set_audio_input_device (const int index) * Set adio ringtone device from its index */ void -dbus_set_audio_ringtone_device (const int index) +dbus_set_audio_ringtone_device(const int device) { GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_audio_ringtone_device ( - configurationManagerProxy, index, &error); + org_sflphone_SFLphone_ConfigurationManager_set_audio_ringtone_device( + configurationManagerProxy, device, &error); if (error) { - ERROR ("Failed to call set_audio_ringtone_device() on ConfigurationManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call set_audio_ringtone_device() on ConfigurationManager: %s", error->message); + g_error_free(error); } } @@ -1311,12 +1318,12 @@ dbus_get_audio_input_device_list() { gchar** array = NULL; GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_audio_input_device_list ( + org_sflphone_SFLphone_ConfigurationManager_get_audio_input_device_list( configurationManagerProxy, &array, &error); if (error) { - ERROR ("Failed to call get_audio_input_device_list() on ConfigurationManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call get_audio_input_device_list() on ConfigurationManager: %s", error->message); + g_error_free(error); } return array; @@ -1330,12 +1337,12 @@ dbus_get_current_audio_devices_index() { gchar** array = NULL; GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_current_audio_devices_index ( + org_sflphone_SFLphone_ConfigurationManager_get_current_audio_devices_index( configurationManagerProxy, &array, &error); if (error) { - ERROR ("Failed to call get_current_audio_devices_index() on ConfigurationManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call get_current_audio_devices_index() on ConfigurationManager: %s", error->message); + g_error_free(error); } return array; @@ -1345,19 +1352,19 @@ dbus_get_current_audio_devices_index() * Get index */ int -dbus_get_audio_device_index (const gchar *name) +dbus_get_audio_device_index(const gchar *name) { - int index = 0; + int device_index = 0; GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_audio_device_index ( - configurationManagerProxy, name, &index, &error); + org_sflphone_SFLphone_ConfigurationManager_get_audio_device_index( + configurationManagerProxy, name, &device_index, &error); if (error) { - ERROR ("Failed to call get_audio_device_index() on ConfigurationManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call get_audio_device_index() on ConfigurationManager: %s", error->message); + g_error_free(error); } - return index; + return device_index; } /** @@ -1368,12 +1375,12 @@ dbus_get_current_audio_output_plugin() { gchar* plugin; GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_current_audio_output_plugin ( + org_sflphone_SFLphone_ConfigurationManager_get_current_audio_output_plugin( configurationManagerProxy, &plugin, &error); if (error) { - ERROR ("Failed to call get_current_audio_output_plugin() on ConfigurationManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call get_current_audio_output_plugin() on ConfigurationManager: %s", error->message); + g_error_free(error); plugin = g_strdup(""); } @@ -1389,11 +1396,11 @@ dbus_get_noise_suppress_state() { gchar* state; GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_noise_suppress_state (configurationManagerProxy, &state, &error); + org_sflphone_SFLphone_ConfigurationManager_get_noise_suppress_state(configurationManagerProxy, &state, &error); if (error) { - ERROR ("DBus: Failed to call get_noise_suppress_state() on ConfigurationManager: %s", error->message); - g_error_free (error); + ERROR("DBus: Failed to call get_noise_suppress_state() on ConfigurationManager: %s", error->message); + g_error_free(error); state = g_strdup(""); } @@ -1404,15 +1411,15 @@ dbus_get_noise_suppress_state() * Set noise reduction state */ void -dbus_set_noise_suppress_state (gchar* state) +dbus_set_noise_suppress_state(gchar* state) { GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_noise_suppress_state ( + org_sflphone_SFLphone_ConfigurationManager_set_noise_suppress_state( configurationManagerProxy, state, &error); if (error) { - ERROR ("Failed to call set_noise_suppress_state() on ConfigurationManager: %s", error->message); - g_error_free (error); + ERROR("Failed to call set_noise_suppress_state() on ConfigurationManager: %s", error->message); + g_error_free(error); } } @@ -1423,7 +1430,7 @@ dbus_get_echo_cancel_state(void) gchar *state; org_sflphone_SFLphone_ConfigurationManager_get_echo_cancel_state(configurationManagerProxy, &state, &error); - if(error) { + if (error) { ERROR("DBus: Failed to call get_echo_cancel_state() on ConfigurationManager: %s", error->message); g_error_free(error); state = g_strdup(""); @@ -1438,7 +1445,7 @@ dbus_set_echo_cancel_state(gchar *state) GError *error = NULL; org_sflphone_SFLphone_ConfigurationManager_set_echo_cancel_state(configurationManagerProxy, state, &error); - if(error) { + if (error) { ERROR("DBus: Failed to call set_echo_cancel_state() on ConfigurationManager: %s", error->message); g_error_free(error); } @@ -1452,7 +1459,7 @@ dbus_get_echo_cancel_tail_length(void) org_sflphone_SFLphone_ConfigurationManager_get_echo_cancel_tail_length(configurationManagerProxy, &length, &error); - if(error) { + if (error) { ERROR("DBus: Failed to call get_echo_cancel_tail_length() on ConfigurationManager: %s", error->message); g_error_free(error); } @@ -1466,7 +1473,7 @@ dbus_set_echo_cancel_tail_length(int length) GError *error = NULL; org_sflphone_SFLphone_ConfigurationManager_set_echo_cancel_tail_length(configurationManagerProxy, length, &error); - if(error) { + if (error) { ERROR("DBus: Failed to call get_echo_cancel_state() on ConfigurationManager: %s", error->message); g_error_free(error); } @@ -1507,40 +1514,41 @@ dbus_is_iax2_enabled() { int res = 0; GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_is_iax2_enabled ( + org_sflphone_SFLphone_ConfigurationManager_is_iax2_enabled( configurationManagerProxy, &res, &error); if (error) - g_error_free (error); + g_error_free(error); return res; } void -dbus_join_participant (const gchar* sel_callID, const gchar* drag_callID) +dbus_join_participant(const gchar* sel_callID, const gchar* drag_callID) { - DEBUG ("DBUS: Join participant %s and %s\n", sel_callID, drag_callID); + DEBUG("DBUS: Join participant %s and %s\n", sel_callID, drag_callID); GError* error = NULL; - org_sflphone_SFLphone_CallManager_join_participant (callManagerProxy, + org_sflphone_SFLphone_CallManager_join_participant(callManagerProxy, sel_callID, drag_callID, &error); if (error) - g_error_free (error); + g_error_free(error); } void -dbus_create_conf_from_participant_list(const gchar **list) { +dbus_create_conf_from_participant_list(const gchar **list) +{ GError *error = NULL; DEBUG("DBUS: Create conference from participant list"); org_sflphone_SFLphone_CallManager_create_conf_from_participant_list(callManagerProxy, - list, &error); + list, &error); if (error) { DEBUG("DBUS: Error: %s", error->message); @@ -1549,111 +1557,111 @@ dbus_create_conf_from_participant_list(const gchar **list) { } void -dbus_add_participant (const gchar* callID, const gchar* confID) +dbus_add_participant(const gchar* callID, const gchar* confID) { - DEBUG ("DBUS: Add participant %s to %s\n", callID, confID); + DEBUG("DBUS: Add participant %s to %s\n", callID, confID); GError* error = NULL; - org_sflphone_SFLphone_CallManager_add_participant (callManagerProxy, callID, + org_sflphone_SFLphone_CallManager_add_participant(callManagerProxy, callID, confID, &error); if (error) - g_error_free (error); + g_error_free(error); } void -dbus_add_main_participant (const gchar* confID) +dbus_add_main_participant(const gchar* confID) { - DEBUG ("DBUS: Add main participant %s\n", confID); + DEBUG("DBUS: Add main participant %s\n", confID); GError* error = NULL; - org_sflphone_SFLphone_CallManager_add_main_participant (callManagerProxy, + org_sflphone_SFLphone_CallManager_add_main_participant(callManagerProxy, confID, &error); if (error) - g_error_free (error); + g_error_free(error); } void -dbus_detach_participant (const gchar* callID) +dbus_detach_participant(const gchar* callID) { - DEBUG ("DBUS: Detach participant %s\n", callID); + DEBUG("DBUS: Detach participant %s\n", callID); GError* error = NULL; - org_sflphone_SFLphone_CallManager_detach_participant (callManagerProxy, + org_sflphone_SFLphone_CallManager_detach_participant(callManagerProxy, callID, &error); if (error) - g_error_free (error); + g_error_free(error); } void -dbus_join_conference (const gchar* sel_confID, const gchar* drag_confID) +dbus_join_conference(const gchar* sel_confID, const gchar* drag_confID) { - DEBUG ("dbus_join_conference %s and %s\n", sel_confID, drag_confID); + DEBUG("dbus_join_conference %s and %s\n", sel_confID, drag_confID); GError* error = NULL; - org_sflphone_SFLphone_CallManager_join_conference (callManagerProxy, + org_sflphone_SFLphone_CallManager_join_conference(callManagerProxy, sel_confID, drag_confID, &error); if (error) - g_error_free (error); + g_error_free(error); } void -dbus_set_record (const gchar* id) +dbus_set_record(const gchar* id) { - DEBUG ("Dbus: dbus_set_record %s", id); + DEBUG("Dbus: dbus_set_record %s", id); GError* error = NULL; - org_sflphone_SFLphone_CallManager_set_recording (callManagerProxy, id, &error); + org_sflphone_SFLphone_CallManager_set_recording(callManagerProxy, id, &error); if (error) - g_error_free (error); + g_error_free(error); } gboolean -dbus_get_is_recording (const callable_obj_t * c) +dbus_get_is_recording(const callable_obj_t * c) { - DEBUG ("Dbus: dbus_get_is_recording %s", c->_callID); + DEBUG("Dbus: dbus_get_is_recording %s", c->_callID); GError* error = NULL; gboolean isRecording; - org_sflphone_SFLphone_CallManager_get_is_recording (callManagerProxy, + org_sflphone_SFLphone_CallManager_get_is_recording(callManagerProxy, c->_callID, &isRecording, &error); if (error) - g_error_free (error); + g_error_free(error); //DEBUG("RECORDING: %i",isRecording); return isRecording; } void -dbus_set_record_path (const gchar* path) +dbus_set_record_path(const gchar* path) { GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_record_path ( + org_sflphone_SFLphone_ConfigurationManager_set_record_path( configurationManagerProxy, path, &error); if (error) - g_error_free (error); + g_error_free(error); } gchar* -dbus_get_record_path (void) +dbus_get_record_path(void) { GError* error = NULL; gchar *path; - org_sflphone_SFLphone_ConfigurationManager_get_record_path ( + org_sflphone_SFLphone_ConfigurationManager_get_record_path( configurationManagerProxy, &path, &error); if (error) - g_error_free (error); + g_error_free(error); return path; } @@ -1664,7 +1672,7 @@ void dbus_set_is_always_recording(const gboolean alwaysRec) org_sflphone_SFLphone_ConfigurationManager_set_is_always_recording( configurationManagerProxy, alwaysRec, &error); - if(error) { + if (error) { ERROR("DBUS: Could not set isAlwaysRecording"); g_error_free(error); } @@ -1677,7 +1685,7 @@ gboolean dbus_get_is_always_recording(void) org_sflphone_SFLphone_ConfigurationManager_get_is_always_recording( configurationManagerProxy, &alwaysRec, &error); - if(error) { + if (error) { ERROR("DBUS: Could not get isAlwaysRecording"); g_error_free(error); } @@ -1686,52 +1694,52 @@ gboolean dbus_get_is_always_recording(void) } void -dbus_set_history_limit (const guint days) +dbus_set_history_limit(const guint days) { GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_history_limit ( + org_sflphone_SFLphone_ConfigurationManager_set_history_limit( configurationManagerProxy, days, &error); if (error) - g_error_free (error); + g_error_free(error); } guint -dbus_get_history_limit (void) +dbus_get_history_limit(void) { GError* error = NULL; gint days = 30; - org_sflphone_SFLphone_ConfigurationManager_get_history_limit ( + org_sflphone_SFLphone_ConfigurationManager_get_history_limit( configurationManagerProxy, &days, &error); if (error) - g_error_free (error); + g_error_free(error); return (guint) days; } void -dbus_set_audio_manager (const gchar *api) +dbus_set_audio_manager(const gchar *api) { GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_audio_manager ( + org_sflphone_SFLphone_ConfigurationManager_set_audio_manager( configurationManagerProxy, api, &error); if (error) - g_error_free (error); + g_error_free(error); } gchar * -dbus_get_audio_manager (void) +dbus_get_audio_manager(void) { gchar *api; GError* error = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_audio_manager ( + org_sflphone_SFLphone_ConfigurationManager_get_audio_manager( configurationManagerProxy, &api, &error); if (error) { - ERROR ("Error calling dbus_get_audio_manager"); - g_error_free (error); + ERROR("Error calling dbus_get_audio_manager"); + g_error_free(error); } return api; @@ -1739,290 +1747,286 @@ dbus_get_audio_manager (void) GHashTable* -dbus_get_addressbook_settings (void) +dbus_get_addressbook_settings(void) { GError *error = NULL; GHashTable *results = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_addressbook_settings ( + org_sflphone_SFLphone_ConfigurationManager_get_addressbook_settings( configurationManagerProxy, &results, &error); if (error) { - ERROR ("Error calling org_sflphone_SFLphone_ConfigurationManager_get_addressbook_settings"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_ConfigurationManager_get_addressbook_settings"); + g_error_free(error); } return results; } void -dbus_set_addressbook_settings (GHashTable * settings) +dbus_set_addressbook_settings(GHashTable * settings) { GError *error = NULL; - DEBUG ("Calling org_sflphone_SFLphone_ConfigurationManager_set_addressbook_settings"); + DEBUG("Calling org_sflphone_SFLphone_ConfigurationManager_set_addressbook_settings"); - org_sflphone_SFLphone_ConfigurationManager_set_addressbook_settings ( + org_sflphone_SFLphone_ConfigurationManager_set_addressbook_settings( configurationManagerProxy, settings, &error); if (error) { - ERROR ("Error calling org_sflphone_SFLphone_ConfigurationManager_set_addressbook_settings"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_ConfigurationManager_set_addressbook_settings"); + g_error_free(error); } } gchar** -dbus_get_addressbook_list (void) +dbus_get_addressbook_list(void) { GError *error = NULL; gchar** array = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_addressbook_list ( + org_sflphone_SFLphone_ConfigurationManager_get_addressbook_list( configurationManagerProxy, &array, &error); if (error) { - ERROR ("Error calling org_sflphone_SFLphone_ConfigurationManager_get_addressbook_list"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_ConfigurationManager_get_addressbook_list"); + g_error_free(error); } return array; } void -dbus_set_addressbook_list (const gchar** list) +dbus_set_addressbook_list(const gchar** list) { GError *error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_addressbook_list ( + org_sflphone_SFLphone_ConfigurationManager_set_addressbook_list( configurationManagerProxy, list, &error); if (error) { - ERROR ("Error calling org_sflphone_SFLphone_ConfigurationManager_set_addressbook_list"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_ConfigurationManager_set_addressbook_list"); + g_error_free(error); } } GHashTable* -dbus_get_hook_settings (void) +dbus_get_hook_settings(void) { - GError *error = NULL; GHashTable *results = NULL; - //DEBUG ("Calling org_sflphone_SFLphone_ConfigurationManager_get_addressbook_settings"); - - org_sflphone_SFLphone_ConfigurationManager_get_hook_settings ( + org_sflphone_SFLphone_ConfigurationManager_get_hook_settings( configurationManagerProxy, &results, &error); if (error) { - ERROR ("Error calling org_sflphone_SFLphone_ConfigurationManager_get_hook_settings"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_ConfigurationManager_get_hook_settings"); + g_error_free(error); } return results; } void -dbus_set_hook_settings (GHashTable * settings) +dbus_set_hook_settings(GHashTable * settings) { GError *error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_hook_settings ( + org_sflphone_SFLphone_ConfigurationManager_set_hook_settings( configurationManagerProxy, settings, &error); if (error) { - ERROR ("Error calling org_sflphone_SFLphone_ConfigurationManager_set_hook_settings"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_ConfigurationManager_set_hook_settings"); + g_error_free(error); } } GHashTable* -dbus_get_call_details (const gchar *callID) +dbus_get_call_details(const gchar *callID) { GError *error = NULL; GHashTable *details = NULL; - org_sflphone_SFLphone_CallManager_get_call_details (callManagerProxy, callID, + org_sflphone_SFLphone_CallManager_get_call_details(callManagerProxy, callID, &details, &error); if (error) { - ERROR ("Error calling org_sflphone_SFLphone_CallManager_get_call_details"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_CallManager_get_call_details"); + g_error_free(error); } return details; } gchar** -dbus_get_call_list (void) +dbus_get_call_list(void) { GError *error = NULL; gchar **list = NULL; - org_sflphone_SFLphone_CallManager_get_call_list (callManagerProxy, &list, + org_sflphone_SFLphone_CallManager_get_call_list(callManagerProxy, &list, &error); if (error) { - ERROR ("Error calling org_sflphone_SFLphone_CallManager_get_call_list"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_CallManager_get_call_list"); + g_error_free(error); } return list; } gchar** -dbus_get_conference_list (void) +dbus_get_conference_list(void) { GError *error = NULL; gchar **list = NULL; - org_sflphone_SFLphone_CallManager_get_conference_list (callManagerProxy, + org_sflphone_SFLphone_CallManager_get_conference_list(callManagerProxy, &list, &error); if (error) { - ERROR ("Error calling org_sflphone_SFLphone_CallManager_get_conference_list"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_CallManager_get_conference_list"); + g_error_free(error); } return list; } gchar** -dbus_get_participant_list (const gchar *confID) +dbus_get_participant_list(const gchar *confID) { GError *error = NULL; char **list = NULL; - DEBUG ("DBUS: Get conference %s participant list", confID); + DEBUG("DBUS: Get conference %s participant list", confID); - org_sflphone_SFLphone_CallManager_get_participant_list (callManagerProxy, + org_sflphone_SFLphone_CallManager_get_participant_list(callManagerProxy, confID, &list, &error); if (error) { - ERROR ("Error calling org_sflphone_SFLphone_CallManager_get_participant_list"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_CallManager_get_participant_list"); + g_error_free(error); } return list; } GHashTable* -dbus_get_conference_details (const gchar *confID) +dbus_get_conference_details(const gchar *confID) { GError *error = NULL; GHashTable *details = NULL; - org_sflphone_SFLphone_CallManager_get_conference_details (callManagerProxy, + org_sflphone_SFLphone_CallManager_get_conference_details(callManagerProxy, confID, &details, &error); if (error) { - ERROR ("Error calling org_sflphone_SFLphone_CallManager_get_conference_details"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_CallManager_get_conference_details"); + g_error_free(error); } return details; } void -dbus_set_accounts_order (const gchar* order) +dbus_set_accounts_order(const gchar* order) { - GError *error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_accounts_order ( + org_sflphone_SFLphone_ConfigurationManager_set_accounts_order( configurationManagerProxy, order, &error); if (error) { - ERROR ("Error calling org_sflphone_SFLphone_ConfigurationManager_set_accounts_order"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_ConfigurationManager_set_accounts_order"); + g_error_free(error); } } gchar ** -dbus_get_history (void) +dbus_get_history(void) { GError *error = NULL; gchar **entries = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_history ( + org_sflphone_SFLphone_ConfigurationManager_get_history( configurationManagerProxy, &entries, &error); if (error) { - ERROR ("Error calling get history: %s", error->message); - g_error_free (error); + ERROR("Error calling get history: %s", error->message); + g_error_free(error); } return entries; } void -dbus_set_history (gchar **entries) +dbus_set_history(gchar **entries) { GError *error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_history ( + org_sflphone_SFLphone_ConfigurationManager_set_history( configurationManagerProxy, (const char **)entries, &error); if (error) { - ERROR ("Error calling org_sflphone_SFLphone_CallManager_set_history"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_CallManager_set_history"); + g_error_free(error); } } void -dbus_confirm_sas (const callable_obj_t * c) +dbus_confirm_sas(const callable_obj_t * c) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_set_sa_sverified (callManagerProxy, + org_sflphone_SFLphone_CallManager_set_sa_sverified(callManagerProxy, c->_callID, &error); if (error) { - ERROR ("Failed to call setSASVerified() on CallManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call setSASVerified() on CallManager: %s", + error->message); + g_error_free(error); } } void -dbus_reset_sas (const callable_obj_t * c) +dbus_reset_sas(const callable_obj_t * c) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_reset_sa_sverified (callManagerProxy, + org_sflphone_SFLphone_CallManager_reset_sa_sverified(callManagerProxy, c->_callID, &error); if (error) { - ERROR ("Failed to call resetSASVerified on CallManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call resetSASVerified on CallManager: %s", + error->message); + g_error_free(error); } } void -dbus_set_confirm_go_clear (const callable_obj_t * c) +dbus_set_confirm_go_clear(const callable_obj_t * c) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_set_confirm_go_clear (callManagerProxy, + org_sflphone_SFLphone_CallManager_set_confirm_go_clear(callManagerProxy, c->_callID, &error); if (error) { - ERROR ("Failed to call set_confirm_go_clear on CallManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call set_confirm_go_clear on CallManager: %s", + error->message); + g_error_free(error); } } void -dbus_request_go_clear (const callable_obj_t * c) +dbus_request_go_clear(const callable_obj_t * c) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_request_go_clear (callManagerProxy, + org_sflphone_SFLphone_CallManager_request_go_clear(callManagerProxy, c->_callID, &error); if (error) { - ERROR ("Failed to call request_go_clear on CallManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call request_go_clear on CallManager: %s", + error->message); + g_error_free(error); } } @@ -2031,136 +2035,139 @@ dbus_get_supported_tls_method() { GError *error = NULL; gchar** array = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_supported_tls_method ( + org_sflphone_SFLphone_ConfigurationManager_get_supported_tls_method( configurationManagerProxy, &array, &error); if (error) { - ERROR ("Failed to call get_supported_tls_method() on ConfigurationManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call get_supported_tls_method() on ConfigurationManager: %s", + error->message); + g_error_free(error); } return array; } GHashTable* -dbus_get_tls_settings_default (void) +dbus_get_tls_settings_default(void) { GError *error = NULL; GHashTable *results = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_tls_settings_default ( + org_sflphone_SFLphone_ConfigurationManager_get_tls_settings_default( configurationManagerProxy, &results, &error); if (error) { - ERROR ("Error calling org_sflphone_SFLphone_ConfigurationManager_get_tls_settings_default"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_ConfigurationManager_get_tls_settings_default"); + g_error_free(error); } return results; } gchar * -dbus_get_address_from_interface_name (gchar* interface) +dbus_get_address_from_interface_name(gchar* interface) { GError *error = NULL; gchar * address = NULL; - org_sflphone_SFLphone_ConfigurationManager_get_addr_from_interface_name ( + org_sflphone_SFLphone_ConfigurationManager_get_addr_from_interface_name( configurationManagerProxy, interface, &address, &error); if (error != NULL) { - ERROR ("Error calling org_sflphone_SFLphone_ConfigurationManager_get_addr_from_interface_name\n"); - g_error_free (error); + ERROR("Error calling org_sflphone_SFLphone_ConfigurationManager_get_addr_from_interface_name\n"); + g_error_free(error); } return address; } gchar ** -dbus_get_all_ip_interface (void) +dbus_get_all_ip_interface(void) { GError *error = NULL; gchar ** array = NULL; - if (!org_sflphone_SFLphone_ConfigurationManager_get_all_ip_interface ( + if (!org_sflphone_SFLphone_ConfigurationManager_get_all_ip_interface( configurationManagerProxy, &array, &error)) { if (error->domain == DBUS_GERROR && error->code == DBUS_GERROR_REMOTE_EXCEPTION) - ERROR ("Caught remote method (get_all_ip_interface) exception %s: %s", dbus_g_error_get_name (error), error->message); + ERROR("Caught remote method (get_all_ip_interface) exception %s: %s", dbus_g_error_get_name(error), error->message); else - ERROR ("Error while calling get_all_ip_interface: %s", error->message); + ERROR("Error while calling get_all_ip_interface: %s", error->message); - g_error_free (error); + g_error_free(error); } else - DEBUG ("DBus called get_all_ip_interface() on ConfigurationManager"); + DEBUG("DBus called get_all_ip_interface() on ConfigurationManager"); + return array; } gchar ** -dbus_get_all_ip_interface_by_name (void) +dbus_get_all_ip_interface_by_name(void) { GError *error = NULL; gchar ** array = NULL; - if (!org_sflphone_SFLphone_ConfigurationManager_get_all_ip_interface_by_name ( + if (!org_sflphone_SFLphone_ConfigurationManager_get_all_ip_interface_by_name( configurationManagerProxy, &array, &error)) { if (error->domain == DBUS_GERROR && error->code == DBUS_GERROR_REMOTE_EXCEPTION) - ERROR ("Caught remote method (get_all_ip_interface) exception %s: %s", dbus_g_error_get_name (error), error->message); + ERROR("Caught remote method (get_all_ip_interface) exception %s: %s", dbus_g_error_get_name(error), error->message); else - ERROR ("Error while calling get_all_ip_interface: %s", error->message); + ERROR("Error while calling get_all_ip_interface: %s", error->message); - g_error_free (error); + g_error_free(error); } else - DEBUG ("DBus called get_all_ip_interface() on ConfigurationManager"); + DEBUG("DBus called get_all_ip_interface() on ConfigurationManager"); + return array; } GHashTable* -dbus_get_shortcuts (void) +dbus_get_shortcuts(void) { GError *error = NULL; GHashTable * shortcuts = NULL; - if (!org_sflphone_SFLphone_ConfigurationManager_get_shortcuts ( + if (!org_sflphone_SFLphone_ConfigurationManager_get_shortcuts( configurationManagerProxy, &shortcuts, &error)) { if (error->domain == DBUS_GERROR && error->code == DBUS_GERROR_REMOTE_EXCEPTION) - ERROR ("Caught remote method (get_shortcuts) exception %s: %s", - dbus_g_error_get_name (error), error->message); + ERROR("Caught remote method (get_shortcuts) exception %s: %s", + dbus_g_error_get_name(error), error->message); else - ERROR ("Error while calling get_shortcuts: %s", error->message); + ERROR("Error while calling get_shortcuts: %s", error->message); - g_error_free (error); + g_error_free(error); } + return shortcuts; } void -dbus_set_shortcuts (GHashTable * shortcuts) +dbus_set_shortcuts(GHashTable * shortcuts) { GError *error = NULL; - org_sflphone_SFLphone_ConfigurationManager_set_shortcuts ( + org_sflphone_SFLphone_ConfigurationManager_set_shortcuts( configurationManagerProxy, shortcuts, &error); if (error) { - ERROR ("Failed to call set_shortcuts() on ConfigurationManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call set_shortcuts() on ConfigurationManager: %s", + error->message); + g_error_free(error); } } void -dbus_send_text_message (const gchar* callID, const gchar *message) +dbus_send_text_message(const gchar* callID, const gchar *message) { GError *error = NULL; - org_sflphone_SFLphone_CallManager_send_text_message ( + org_sflphone_SFLphone_CallManager_send_text_message( callManagerProxy, callID, message, &error); if (error) { - ERROR ("Failed to call send_text_message() on CallManager: %s", - error->message); - g_error_free (error); + ERROR("Failed to call send_text_message() on CallManager: %s", + error->message); + g_error_free(error); } } diff --git a/gnome/src/dbus/dbus.h b/gnome/src/dbus/dbus.h index b6e4eaafd95152bf4bd536c5ac81987ffa1fce56..41193d89dc991a2dce2bf5747e03b4feda1dec31 100644 --- a/gnome/src/dbus/dbus.h +++ b/gnome/src/dbus/dbus.h @@ -27,7 +27,6 @@ * grants you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well - * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ @@ -36,11 +35,11 @@ #include <dbus/dbus-glib.h> -#include <accountlist.h> -#include <calllist.h> -#include <conferencelist.h> -#include <conference_obj.h> -#include <sflnotify.h> +#include "accountlist.h" +#include "calllist.h" +#include "conferencelist.h" +#include "conference_obj.h" +#include "sflnotify.h" /** @file dbus.h * @brief General DBus functions wrappers. diff --git a/gnome/src/dialpad.c b/gnome/src/dialpad.c index 6e0783b4ee1d0a01a112f3b5d6d3276a4300805f..0ae6f527976d2801bf7e202bbebeff668f1a414a 100644 --- a/gnome/src/dialpad.c +++ b/gnome/src/dialpad.c @@ -28,9 +28,10 @@ * as that of the covered work. */ -#include <dialpad.h> -#include <actions.h> +#include "dialpad.h" +#include "actions.h" #include "calltab.h" +#include "unused.h" /** * button pressed event @@ -38,7 +39,7 @@ static void dialpad_pressed(GtkWidget * widget UNUSED, gpointer data) { - gtk_widget_grab_focus(GTK_WIDGET(current_calls->view)); + gtk_widget_grab_focus(GTK_WIDGET(current_calls_tab->view)); sflphone_keypad(0, (gchar*) data); } @@ -49,11 +50,11 @@ get_numpad_button(const gchar* number, gboolean twolines, const gchar * letters) GtkWidget *label = gtk_label_new("1"); gtk_label_set_single_line_mode(GTK_LABEL(label), FALSE); gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_CENTER); - gchar *markup = g_markup_printf_escaped("<big><b>%s</b></big>%s%s", number,(twolines == TRUE ? "\n": ""), letters); + gchar *markup = g_markup_printf_escaped("<big><b>%s</b></big>%s%s", number, (twolines == TRUE ? "\n": ""), letters); gtk_label_set_markup(GTK_LABEL(label), markup); gtk_container_add(GTK_CONTAINER(button), label); g_signal_connect(G_OBJECT(button), "clicked", - G_CALLBACK(dialpad_pressed),(gchar*) number); + G_CALLBACK(dialpad_pressed),(gchar*) number); g_free(markup); return button; @@ -62,18 +63,20 @@ get_numpad_button(const gchar* number, gboolean twolines, const gchar * letters) GtkWidget * create_dialpad() { - static const gchar * const key_strings[] = {"1", "", - "2", "a b c", - "3", "d e f", - "4", "g h i", - "5", "j k l", - "6", "m n o", - "7", "p q r s", - "8", "t u v", - "9", "w x y z", - "*", "", - "0", "", - "#", ""}; + static const gchar * const key_strings[] = { + "1", "", + "2", "a b c", + "3", "d e f", + "4", "g h i", + "5", "j k l", + "6", "m n o", + "7", "p q r s", + "8", "t u v", + "9", "w x y z", + "*", "", + "0", "", + "#", "" + }; enum {ROWS = 4, COLS = 3}; GtkWidget *table = gtk_table_new(ROWS, COLS, TRUE /* homogeneous */); gtk_table_set_row_spacings(GTK_TABLE(table), 5); @@ -86,5 +89,6 @@ create_dialpad() gtk_table_attach(GTK_TABLE(table), button, col, col + 1, row, row + 1, GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0); entry += 2; } + return table; } diff --git a/gnome/src/eel-gconf-extensions.c b/gnome/src/eel-gconf-extensions.c index d2d0654fa7a5f7dfce8c68b28726a0cf776b9aeb..c1947f24ae8ad3a10529d974a2dbc19e393dc7f7 100644 --- a/gnome/src/eel-gconf-extensions.c +++ b/gnome/src/eel-gconf-extensions.c @@ -23,80 +23,80 @@ */ #include <stdlib.h> -#include <config.h> +#include "config.h" #include "eel-gconf-extensions.h" #include <gconf/gconf-client.h> #include <gconf/gconf.h> #include <gtk/gtk.h> -#include <libgnome/gnome-i18n.h> +#include <glib/gi18n.h> static GConfClient *global_gconf_client = NULL; static void -global_client_free (void) +global_client_free(void) { if (global_gconf_client == NULL) { return; } - g_object_unref (G_OBJECT (global_gconf_client)); + g_object_unref(G_OBJECT(global_gconf_client)); global_gconf_client = NULL; } /* Public */ GConfClient * -eel_gconf_client_get_global (void) +eel_gconf_client_get_global(void) { /* Initialize gconf if needed */ - if (!gconf_is_initialized ()) { + if (!gconf_is_initialized()) { char *argv[] = { "eel-preferences", NULL }; GError *error = NULL; char *teststr; - if (!gconf_init (1, argv, &error)) { - if (eel_gconf_handle_error (&error)) { + if (!gconf_init(1, argv, &error)) { + if (eel_gconf_handle_error(&error)) { return NULL; } } /* check if gconf schemas are working */ - teststr = gconf_client_get_string (eel_gconf_client_get_global(), - "/apps/gpdf/gconf_test", NULL); + teststr = gconf_client_get_string(eel_gconf_client_get_global(), + "/apps/gpdf/gconf_test", NULL); if (!teststr) { GtkWidget *dialog; - dialog = gtk_message_dialog_new (NULL, - GTK_DIALOG_MODAL, - GTK_MESSAGE_ERROR, - GTK_BUTTONS_OK, - _ ("Cannot find a schema for gpdf preferences. \n" - "Check your gconf setup, look at gpdf FAQ for \n" - "more info")); - gtk_dialog_run (GTK_DIALOG (dialog)); - exit (0); + dialog = gtk_message_dialog_new(NULL, + GTK_DIALOG_MODAL, + GTK_MESSAGE_ERROR, + GTK_BUTTONS_OK, + _("Cannot find a schema for gpdf preferences. \n" + "Check your gconf setup, look at gpdf FAQ for \n" + "more info")); + gtk_dialog_run(GTK_DIALOG(dialog)); + exit(0); } else { - g_free (teststr); + g_free(teststr); } } if (global_gconf_client == NULL) { - global_gconf_client = gconf_client_get_default (); - g_atexit (global_client_free); + global_gconf_client = gconf_client_get_default(); + g_atexit(global_client_free); } return global_gconf_client; } gboolean -eel_gconf_handle_error (GError **error) +eel_gconf_handle_error(GError **error) { - g_return_val_if_fail (error != NULL, FALSE); + g_return_val_if_fail(error != NULL, FALSE); if (*error != NULL) { - g_warning ("GConf error: %s\n", (*error)->message); - g_error_free (*error); + g_warning("GConf error: %s\n", (*error)->message); + g_error_free(*error); *error = NULL; return TRUE; @@ -106,36 +106,36 @@ eel_gconf_handle_error (GError **error) } void -eel_gconf_set_boolean (const char *key, - gboolean boolean_value) +eel_gconf_set_boolean(const char *key, + gboolean boolean_value) { GConfClient *client; GError *error = NULL; - g_return_if_fail (key != NULL); + g_return_if_fail(key != NULL); - client = eel_gconf_client_get_global (); - g_return_if_fail (client != NULL); + client = eel_gconf_client_get_global(); + g_return_if_fail(client != NULL); - gconf_client_set_bool (client, key, boolean_value, &error); - eel_gconf_handle_error (&error); + gconf_client_set_bool(client, key, boolean_value, &error); + eel_gconf_handle_error(&error); } gboolean -eel_gconf_get_boolean (const char *key) +eel_gconf_get_boolean(const char *key) { gboolean result; GConfClient *client; GError *error = NULL; - g_return_val_if_fail (key != NULL, FALSE); + g_return_val_if_fail(key != NULL, FALSE); - client = eel_gconf_client_get_global (); - g_return_val_if_fail (client != NULL, FALSE); + client = eel_gconf_client_get_global(); + g_return_val_if_fail(client != NULL, FALSE); - result = gconf_client_get_bool (client, key, &error); + result = gconf_client_get_bool(client, key, &error); - if (eel_gconf_handle_error (&error)) { + if (eel_gconf_handle_error(&error)) { result = FALSE; } @@ -143,36 +143,36 @@ eel_gconf_get_boolean (const char *key) } void -eel_gconf_set_integer (const char *key, - int int_value) +eel_gconf_set_integer(const char *key, + int int_value) { GConfClient *client; GError *error = NULL; - g_return_if_fail (key != NULL); + g_return_if_fail(key != NULL); - client = eel_gconf_client_get_global (); - g_return_if_fail (client != NULL); + client = eel_gconf_client_get_global(); + g_return_if_fail(client != NULL); - gconf_client_set_int (client, key, int_value, &error); - eel_gconf_handle_error (&error); + gconf_client_set_int(client, key, int_value, &error); + eel_gconf_handle_error(&error); } int -eel_gconf_get_integer (const char *key) +eel_gconf_get_integer(const char *key) { int result; GConfClient *client; GError *error = NULL; - g_return_val_if_fail (key != NULL, 0); + g_return_val_if_fail(key != NULL, 0); - client = eel_gconf_client_get_global (); - g_return_val_if_fail (client != NULL, 0); + client = eel_gconf_client_get_global(); + g_return_val_if_fail(client != NULL, 0); - result = gconf_client_get_int (client, key, &error); + result = gconf_client_get_int(client, key, &error); - if (eel_gconf_handle_error (&error)) { + if (eel_gconf_handle_error(&error)) { result = 0; } @@ -180,36 +180,36 @@ eel_gconf_get_integer (const char *key) } void -eel_gconf_set_float (const char *key, - gfloat float_value) +eel_gconf_set_float(const char *key, + gfloat float_value) { GConfClient *client; GError *error = NULL; - g_return_if_fail (key != NULL); + g_return_if_fail(key != NULL); - client = eel_gconf_client_get_global (); - g_return_if_fail (client != NULL); + client = eel_gconf_client_get_global(); + g_return_if_fail(client != NULL); - gconf_client_set_float (client, key, float_value, &error); - eel_gconf_handle_error (&error); + gconf_client_set_float(client, key, float_value, &error); + eel_gconf_handle_error(&error); } gfloat -eel_gconf_get_float (const char *key) +eel_gconf_get_float(const char *key) { gfloat result; GConfClient *client; GError *error = NULL; - g_return_val_if_fail (key != NULL, 0); + g_return_val_if_fail(key != NULL, 0); - client = eel_gconf_client_get_global (); - g_return_val_if_fail (client != NULL, 0); + client = eel_gconf_client_get_global(); + g_return_val_if_fail(client != NULL, 0); - result = gconf_client_get_float (client, key, &error); + result = gconf_client_get_float(client, key, &error); - if (eel_gconf_handle_error (&error)) { + if (eel_gconf_handle_error(&error)) { result = 0; } @@ -217,94 +217,94 @@ eel_gconf_get_float (const char *key) } void -eel_gconf_set_string (const char *key, - const char *string_value) +eel_gconf_set_string(const char *key, + const char *string_value) { GConfClient *client; GError *error = NULL; - g_return_if_fail (key != NULL); - g_return_if_fail (string_value != NULL); + g_return_if_fail(key != NULL); + g_return_if_fail(string_value != NULL); - client = eel_gconf_client_get_global (); - g_return_if_fail (client != NULL); + client = eel_gconf_client_get_global(); + g_return_if_fail(client != NULL); - gconf_client_set_string (client, key, string_value, &error); - eel_gconf_handle_error (&error); + gconf_client_set_string(client, key, string_value, &error); + eel_gconf_handle_error(&error); } void -eel_gconf_unset (const char *key) +eel_gconf_unset(const char *key) { GConfClient *client; GError *error = NULL; - g_return_if_fail (key != NULL); + g_return_if_fail(key != NULL); - client = eel_gconf_client_get_global (); - g_return_if_fail (client != NULL); + client = eel_gconf_client_get_global(); + g_return_if_fail(client != NULL); - gconf_client_unset (client, key, &error); - eel_gconf_handle_error (&error); + gconf_client_unset(client, key, &error); + eel_gconf_handle_error(&error); } char * -eel_gconf_get_string (const char *key) +eel_gconf_get_string(const char *key) { char *result; GConfClient *client; GError *error = NULL; - g_return_val_if_fail (key != NULL, NULL); + g_return_val_if_fail(key != NULL, NULL); - client = eel_gconf_client_get_global (); - g_return_val_if_fail (client != NULL, NULL); + client = eel_gconf_client_get_global(); + g_return_val_if_fail(client != NULL, NULL); - result = gconf_client_get_string (client, key, &error); + result = gconf_client_get_string(client, key, &error); - if (eel_gconf_handle_error (&error)) { - result = g_strdup (""); + if (eel_gconf_handle_error(&error)) { + result = g_strdup(""); } return result; } void -eel_gconf_set_string_list (const char *key, - const GSList *slist) +eel_gconf_set_string_list(const char *key, + const GSList *slist) { GConfClient *client; GError *error; - g_return_if_fail (key != NULL); + g_return_if_fail(key != NULL); - client = eel_gconf_client_get_global (); - g_return_if_fail (client != NULL); + client = eel_gconf_client_get_global(); + g_return_if_fail(client != NULL); error = NULL; - gconf_client_set_list (client, key, GCONF_VALUE_STRING, - /* Need cast cause of GConf api bug */ - (GSList *) slist, - &error); - eel_gconf_handle_error (&error); + gconf_client_set_list(client, key, GCONF_VALUE_STRING, + /* Need cast cause of GConf api bug */ + (GSList *) slist, + &error); + eel_gconf_handle_error(&error); } GSList * -eel_gconf_get_string_list (const char *key) +eel_gconf_get_string_list(const char *key) { GSList *slist; GConfClient *client; GError *error; - g_return_val_if_fail (key != NULL, NULL); + g_return_val_if_fail(key != NULL, NULL); - client = eel_gconf_client_get_global (); - g_return_val_if_fail (client != NULL, NULL); + client = eel_gconf_client_get_global(); + g_return_val_if_fail(client != NULL, NULL); error = NULL; - slist = gconf_client_get_list (client, key, GCONF_VALUE_STRING, &error); + slist = gconf_client_get_list(client, key, GCONF_VALUE_STRING, &error); - if (eel_gconf_handle_error (&error)) { + if (eel_gconf_handle_error(&error)) { slist = NULL; } @@ -313,41 +313,41 @@ eel_gconf_get_string_list (const char *key) /* This code wasn't part of the original eel-gconf-extensions.c */ void -eel_gconf_set_integer_list (const char *key, - const GSList *slist) +eel_gconf_set_integer_list(const char *key, + const GSList *slist) { GConfClient *client; GError *error; - g_return_if_fail (key != NULL); + g_return_if_fail(key != NULL); - client = eel_gconf_client_get_global (); - g_return_if_fail (client != NULL); + client = eel_gconf_client_get_global(); + g_return_if_fail(client != NULL); error = NULL; - gconf_client_set_list (client, key, GCONF_VALUE_INT, - /* Need cast cause of GConf api bug */ - (GSList *) slist, - &error); - eel_gconf_handle_error (&error); + gconf_client_set_list(client, key, GCONF_VALUE_INT, + /* Need cast cause of GConf api bug */ + (GSList *) slist, + &error); + eel_gconf_handle_error(&error); } GSList * -eel_gconf_get_integer_list (const char *key) +eel_gconf_get_integer_list(const char *key) { GSList *slist; GConfClient *client; GError *error; - g_return_val_if_fail (key != NULL, NULL); + g_return_val_if_fail(key != NULL, NULL); - client = eel_gconf_client_get_global (); - g_return_val_if_fail (client != NULL, NULL); + client = eel_gconf_client_get_global(); + g_return_val_if_fail(client != NULL, NULL); error = NULL; - slist = gconf_client_get_list (client, key, GCONF_VALUE_INT, &error); + slist = gconf_client_get_list(client, key, GCONF_VALUE_INT, &error); - if (eel_gconf_handle_error (&error)) { + if (eel_gconf_handle_error(&error)) { slist = NULL; } @@ -356,19 +356,19 @@ eel_gconf_get_integer_list (const char *key) /* End of added code */ gboolean -eel_gconf_is_default (const char *key) +eel_gconf_is_default(const char *key) { gboolean result; GConfValue *value; GError *error = NULL; - g_return_val_if_fail (key != NULL, FALSE); + g_return_val_if_fail(key != NULL, FALSE); - value = gconf_client_get_without_default (eel_gconf_client_get_global (), key, &error); + value = gconf_client_get_without_default(eel_gconf_client_get_global(), key, &error); - if (eel_gconf_handle_error (&error)) { + if (eel_gconf_handle_error(&error)) { if (value != NULL) { - gconf_value_free (value); + gconf_value_free(value); } return FALSE; @@ -377,7 +377,7 @@ eel_gconf_is_default (const char *key) result = (value == NULL); if (value != NULL) { - gconf_value_free (value); + gconf_value_free(value); } @@ -385,22 +385,22 @@ eel_gconf_is_default (const char *key) } gboolean -eel_gconf_monitor_add (const char *directory) +eel_gconf_monitor_add(const char *directory) { GError *error = NULL; GConfClient *client; - g_return_val_if_fail (directory != NULL, FALSE); + g_return_val_if_fail(directory != NULL, FALSE); - client = eel_gconf_client_get_global (); - g_return_val_if_fail (client != NULL, FALSE); + client = eel_gconf_client_get_global(); + g_return_val_if_fail(client != NULL, FALSE); - gconf_client_add_dir (client, - directory, - GCONF_CLIENT_PRELOAD_NONE, - &error); + gconf_client_add_dir(client, + directory, + GCONF_CLIENT_PRELOAD_NONE, + &error); - if (eel_gconf_handle_error (&error)) { + if (eel_gconf_handle_error(&error)) { return FALSE; } @@ -408,7 +408,7 @@ eel_gconf_monitor_add (const char *directory) } gboolean -eel_gconf_monitor_remove (const char *directory) +eel_gconf_monitor_remove(const char *directory) { GError *error = NULL; GConfClient *client; @@ -417,14 +417,14 @@ eel_gconf_monitor_remove (const char *directory) return FALSE; } - client = eel_gconf_client_get_global (); - g_return_val_if_fail (client != NULL, FALSE); + client = eel_gconf_client_get_global(); + g_return_val_if_fail(client != NULL, FALSE); - gconf_client_remove_dir (client, - directory, - &error); + gconf_client_remove_dir(client, + directory, + &error); - if (eel_gconf_handle_error (&error)) { + if (eel_gconf_handle_error(&error)) { return FALSE; } @@ -432,35 +432,35 @@ eel_gconf_monitor_remove (const char *directory) } void -eel_gconf_suggest_sync (void) +eel_gconf_suggest_sync(void) { GConfClient *client; GError *error = NULL; - client = eel_gconf_client_get_global (); - g_return_if_fail (client != NULL); + client = eel_gconf_client_get_global(); + g_return_if_fail(client != NULL); - gconf_client_suggest_sync (client, &error); - eel_gconf_handle_error (&error); + gconf_client_suggest_sync(client, &error); + eel_gconf_handle_error(&error); } GConfValue* -eel_gconf_get_value (const char *key) +eel_gconf_get_value(const char *key) { GConfValue *value = NULL; GConfClient *client; GError *error = NULL; - g_return_val_if_fail (key != NULL, NULL); + g_return_val_if_fail(key != NULL, NULL); - client = eel_gconf_client_get_global (); - g_return_val_if_fail (client != NULL, NULL); + client = eel_gconf_client_get_global(); + g_return_val_if_fail(client != NULL, NULL); - value = gconf_client_get (client, key, &error); + value = gconf_client_get(client, key, &error); - if (eel_gconf_handle_error (&error)) { + if (eel_gconf_handle_error(&error)) { if (value != NULL) { - gconf_value_free (value); + gconf_value_free(value); value = NULL; } } @@ -469,25 +469,25 @@ eel_gconf_get_value (const char *key) } void -eel_gconf_set_value (const char *key, const GConfValue *value) +eel_gconf_set_value(const char *key, const GConfValue *value) { GConfClient *client; GError *error = NULL; - g_return_if_fail (key != NULL); + g_return_if_fail(key != NULL); - client = eel_gconf_client_get_global (); - g_return_if_fail (client != NULL); + client = eel_gconf_client_get_global(); + g_return_if_fail(client != NULL); - gconf_client_set (client, key, value, &error); + gconf_client_set(client, key, value, &error); - if (eel_gconf_handle_error (&error)) { + if (eel_gconf_handle_error(&error)) { return; } } gboolean -eel_gconf_key_exists (const char *key) +eel_gconf_key_exists(const char *key) { GConfValue *value = NULL; GConfClient *client; @@ -495,60 +495,60 @@ eel_gconf_key_exists (const char *key) gboolean error_occurred; gboolean value_found; - g_return_val_if_fail (key != NULL, FALSE); + g_return_val_if_fail(key != NULL, FALSE); - client = eel_gconf_client_get_global (); - g_return_val_if_fail (client != NULL, FALSE); + client = eel_gconf_client_get_global(); + g_return_val_if_fail(client != NULL, FALSE); - value = gconf_client_get (client, key, &error); + value = gconf_client_get(client, key, &error); value_found = (value != NULL); error_occurred = (error != NULL); - eel_gconf_value_free (value); + eel_gconf_value_free(value); if (error != NULL) { - g_error_free (error); + g_error_free(error); } return (!error_occurred && value_found); } void -eel_gconf_value_free (GConfValue *value) +eel_gconf_value_free(GConfValue *value) { if (value == NULL) { return; } - gconf_value_free (value); + gconf_value_free(value); } guint -eel_gconf_notification_add (const char *key, - GConfClientNotifyFunc notification_callback, - gpointer callback_data) +eel_gconf_notification_add(const char *key, + GConfClientNotifyFunc notification_callback, + gpointer callback_data) { guint notification_id; GConfClient *client; GError *error = NULL; - g_return_val_if_fail (key != NULL, EEL_GCONF_UNDEFINED_CONNECTION); - g_return_val_if_fail (notification_callback != NULL, EEL_GCONF_UNDEFINED_CONNECTION); + g_return_val_if_fail(key != NULL, EEL_GCONF_UNDEFINED_CONNECTION); + g_return_val_if_fail(notification_callback != NULL, EEL_GCONF_UNDEFINED_CONNECTION); - client = eel_gconf_client_get_global (); - g_return_val_if_fail (client != NULL, EEL_GCONF_UNDEFINED_CONNECTION); + client = eel_gconf_client_get_global(); + g_return_val_if_fail(client != NULL, EEL_GCONF_UNDEFINED_CONNECTION); - notification_id = gconf_client_notify_add (client, + notification_id = gconf_client_notify_add(client, key, notification_callback, callback_data, NULL, &error); - if (eel_gconf_handle_error (&error)) { + if (eel_gconf_handle_error(&error)) { if (notification_id != EEL_GCONF_UNDEFINED_CONNECTION) { - gconf_client_notify_remove (client, notification_id); + gconf_client_notify_remove(client, notification_id); notification_id = EEL_GCONF_UNDEFINED_CONNECTION; } } @@ -557,7 +557,7 @@ eel_gconf_notification_add (const char *key, } void -eel_gconf_notification_remove (guint notification_id) +eel_gconf_notification_remove(guint notification_id) { GConfClient *client; @@ -565,10 +565,10 @@ eel_gconf_notification_remove (guint notification_id) return; } - client = eel_gconf_client_get_global (); - g_return_if_fail (client != NULL); + client = eel_gconf_client_get_global(); + g_return_if_fail(client != NULL); - gconf_client_notify_remove (client, notification_id); + gconf_client_notify_remove(client, notification_id); } /* Simple wrapper for eel_gconf_notifier_add which @@ -576,32 +576,32 @@ eel_gconf_notification_remove (guint notification_id) * so that a call to gpdf_notification_free can remove the notifiers */ void -gpdf_notification_add (const char *key, - GConfClientNotifyFunc notification_callback, - gpointer callback_data, - GList **notifiers) +gpdf_notification_add(const char *key, + GConfClientNotifyFunc notification_callback, + gpointer callback_data, + GList **notifiers) { guint id = 0; - id = eel_gconf_notification_add (key, - notification_callback, - callback_data); + id = eel_gconf_notification_add(key, + notification_callback, + callback_data); if (notifiers != NULL) { - *notifiers = g_list_append (*notifiers, - GINT_TO_POINTER (id)); + *notifiers = g_list_append(*notifiers, + GINT_TO_POINTER(id)); } } /* Removes all the notifiers listed in notifiers */ /* Frees the notifiers list */ void -gpdf_notification_remove (GList **notifiers) +gpdf_notification_remove(GList **notifiers) { - g_list_foreach (*notifiers, - (GFunc) eel_gconf_notification_remove, - NULL); - g_list_free (*notifiers); + g_list_foreach(*notifiers, + (GFunc) eel_gconf_notification_remove, + NULL); + g_list_free(*notifiers); *notifiers = NULL; } diff --git a/gnome/src/eel-gconf-extensions.h b/gnome/src/eel-gconf-extensions.h index f9e4f5c381159e79d732e5c55a687a009d7814c4..0068b15b2f4bf6b35a5f426685c3b67cba5bf12b 100644 --- a/gnome/src/eel-gconf-extensions.h +++ b/gnome/src/eel-gconf-extensions.h @@ -32,6 +32,28 @@ #ifdef __cplusplus BEGIN_EXTERN_C #endif +/** + * Gconf + */ +#define CONF_PREFIX "/apps/sflphone-client-gnome" +#define CONF_MAIN_WINDOW_WIDTH CONF_PREFIX "/state/window_width" +#define CONF_MAIN_WINDOW_HEIGHT CONF_PREFIX "/state/window_height" +#define CONF_MAIN_WINDOW_POSITION_X CONF_PREFIX "/state/window_position_x" +#define CONF_MAIN_WINDOW_POSITION_Y CONF_PREFIX "/state/window_position_y" +#define CONF_IM_WINDOW_WIDTH CONF_PREFIX "/state/im_width" +#define CONF_IM_WINDOW_HEIGHT CONF_PREFIX "/state/im_height" +#define CONF_IM_WINDOW_POSITION_X CONF_PREFIX "/state/im_position_x" +#define CONF_IM_WINDOW_POSITION_Y CONF_PREFIX "/state/im_position_y" +/** Show/Hide the dialpad */ +#define CONF_SHOW_DIALPAD CONF_PREFIX "/state/dialpad" +#define SHOW_VOLUME_CONTROLS CONF_PREFIX "/state/volume_controls" +#define SHOW_STATUSICON CONF_PREFIX "/state/statusicon" +#define NOTIFY_ALL CONF_PREFIX "/state/notify_all" +#define START_HIDDEN CONF_PREFIX "/state/start_hidden" +#define POPUP_ON_CALL CONF_PREFIX "/state/popup" +#define HISTORY_ENABLED CONF_PREFIX "/state/history" +#define INSTANT_MESSAGING_ENABLED CONF_PREFIX "/state/instant_messaging" + #define EEL_GCONF_UNDEFINED_CONNECTION 0 diff --git a/gnome/src/icons/Makefile.am b/gnome/src/icons/Makefile.am index b9cdfbdcbf420f6508f0372cacb136c3a9d623bc..ecb4274268bf03772f37b30e7f99547d4a3b7dbf 100644 --- a/gnome/src/icons/Makefile.am +++ b/gnome/src/icons/Makefile.am @@ -7,9 +7,7 @@ libicons_la_SOURCES = icon_factory.c \ pixmap_data.h libicons_la_LDFLAGS = $(DBUSGLIB_LDFLAGS) $(LIBNOTIFY_LDFLAGS) \ - $(GTK_LDFLAGS) $(GLIB_LDFLAGS) $(WEBKIT_LDFLAGS) $(LIBGNOMEUI_LDFLAGS) \ - $(GNOMEDOCUTILS_LDFLAGS) + $(GTK_LDFLAGS) $(GLIB_LDFLAGS) $(WEBKIT_LDFLAGS) libicons_la_CFLAGS = $(DBUSGLIB_CFLAGS) $(LIBNOTIFY_CFLAGS) \ - $(GTK_CFLAGS) $(GLIB_CFLAGS) $(WEBKIT_CFLAGS) $(LIBGNOMEUI_CFLAGS) \ - $(GNOMEDOCUTILS_CFLAGS) + $(GTK_CFLAGS) $(GLIB_CFLAGS) $(WEBKIT_CFLAGS) diff --git a/gnome/src/icons/icon_factory.c b/gnome/src/icons/icon_factory.c index a888aec6eb96ae189af172e5d419a1a59721dcaf..134ebf9bda91ed0a9216df8197da237e6461b3ae 100644 --- a/gnome/src/icons/icon_factory.c +++ b/gnome/src/icons/icon_factory.c @@ -29,63 +29,55 @@ */ #include "icon_factory.h" -#include "icons/pixmap_data.h" - - +#include "logger.h" #include <gtk/gtk.h> #include "icons/pixmap_data.h" -#include "sflphone_const.h" static GtkIconFactory *icon_factory = NULL; -void add_icon (GtkIconFactory *factory, const gchar *stock_id, const guint8 *icon_data, GtkIconSize size) +void add_icon(GtkIconFactory *factory, const gchar *stock_id, const guint8 *icon_data, GtkIconSize size) { - GtkIconSet *icons; - GtkIconSource *source; - GdkPixbuf *pixbuf; - - icons = gtk_icon_factory_lookup (factory, stock_id); + GtkIconSet *icons = gtk_icon_factory_lookup(factory, stock_id); if (!icons) { - pixbuf = gdk_pixbuf_new_from_inline (-1, icon_data, FALSE, NULL); - source = gtk_icon_source_new (); - gtk_icon_source_set_pixbuf (source, pixbuf); - gtk_icon_source_set_size (source, size); + GdkPixbuf *pixbuf = gdk_pixbuf_new_from_inline(-1, icon_data, FALSE, NULL); + GtkIconSource *source = gtk_icon_source_new(); + gtk_icon_source_set_pixbuf(source, pixbuf); + gtk_icon_source_set_size(source, size); - icons = gtk_icon_set_new (); - gtk_icon_set_add_source (icons, source); + icons = gtk_icon_set_new(); + gtk_icon_set_add_source(icons, source); - gtk_icon_factory_add (factory, stock_id, icons); + gtk_icon_factory_add(factory, stock_id, icons); - g_object_unref (G_OBJECT (pixbuf)); - gtk_icon_source_free (source); - gtk_icon_set_unref (icons); + g_object_unref(G_OBJECT(pixbuf)); + gtk_icon_source_free(source); + gtk_icon_set_unref(icons); } else - DEBUG ("Icon %s already exists in factory\n", stock_id); + DEBUG("Icon %s already exists in factory\n", stock_id); } -void register_sflphone_stock_icons (GtkIconFactory *factory) +void register_sflphone_stock_icons(GtkIconFactory *factory) { - add_icon (factory, GTK_STOCK_PICKUP, gnome_stock_pickup, GTK_ICON_SIZE_SMALL_TOOLBAR); - add_icon (factory, GTK_STOCK_HANGUP, gnome_stock_hangup, GTK_ICON_SIZE_SMALL_TOOLBAR); - add_icon (factory, GTK_STOCK_DIAL, gnome_stock_dial, GTK_ICON_SIZE_SMALL_TOOLBAR); - add_icon (factory, GTK_STOCK_TRANSFER, gnome_stock_transfer, GTK_ICON_SIZE_SMALL_TOOLBAR); - add_icon (factory, GTK_STOCK_ONHOLD, gnome_stock_onhold, GTK_ICON_SIZE_SMALL_TOOLBAR); - add_icon (factory, GTK_STOCK_OFFHOLD, gnome_stock_offhold, GTK_ICON_SIZE_SMALL_TOOLBAR); - add_icon (factory, GTK_STOCK_IM, gnome_stock_im, GTK_ICON_SIZE_SMALL_TOOLBAR); - add_icon (factory, GTK_STOCK_CALL_CURRENT, gnome_stock_call_current, GTK_ICON_SIZE_SMALL_TOOLBAR); - add_icon (factory, GTK_STOCK_ADDRESSBOOK, gnome_stock_addressbook, GTK_ICON_SIZE_SMALL_TOOLBAR); - add_icon (factory, GTK_STOCK_CALLS, gnome_stock_calls, GTK_ICON_SIZE_SMALL_TOOLBAR); - add_icon (factory, GTK_STOCK_SFLPHONE, gnome_stock_sflphone, GTK_ICON_SIZE_SMALL_TOOLBAR); - add_icon (factory, GTK_STOCK_FAIL, gnome_stock_fail, GTK_ICON_SIZE_SMALL_TOOLBAR); - add_icon (factory, GTK_STOCK_USER, gnome_stock_user, GTK_ICON_SIZE_SMALL_TOOLBAR); + add_icon(factory, GTK_STOCK_PICKUP, gnome_stock_pickup, GTK_ICON_SIZE_SMALL_TOOLBAR); + add_icon(factory, GTK_STOCK_HANGUP, gnome_stock_hangup, GTK_ICON_SIZE_SMALL_TOOLBAR); + add_icon(factory, GTK_STOCK_DIAL, gnome_stock_dial, GTK_ICON_SIZE_SMALL_TOOLBAR); + add_icon(factory, GTK_STOCK_TRANSFER, gnome_stock_transfer, GTK_ICON_SIZE_SMALL_TOOLBAR); + add_icon(factory, GTK_STOCK_ONHOLD, gnome_stock_onhold, GTK_ICON_SIZE_SMALL_TOOLBAR); + add_icon(factory, GTK_STOCK_OFFHOLD, gnome_stock_offhold, GTK_ICON_SIZE_SMALL_TOOLBAR); + add_icon(factory, GTK_STOCK_IM, gnome_stock_im, GTK_ICON_SIZE_SMALL_TOOLBAR); + add_icon(factory, GTK_STOCK_CALL_CURRENT, gnome_stock_call_current, GTK_ICON_SIZE_SMALL_TOOLBAR); + add_icon(factory, GTK_STOCK_ADDRESSBOOK, gnome_stock_addressbook, GTK_ICON_SIZE_SMALL_TOOLBAR); + add_icon(factory, GTK_STOCK_CALLS, gnome_stock_calls, GTK_ICON_SIZE_SMALL_TOOLBAR); + add_icon(factory, GTK_STOCK_SFLPHONE, gnome_stock_sflphone, GTK_ICON_SIZE_SMALL_TOOLBAR); + add_icon(factory, GTK_STOCK_FAIL, gnome_stock_fail, GTK_ICON_SIZE_SMALL_TOOLBAR); + add_icon(factory, GTK_STOCK_USER, gnome_stock_user, GTK_ICON_SIZE_SMALL_TOOLBAR); } -void init_icon_factory (void) +void init_icon_factory(void) { - icon_factory = gtk_icon_factory_new (); - register_sflphone_stock_icons (icon_factory); - gtk_icon_factory_add_default (icon_factory); + icon_factory = gtk_icon_factory_new(); + register_sflphone_stock_icons(icon_factory); + gtk_icon_factory_add_default(icon_factory); } - diff --git a/gnome/src/icons/icon_factory.h b/gnome/src/icons/icon_factory.h index 2443cfca69ee57ba505199f21fde6d4c0a6348d2..d7b5fccdd2c1c9d01111913d5a0530662bcd4ca2 100644 --- a/gnome/src/icons/icon_factory.h +++ b/gnome/src/icons/icon_factory.h @@ -36,14 +36,15 @@ #define GTK_STOCK_ONHOLD "gnome-stock-onhold" #define GTK_STOCK_OFFHOLD "gnome-stock-offhold" #define GTK_STOCK_IM "gnome-stock-im" -#define GTK_STOCK_TRANSFER "gnome-stock-transfer" -#define GTK_STOCK_DIAL "gnome-stock-dial" -#define GTK_STOCK_CALL_CURRENT "gnome-stock-call-current" -#define GTK_STOCK_ADDRESSBOOK "gnome-stock-addressbook" +#define GTK_STOCK_TRANSFER "gnome-stock-transfer" +#define GTK_STOCK_DIAL "gnome-stock-dial" +#define GTK_STOCK_CALL_CURRENT "gnome-stock-call-current" +#define GTK_STOCK_ADDRESSBOOK "gnome-stock-addressbook" #define GTK_STOCK_CALLS "gnome-stock-calls" #define GTK_STOCK_SFLPHONE "gnome-stock-sflphone" #define GTK_STOCK_FAIL "gnome-stock-fail" #define GTK_STOCK_USER "gnome-stock-user" +#define GTK_STOCK_AUDIO_CARD "audio-card" void init_icon_factory (void); diff --git a/gnome/src/imwindow.c b/gnome/src/imwindow.c index 301ae698ed96310993acfbc0870982c1c292f88f..9b170a22c7a8bb87eaa9fc992f356a9680b01dc2 100644 --- a/gnome/src/imwindow.c +++ b/gnome/src/imwindow.c @@ -30,14 +30,14 @@ * as that of the covered work. */ -#include <config.h> -#include <gtk/gtk.h> -#include <eel-gconf-extensions.h> -#include <sflphone_const.h> - -#include <imwindow.h> -#include <contacts/calltab.h> -#include <contacts/calltab.h> +#include "config.h" +#include "eel-gconf-extensions.h" +#include "logger.h" +#include "imwindow.h" +#include "unused.h" +#include "contacts/calltab.h" +#include "contacts/calltab.h" +#include "sflphone_const.h" #include <sys/stat.h> /** Local variables */ @@ -47,24 +47,24 @@ static GtkWidget *im_notebook = NULL; static void im_window_init(); -static GtkWindow *im_window_get() +static GtkWidget *im_window_get() { if (im_window == NULL) im_window_init(); - return GTK_WINDOW(im_window); + return im_window; } -static gboolean window_configure_cb (GtkWidget *wini UNUSED, GdkEventConfigure *event) +static gboolean window_configure_cb(GtkWidget *wini UNUSED, GdkEventConfigure *event) { int pos_x, pos_y; - eel_gconf_set_integer (CONF_IM_WINDOW_WIDTH, event->width); - eel_gconf_set_integer (CONF_IM_WINDOW_HEIGHT, event->height); + eel_gconf_set_integer(CONF_IM_WINDOW_WIDTH, event->width); + eel_gconf_set_integer(CONF_IM_WINDOW_HEIGHT, event->height); - gtk_window_get_position (im_window_get(), &pos_x, &pos_y); - eel_gconf_set_integer (CONF_IM_WINDOW_POSITION_X, pos_x); - eel_gconf_set_integer (CONF_IM_WINDOW_POSITION_Y, pos_y); + gtk_window_get_position(GTK_WINDOW(im_window_get()), &pos_x, &pos_y); + eel_gconf_set_integer(CONF_IM_WINDOW_POSITION_X, pos_x); + eel_gconf_set_integer(CONF_IM_WINDOW_POSITION_Y, pos_y); return FALSE; } @@ -73,21 +73,21 @@ static gboolean window_configure_cb (GtkWidget *wini UNUSED, GdkEventConfigure * * Minimize the main window. */ static gboolean -on_delete (GtkWidget * widget UNUSED, gpointer data UNUSED) +on_delete(GtkWidget * widget UNUSED, gpointer data UNUSED) { /* Only hide the main window that contains all the instant messaging instances */ - gtk_widget_hide (GTK_WIDGET (im_window_get())); + gtk_widget_hide(im_window_get()); return TRUE; } static void -on_switch_page (GtkNotebook *notebook, GtkNotebookPage *page UNUSED, guint page_num, gpointer userdata UNUSED) +on_switch_page(GtkNotebook *notebook, gpointer page UNUSED, guint page_num, gpointer userdata UNUSED) { - GtkWidget *tab = gtk_notebook_get_nth_page (GTK_NOTEBOOK (notebook), page_num); + GtkWidget *tab = gtk_notebook_get_nth_page(GTK_NOTEBOOK(notebook), page_num); // show the current widget - gtk_widget_grab_focus (tab); - gtk_widget_show_now (tab); + gtk_widget_grab_focus(tab); + gtk_widget_show_now(tab); } static void @@ -97,70 +97,72 @@ im_window_init() int width, height, position_x, position_y; // Get configuration stored in gconf - width = eel_gconf_get_integer (CONF_IM_WINDOW_WIDTH); + width = eel_gconf_get_integer(CONF_IM_WINDOW_WIDTH); if (width <= 0) width = 400; - height = eel_gconf_get_integer (CONF_IM_WINDOW_HEIGHT); + height = eel_gconf_get_integer(CONF_IM_WINDOW_HEIGHT); if (height <= 0) height = 500; - position_x = eel_gconf_get_integer (CONF_IM_WINDOW_POSITION_X); - position_y = eel_gconf_get_integer (CONF_IM_WINDOW_POSITION_Y); + position_x = eel_gconf_get_integer(CONF_IM_WINDOW_POSITION_X); + position_y = eel_gconf_get_integer(CONF_IM_WINDOW_POSITION_Y); - im_window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_container_set_border_width (GTK_CONTAINER (im_window), 0); - gtk_window_set_title (GTK_WINDOW (im_window), window_title); - gtk_window_set_default_size (GTK_WINDOW (im_window), width, height); + im_window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_container_set_border_width(GTK_CONTAINER(im_window), 0); + gtk_window_set_title(GTK_WINDOW(im_window), window_title); + gtk_window_set_default_size(GTK_WINDOW(im_window), width, height); struct stat st; + if (!stat(LOGO, &st)) - gtk_window_set_default_icon_from_file (LOGO, NULL); - gtk_window_set_position (GTK_WINDOW (im_window), GTK_WIN_POS_MOUSE); + gtk_window_set_default_icon_from_file(LOGO, NULL); + + gtk_window_set_position(GTK_WINDOW(im_window), GTK_WIN_POS_MOUSE); - gtk_widget_set_name (im_window, "imwindow"); + gtk_widget_set_name(im_window, "imwindow"); - GtkWidget *im_vbox = gtk_vbox_new (FALSE /*homogeneous*/, 0 /*spacing*/); - im_notebook = gtk_notebook_new (); + GtkWidget *im_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0 /*spacing*/); + im_notebook = gtk_notebook_new(); - gtk_container_add (GTK_CONTAINER (im_window), im_vbox); - gtk_box_pack_start (GTK_BOX (im_vbox), im_notebook, TRUE, TRUE, 0); - gtk_widget_show (im_notebook); + gtk_container_add(GTK_CONTAINER(im_window), im_box); + gtk_box_pack_start(GTK_BOX(im_box), im_notebook, TRUE, TRUE, 0); + gtk_widget_show(im_notebook); - g_signal_connect (G_OBJECT (im_window), "delete-event", G_CALLBACK (on_delete), NULL); - g_signal_connect_object (G_OBJECT (im_window), "configure-event", G_CALLBACK (window_configure_cb), NULL, 0); - g_signal_connect (G_OBJECT (im_notebook), "switch-page", G_CALLBACK (on_switch_page), NULL); + g_signal_connect(G_OBJECT(im_window), "delete-event", G_CALLBACK(on_delete), NULL); + g_signal_connect_object(G_OBJECT(im_window), "configure-event", G_CALLBACK(window_configure_cb), NULL, 0); + g_signal_connect(G_OBJECT(im_notebook), "switch-page", G_CALLBACK(on_switch_page), NULL); /* make sure that everything is visible */ - gtk_widget_show_all (im_window); + gtk_widget_show_all(im_window); // Restore position according to the configuration stored in gconf - gtk_window_move (GTK_WINDOW (im_window), position_x, position_y); + gtk_window_move(GTK_WINDOW(im_window), position_x, position_y); gtk_widget_set_visible(im_window, FALSE); } gboolean -im_window_is_active () +im_window_is_active() { if (!im_window) return FALSE; else - return gtk_window_is_active (GTK_WINDOW (im_window)); + return gtk_window_is_active(GTK_WINDOW(im_window)); } gboolean -im_window_is_visible () +im_window_is_visible() { - return gtk_widget_get_visible(GTK_WIDGET(im_window_get())); + return gtk_widget_get_visible(im_window_get()); } void -im_window_add (GtkWidget *widget) +im_window_add(IMWidget *widget) { if (im_window_get()) { - im_window_add_tab (widget); - gtk_widget_show_all (GTK_WIDGET(im_window_get())); + im_window_add_tab(widget); + gtk_widget_show_all(im_window_get()); } } @@ -168,99 +170,96 @@ gint im_window_get_nb_tabs() { if (im_notebook != NULL) - return gtk_notebook_get_n_pages (GTK_NOTEBOOK(im_notebook)); + return gtk_notebook_get_n_pages(GTK_NOTEBOOK(im_notebook)); else return 0; } static void -close_tab_cb (GtkButton *button UNUSED, gpointer userdata) +close_tab_cb(GtkButton *button UNUSED, gpointer userdata) { /* We want here to close the current tab */ - im_window_remove_tab (GTK_WIDGET (userdata)); + im_window_remove_tab(GTK_WIDGET(userdata)); /* If no tabs are opened anymore, close the IM window */ // gtk_widget_destroy (im_window); } static void -im_window_hide_show_tabs () +im_window_hide_show_tabs() { /* If only one tab is open, do not display the tab, only the content */ - gtk_notebook_set_show_tabs(GTK_NOTEBOOK (im_notebook), - gtk_notebook_get_n_pages (GTK_NOTEBOOK (im_notebook)) != 1); + gtk_notebook_set_show_tabs(GTK_NOTEBOOK(im_notebook), + gtk_notebook_get_n_pages(GTK_NOTEBOOK(im_notebook)) != 1); } void -im_window_add_tab (GtkWidget *widget) +im_window_add_tab(IMWidget *im) { - /* Cast the paramater */ - IMWidget *im = IM_WIDGET (widget); - /* Fetch the call */ - callable_obj_t *im_widget_call = calllist_get_call (current_calls, im->call_id); - conference_obj_t *im_widget_conf = conferencelist_get (current_calls, im->call_id); + callable_obj_t *im_widget_call = calllist_get_call(current_calls_tab, im->call_id); + conference_obj_t *im_widget_conf = conferencelist_get(current_calls_tab, im->call_id); /* A container to include the tab label and the close button */ - GtkWidget *tab_Container = gtk_hbox_new (FALSE, 3); - GtkWidget *tab_Label; - im->tab = tab_Container; + GtkWidget *tab_container = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 3); + GtkWidget *tab_label; + im->tab = tab_container; if (im_widget_call) - tab_Label = gtk_label_new (*im_widget_call->_peer_name ? im_widget_call->_peer_name : im_widget_call->_peer_number); + tab_label = gtk_label_new(*im_widget_call->_peer_name ? im_widget_call->_peer_name : im_widget_call->_peer_number); else if (im_widget_conf) - tab_Label = gtk_label_new ("Conferencing"); + tab_label = gtk_label_new("Conferencing"); else - tab_Label = gtk_label_new (""); + tab_label = gtk_label_new(""); - GtkWidget *tab_CloseButton = gtk_button_new (); + GtkWidget *tab_close_button = gtk_button_new(); /* Pack it all */ - gtk_button_set_relief (GTK_BUTTON (tab_CloseButton), GTK_RELIEF_NONE); - gtk_box_pack_start (GTK_BOX (tab_Container), tab_Label, TRUE, TRUE, 0); - gtk_box_pack_start (GTK_BOX (tab_Container), tab_CloseButton, FALSE, FALSE, 0); - gtk_container_add (GTK_CONTAINER (tab_CloseButton), gtk_image_new_from_stock (GTK_STOCK_CLOSE, GTK_ICON_SIZE_MENU)); + gtk_button_set_relief(GTK_BUTTON(tab_close_button), GTK_RELIEF_NONE); + gtk_box_pack_start(GTK_BOX(tab_container), tab_label, TRUE, TRUE, 0); + gtk_box_pack_start(GTK_BOX(tab_container), tab_close_button, FALSE, FALSE, 0); + gtk_container_add(GTK_CONTAINER(tab_close_button), gtk_image_new_from_stock(GTK_STOCK_CLOSE, GTK_ICON_SIZE_MENU)); /* Connect a signal to the close button on each tab, to be able to close the tabs individually */ - g_signal_connect (tab_CloseButton, "clicked", G_CALLBACK (close_tab_cb), widget); + g_signal_connect(tab_close_button, "clicked", G_CALLBACK(close_tab_cb), im); /* Show it */ - gtk_widget_show_all (im_notebook); - gtk_widget_show_all (tab_Container); + gtk_widget_show_all(im_notebook); + gtk_widget_show_all(tab_container); /* Add the page to the notebook */ - guint tabIndex = gtk_notebook_append_page (GTK_NOTEBOOK (im_notebook), widget, tab_Container); + guint tab_index = gtk_notebook_append_page(GTK_NOTEBOOK(im_notebook), GTK_WIDGET(im), tab_container); /* TODO Switch to the newly opened tab. Still not working */ - DEBUG ("InstantMessaging: Switch to tab: %i", tabIndex); - gtk_notebook_set_current_page (GTK_NOTEBOOK (im_notebook), -1); + DEBUG("InstantMessaging: Switch to tab: %i", tab_index); + gtk_notebook_set_current_page(GTK_NOTEBOOK(im_notebook), -1); /* Decide whether or not displaying the tabs of the notebook */ - im_window_hide_show_tabs (); + im_window_hide_show_tabs(); } void -im_window_show_tab (GtkWidget *widget) +im_window_show_tab(GtkWidget *widget) { - int pageIndex = gtk_notebook_page_num (GTK_NOTEBOOK (im_notebook), widget); + int pageIndex = gtk_notebook_page_num(GTK_NOTEBOOK(im_notebook), widget); if (pageIndex != -1) - gtk_notebook_set_current_page (GTK_NOTEBOOK (im_notebook), pageIndex); + gtk_notebook_set_current_page(GTK_NOTEBOOK(im_notebook), pageIndex); } void -im_window_remove_tab (GtkWidget *widget) +im_window_remove_tab(GtkWidget *widget) { // Remove the widget from the window /* We want here to close the current tab */ - guint index = gtk_notebook_page_num (GTK_NOTEBOOK (im_notebook), GTK_WIDGET (widget)); - gtk_notebook_remove_page (GTK_NOTEBOOK (im_notebook), index); + guint page_index = gtk_notebook_page_num(GTK_NOTEBOOK(im_notebook), GTK_WIDGET(widget)); + gtk_notebook_remove_page(GTK_NOTEBOOK(im_notebook), page_index); /* Need to do some memory clean up, so that we could re-open an Im widget for this call later. */ - IMWidget *im = IM_WIDGET (widget); - callable_obj_t *call = calllist_get_call (current_calls, im->call_id); - conference_obj_t *conf = conferencelist_get (current_calls, im->call_id); + IMWidget *im = IM_WIDGET(widget); + callable_obj_t *call = calllist_get_call(current_calls_tab, im->call_id); + conference_obj_t *conf = conferencelist_get(current_calls_tab, im->call_id); if (call) call->_im_widget = NULL; @@ -269,5 +268,5 @@ im_window_remove_tab (GtkWidget *widget) conf->_im_widget = NULL; /* Decide whether or not displaying the tabs of the notebook */ - im_window_hide_show_tabs (); + im_window_hide_show_tabs(); } diff --git a/gnome/src/imwindow.h b/gnome/src/imwindow.h index 0db8c628c4ba13e219465132a8fddacce88718c6..d7ef33b7aa9bff0c690cdf37e7100ffc3c6cd8d0 100644 --- a/gnome/src/imwindow.h +++ b/gnome/src/imwindow.h @@ -31,12 +31,8 @@ #define __IMWINDOW_H__ #include <gtk/gtk.h> -#include <gtk/gtk.h> - -#include <widget/imwidget.h> -#define IM_WINDOW_WIDTH 280 -#define IM_WINDOW_HEIGHT 320 +#include "widget/imwidget.h" /** @file imwindow.h * @brief The IM window of the client. @@ -45,7 +41,7 @@ /*! @function @abstract Add IM widget to the IM window */ -void im_window_add (GtkWidget *widget); +void im_window_add (IMWidget *widget); /*! @function @abstract Remove IM widget from the IM window @@ -71,7 +67,7 @@ gint im_window_get_nb_tabs (void); @abstract Add a new tab in the notebook. Each tab is an IM Widget @param The IM widget */ -void im_window_add_tab (GtkWidget *widget); +void im_window_add_tab (IMWidget *widget); /*! @function @abstract Select the specified tab as current in instant messaging window diff --git a/gnome/src/logger.c b/gnome/src/logger.c index 917774921b847a178e50a7d6692c594842491aa4..722bc2b80bda447d1cb5f845037db952c922593e 100644 --- a/gnome/src/logger.c +++ b/gnome/src/logger.c @@ -35,7 +35,7 @@ static int log_level = LOG_INFO; -void internal_log (const int level, const char* format, ...) +void internal_log(const int level, const char* format, ...) { if (level > log_level) return; @@ -64,19 +64,19 @@ void internal_log (const int level, const char* format, ...) } } - va_start (ap, format); - vsprintf (buffer, format, ap); - va_end (ap); + va_start(ap, format); + vsprintf(buffer, format, ap); + va_end(ap); message[0] = '\0'; - strncat (message, prefix, strlen (prefix)); - strncat (message, buffer, strlen (buffer)); - strncat (message, "\n", 1); + strncat(message, prefix, strlen(prefix)); + strncat(message, buffer, strlen(buffer)); + strncat(message, "\n", 1); - fprintf (stderr, "%s", message); + fprintf(stderr, "%s", message); } -void set_log_level (const int level) +void set_log_level(const int level) { log_level = level; } diff --git a/gnome/src/main.c b/gnome/src/main.c index 8f5e5570e489bce307fb81d880776ad0e0e3fc44..5998bbcc681e4418462c76a85bafe0598d43101a 100644 --- a/gnome/src/main.c +++ b/gnome/src/main.c @@ -28,17 +28,14 @@ * as that of the covered work. */ -#include <actions.h> -#include <calllist.h> -#include <config.h> -#include <logger.h> -#include <dbus/dbus.h> -#include <mainwindow.h> -#include <statusicon.h> -#include <libgnome/libgnome.h> -#include <libgnomeui/libgnomeui.h> -#include <eel-gconf-extensions.h> - +#include "actions.h" +#include "calllist.h" +#include "config.h" +#include "logger.h" +#include "dbus/dbus.h" +#include "mainwindow.h" +#include "statusicon.h" +#include "eel-gconf-extensions.h" #include <gtk/gtk.h> #include <stdlib.h> @@ -46,7 +43,7 @@ #include "history.h" int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { GError *error = NULL; // Handle logging @@ -54,88 +51,83 @@ main (int argc, char *argv[]) // Check arguments if debug mode is activated for (i = 0; i < argc; i++) - if (g_strcmp0 (argv[i], "--debug") == 0) - set_log_level (LOG_DEBUG); + if (g_strcmp0(argv[i], "--debug") == 0) + set_log_level(LOG_DEBUG); - g_thread_init (NULL); - gdk_threads_init (); - gdk_threads_enter (); + g_thread_init(NULL); + gdk_threads_init(); + gdk_threads_enter(); // Start GTK application - gtk_init (&argc, &argv); - - g_print ("%s %s\n", PACKAGE, VERSION); - g_print ("\nCopyright (c) 2005 - 2011 Savoir-faire Linux Inc.\n\n"); - g_print ("This is free software. You may redistribute copies of it under the terms of\n" \ - "the GNU General Public License Version 3 <http://www.gnu.org/licenses/gpl.html>.\n" \ - "There is NO WARRANTY, to the extent permitted by law.\n\n" \ - "Additional permission under GNU GPL version 3 section 7:\n\n" \ - "If you modify this program, or any covered work, by linking or\n" \ - "combining it with the OpenSSL project's OpenSSL library (or a\n" \ - "modified version of that library), containing parts covered by the\n" \ - "terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc.\n" \ - "grants you additional permission to convey the resulting work.\n" \ - "Corresponding Source for a non-source form of such a combination\n" \ - "shall include the source code for the parts of OpenSSL used as well\n" \ - "as that of the covered work.\n\n"); - - srand (time (NULL)); + gtk_init(&argc, &argv); + + g_print("%s %s\n", PACKAGE, VERSION); + g_print("\nCopyright (c) 2005 - 2011 Savoir-faire Linux Inc.\n\n"); + g_print("This is free software. You may redistribute copies of it under the terms of\n" \ + "the GNU General Public License Version 3 <http://www.gnu.org/licenses/gpl.html>.\n" \ + "There is NO WARRANTY, to the extent permitted by law.\n\n" \ + "Additional permission under GNU GPL version 3 section 7:\n\n" \ + "If you modify this program, or any covered work, by linking or\n" \ + "combining it with the OpenSSL project's OpenSSL library (or a\n" \ + "modified version of that library), containing parts covered by the\n" \ + "terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc.\n" \ + "grants you additional permission to convey the resulting work.\n" \ + "Corresponding Source for a non-source form of such a combination\n" \ + "shall include the source code for the parts of OpenSSL used as well\n" \ + "as that of the covered work.\n\n"); + + srand(time(NULL)); // Internationalization - bindtextdomain ("sflphone-client-gnome", LOCALEDIR); - textdomain ("sflphone-client-gnome"); - - // Initialises the GNOME libraries - gnome_program_init ("sflphone", VERSION, LIBGNOMEUI_MODULE, argc, argv, - GNOME_PROGRAM_STANDARD_PROPERTIES, - NULL) ; + bindtextdomain("sflphone-client-gnome", LOCALEDIR); + textdomain("sflphone-client-gnome"); - if (!sflphone_init (&error)) { - ERROR (error->message); + if (!sflphone_init(&error)) { + ERROR(error->message); GtkWidget *dialog = gtk_message_dialog_new( - GTK_WINDOW (get_main_window()), - GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, - GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, - "Unable to initialize.\nMake sure the daemon is running.\nError: %s", - error->message); + GTK_WINDOW(get_main_window()), + GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, + "Unable to initialize.\nMake sure the daemon is running.\nError: %s", + error->message); - gtk_window_set_title (GTK_WINDOW (dialog), _ ("SFLphone Error")); - gtk_dialog_run (GTK_DIALOG (dialog)); - gtk_widget_destroy (dialog); + gtk_window_set_title(GTK_WINDOW(dialog), _("SFLphone Error")); + gtk_dialog_run(GTK_DIALOG(dialog)); + gtk_widget_destroy(dialog); - g_error_free (error); + g_error_free(error); goto OUT; } - if (eel_gconf_get_integer (SHOW_STATUSICON)) - show_status_icon (); + if (eel_gconf_get_integer(SHOW_STATUSICON)) + show_status_icon(); - create_main_window (); + create_main_window(); - if (eel_gconf_get_integer (SHOW_STATUSICON) && eel_gconf_get_integer (START_HIDDEN)) { - gtk_widget_hide (GTK_WIDGET (get_main_window())); - set_minimized (TRUE); + if (eel_gconf_get_integer(SHOW_STATUSICON) && eel_gconf_get_integer(START_HIDDEN)) { + gtk_widget_hide(GTK_WIDGET(get_main_window())); + set_minimized(TRUE); } - status_bar_display_account (); + status_bar_display_account(); - sflphone_fill_history (); - sflphone_fill_call_list (); - sflphone_fill_conference_list (); + sflphone_fill_history(); + sflphone_fill_call_list(); + sflphone_fill_conference_list(); history_search_init(); // Update the GUI - update_actions (); + update_actions(); shortcuts_initialize_bindings(); - gtk_main (); + gtk_main(); shortcuts_destroy_bindings(); OUT: - gdk_threads_leave (); + gdk_threads_leave(); return error != NULL; } diff --git a/gnome/src/mainwindow.c b/gnome/src/mainwindow.c index 2ab7f2f5de02da7b7e5cf5d1fa8eeeca8dcdd9a5..919613b9884ce9bcd442f35ce2a43ed112b5de71 100644 --- a/gnome/src/mainwindow.c +++ b/gnome/src/mainwindow.c @@ -32,30 +32,28 @@ #include "config.h" #include "actions.h" +#include "dbus.h" #include "calltree.h" #include "calltab.h" +#include "logger.h" #include "preferencesdialog.h" #include "dialpad.h" #include "mainwindow.h" #include "sliders.h" #include "contacts/searchbar.h" +#include "statusicon.h" /* for set_minimized */ #include "assistant.h" -#include "widget/gtkscrollbook.h" #include "widget/minidialog.h" #include "uimanager.h" +#include "unused.h" #include "config/audioconf.h" +#include "eel-gconf-extensions.h" + #include <sys/stat.h> #include <gtk/gtk.h> -/* Backward compatibility for gtk < 2.22.0 */ -#if GTK_CHECK_VERSION(2,22,0) -#include <gdk/gdkkeysyms-compat.h> -#else #include <gdk/gdkkeysyms.h> -#endif - -#include <eel-gconf-extensions.h> /** Local variables */ static GtkUIManager *ui_manager; @@ -67,7 +65,6 @@ static GtkWidget *dialpad; static GtkWidget *speaker_control; static GtkWidget *mic_control; static GtkWidget *statusBar; -static PidginScrollBook *embedded_error_notebook; static gchar *status_current_message; static GMutex *gmutex; @@ -125,14 +122,15 @@ gboolean main_window_ask_quit() { gchar * question; - if (calllist_get_size(current_calls) == 1) + + if (calllist_get_size(current_calls_tab) == 1) question = _("There is one call in progress."); else question = _("There are calls in progress."); GtkWidget *dialog = gtk_message_dialog_new_with_markup(GTK_WINDOW(window), - GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, "%s\n%s", - question, _("Do you still want to quit?")); + GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, "%s\n%s", + question, _("Do you still want to quit?")); gint response = gtk_dialog_run(GTK_DIALOG(dialog)); @@ -147,12 +145,11 @@ on_key_released(GtkWidget *widget UNUSED, GdkEventKey *event, gpointer user_data if (focus_is_on_searchbar) return TRUE; - if (event->keyval == GDK_Return) { - if (active_calltree == current_calls) { + if (event->keyval == GDK_KEY_Return) { + if (active_calltree_tab == current_calls_tab) { sflphone_keypad(event->keyval, event->string); return TRUE; - } - else if (active_calltree == history) + } else if (active_calltree_tab == history_tab) return FALSE; } @@ -161,13 +158,13 @@ on_key_released(GtkWidget *widget UNUSED, GdkEventKey *event, gpointer user_data event->keyval == '<' || event->keyval == '>' || event->keyval == '\"'|| - event->keyval == GDK_Tab || - event->keyval == GDK_Return || - event->keyval == GDK_Left || - event->keyval == GDK_Up || - event->keyval == GDK_Right || - event->keyval == GDK_Down || - (event->keyval >= GDK_F1 && event->keyval <= GDK_F12) || + event->keyval == GDK_KEY_Tab || + event->keyval == GDK_KEY_Return || + event->keyval == GDK_KEY_Left || + event->keyval == GDK_KEY_Up || + event->keyval == GDK_KEY_Right || + event->keyval == GDK_KEY_Down || + (event->keyval >= GDK_KEY_F1 && event->keyval <= GDK_KEY_F12) || event->keyval == ' ') return FALSE; else @@ -192,8 +189,10 @@ create_main_window() gtk_window_set_title(GTK_WINDOW(window), "SFLphone VoIP Client"); gtk_window_set_default_size(GTK_WINDOW(window), width, height); struct stat st; + if (!stat(LOGO, &st)) gtk_window_set_default_icon_from_file(LOGO, NULL); + gtk_window_set_position(GTK_WINDOW(window) , GTK_WIN_POS_MOUSE); /* Connect the destroy event of the window with our on_destroy function @@ -222,8 +221,8 @@ create_main_window() gtk_window_add_accel_group(GTK_WINDOW(window), gtk_ui_manager_get_accel_group(ui_manager)); - vbox = gtk_vbox_new(FALSE /*homogeneous*/, 0 /*spacing*/); - subvbox = gtk_vbox_new(FALSE /*homogeneous*/, 5 /*spacing*/); + vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0 /*spacing*/); + subvbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5 /*spacing*/); GtkWidget *widget = create_menus(ui_manager); gtk_box_pack_start(GTK_BOX(vbox), widget, FALSE /*expand*/, TRUE /*fill*/, @@ -234,11 +233,11 @@ create_main_window() gtk_box_pack_start(GTK_BOX(vbox), widget, FALSE /*expand*/, TRUE /*fill*/, 0 /*padding*/); - gtk_box_pack_start(GTK_BOX(vbox), current_calls->tree, TRUE /*expand*/, + gtk_box_pack_start(GTK_BOX(vbox), current_calls_tab->tree, TRUE /*expand*/, TRUE /*fill*/, 0 /*padding*/); - gtk_box_pack_start(GTK_BOX(vbox), history->tree, TRUE /*expand*/, + gtk_box_pack_start(GTK_BOX(vbox), history_tab->tree, TRUE /*expand*/, TRUE /*fill*/, 0 /*padding*/); - gtk_box_pack_start(GTK_BOX(vbox), contacts->tree, TRUE /*expand*/, + gtk_box_pack_start(GTK_BOX(vbox), contacts_tab->tree, TRUE /*expand*/, TRUE /*fill*/, 0 /*padding*/); g_signal_connect_object(G_OBJECT(window), "configure-event", @@ -246,10 +245,6 @@ create_main_window() gtk_box_pack_start(GTK_BOX(vbox), subvbox, FALSE /*expand*/, FALSE /*fill*/, 0 /*padding*/); - embedded_error_notebook = PIDGIN_SCROLL_BOOK(pidgin_scroll_book_new()); - gtk_box_pack_start(GTK_BOX(subvbox), GTK_WIDGET(embedded_error_notebook), - FALSE, FALSE, 0); - if (SHOW_VOLUME) { speaker_control = create_slider("speaker"); gtk_box_pack_end(GTK_BOX(subvbox), speaker_control, FALSE /*expand*/, @@ -277,10 +272,10 @@ create_main_window() gtk_widget_show_all(window); /* dont't show the history */ - gtk_widget_hide(history->tree); + gtk_widget_hide(history_tab->tree); /* dont't show the contact list */ - gtk_widget_hide(contacts->tree); + gtk_widget_hide(contacts_tab->tree); /* don't show waiting layer */ gtk_widget_hide(waitingLayer); @@ -350,9 +345,10 @@ statusbar_push_message(const gchar * const left_hand_message, const gchar * cons // Format message according to right hand member gchar *message_to_display; + if (right_hand_message) message_to_display = g_strdup_printf("%s %s", - left_hand_message, right_hand_message); + left_hand_message, right_hand_message); else message_to_display = g_strdup(left_hand_message); @@ -385,17 +381,22 @@ statusbar_update_clock(const gchar * const msg) g_free(message); } + static void -add_error_dialog(GtkWidget *dialog, callable_obj_t * call) +destroy_error_dialog_cb(GtkWidget *dialog UNUSED, GtkWidget *win) { - gtk_container_add(GTK_CONTAINER(embedded_error_notebook), dialog); - call_add_error(call, dialog); + gtk_widget_destroy(win); } static void -destroy_error_dialog_cb(GtkObject *dialog, callable_obj_t * call) +add_error_dialog(GtkWidget *dialog) { - call_remove_error(call, dialog); + GtkWidget *win = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_container_add(GTK_CONTAINER(win), dialog); + + g_signal_connect_after(dialog, "destroy", (GCallback)destroy_error_dialog_cb, win); + + gtk_widget_show(win); } void @@ -413,9 +414,9 @@ main_window_zrtp_not_supported(callable_obj_t * c) DEBUG("Account is null callID %s", c->_callID); GHashTable * properties = sflphone_get_ip2ip_properties(); - if (properties != NULL) - warning_enabled = g_hash_table_lookup(properties, - ACCOUNT_ZRTP_NOT_SUPP_WARNING); + if (properties) + warning_enabled = g_hash_table_lookup (properties, + ACCOUNT_ZRTP_NOT_SUPP_WARNING); } if (g_strcasecmp(warning_enabled, "true") == 0) { @@ -428,21 +429,19 @@ main_window_zrtp_not_supported(callable_obj_t * c) g_free(desc); pidgin_mini_dialog_add_button(mini_dialog, _("Continue"), NULL, NULL); pidgin_mini_dialog_add_button(mini_dialog, _("Stop Call"), - sflphone_hang_up, NULL); - - g_signal_connect_after(mini_dialog, "destroy", (GCallback)destroy_error_dialog_cb, c); + sflphone_hang_up, NULL); - add_error_dialog(GTK_WIDGET(mini_dialog), c); + add_error_dialog(GTK_WIDGET(mini_dialog)); } } void main_window_zrtp_negotiation_failed(const gchar* const callID, const gchar* const reason, - const gchar* const severity) + const gchar* const severity) { gchar* peer_number = "(number unknown)"; callable_obj_t * c = NULL; - c = calllist_get_call(current_calls, callID); + c = calllist_get_call(current_calls_tab, callID); if (c != NULL) peer_number = c->_peer_number; @@ -450,31 +449,30 @@ main_window_zrtp_negotiation_failed(const gchar* const callID, const gchar* cons gchar *desc = g_markup_printf_escaped(_("A %s error forced the call with " "%s to fall under unencrypted " "mode.\nExact reason: %s\n"), - severity, peer_number, reason); + severity, peer_number, reason); PidginMiniDialog *mini_dialog = pidgin_mini_dialog_new(_("ZRTP negotiation failed"), desc, - GTK_STOCK_DIALOG_WARNING); + GTK_STOCK_DIALOG_WARNING); g_free(desc); pidgin_mini_dialog_add_button(mini_dialog, _("Continue"), NULL, NULL); pidgin_mini_dialog_add_button(mini_dialog, _("Stop Call"), sflphone_hang_up, NULL); - g_signal_connect_after(mini_dialog, "destroy",(GCallback) destroy_error_dialog_cb, c); - add_error_dialog(GTK_WIDGET(mini_dialog), c); + add_error_dialog(GTK_WIDGET(mini_dialog)); } void main_window_confirm_go_clear(callable_obj_t * c) { gchar *desc = g_markup_printf_escaped( - _("%s wants to stop using secure communication. Confirm will resume conversation without SRTP.\n"), - c->_peer_number); + _("%s wants to stop using secure communication. Confirm will resume conversation without SRTP.\n"), + c->_peer_number); PidginMiniDialog *mini_dialog = pidgin_mini_dialog_new(_("Confirm Go Clear"), desc, - GTK_STOCK_STOP); + GTK_STOCK_STOP); g_free(desc); pidgin_mini_dialog_add_button(mini_dialog, _("Confirm"), (PidginMiniDialogCallback) dbus_set_confirm_go_clear, NULL); pidgin_mini_dialog_add_button(mini_dialog, _("Stop Call"), sflphone_hang_up, NULL); - add_error_dialog(GTK_WIDGET(mini_dialog), c); + add_error_dialog(GTK_WIDGET(mini_dialog)); } diff --git a/gnome/src/mainwindow.h b/gnome/src/mainwindow.h index 028c16305f0f45ec888bc872959e156dbb17311f..f5605bffa3a2f42af586d62f23196108deda5b76 100644 --- a/gnome/src/mainwindow.h +++ b/gnome/src/mainwindow.h @@ -31,9 +31,9 @@ #ifndef __MAINWINDOW_H__ #define __MAINWINDOW_H__ -#include <calllist.h> -#include <calltree.h> -#include <uimanager.h> +#include "calllist.h" +#include "calltree.h" +#include "uimanager.h" #define MAIN_WINDOW_WIDTH 280 #define MAIN_WINDOW_HEIGHT 320 diff --git a/gnome/src/reqaccount.c b/gnome/src/reqaccount.c index c5b8d3c0da158820b85c71c22a4d7eb6f801af44..e6120302a9e6a91b70196520b4aed2af2c4afe24 100644 --- a/gnome/src/reqaccount.c +++ b/gnome/src/reqaccount.c @@ -46,13 +46,12 @@ #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> -#include <sflphone_const.h> - +#include "sflphone_const.h" +#include "logger.h" #include "reqaccount.h" -int req (char *host, int port, char *req, char *ret) +int req(char *host, int port, char *request, char *ret) { - int s; struct sockaddr_in servSockAddr; struct hostent *servHostEnt; @@ -62,96 +61,96 @@ int req (char *host, int port, char *req, char *ret) FILE *f; char buf[1024]; - bzero (&servSockAddr, sizeof (servSockAddr)); - servHostEnt = gethostbyname (host); + bzero(&servSockAddr, sizeof(servSockAddr)); + servHostEnt = gethostbyname(host); if (servHostEnt == NULL) { - strcpy (ret, "gethostbyname"); + strcpy(ret, "gethostbyname"); return -1; } - bcopy ( (char *) servHostEnt->h_addr, (char *) &servSockAddr.sin_addr, servHostEnt->h_length); - servSockAddr.sin_port = htons (port); + bcopy((char *) servHostEnt->h_addr, (char *) &servSockAddr.sin_addr, servHostEnt->h_length); + servSockAddr.sin_port = htons(port); servSockAddr.sin_family = AF_INET; - if ( (s = socket (AF_INET,SOCK_STREAM,0)) < 0) { - strcpy (ret, "socket"); + if ((s = socket(AF_INET,SOCK_STREAM,0)) < 0) { + strcpy(ret, "socket"); return -1; } - if (connect (s, (const struct sockaddr *) &servSockAddr, (socklen_t) sizeof (servSockAddr)) < 0) { - perror ("foo"); - strcpy (ret, "connect"); + if (connect(s, (const struct sockaddr *) &servSockAddr, (socklen_t) sizeof(servSockAddr)) < 0) { + perror("foo"); + strcpy(ret, "connect"); return -1; } - f = fdopen (s, "r+"); + f = fdopen(s, "r+"); - fprintf (f, "%s HTTP/1.1\r\n", req); - fprintf (f, "Host: %s\r\n", host); - fputs ("User-Agent: SFLphone\r\n", f); - fputs ("\r\n", f); + fprintf(f, "%s HTTP/1.1\r\n", request); + fprintf(f, "Host: %s\r\n", host); + fputs("User-Agent: SFLphone\r\n", f); + fputs("\r\n", f); - while (strncmp (fgets (buf, sizeof (buf), f), "\r\n", 2)) { + while (strncmp(fgets(buf, sizeof(buf), f), "\r\n", 2)) { const char *len_h = "content-length"; const char *status_h = "HTTP/1.1"; - if (strncasecmp (buf, len_h, strlen (len_h)) == 0) - length = atoi (buf + strlen (len_h) + 1); + if (strncasecmp(buf, len_h, strlen(len_h)) == 0) + length = atoi(buf + strlen(len_h) + 1); - if (strncasecmp (buf, status_h, strlen (status_h)) == 0) - status = atoi (buf + strlen (status_h) + 1); + if (strncasecmp(buf, status_h, strlen(status_h)) == 0) + status = atoi(buf + strlen(status_h) + 1); } for (i = 0; i < length; i++) - ret[i] = fgetc (f); + ret[i] = fgetc(f); if (status != 200) { - sprintf (ret, "http error: %ld", status); + sprintf(ret, "http error: %ld", status); return -1; } - fclose (f); - shutdown (s, 2); - close (s); + fclose(f); + shutdown(s, 2); + close(s); return 0; } -rest_account get_rest_account (char *host,char *email) +rest_account get_rest_account(char *host,char *email) { char ret[4096]; rest_account ra; - bzero (ret, sizeof (ret)); - DEBUG ("HOST: %s", host); - strcpy (ret,"GET /rest/accountcreator?email="); - strcat (ret, email); - - if (req (host, 80, ret, ret) != -1) { - strcpy (ra.user, strtok (ret, "\n")); - strcpy (ra.passwd, strtok (NULL, "\n")); + bzero(ret, sizeof(ret)); + DEBUG("HOST: %s", host); + strcpy(ret,"GET /rest/accountcreator?email="); + strcat(ret, email); + + if (req(host, 80, ret, ret) != -1) { + strcpy(ra.user, strtok(ret, "\n")); + strcpy(ra.passwd, strtok(NULL, "\n")); \ ra.success = 1; } else { ra.success = 0; - strcpy (ra.reason, ret); + strcpy(ra.reason, ret); } - puts (ret); + puts(ret); return ra; } #ifdef BUILD_EXAMPLE -int main (void) +int main(void) { - rest_account acc = get_rest_account ("sip.sflphone.org","email@email.com"); + rest_account acc = get_rest_account("sip.sflphone.org","email@email.com"); if (acc.success) { - puts (acc.user); - puts (acc.passwd); + puts(acc.user); + puts(acc.passwd); } else { - ERROR ("FAILED: %s", acc.reason); + ERROR("FAILED: %s", acc.reason); } } #endif diff --git a/gnome/src/sflnotify.c b/gnome/src/sflnotify.c index b3fc8a8611a85a2851cb2397e75bd446d1fa73a2..caf6636e88214da1679cc1aa23d11447be5b3516 100644 --- a/gnome/src/sflnotify.c +++ b/gnome/src/sflnotify.c @@ -27,77 +27,80 @@ * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ -#include <eel-gconf-extensions.h> #include "config.h" +#include "eel-gconf-extensions.h" #include "sflnotify.h" +#include "logger.h" +#define USE_NOTIFY NOTIFY_CHECK_VERSION(0,7,2) + +#if USE_NOTIFY typedef struct { NotifyNotification *notification; gchar *title; gchar *body; GdkPixbuf *icon; } GnomeNotification; +#endif static void -create_new_gnome_notification (gchar *title, gchar *body, NotifyUrgency urgency, gint timeout) +create_new_gnome_notification(gchar *title, gchar *body, NotifyUrgency urgency, gint timeout) { +#if USE_NOTIFY GnomeNotification notif; - if (eel_gconf_get_integer (NOTIFY_ALL)) { - notify_init ("SFLphone"); + if (eel_gconf_get_integer(NOTIFY_ALL)) { + notify_init("SFLphone"); // Set struct fields -#ifdef LIBNOTIFY_VERSION_0_7_2 - notif.notification = notify_notification_new (title, body, NULL); -#else - notif.notification = notify_notification_new (title, body, NULL, NULL); -#endif - notif.icon = gdk_pixbuf_new_from_file (LOGO_SMALL, NULL); -#ifdef LIBNOTIFY_VERSION_0_7_2 -#else - notify_notification_attach_to_status_icon (notif.notification , get_status_icon()); -#endif + notif.notification = notify_notification_new(title, body, NULL); + notif.icon = gdk_pixbuf_new_from_file(LOGO_SMALL, NULL); - notify_notification_set_urgency (notif.notification, urgency); + notify_notification_set_urgency(notif.notification, urgency); if (notif.icon != NULL) - notify_notification_set_icon_from_pixbuf (notif.notification, notif.icon); + notify_notification_set_icon_from_pixbuf(notif.notification, notif.icon); else - ERROR ("notify(), cannot load notification icon"); + ERROR("notify(), cannot load notification icon"); - notify_notification_set_timeout (notif.notification, timeout); + notify_notification_set_timeout(notif.notification, timeout); - if (!notify_notification_show (notif.notification, NULL)) { - ERROR ("notify(), failed to send notification"); + if (!notify_notification_show(notif.notification, NULL)) { + ERROR("notify(), failed to send notification"); } } + g_free(title); g_free(body); +#endif } void -notify_incoming_message (const gchar *callID, const gchar *msg) +notify_incoming_message(const gchar *callID, const gchar *msg) { +#if USE_NOTIFY gchar* title = g_markup_printf_escaped(_("%s says:"), callID); create_new_gnome_notification(title, (gchar *)msg, NOTIFY_URGENCY_CRITICAL, - (g_strcasecmp (__TIMEOUT_MODE, "default") == 0) ? __TIMEOUT_TIME : NOTIFY_EXPIRES_NEVER); + (g_strcasecmp(__TIMEOUT_MODE, "default") == 0) ? __TIMEOUT_TIME : NOTIFY_EXPIRES_NEVER); +#endif } void -notify_incoming_call (callable_obj_t* c) +notify_incoming_call(callable_obj_t* c) { +#if USE_NOTIFY gchar* title; if (strlen(c->_accountID) == 0) title = g_markup_printf_escaped("IP-to-IP call"); else { - title = g_markup_printf_escaped(_ ("%s account : %s") , - (gchar*) g_hash_table_lookup (account_list_get_by_id (c->_accountID)->properties , ACCOUNT_TYPE) , - (gchar*) g_hash_table_lookup (account_list_get_by_id (c->_accountID)->properties , ACCOUNT_ALIAS)) ; + title = g_markup_printf_escaped(_("%s account : %s") , + (gchar*) g_hash_table_lookup(account_list_get_by_id(c->_accountID)->properties , ACCOUNT_TYPE) , + (gchar*) g_hash_table_lookup(account_list_get_by_id(c->_accountID)->properties , ACCOUNT_ALIAS)) ; } gchar *callerid = g_markup_printf_escaped(_("<i>From</i> %s"), c->_peer_number); @@ -105,100 +108,117 @@ notify_incoming_call (callable_obj_t* c) create_new_gnome_notification(title, callerid, NOTIFY_URGENCY_CRITICAL, - (g_strcasecmp (__TIMEOUT_MODE, "default") == 0) ? __TIMEOUT_TIME : NOTIFY_EXPIRES_NEVER); + (g_strcasecmp(__TIMEOUT_MODE, "default") == 0) ? __TIMEOUT_TIME : NOTIFY_EXPIRES_NEVER); +#endif } void notify_voice_mails(guint count, account_t* acc) { +#if USE_NOTIFY // the account is different from NULL gchar *title = g_markup_printf_escaped(_("%s account : %s") , - (gchar*) g_hash_table_lookup (acc->properties , ACCOUNT_TYPE) , - (gchar*) g_hash_table_lookup (acc->properties , ACCOUNT_ALIAS)) ; + (gchar*) g_hash_table_lookup(acc->properties , ACCOUNT_TYPE) , + (gchar*) g_hash_table_lookup(acc->properties , ACCOUNT_ALIAS)) ; gchar *body = g_markup_printf_escaped(n_("%d voice mail", "%d voice mails", count), count); create_new_gnome_notification(title, body, NOTIFY_URGENCY_LOW, NOTIFY_EXPIRES_DEFAULT); +#endif } void -notify_current_account (account_t* acc) +notify_current_account(account_t* acc) { +#if USE_NOTIFY // the account is different from NULL - gchar *body = g_markup_printf_escaped (_("Calling with %s account <i>%s</i>"), - (gchar*) g_hash_table_lookup(acc->properties, ACCOUNT_TYPE) , - (gchar*) g_hash_table_lookup(acc->properties, ACCOUNT_ALIAS)); + gchar *body = g_markup_printf_escaped(_("Calling with %s account <i>%s</i>"), + (gchar*) g_hash_table_lookup(acc->properties, ACCOUNT_TYPE) , + (gchar*) g_hash_table_lookup(acc->properties, ACCOUNT_ALIAS)); gchar *title = g_markup_printf_escaped(_("Current account")); create_new_gnome_notification(title, body, NOTIFY_URGENCY_NORMAL, NOTIFY_EXPIRES_DEFAULT); +#endif } void notify_no_accounts() { +#if USE_NOTIFY gchar *body = g_markup_printf_escaped(_("You have no accounts set up")); gchar *title = g_markup_printf_escaped(_("Error")); create_new_gnome_notification(title, body, NOTIFY_URGENCY_CRITICAL, NOTIFY_EXPIRES_DEFAULT); +#endif } void -notify_no_registered_accounts () +notify_no_registered_accounts() { +#if USE_NOTIFY gchar *body = g_markup_printf_escaped(_("You have no registered accounts")); gchar *title = g_markup_printf_escaped(_("Error")); create_new_gnome_notification(title, body, NOTIFY_URGENCY_CRITICAL, NOTIFY_EXPIRES_DEFAULT); +#endif } void -notify_secure_on (callable_obj_t* c) +notify_secure_on(callable_obj_t* c) { +#if USE_NOTIFY gchar *title = g_markup_printf_escaped("Secure mode on."); gchar *callerid = g_markup_printf_escaped(_("<i>With:</i> %s \nusing %s") , c->_peer_number, c->_srtp_cipher); create_new_gnome_notification(title, callerid, NOTIFY_URGENCY_CRITICAL, (g_strcasecmp(__TIMEOUT_MODE, "default") == 0) ? __TIMEOUT_TIME : NOTIFY_EXPIRES_NEVER); +#endif } void -notify_zrtp_not_supported (callable_obj_t* c) +notify_zrtp_not_supported(callable_obj_t* c) { - gchar *title = g_markup_printf_escaped ("ZRTP Error."); - gchar *callerid = g_markup_printf_escaped (_("%s does not support ZRTP.") , c->_peer_number); - create_new_gnome_notification (title, - callerid, - NOTIFY_URGENCY_CRITICAL, - (g_strcasecmp(__TIMEOUT_MODE, "default") == 0) ? __TIMEOUT_TIME : NOTIFY_EXPIRES_NEVER); +#if USE_NOTIFY + gchar *title = g_markup_printf_escaped("ZRTP Error."); + gchar *callerid = g_markup_printf_escaped(_("%s does not support ZRTP.") , c->_peer_number); + create_new_gnome_notification(title, + callerid, + NOTIFY_URGENCY_CRITICAL, + (g_strcasecmp(__TIMEOUT_MODE, "default") == 0) ? __TIMEOUT_TIME : NOTIFY_EXPIRES_NEVER); +#endif } void -notify_zrtp_negotiation_failed (callable_obj_t* c) +notify_zrtp_negotiation_failed(callable_obj_t* c) { +#if USE_NOTIFY gchar *title = g_markup_printf_escaped("ZRTP Error."); gchar *callerid = g_markup_printf_escaped(_("ZRTP negotiation failed with %s"), c->_peer_number); create_new_gnome_notification(title, callerid, NOTIFY_URGENCY_CRITICAL, (g_strcasecmp(__TIMEOUT_MODE, "default") == 0) ? __TIMEOUT_TIME : NOTIFY_EXPIRES_NEVER); +#endif } void -notify_secure_off (callable_obj_t* c) +notify_secure_off(callable_obj_t* c) { - gchar *title = g_markup_printf_escaped ("Secure mode is off."); +#if USE_NOTIFY + gchar *title = g_markup_printf_escaped("Secure mode is off."); gchar *callerid = g_markup_printf_escaped(_("<i>With:</i> %s"), c->_peer_number); create_new_gnome_notification(title, callerid, NOTIFY_URGENCY_CRITICAL, - (g_strcasecmp (__TIMEOUT_MODE, "default") == 0) ? __TIMEOUT_TIME : NOTIFY_EXPIRES_NEVER); + (g_strcasecmp(__TIMEOUT_MODE, "default") == 0) ? __TIMEOUT_TIME : NOTIFY_EXPIRES_NEVER); +#endif } diff --git a/gnome/src/sflphone_const.h b/gnome/src/sflphone_const.h index c7d27a8cbfffa69bf82d1c8e44399a2537f5ff6a..fd7cec91d20a169620047955d07a11c3451d739d 100644 --- a/gnome/src/sflphone_const.h +++ b/gnome/src/sflphone_const.h @@ -32,8 +32,6 @@ #define __SFLPHONE_CONST_H #include <libintl.h> -#include "logger.h" -#include "dbus.h" #include <glib/gi18n.h> /* @file sflphone_const.h @@ -57,11 +55,6 @@ #define IP2IP "IP2IP" -/** Warnings unused variables **/ -#define UNUSED_VAR(var) (void*)var - -#define UNUSED __attribute__((__unused__)) - #define IP2IP_PROFILE "IP2IP" #define ACCOUNT_ID "Account.id" @@ -172,26 +165,4 @@ /** Desktop notifications - Time before to close the notification*/ #define __TIMEOUT_TIME 18000 // 30 secondes -/** - * Gconf - */ -#define CONF_PREFIX "/apps/sflphone-client-gnome" -#define CONF_MAIN_WINDOW_WIDTH CONF_PREFIX "/state/window_width" -#define CONF_MAIN_WINDOW_HEIGHT CONF_PREFIX "/state/window_height" -#define CONF_MAIN_WINDOW_POSITION_X CONF_PREFIX "/state/window_position_x" -#define CONF_MAIN_WINDOW_POSITION_Y CONF_PREFIX "/state/window_position_y" -#define CONF_IM_WINDOW_WIDTH CONF_PREFIX "/state/im_width" -#define CONF_IM_WINDOW_HEIGHT CONF_PREFIX "/state/im_height" -#define CONF_IM_WINDOW_POSITION_X CONF_PREFIX "/state/im_position_x" -#define CONF_IM_WINDOW_POSITION_Y CONF_PREFIX "/state/im_position_y" -/** Show/Hide the dialpad */ -#define CONF_SHOW_DIALPAD CONF_PREFIX "/state/dialpad" -#define SHOW_VOLUME_CONTROLS CONF_PREFIX "/state/volume_controls" -#define SHOW_STATUSICON CONF_PREFIX "/state/statusicon" -#define NOTIFY_ALL CONF_PREFIX "/state/notify_all" -#define START_HIDDEN CONF_PREFIX "/state/start_hidden" -#define POPUP_ON_CALL CONF_PREFIX "/state/popup" -#define HISTORY_ENABLED CONF_PREFIX "/state/history" -#define INSTANT_MESSAGING_ENABLED CONF_PREFIX "/state/instant_messaging" - #endif diff --git a/gnome/src/shortcuts.c b/gnome/src/shortcuts.c index dc56c3cd3e78aee1066e5e0d9982f10ea94ac489..b35333bcec4d894f8b244c17cffe9727a632122c 100644 --- a/gnome/src/shortcuts.c +++ b/gnome/src/shortcuts.c @@ -40,17 +40,19 @@ #include "shortcuts.h" #include "mainwindow.h" +#include "logger.h" #include "callable_obj.h" +#include "contacts/calltab.h" #include "sflphone_const.h" #include "dbus.h" #include "actions.h" +#include "unused.h" static void -ungrab_key (guint key, GdkModifierType mask, const GdkWindow *root); +ungrab_key(guint key, GdkModifierType mask, GdkWindow *root); static void -grab_key (guint key, GdkModifierType mask, const GdkWindow *root); - +grab_key(guint key, GdkModifierType mask, GdkWindow *root); // used to store accelerator config static Accelerator* accelerators_list; @@ -67,38 +69,20 @@ static GHashTable* shortcutsMap; * filter used when an event is catched */ static GdkFilterReturn -filter_keys (const GdkXEvent *xevent, const GdkEvent *event UNUSED, gpointer data UNUSED) +filter_keys(const GdkXEvent *xevent, const GdkEvent *event UNUSED, gpointer data UNUSED) { - XEvent *xev = NULL; - XKeyEvent *key = NULL; - GdkModifierType keystate = 0; - int i = 0; - - xev = (XEvent *) xevent; - - if (xev->type != KeyPress) { + if (((XEvent *) xevent)->type != KeyPress) return GDK_FILTER_CONTINUE; - } - key = (XKeyEvent *) xevent; - keystate = key->state & ~ (Mod2Mask | Mod5Mask | LockMask); - - // try to find corresponding action - while (accelerators_list[i].action != NULL) { - if (accelerators_list[i].key == key->keycode && accelerators_list[i].mask - == keystate) { - DEBUG ("Shortcuts: Catched key for action: %s", accelerators_list[i].action, - accelerators_list[i].key); - - // call associated callback function - accelerators_list[i].callback (); + XKeyEvent *key = (XKeyEvent *) xevent; + GdkModifierType keystate = key->state & ~(Mod2Mask | Mod5Mask | LockMask); + for (int i = 0; accelerators_list[i].action; ++i) + if (accelerators_list[i].key == key->keycode && accelerators_list[i].mask == keystate) { + accelerators_list[i].callback(); return GDK_FILTER_REMOVE; } - i++; - } - return GDK_FILTER_CONTINUE; } @@ -106,105 +90,104 @@ filter_keys (const GdkXEvent *xevent, const GdkEvent *event UNUSED, gpointer dat * Callbacks */ static void -toggle_pick_up_hang_up_callback () +toggle_pick_up_hang_up_callback() { - callable_obj_t * selectedCall = calltab_get_selected_call (active_calltree); - conference_obj_t * selectedConf = calltab_get_selected_conf (active_calltree); + callable_obj_t * selectedCall = calltab_get_selected_call(active_calltree_tab); + conference_obj_t * selectedConf = calltab_get_selected_conf(active_calltree_tab); - DEBUG ("Shortcuts: Toggle pickup/hangup callback"); + DEBUG("Shortcuts: Toggle pickup/hangup callback"); if (selectedCall) { switch (selectedCall->_state) { case CALL_STATE_INCOMING: case CALL_STATE_TRANSFER: - sflphone_pick_up (); + sflphone_pick_up(); break; case CALL_STATE_DIALING: case CALL_STATE_HOLD: case CALL_STATE_CURRENT: case CALL_STATE_RECORD: case CALL_STATE_RINGING: - sflphone_hang_up (); + sflphone_hang_up(); break; default: break; } } else if (selectedConf) { - dbus_hang_up_conference (selectedConf); + dbus_hang_up_conference(selectedConf); } else - sflphone_pick_up (); + sflphone_pick_up(); } static void -pick_up_callback () +pick_up_callback() { - sflphone_pick_up (); + sflphone_pick_up(); } static void -hang_up_callback () +hang_up_callback() { - sflphone_hang_up (); + sflphone_hang_up(); } static void -toggle_hold_callback () +toggle_hold_callback() { - callable_obj_t * selectedCall = calltab_get_selected_call (current_calls); - conference_obj_t * selectedConf = calltab_get_selected_conf (active_calltree); + callable_obj_t * selectedCall = calltab_get_selected_call(current_calls_tab); + conference_obj_t * selectedConf = calltab_get_selected_conf(active_calltree_tab); if (selectedCall) { switch (selectedCall->_state) { case CALL_STATE_CURRENT: case CALL_STATE_RECORD: - sflphone_on_hold (); + sflphone_on_hold(); break; case CALL_STATE_HOLD: - sflphone_off_hold (); + sflphone_off_hold(); break; default: break; } - } - else if (selectedConf) - dbus_hold_conference (selectedConf); + } else if (selectedConf) + dbus_hold_conference(selectedConf); else { - ERROR ("Shortcuts: Error: No callable object selected"); + ERROR("Shortcuts: Error: No callable object selected"); } } static void -popup_window_callback () +popup_window_callback() { - gtk_widget_hide (GTK_WIDGET (get_main_window())); - gtk_widget_show (GTK_WIDGET (get_main_window())); + gtk_widget_hide(GTK_WIDGET(get_main_window())); + gtk_widget_show(GTK_WIDGET(get_main_window())); } static void -default_callback () +default_callback() { - ERROR ("Shortcuts: Error: Missing shortcut callback"); + ERROR("Shortcuts: Error: Missing shortcut callback"); } /* * return callback corresponding to a specific action */ static void* -get_action_callback (const gchar* action) +get_action_callback(const gchar* action) { - if (g_strcmp0 (action, SHORTCUT_PICKUP) == 0) + if (g_strcmp0(action, SHORTCUT_PICKUP) == 0) return pick_up_callback; - if (g_strcmp0 (action, SHORTCUT_HANGUP) == 0) + if (g_strcmp0(action, SHORTCUT_HANGUP) == 0) return hang_up_callback; - if (g_strcmp0 (action, SHORTCUT_POPUP) == 0) + if (g_strcmp0(action, SHORTCUT_POPUP) == 0) return popup_window_callback; - if (g_strcmp0 (action, SHORTCUT_TOGGLEPICKUPHANGUP) == 0) + if (g_strcmp0(action, SHORTCUT_TOGGLEPICKUPHANGUP) == 0) return toggle_pick_up_hang_up_callback; - if (g_strcmp0 (action, SHORTCUT_TOGGLEHOLD) == 0) + if (g_strcmp0(action, SHORTCUT_TOGGLEHOLD) == 0) return toggle_hold_callback; return default_callback; @@ -218,30 +201,30 @@ get_action_callback (const gchar* action) * Remove all existing bindings */ static void -remove_bindings () +remove_bindings() { GdkDisplay *display = NULL; GdkScreen *screen = NULL; GdkWindow *root = NULL; int i, j = 0; - display = gdk_display_get_default (); + display = gdk_display_get_default(); - for (i = 0; i < gdk_display_get_n_screens (display); i++) { - screen = gdk_display_get_screen (display, i); + for (i = 0; i < gdk_display_get_n_screens(display); i++) { + screen = gdk_display_get_screen(display, i); if (screen != NULL) { j = 0; - root = gdk_screen_get_root_window (screen); + root = gdk_screen_get_root_window(screen); // remove filter - gdk_window_remove_filter (root, (GdkFilterFunc) filter_keys, NULL); + gdk_window_remove_filter(root, (GdkFilterFunc) filter_keys, NULL); // unbind shortcuts while (accelerators_list[j].action != NULL) { if (accelerators_list[j].key != 0) { - ungrab_key (accelerators_list[j].key, - accelerators_list[j].mask, root); + ungrab_key(accelerators_list[j].key, + accelerators_list[j].mask, root); } j++; @@ -254,30 +237,30 @@ remove_bindings () * Create all bindings, using stored configuration */ static void -create_bindings () +create_bindings() { GdkDisplay *display; GdkScreen *screen; GdkWindow *root; int i, j = 0; - display = gdk_display_get_default (); + display = gdk_display_get_default(); - for (i = 0; i < gdk_display_get_n_screens (display); i++) { - screen = gdk_display_get_screen (display, i); + for (i = 0; i < gdk_display_get_n_screens(display); i++) { + screen = gdk_display_get_screen(display, i); if (screen != NULL) { j = 0; - root = gdk_screen_get_root_window (screen); + root = gdk_screen_get_root_window(screen); // add filter - gdk_window_add_filter (root, (GdkFilterFunc) filter_keys, NULL); + gdk_window_add_filter(root, (GdkFilterFunc) filter_keys, NULL); // bind shortcuts while (accelerators_list[j].action != NULL) { if (accelerators_list[j].key != 0) { - grab_key (accelerators_list[j].key, - accelerators_list[j].mask, root); + grab_key(accelerators_list[j].key, + accelerators_list[j].mask, root); } j++; @@ -290,12 +273,12 @@ create_bindings () * Initialize a specific binding */ static void -initialize_binding (const gchar* action, guint key, GdkModifierType mask) +initialize_binding(const gchar* action, guint key, GdkModifierType mask) { int i = 0; while (accelerators_list[i].action != NULL) { - if (g_strcmp0 (action, accelerators_list[i].action) == 0) { + if (g_strcmp0(action, accelerators_list[i].action) == 0) { break; } @@ -303,7 +286,7 @@ initialize_binding (const gchar* action, guint key, GdkModifierType mask) } if (accelerators_list[i].action == NULL) { - ERROR ("Shortcut: Error: Cannot find corresponding action"); + ERROR("Shortcut: Error: Cannot find corresponding action"); return; } @@ -312,34 +295,35 @@ initialize_binding (const gchar* action, guint key, GdkModifierType mask) accelerators_list[i].mask = mask; // update bindings - create_bindings (); + create_bindings(); } /* * Prepare accelerators list */ static void -initialize_accelerators_list () +initialize_accelerators_list() { GList* shortcutsKeysElement, *shortcutsKeys; int i = 0; - shortcutsKeys = g_hash_table_get_keys (shortcutsMap); + shortcutsKeys = g_hash_table_get_keys(shortcutsMap); - accelerators_list = (Accelerator*) malloc ( - (g_list_length (shortcutsKeys) + 1) * sizeof (Accelerator)); + accelerators_list = (Accelerator*) malloc( + (g_list_length(shortcutsKeys) + 1) * sizeof(Accelerator)); for (shortcutsKeysElement = shortcutsKeys; shortcutsKeysElement; shortcutsKeysElement = shortcutsKeysElement->next) { gchar* action = shortcutsKeysElement->data; - accelerators_list[i].action = g_strdup (action); - accelerators_list[i].callback = get_action_callback (action); + accelerators_list[i].action = g_strdup(action); + accelerators_list[i].callback = get_action_callback(action); accelerators_list[i].mask = 0; accelerators_list[i].key = 0; i++; } + g_list_free(shortcutsKeys); // last element must be null @@ -350,15 +334,15 @@ initialize_accelerators_list () } static void -update_shortcuts_map (const gchar* action, guint key, GdkModifierType mask) +update_shortcuts_map(const gchar* action, guint key, GdkModifierType mask) { // Bindings: MASKxCODE gchar *buffer = g_strdup_printf("%dx%d", mask, key); - g_hash_table_replace (shortcutsMap, g_strdup (action), buffer); + g_hash_table_replace(shortcutsMap, g_strdup(action), buffer); } static void -update_bindings_data (guint index, guint key, GdkModifierType mask) +update_bindings_data(guint accel_index, guint key, GdkModifierType mask) { int i = 0; @@ -367,26 +351,27 @@ update_bindings_data (guint index, guint key, GdkModifierType mask) while (accelerators_list[i].action != NULL) { if (accelerators_list[i].key == key && accelerators_list[i].mask == mask && accelerators_list[i].key != 0) { - DEBUG ("Shortcuts: Existing mapping found %d+%d", mask, key); + DEBUG("Shortcuts: Existing mapping found %d+%d", mask, key); // disable old binding accelerators_list[i].key = 0; accelerators_list[i].mask = 0; // update config table - update_shortcuts_map (accelerators_list[i].action, 0, 0); + update_shortcuts_map(accelerators_list[i].action, 0, 0); } i++; } // store new key - accelerators_list[index].key = key; - accelerators_list[index].mask = mask; + accelerators_list[accel_index].key = key; + accelerators_list[accel_index].mask = mask; // update value in hashtable (used for dbus calls) - update_shortcuts_map (accelerators_list[index].action, - accelerators_list[index].key, accelerators_list[index].mask); + update_shortcuts_map(accelerators_list[accel_index].action, + accelerators_list[accel_index].key, + accelerators_list[accel_index].mask); } /* @@ -397,63 +382,63 @@ update_bindings_data (guint index, guint key, GdkModifierType mask) * Update current bindings with a new value */ void -shortcuts_update_bindings (guint index, guint key, GdkModifierType mask) +shortcuts_update_bindings(guint shortcut_index, guint key, GdkModifierType mask) { // first remove all existing bindings - remove_bindings (); + remove_bindings(); // update data - update_bindings_data (index, key, mask); + update_bindings_data(shortcut_index, key, mask); // recreate all bindings - create_bindings (); + create_bindings(); // update configuration - dbus_set_shortcuts (shortcutsMap); + dbus_set_shortcuts(shortcutsMap); } /* * Initialize bindings with configuration retrieved from dbus */ void -shortcuts_initialize_bindings () +shortcuts_initialize_bindings() { GList* shortcutsKeys, *shortcutsKeysElement = NULL; gchar* action, *maskAndKey, *token1, *token2 = NULL; guint mask, key = 0; - DEBUG ("Shortcuts: Initialize bindings"); + DEBUG("Shortcuts: Initialize bindings"); // get shortcuts stored in config through dbus - shortcutsMap = dbus_get_shortcuts (); + shortcutsMap = dbus_get_shortcuts(); // initialize list of keys - initialize_accelerators_list (); + initialize_accelerators_list(); // iterate through keys to initialize bindings - shortcutsKeys = g_hash_table_get_keys (shortcutsMap); + shortcutsKeys = g_hash_table_get_keys(shortcutsMap); for (shortcutsKeysElement = shortcutsKeys; shortcutsKeysElement; shortcutsKeysElement = shortcutsKeysElement->next) { action = shortcutsKeysElement->data; - maskAndKey = g_hash_table_lookup (shortcutsMap, action); + maskAndKey = g_hash_table_lookup(shortcutsMap, action); - token1 = strtok (maskAndKey, "x"); - token2 = strtok (NULL, "x"); + token1 = strtok(maskAndKey, "x"); + token2 = strtok(NULL, "x"); mask = 0; key = 0; // Value not setted if (token1 && token2) { - DEBUG ("Shortcuts: token1 %s, token2 %s", token1, token2); + DEBUG("Shortcuts: token1 %s, token2 %s", token1, token2); - mask = atoi (token1); - key = atoi (token2); + mask = atoi(token1); + key = atoi(token2); } if (key != 0) - initialize_binding (action, key, mask); + initialize_binding(action, key, mask); } } @@ -461,24 +446,24 @@ shortcuts_initialize_bindings () * Initialize bindings with configuration retrieved from dbus */ void -shortcuts_destroy_bindings () +shortcuts_destroy_bindings() { int i = 0; // remove bindings - remove_bindings (); + remove_bindings(); // free pointers while (accelerators_list[i].action != NULL) { - g_free (accelerators_list[i].action); + g_free(accelerators_list[i].action); i++; } - free (accelerators_list); + free(accelerators_list); } Accelerator* -shortcuts_get_list () +shortcuts_get_list() { return accelerators_list; } @@ -487,62 +472,54 @@ shortcuts_get_list () * Remove key "catcher" from GDK layer */ static void -ungrab_key (guint key, GdkModifierType mask, const GdkWindow *root) +ungrab_key(guint key, GdkModifierType mask, GdkWindow *root) { - DEBUG ("Shortcuts: Ungrabbing key %d+%d", mask, key); - - gdk_error_trap_push (); - - XUngrabKey (GDK_DISPLAY (), key, mask, GDK_WINDOW_XID ( (GdkDrawable*) root)); - XUngrabKey (GDK_DISPLAY (), key, Mod2Mask | mask, GDK_WINDOW_XID ( (GdkDrawable*) root)); - XUngrabKey (GDK_DISPLAY (), key, Mod5Mask | mask, GDK_WINDOW_XID ( (GdkDrawable*) root)); - XUngrabKey (GDK_DISPLAY (), key, LockMask | mask, GDK_WINDOW_XID ( (GdkDrawable*) root)); - XUngrabKey (GDK_DISPLAY (), key, Mod2Mask | Mod5Mask | mask, - GDK_WINDOW_XID ( (GdkDrawable*) root)); - XUngrabKey (GDK_DISPLAY (), key, Mod2Mask | LockMask | mask, - GDK_WINDOW_XID ( (GdkDrawable*) root)); - XUngrabKey (GDK_DISPLAY (), key, Mod5Mask | LockMask | mask, - GDK_WINDOW_XID ( (GdkDrawable*) root)); - XUngrabKey (GDK_DISPLAY (), key, Mod2Mask | Mod5Mask | LockMask | mask, - GDK_WINDOW_XID ( (GdkDrawable*) root)); - - gdk_flush (); - - if (gdk_error_trap_pop ()) { - ERROR ("Shortcuts: Error: Ungrabbing key %d+%d", mask, key); - } + DEBUG("Shortcuts: Ungrabbing key %d+%d", mask, key); + + gdk_error_trap_push(); + Display *d = GDK_DISPLAY_XDISPLAY(gdk_display_get_default()); + XID x = GDK_WINDOW_XID(root); + + XUngrabKey(d, key, mask | 0, x); + XUngrabKey(d, key, mask | Mod2Mask, x); + XUngrabKey(d, key, mask | Mod5Mask, x); + XUngrabKey(d, key, mask | LockMask, x); + XUngrabKey(d, key, mask | Mod2Mask | LockMask, x); + XUngrabKey(d, key, mask | Mod2Mask | Mod5Mask, x); + XUngrabKey(d, key, mask | Mod2Mask | LockMask, x); + XUngrabKey(d, key, mask | Mod5Mask | LockMask, x); + XUngrabKey(d, key, mask | Mod2Mask | Mod5Mask | LockMask, x); + + gdk_flush(); + + if (gdk_error_trap_pop()) + ERROR("Shortcuts: Error: Ungrabbing key %d+%d", mask, key); } /* * Add key "catcher" to GDK layer */ static void -grab_key (guint key, GdkModifierType mask, const GdkWindow *root) +grab_key(guint key, GdkModifierType mask, GdkWindow *root) { - gdk_error_trap_push (); - - DEBUG ("Shortcuts: Grabbing key %d+%d", mask, key); - - XGrabKey (GDK_DISPLAY(), key, mask, GDK_WINDOW_XID ( (GdkDrawable*) root), True, - GrabModeAsync, GrabModeAsync); - XGrabKey (GDK_DISPLAY (), key, Mod2Mask | mask, GDK_WINDOW_XID ( (GdkDrawable*) root), True, - GrabModeAsync, GrabModeAsync); - XGrabKey (GDK_DISPLAY (), key, Mod5Mask | mask, GDK_WINDOW_XID ( (GdkDrawable*) root), True, - GrabModeAsync, GrabModeAsync); - XGrabKey (GDK_DISPLAY (), key, LockMask | mask, GDK_WINDOW_XID ( (GdkDrawable*) root), True, - GrabModeAsync, GrabModeAsync); - XGrabKey (GDK_DISPLAY (), key, Mod2Mask | Mod5Mask | mask, - GDK_WINDOW_XID ( (GdkDrawable*) root), True, GrabModeAsync, GrabModeAsync); - XGrabKey (GDK_DISPLAY (), key, Mod2Mask | LockMask | mask, - GDK_WINDOW_XID ( (GdkDrawable*) root), True, GrabModeAsync, GrabModeAsync); - XGrabKey (GDK_DISPLAY (), key, Mod5Mask | LockMask | mask, - GDK_WINDOW_XID ( (GdkDrawable*) root), True, GrabModeAsync, GrabModeAsync); - XGrabKey (GDK_DISPLAY (), key, Mod2Mask | Mod5Mask | LockMask | mask, - GDK_WINDOW_XID ( (GdkDrawable*) root), True, GrabModeAsync, GrabModeAsync); - - gdk_flush (); - - if (gdk_error_trap_pop ()) { - ERROR ("Shortcuts: Error: Grabbing key %d+%d", mask, key); - } + gdk_error_trap_push(); + + DEBUG("Shortcuts: Grabbing key %d+%d", mask, key); + + Display *d = GDK_DISPLAY_XDISPLAY(gdk_display_get_default()); + XID x = GDK_WINDOW_XID(root); + + XGrabKey(d, key, mask | 0, x, True, GrabModeAsync, GrabModeAsync); + XGrabKey(d, key, mask | Mod2Mask, x, True, GrabModeAsync, GrabModeAsync); + XGrabKey(d, key, mask | Mod5Mask, x, True, GrabModeAsync, GrabModeAsync); + XGrabKey(d, key, mask | LockMask, x, True, GrabModeAsync, GrabModeAsync); + XGrabKey(d, key, mask | Mod2Mask | Mod5Mask, x, True, GrabModeAsync, GrabModeAsync); + XGrabKey(d, key, mask | Mod2Mask | LockMask, x, True, GrabModeAsync, GrabModeAsync); + XGrabKey(d, key, mask | Mod5Mask | LockMask, x, True, GrabModeAsync, GrabModeAsync); + XGrabKey(d, key, mask | Mod2Mask | Mod5Mask | LockMask, x, True, GrabModeAsync, GrabModeAsync); + + gdk_flush(); + + if (gdk_error_trap_pop()) + ERROR("Shortcuts: Error: Grabbing key %d+%d", mask, key); } diff --git a/gnome/src/sliders.c b/gnome/src/sliders.c index e01fb7f1ebd401da8df5146cc80e19c6cfc60216..34064901e33143d16aa50653ae7d29e91fdeb3fc 100644 --- a/gnome/src/sliders.c +++ b/gnome/src/sliders.c @@ -28,9 +28,10 @@ * as that of the covered work. */ -#include <sliders.h> -#include <dbus/dbus.h> -#include <actions.h> +#include "sliders.h" +#include "dbus/dbus.h" +#include "actions.h" +#include "logger.h" #include <string.h> static gdouble value[2]; @@ -56,9 +57,9 @@ static guint toggledConnId[2]; // The button toggled signal connection ID static guint movedConnId[2]; // The slider_moved signal connection ID void -update_icons (int dev) +update_icons(int dev) { - float val = gtk_range_get_value (GTK_RANGE (slider[dev])); + float val = gtk_range_get_value(GTK_RANGE(slider[dev])); if (button[dev]) { int icon = MUTED; @@ -72,69 +73,69 @@ update_icons (int dev) else if (val <= 1) icon = VOL75; - gtk_button_set_image (GTK_BUTTON (button[dev]), GTK_WIDGET (images[dev][icon])); + gtk_button_set_image(GTK_BUTTON(button[dev]), GTK_WIDGET(images[dev][icon])); } } void -slider_moved (GtkRange* range, gchar* device) +slider_moved(GtkRange* range, gchar* device) { - gdouble value = gtk_range_get_value (range); - DEBUG ("Volume changed for %s: %f ", device, value); - dbus_set_volume (device, value); + gdouble slider_value = gtk_range_get_value(range); + DEBUG("Volume changed for %s: %f ", device, slider_value); + dbus_set_volume(device, slider_value); - if (g_strcmp0 (device, "speaker") == 0) - update_icons (SPEAKER); + if (g_strcmp0(device, "speaker") == 0) + update_icons(SPEAKER); else - update_icons (MIKE); + update_icons(MIKE); } static void -mute_cb (GtkWidget *widget, gchar* device) +mute_cb(GtkWidget *widget, gchar* device) { int dev; - if (g_strcmp0 (device, "speaker") == 0) + if (g_strcmp0(device, "speaker") == 0) dev = SPEAKER; else dev = MIKE; - if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget))) { // Save value - DEBUG ("Save"); - value[dev] = gtk_range_get_value (GTK_RANGE (slider[dev])); - dbus_set_volume (device, 0); + if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget))) { // Save value + DEBUG("Save"); + value[dev] = gtk_range_get_value(GTK_RANGE(slider[dev])); + dbus_set_volume(device, 0); } else { //Restore value - DEBUG ("Restore"); - dbus_set_volume (device, value[dev]); + DEBUG("Restore"); + dbus_set_volume(device, value[dev]); } - update_icons (dev); + update_icons(dev); } void -set_slider (const gchar * device, gdouble newval) +set_slider(const gchar * device, gdouble newval) { int dev; - if (g_strcmp0 (device, "speaker") == 0) + if (g_strcmp0(device, "speaker") == 0) dev = SPEAKER; else dev = MIKE; - gtk_signal_handler_block (GTK_OBJECT (slider[dev]), movedConnId[dev]); - gtk_range_set_value (GTK_RANGE (slider[dev]), newval); - gtk_signal_handler_unblock (slider[dev], movedConnId[dev]); + g_signal_handler_block(G_OBJECT(slider[dev]), movedConnId[dev]); + gtk_range_set_value(GTK_RANGE(slider[dev]), newval); + g_signal_handler_unblock(slider[dev], movedConnId[dev]); - gtk_signal_handler_block (GTK_OBJECT (button[dev]),toggledConnId[dev]); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button[dev]), (newval == 0 ? TRUE: FALSE)); - gtk_signal_handler_unblock (button[dev], toggledConnId[dev]); + g_signal_handler_block(G_OBJECT(button[dev]),toggledConnId[dev]); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(button[dev]), (newval == 0 ? TRUE: FALSE)); + g_signal_handler_unblock(button[dev], toggledConnId[dev]); - update_icons (dev); + update_icons(dev); } /** Generates the speaker slider and mute button */ GtkWidget * -create_slider (const gchar * device) +create_slider(const gchar * device) { // Increment the references count for the images // When the image is removed from a button, if the ref count = 0, then it is destroyed @@ -143,47 +144,47 @@ create_slider (const gchar * device) GtkWidget * ret; int dev=0; - if (g_strcmp0 (device, "speaker") == 0) { + if (g_strcmp0(device, "speaker") == 0) { dev = SPEAKER; - images[SPEAKER][MUTED] = gtk_image_new_from_file (ICONS_DIR "/speaker.svg"); - images[SPEAKER][VOL25] = gtk_image_new_from_file (ICONS_DIR "/speaker_25.svg"); - images[SPEAKER][VOL50] = gtk_image_new_from_file (ICONS_DIR "/speaker_50.svg"); - images[SPEAKER][VOL75] = gtk_image_new_from_file (ICONS_DIR "/speaker_75.svg"); - g_object_ref (images[SPEAKER][MUTED]); - g_object_ref (images[SPEAKER][VOL25]); - g_object_ref (images[SPEAKER][VOL50]); - g_object_ref (images[SPEAKER][VOL75]); - } else if (g_strcmp0 (device, "mic") == 0) { + images[SPEAKER][MUTED] = gtk_image_new_from_file(ICONS_DIR "/speaker.svg"); + images[SPEAKER][VOL25] = gtk_image_new_from_file(ICONS_DIR "/speaker_25.svg"); + images[SPEAKER][VOL50] = gtk_image_new_from_file(ICONS_DIR "/speaker_50.svg"); + images[SPEAKER][VOL75] = gtk_image_new_from_file(ICONS_DIR "/speaker_75.svg"); + g_object_ref(images[SPEAKER][MUTED]); + g_object_ref(images[SPEAKER][VOL25]); + g_object_ref(images[SPEAKER][VOL50]); + g_object_ref(images[SPEAKER][VOL75]); + } else if (g_strcmp0(device, "mic") == 0) { dev = MIKE; - images[MIKE][MUTED] = gtk_image_new_from_file (ICONS_DIR "/mic.svg"); - images[MIKE][VOL25] = gtk_image_new_from_file (ICONS_DIR "/mic_25.svg"); - images[MIKE][VOL50] = gtk_image_new_from_file (ICONS_DIR "/mic_50.svg"); - images[MIKE][VOL75] = gtk_image_new_from_file (ICONS_DIR "/mic_75.svg"); - g_object_ref (images[MIKE][MUTED]); - g_object_ref (images[MIKE][VOL25]); - g_object_ref (images[MIKE][VOL50]); - g_object_ref (images[MIKE][VOL75]); + images[MIKE][MUTED] = gtk_image_new_from_file(ICONS_DIR "/mic.svg"); + images[MIKE][VOL25] = gtk_image_new_from_file(ICONS_DIR "/mic_25.svg"); + images[MIKE][VOL50] = gtk_image_new_from_file(ICONS_DIR "/mic_50.svg"); + images[MIKE][VOL75] = gtk_image_new_from_file(ICONS_DIR "/mic_75.svg"); + g_object_ref(images[MIKE][MUTED]); + g_object_ref(images[MIKE][VOL25]); + g_object_ref(images[MIKE][VOL50]); + g_object_ref(images[MIKE][VOL75]); } - ret = gtk_hbox_new (FALSE /*homogeneous*/, 5 /*spacing*/); - gtk_container_set_border_width (GTK_CONTAINER (ret), 5); + ret = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5 /*spacing*/); + gtk_container_set_border_width(GTK_CONTAINER(ret), 5); - gtk_widget_set_tooltip_text (GTK_WIDGET (ret), - !g_strcmp0 (device, "speaker") ? _("Speakers volume") : _("Mic volume")); + gtk_widget_set_tooltip_text(GTK_WIDGET(ret), + !g_strcmp0(device, "speaker") ? _("Speakers volume") : _("Mic volume")); button[dev] = gtk_toggle_button_new(); - gtk_box_pack_start (GTK_BOX (ret), button[dev], FALSE /*expand*/, TRUE /*fill*/, 0 /*padding*/); - toggledConnId[dev] = g_signal_connect (G_OBJECT (button[dev]), "toggled", - G_CALLBACK (mute_cb), (gpointer) device); + gtk_box_pack_start(GTK_BOX(ret), button[dev], FALSE /*expand*/, TRUE /*fill*/, 0 /*padding*/); + toggledConnId[dev] = g_signal_connect(G_OBJECT(button[dev]), "toggled", + G_CALLBACK(mute_cb), (gpointer) device); - slider[dev] = gtk_hscale_new_with_range (0, 1, 0.05); - gtk_scale_set_draw_value (GTK_SCALE (slider[dev]), FALSE); + slider[dev] = gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, 0, 1, 0.05); + gtk_scale_set_draw_value(GTK_SCALE(slider[dev]), FALSE); //gtk_range_set_update_policy(GTK_RANGE(slider), GTK_UPDATE_DELAYED); - movedConnId[dev] = g_signal_connect (G_OBJECT (slider[dev]), "value_changed", - G_CALLBACK (slider_moved), (gpointer) device); - gtk_box_pack_start (GTK_BOX (ret), slider[dev], TRUE /*expand*/, TRUE /*fill*/, 0 /*padding*/); + movedConnId[dev] = g_signal_connect(G_OBJECT(slider[dev]), "value_changed", + G_CALLBACK(slider_moved), (gpointer) device); + gtk_box_pack_start(GTK_BOX(ret), slider[dev], TRUE /*expand*/, TRUE /*fill*/, 0 /*padding*/); - set_slider (device, dbus_get_volume (device)); + set_slider(device, dbus_get_volume(device)); return ret; } diff --git a/gnome/src/statusicon.c b/gnome/src/statusicon.c index 92e2564de5a430b48cfe9220534a7e45f028cd50..2fe79ee9b61e5735d3aaf8f655dede4448c16107 100644 --- a/gnome/src/statusicon.c +++ b/gnome/src/statusicon.c @@ -30,24 +30,26 @@ */ #include <gtk/gtk.h> -#include <actions.h> -#include <mainwindow.h> -#include <accountlist.h> -#include <statusicon.h> -#include <eel-gconf-extensions.h> +#include "actions.h" +#include "mainwindow.h" +#include "accountlist.h" +#include "statusicon.h" +#include "eel-gconf-extensions.h" +#include "logger.h" +#include "unused.h" static GtkStatusIcon *status; static GtkWidget *show_menu_item, *hangup_menu_item; -static gboolean __minimized = MINIMIZED; +static gboolean minimized_ = MINIMIZED; void -popup_main_window (void) +popup_main_window(void) { if (__POPUP_WINDOW) { - gtk_widget_show (get_main_window()); + gtk_widget_show(get_main_window()); //gtk_window_move(GTK_WINDOW (get_main_window ()), // dbus_get_window_position_x(), dbus_get_window_position_y()); - set_minimized (FALSE); + set_minimized(FALSE); } } @@ -55,9 +57,9 @@ void show_status_hangup_icon() { if (__POPUP_WINDOW) { - gtk_widget_show (get_main_window ()); - gtk_window_move (GTK_WINDOW (get_main_window ()), eel_gconf_get_integer (CONF_MAIN_WINDOW_POSITION_X), eel_gconf_get_integer (CONF_MAIN_WINDOW_POSITION_Y)); - set_minimized (FALSE); + gtk_widget_show(get_main_window()); + gtk_window_move(GTK_WINDOW(get_main_window()), eel_gconf_get_integer(CONF_MAIN_WINDOW_POSITION_X), eel_gconf_get_integer(CONF_MAIN_WINDOW_POSITION_Y)); + set_minimized(FALSE); } } @@ -65,13 +67,13 @@ void hide_status_hangup_icon() { if (status) { - DEBUG ("Hide Hangup in Systray"); - gtk_widget_hide (GTK_WIDGET (hangup_menu_item)); + DEBUG("Hide Hangup in Systray"); + gtk_widget_hide(GTK_WIDGET(hangup_menu_item)); } } void -status_quit (void * foo UNUSED) +status_quit(void * foo UNUSED) { sflphone_quit(); } @@ -85,101 +87,99 @@ status_hangup() void status_icon_unminimize() { - gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (show_menu_item), TRUE); + gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(show_menu_item), TRUE); } gboolean main_widget_minimized() { - return __minimized; + return minimized_; } void -show_hide (void) +show_hide(void) { - if (gtk_check_menu_item_get_active (GTK_CHECK_MENU_ITEM (show_menu_item))) { - gtk_widget_show (GTK_WIDGET (get_main_window())); - gtk_window_move (GTK_WINDOW (get_main_window ()), eel_gconf_get_integer (CONF_MAIN_WINDOW_POSITION_X), eel_gconf_get_integer (CONF_MAIN_WINDOW_POSITION_Y)); - set_minimized (!MINIMIZED); + if (gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(show_menu_item))) { + gtk_widget_show(GTK_WIDGET(get_main_window())); + gtk_window_move(GTK_WINDOW(get_main_window()), eel_gconf_get_integer(CONF_MAIN_WINDOW_POSITION_X), eel_gconf_get_integer(CONF_MAIN_WINDOW_POSITION_Y)); + set_minimized(!MINIMIZED); } else { - gtk_widget_hide (GTK_WIDGET (get_main_window())); - set_minimized (MINIMIZED); + gtk_widget_hide(GTK_WIDGET(get_main_window())); + set_minimized(MINIMIZED); } } void -status_click (GtkStatusIcon *status_icon UNUSED, void * foo UNUSED) +status_click(GtkStatusIcon *status_icon UNUSED, void * foo UNUSED) { - gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (show_menu_item), - !gtk_check_menu_item_get_active (GTK_CHECK_MENU_ITEM (show_menu_item))); + gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(show_menu_item), + !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(show_menu_item))); } -void -menu (GtkStatusIcon *status_icon, guint button, guint activate_time, - GtkWidget * menu) +static void menu(GtkStatusIcon *status_icon, guint button, guint activate_time, GtkWidget * menu_widget) { - gtk_menu_popup (GTK_MENU (menu), NULL, NULL, gtk_status_icon_position_menu, - status_icon, button, activate_time); + gtk_menu_popup(GTK_MENU(menu_widget), NULL, NULL, gtk_status_icon_position_menu, + status_icon, button, activate_time); } GtkWidget* create_menu() { - GtkWidget * menu; + GtkWidget * menu_widget; GtkWidget * menu_items; GtkWidget * image; - menu = gtk_menu_new(); + menu_widget = gtk_menu_new(); show_menu_item - = gtk_check_menu_item_new_with_mnemonic (_ ("_Show main window")); - gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (show_menu_item), TRUE); - gtk_menu_shell_append (GTK_MENU_SHELL (menu), show_menu_item); - g_signal_connect (G_OBJECT (show_menu_item), "toggled", - G_CALLBACK (show_hide), - NULL); - - hangup_menu_item = gtk_image_menu_item_new_with_mnemonic (_ ("_Hang up")); - image = gtk_image_new_from_file (ICONS_DIR "/icon_hangup.svg"); - gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (hangup_menu_item), image); - gtk_menu_shell_append (GTK_MENU_SHELL (menu), hangup_menu_item); - g_signal_connect (G_OBJECT (hangup_menu_item), "activate", - G_CALLBACK (status_hangup), - NULL); + = gtk_check_menu_item_new_with_mnemonic(_("_Show main window")); + gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(show_menu_item), TRUE); + gtk_menu_shell_append(GTK_MENU_SHELL(menu_widget), show_menu_item); + g_signal_connect(G_OBJECT(show_menu_item), "toggled", + G_CALLBACK(show_hide), + NULL); + + hangup_menu_item = gtk_image_menu_item_new_with_mnemonic(_("_Hang up")); + image = gtk_image_new_from_file(ICONS_DIR "/icon_hangup.svg"); + gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(hangup_menu_item), image); + gtk_menu_shell_append(GTK_MENU_SHELL(menu_widget), hangup_menu_item); + g_signal_connect(G_OBJECT(hangup_menu_item), "activate", + G_CALLBACK(status_hangup), + NULL); menu_items = gtk_separator_menu_item_new(); - gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_items); + gtk_menu_shell_append(GTK_MENU_SHELL(menu_widget), menu_items); - menu_items = gtk_image_menu_item_new_from_stock (GTK_STOCK_QUIT, + menu_items = gtk_image_menu_item_new_from_stock(GTK_STOCK_QUIT, get_accel_group()); - g_signal_connect_swapped (G_OBJECT (menu_items), "activate", - G_CALLBACK (status_quit), - NULL); - gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_items); + g_signal_connect_swapped(G_OBJECT(menu_items), "activate", + G_CALLBACK(status_quit), + NULL); + gtk_menu_shell_append(GTK_MENU_SHELL(menu_widget), menu_items); - gtk_widget_show_all (menu); + gtk_widget_show_all(menu_widget); - return menu; + return menu_widget; } void show_status_icon() { - status = gtk_status_icon_new_from_file (LOGO); - g_signal_connect (G_OBJECT (status), "activate", - G_CALLBACK (status_click), - NULL); - g_signal_connect (G_OBJECT (status), "popup-menu", - G_CALLBACK (menu), - create_menu()); + status = gtk_status_icon_new_from_file(LOGO); + g_signal_connect(G_OBJECT(status), "activate", + G_CALLBACK(status_click), + NULL); + g_signal_connect(G_OBJECT(status), "popup-menu", + G_CALLBACK(menu), + create_menu()); statusicon_set_tooltip(); } -void hide_status_icon (void) +void hide_status_icon(void) { - g_object_unref (status); + g_object_unref(status); status = NULL; } @@ -193,34 +193,34 @@ statusicon_set_tooltip() gchar *accounts = g_markup_printf_escaped(n_("%i active account", "%i active accounts", count), count); gchar *tip = g_markup_printf_escaped("%s - %s", _("SFLphone"), accounts); g_free(accounts); - gtk_status_icon_set_tooltip(status, tip); + gtk_status_icon_set_tooltip_markup(status, tip); g_free(tip); } } void -status_tray_icon_blink (gboolean active) +status_tray_icon_blink(gboolean active) { if (status) - gtk_status_icon_set_from_file (status, active ? LOGO_NOTIF : LOGO); + gtk_status_icon_set_from_file(status, active ? LOGO_NOTIF : LOGO); } void -status_tray_icon_online (gboolean online) +status_tray_icon_online(gboolean online) { if (status) gtk_status_icon_set_from_file(status, online ? LOGO : LOGO_OFFLINE); } GtkStatusIcon* -get_status_icon (void) +get_status_icon(void) { return status; } void -set_minimized (gboolean state) +set_minimized(gboolean state) { - __minimized = state; - gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (show_menu_item), !state); + minimized_ = state; + gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(show_menu_item), !state); } diff --git a/gnome/src/ui.xml b/gnome/src/ui.xml index 170665086346f4dfd52a6c6f781ceda0229662cb..52058b4947b5fea98095d8f4f8435b447dcd0be8 100644 --- a/gnome/src/ui.xml +++ b/gnome/src/ui.xml @@ -1,5 +1,4 @@ <ui> - <menubar name="MenuBar"> <menu name="CallMenu" action="Call"> <menuitem action="NewCall"/> @@ -39,7 +38,6 @@ <menuitem action="HelpContents"/> <menuitem action="About"/> </menu> - </menubar> <toolbar name="ToolbarActions"> @@ -51,7 +49,8 @@ <toolitem name="TransferToolbar" action="Transfer"/> <toolitem name="InstantMessagingToolbar" action="InstantMessaging"/> <toolitem name="RecordToolbar" action="Record"/> - <separator/> + <!-- FIXME: commented out because it is responsible for #7495 --> + <!-- separator/--> <toolitem name="VoicemailToolbar" action="Voicemail"/> <toolitem name="HistoryToolbar" action="History"/> <toolitem name="StartPlaybackRecordToolbar" action="StartPlaybackRecord"/> diff --git a/gnome/src/uimanager.c b/gnome/src/uimanager.c index 9484f8284783930a53e6e99200764e5ab5ac3859..cfd3c67f5fedf1290d5ea3f5e4f21d157194ee0f 100644 --- a/gnome/src/uimanager.c +++ b/gnome/src/uimanager.c @@ -28,29 +28,32 @@ * as that of the covered work. */ -#include <config.h> -#include <preferencesdialog.h> -#include <dbus/dbus.h> -#include <mainwindow.h> -#include <assistant.h> +#include "config.h" +#include "preferencesdialog.h" +#include "logger.h" +#include "dbus/dbus.h" +#include "mainwindow.h" +#include "assistant.h" #include <gtk/gtk.h> #include <string.h> #include <glib/gprintf.h> -#include <libgnome/gnome-help.h> - -#include <uimanager.h> -#include <statusicon.h> -#include <widget/imwidget.h> -#include <eel-gconf-extensions.h> +#include "uimanager.h" +#include "statusicon.h" +#include "widget/imwidget.h" +#include "eel-gconf-extensions.h" #include "config/audioconf.h" +#include "unused.h" #include "uimanager.h" #include "statusicon.h" #include "contacts/addrbookfactory.h" +#include "contacts/calltab.h" #include "config/addressbook-config.h" +#include "eel-gconf-extensions.h" + #include "accountlist.h" #include "config/accountlistconfigdialog.h" @@ -114,6 +117,7 @@ update_actions() g_object_ref(recordWidget_); g_object_ref(holdToolbar_); g_object_ref(offHoldToolbar_); + if (addrbook) g_object_ref(contactButton_); @@ -144,6 +148,7 @@ update_actions() gtk_widget_set_sensitive(contactButton_, FALSE); gtk_widget_set_sensitive(historyButton_, FALSE); + if (addrbook) gtk_widget_set_tooltip_text(contactButton_, _("No address book selected")); @@ -173,8 +178,8 @@ update_actions() } } - callable_obj_t * selectedCall = calltab_get_selected_call(active_calltree); - conference_obj_t * selectedConf = calltab_get_selected_conf(active_calltree); + callable_obj_t * selectedCall = calltab_get_selected_call(active_calltree_tab); + conference_obj_t * selectedConf = calltab_get_selected_conf(active_calltree_tab); gboolean instant_messaging_enabled = TRUE; @@ -197,7 +202,7 @@ update_actions() gtk_action_set_sensitive(hangUpAction_, TRUE); // Replace the dial button with the hangup button g_object_ref(newCallWidget_); - gtk_container_remove(GTK_CONTAINER(toolbar_), newCallWidget_); + remove_from_toolbar(newCallWidget_); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(pickUpWidget_), 0); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(hangUpWidget_), @@ -230,23 +235,24 @@ update_actions() DEBUG("UIManager: Call State Dialing"); gtk_action_set_sensitive(pickUpAction_, TRUE); - if (active_calltree == current_calls) + if (active_calltree_tab == current_calls_tab) gtk_action_set_sensitive(hangUpAction_, TRUE); g_object_ref(newCallWidget_); - gtk_container_remove(GTK_CONTAINER(toolbar_), newCallWidget_); + remove_from_toolbar(newCallWidget_); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(pickUpWidget_), 0); - if (active_calltree == current_calls) + if (active_calltree_tab == current_calls_tab) gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(hangUpWidget_), 1); - else if (active_calltree == history) { - if (selectedCall->_recordfile &&(g_strcmp0(selectedCall->_recordfile, "") != 0)) { + else if (active_calltree_tab == history_tab) { + if (selectedCall->_recordfile && strlen(selectedCall->_recordfile) > 0) { if (selectedCall->_record_is_playing) gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(stopRecordWidget_), 3); else gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(playRecordWidget_), 3); } } + break; case CALL_STATE_CURRENT: { DEBUG("UIManager: Call State Current"); @@ -260,17 +266,18 @@ update_actions() gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(holdToolbar_), pos++); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(transferToolbar_), pos++); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(recordWidget_), pos++); - gtk_signal_handler_block(GTK_OBJECT(transferToolbar_), transferButtonConnId_); + g_signal_handler_block(transferToolbar_, transferButtonConnId_); gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(transferToolbar_), FALSE); - gtk_signal_handler_unblock(transferToolbar_, transferButtonConnId_); - g_signal_handler_block(GTK_OBJECT(recordWidget_), recordButtonConnId_); + g_signal_handler_unblock(transferToolbar_, transferButtonConnId_); + g_signal_handler_block(recordWidget_, recordButtonConnId_); gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(recordWidget_), FALSE); - g_signal_handler_unblock(GTK_OBJECT(recordWidget_), recordButtonConnId_); + g_signal_handler_unblock(recordWidget_, recordButtonConnId_); if (instant_messaging_enabled) { gtk_action_set_sensitive(imAction_, TRUE); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(imToolbar_), pos); } + break; } @@ -286,12 +293,12 @@ update_actions() gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(holdToolbar_), pos++); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(transferToolbar_), pos++); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(recordWidget_), pos++); - gtk_signal_handler_block(GTK_OBJECT(transferToolbar_), transferButtonConnId_); + g_signal_handler_block(transferToolbar_, transferButtonConnId_); gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(transferToolbar_), FALSE); - gtk_signal_handler_unblock(transferToolbar_, transferButtonConnId_); - g_signal_handler_block(GTK_OBJECT(recordWidget_), recordButtonConnId_); + g_signal_handler_unblock(transferToolbar_, transferButtonConnId_); + g_signal_handler_block(recordWidget_, recordButtonConnId_); gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(recordWidget_), TRUE); - g_signal_handler_unblock(GTK_OBJECT(recordWidget_), recordButtonConnId_); + g_signal_handler_unblock(recordWidget_, recordButtonConnId_); if (instant_messaging_enabled) { gtk_action_set_sensitive(imAction_, TRUE); @@ -309,9 +316,9 @@ update_actions() case CALL_STATE_TRANSFER: gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(hangUpWidget_), 1); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(transferToolbar_), 2); - gtk_signal_handler_block(GTK_OBJECT(transferToolbar_), transferButtonConnId_); + g_signal_handler_block(transferToolbar_, transferButtonConnId_); gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(transferToolbar_), TRUE); - gtk_signal_handler_unblock(transferToolbar_, transferButtonConnId_); + g_signal_handler_unblock(transferToolbar_, transferButtonConnId_); gtk_action_set_sensitive(hangUpAction_, TRUE); gtk_widget_set_sensitive(holdMenu_, TRUE); gtk_widget_set_sensitive(holdToolbar_, TRUE); @@ -330,10 +337,11 @@ update_actions() switch (selectedConf->_state) { - case CONFERENCE_STATE_ACTIVE_ATACHED: + case CONFERENCE_STATE_ACTIVE_ATTACHED: case CONFERENCE_STATE_ACTIVE_DETACHED: DEBUG("UIManager: Conference State Active"); - if (active_calltree == current_calls) { + + if (active_calltree_tab == current_calls_tab) { int pos = 1; gtk_action_set_sensitive(hangUpAction_, TRUE); gtk_widget_set_sensitive(holdToolbar_, TRUE); @@ -341,19 +349,20 @@ update_actions() gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(hangUpWidget_), pos++); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(holdToolbar_), pos++); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(recordWidget_), pos++); + if (instant_messaging_enabled) { gtk_action_set_sensitive(imAction_, TRUE); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(imToolbar_), pos); } - } - else if (active_calltree == history) { - if (selectedConf->_recordfile &&(g_strcmp0(selectedConf->_recordfile, "") != 0)) { + } else if (active_calltree_tab == history_tab) { + if (selectedConf->_recordfile && strlen(selectedConf->_recordfile) > 0) { if (selectedConf->_record_is_playing) gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(stopRecordWidget_), 3); else gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(playRecordWidget_), 3); } } + break; case CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD: case CONFERENCE_STATE_ACTIVE_DETACHED_RECORD: { @@ -365,10 +374,12 @@ update_actions() gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(hangUpWidget_), pos++); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(holdToolbar_), pos++); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(recordWidget_), pos++); + if (instant_messaging_enabled) { gtk_action_set_sensitive(imAction_, TRUE); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(imToolbar_), pos); } + break; } case CONFERENCE_STATE_HOLD: @@ -381,10 +392,12 @@ update_actions() gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(hangUpWidget_), pos++); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(offHoldToolbar_), pos++); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(recordWidget_), pos++); + if (instant_messaging_enabled) { gtk_action_set_sensitive(imAction_, TRUE); gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), GTK_TOOL_ITEM(imToolbar_), pos); } + break; } default: @@ -397,7 +410,7 @@ update_actions() if (account_list_get_size() > 0 && current_account_has_mailbox()) { gtk_toolbar_insert(GTK_TOOLBAR(toolbar_), - GTK_TOOL_ITEM(voicemailToolbar_), -2); + GTK_TOOL_ITEM(voicemailToolbar_), -2); update_voicemail_status(); } } @@ -407,14 +420,15 @@ void update_voicemail_status() { gchar *messages = g_markup_printf_escaped(_("Voicemail(%i)"), - current_account_get_message_number()); + current_account_get_message_number()); if (current_account_has_new_message()) gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(voicemailToolbar_), - "mail-message-new"); + "mail-message-new"); else gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(voicemailToolbar_), "mail-read"); + gtk_tool_button_set_label(GTK_TOOL_BUTTON(voicemailToolbar_), messages); g_free(messages); } @@ -452,9 +466,7 @@ static void help_contents_cb(GtkAction *action UNUSED) { GError *error = NULL; - - gnome_help_display("sflphone.xml", NULL, &error); - + gtk_show_uri(NULL, "ghelp:sflphone", GDK_CURRENT_TIME, &error); if (error != NULL) { g_warning("%s", error->message); g_error_free(error); @@ -464,8 +476,7 @@ help_contents_cb(GtkAction *action UNUSED) static void help_about(void * foo UNUSED) { - gchar - *authors[] = { + static const gchar *authors[] = { "Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com>", "Jean-Philippe Barrette-LaPierre", "Pierre-Luc Beaudoin <pierre-luc.beaudoin@savoirfairelinux.com>", @@ -479,17 +490,21 @@ help_about(void * foo UNUSED) "Julien Plissonneau Duquene <julien.plissonneau.duquene@savoirfairelinux.com>", "Alexandre Savard <alexandre.savard@savoirfairelinux.com>", NULL }; - gchar *artists[] = { "Pierre-Luc Beaudoin <pierre-luc.beaudoin@savoirfairelinux.com>", - "Emmanuel Milou <emmanuel.milou@savoirfairelinux.com>", NULL - }; - - gtk_show_about_dialog(GTK_WINDOW(get_main_window()), "artists", artists, - "authors", authors, "comments", - _("SFLphone is a VoIP client compatible with SIP and IAX2 protocols."), - "copyright", "Copyright © 2004-2011 Savoir-faire Linux Inc.", "name", - PACKAGE, "title", _("About SFLphone"), "version", VERSION, "website", - "http://www.sflphone.org", NULL); + static const gchar *artists[] = { + "Pierre-Luc Beaudoin <pierre-luc.beaudoin@savoirfairelinux.com>", + "Emmanuel Milou <emmanuel.milou@savoirfairelinux.com>", NULL + }; + gtk_show_about_dialog(GTK_WINDOW(get_main_window()), + "artists", artists, + "authors", authors, + "comments", _("SFLphone is a VoIP client compatible with SIP and IAX2 protocols."), + "copyright", "Copyright © 2004-2011 Savoir-faire Linux Inc.", + "name", PACKAGE, + "title", _("About SFLphone"), + "version", VERSION, + "website", "http://www.sflphone.org", + NULL); } /* ----------------------------------------------------------------- */ @@ -529,8 +544,8 @@ switch_account(GtkWidget* item, gpointer data UNUSED) static void call_hold(void* foo UNUSED) { - callable_obj_t * selectedCall = calltab_get_selected_call(current_calls); - conference_obj_t * selectedConf = calltab_get_selected_conf(current_calls); + callable_obj_t * selectedCall = calltab_get_selected_call(current_calls_tab); + conference_obj_t * selectedConf = calltab_get_selected_conf(current_calls_tab); DEBUG("UIManager: Hold button pressed"); @@ -542,24 +557,24 @@ call_hold(void* foo UNUSED) } else if (selectedConf) { switch (selectedConf->_state) { case CONFERENCE_STATE_HOLD: - selectedConf->_state = CONFERENCE_STATE_ACTIVE_ATACHED; - sflphone_conference_off_hold(selectedConf); + selectedConf->_state = CONFERENCE_STATE_ACTIVE_ATTACHED; + dbus_unhold_conference(selectedConf); break; case CONFERENCE_STATE_HOLD_RECORD: selectedConf->_state = CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD; - sflphone_conference_off_hold(selectedConf); + dbus_unhold_conference(selectedConf); break; - case CONFERENCE_STATE_ACTIVE_ATACHED: + case CONFERENCE_STATE_ACTIVE_ATTACHED: case CONFERENCE_STATE_ACTIVE_DETACHED: selectedConf->_state = CONFERENCE_STATE_HOLD; - sflphone_conference_on_hold(selectedConf); + dbus_hold_conference(selectedConf); break; case CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD: case CONFERENCE_STATE_ACTIVE_DETACHED_RECORD: - selectedConf->_state = CONFERENCE_STATE_HOLD_RECORD; - sflphone_conference_on_hold(selectedConf); - break; + selectedConf->_state = CONFERENCE_STATE_HOLD_RECORD; + dbus_hold_conference(selectedConf); + break; default: break; } @@ -569,10 +584,10 @@ call_hold(void* foo UNUSED) static void call_im(void* foo UNUSED) { - callable_obj_t *selectedCall = calltab_get_selected_call(current_calls); - conference_obj_t *selectedConf = calltab_get_selected_conf(current_calls); + callable_obj_t *selectedCall = calltab_get_selected_call(current_calls_tab); + conference_obj_t *selectedConf = calltab_get_selected_conf(current_calls_tab); - if (calltab_get_selected_type(current_calls) == A_CALL) { + if (calltab_get_selected_type(current_calls_tab) == A_CALL) { if (selectedCall) { if (!selectedCall->_im_widget) selectedCall->_im_widget = im_widget_display(selectedCall->_callID); @@ -590,7 +605,7 @@ call_im(void* foo UNUSED) static void conference_hold(void* foo UNUSED) { - conference_obj_t * selectedConf = calltab_get_selected_conf(current_calls); + conference_obj_t * selectedConf = calltab_get_selected_conf(current_calls_tab); DEBUG("UIManager: Hold button pressed for conference"); @@ -601,22 +616,22 @@ conference_hold(void* foo UNUSED) switch (selectedConf->_state) { case CONFERENCE_STATE_HOLD: - selectedConf->_state = CONFERENCE_STATE_ACTIVE_ATACHED; - sflphone_conference_off_hold(selectedConf); + selectedConf->_state = CONFERENCE_STATE_ACTIVE_ATTACHED; + dbus_unhold_conference(selectedConf); break; case CONFERENCE_STATE_HOLD_RECORD: selectedConf->_state = CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD; - sflphone_conference_off_hold(selectedConf); + dbus_unhold_conference(selectedConf); break; - case CONFERENCE_STATE_ACTIVE_ATACHED: + case CONFERENCE_STATE_ACTIVE_ATTACHED: case CONFERENCE_STATE_ACTIVE_DETACHED: selectedConf->_state = CONFERENCE_STATE_HOLD; - sflphone_conference_on_hold(selectedConf); + dbus_hold_conference(selectedConf); break; case CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD: case CONFERENCE_STATE_ACTIVE_DETACHED_RECORD: selectedConf->_state = CONFERENCE_STATE_HOLD_RECORD; - sflphone_conference_on_hold(selectedConf); + dbus_hold_conference(selectedConf); default: break; } @@ -627,25 +642,25 @@ call_pick_up(void * foo UNUSED) { DEBUG("UIManager: Pick up"); - if (calllist_get_size(current_calls) > 0) { + if (calllist_get_size(current_calls_tab) > 0) { sflphone_pick_up(); - } else if (calllist_get_size(active_calltree) > 0) { - callable_obj_t *selectedCall = calltab_get_selected_call(active_calltree); + } else if (calllist_get_size(active_calltree_tab) > 0) { + callable_obj_t *selectedCall = calltab_get_selected_call(active_calltree_tab); if (selectedCall) { callable_obj_t *new_call = create_new_call(CALL, CALL_STATE_DIALING, "", "", "", - selectedCall->_peer_number); - calllist_add_call(current_calls, new_call); - calltree_add_call(current_calls, new_call, NULL); + selectedCall->_peer_number); + calllist_add_call(current_calls_tab, new_call); + calltree_add_call(current_calls_tab, new_call, NULL); sflphone_place_call(new_call); - calltree_display(current_calls); + calltree_display(current_calls_tab); } else { sflphone_new_call(); - calltree_display(current_calls); + calltree_display(current_calls_tab); } } else { sflphone_new_call(); - calltree_display(current_calls); + calltree_display(current_calls_tab); } } @@ -665,7 +680,8 @@ static void conference_hang_up(void) { DEBUG("UIManager: Hang up button pressed(conference)"); - conference_obj_t * selectedConf = calltab_get_selected_conf(current_calls); + conference_obj_t * selectedConf = calltab_get_selected_conf(current_calls_tab); + if (selectedConf) dbus_hang_up_conference(selectedConf); } @@ -682,27 +698,15 @@ start_playback_record_cb(void) { DEBUG("UIManager: Start playback button pressed"); - callable_obj_t *selectedCall = calltab_get_selected_call(history); - conference_obj_t *selectedConf = calltab_get_selected_conf(history); + callable_obj_t *selectedCall = calltab_get_selected_call(history_tab); - if (selectedCall == NULL && selectedConf == NULL) { + if (selectedCall == NULL) { ERROR("UIManager: Error: No selected object in playback record callback"); return; } - if (selectedCall && selectedConf) { - ERROR("UIManager: Error: Two selected object in playback record callback"); - return; - } - - if (selectedCall) { - DEBUG("UIManager: Start selected call file playback %s", selectedCall->_recordfile); - selectedCall->_record_is_playing = dbus_start_recorded_file_playback(selectedCall->_recordfile); - } - else if (selectedConf) { - DEBUG("UIMAnager: Start selected conf file playback %s", selectedConf->_recordfile); - selectedConf->_record_is_playing = dbus_start_recorded_file_playback(selectedConf->_recordfile); - } + DEBUG("UIManager: Start selected call file playback %s", selectedCall->_recordfile); + selectedCall->_record_is_playing = dbus_start_recorded_file_playback(selectedCall->_recordfile); update_actions(); } @@ -712,15 +716,9 @@ stop_playback_record_cb(void) { DEBUG("UIManager: Stop playback button pressed"); - callable_obj_t *selectedCall = calltab_get_selected_call(history); - conference_obj_t *selectedConf = calltab_get_selected_conf(history); + callable_obj_t *selectedCall = calltab_get_selected_call(history_tab); - if (selectedCall && selectedConf) { - ERROR("UIManager: Error: Two selected object in history treeview"); - return; - } - - if (selectedCall == NULL && selectedConf == NULL) { + if (selectedCall == NULL) { ERROR("UIManager: Error: No selected object in history treeview"); return; } @@ -730,19 +728,11 @@ stop_playback_record_cb(void) ERROR("UIManager: Error: Record file is NULL"); return; } + dbus_stop_recorded_file_playback(selectedCall->_recordfile); DEBUG("UIManager: Stop selected call file playback %s", selectedCall->_recordfile); selectedCall->_record_is_playing = FALSE; } - else if (selectedConf) { - if (selectedConf->_recordfile == NULL) { - ERROR("UIManager: Error: Record file is NULL"); - return; - } - dbus_stop_recorded_file_playback(selectedConf->_recordfile); - DEBUG("UIMAnager: Start selected call file playback: %s", selectedConf->_recordfile); - selectedConf->_record_is_playing = FALSE; - } update_actions(); } @@ -756,13 +746,13 @@ call_configuration_assistant(void * foo UNUSED) static void remove_from_history(void * foo UNUSED) { - callable_obj_t* call = calltab_get_selected_call(history); + callable_obj_t* call = calltab_get_selected_call(history_tab); DEBUG("UIManager: Remove the call from the history"); if (call == NULL) { ERROR("UIManager: Error: Call is NULL"); - return; + return; } calllist_remove_from_history(call); @@ -771,7 +761,7 @@ remove_from_history(void * foo UNUSED) static void call_back(void * foo UNUSED) { - callable_obj_t *selected_call = calltab_get_selected_call(active_calltree); + callable_obj_t *selected_call = calltab_get_selected_call(active_calltree_tab); DEBUG("UIManager: Call back"); @@ -781,13 +771,13 @@ call_back(void * foo UNUSED) } callable_obj_t *new_call = create_new_call(CALL, CALL_STATE_DIALING, "", - "", selected_call->_peer_name, - selected_call->_peer_number); + "", selected_call->_peer_name, + selected_call->_peer_number); - calllist_add_call(current_calls, new_call); - calltree_add_call(current_calls, new_call, NULL); + calllist_add_call(current_calls_tab, new_call); + calltree_add_call(current_calls_tab, new_call, NULL); sflphone_place_call(new_call); - calltree_display(current_calls); + calltree_display(current_calls_tab); } static void @@ -807,18 +797,18 @@ static void edit_copy(void * foo UNUSED) { GtkClipboard* clip = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); - callable_obj_t * selectedCall = calltab_get_selected_call(current_calls); + callable_obj_t * selectedCall = calltab_get_selected_call(current_calls_tab); DEBUG("UIManager: Edit/Copy"); if (selectedCall == NULL) { ERROR("UIManager: Error: No selected call", selectedCall); - return; + return; } DEBUG("UIManager: Clipboard number: %s\n", selectedCall->_peer_number); gtk_clipboard_set_text(clip, selectedCall->_peer_number, - strlen(selectedCall->_peer_number)); + strlen(selectedCall->_peer_number)); } // The menu Edit/Paste should paste the clipboard into the current selected call @@ -826,25 +816,24 @@ static void edit_paste(void * foo UNUSED) { GtkClipboard* clip = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); - callable_obj_t * selectedCall = calltab_get_selected_call(current_calls); + callable_obj_t * selectedCall = calltab_get_selected_call(current_calls_tab); gchar * no = gtk_clipboard_wait_for_text(clip); if (no && selectedCall) { switch (selectedCall->_state) { case CALL_STATE_TRANSFER: - case CALL_STATE_DIALING: - { + case CALL_STATE_DIALING: { /* Add the text to the number */ - gchar *before = selectedCall->_peer_number; - DEBUG("TO: %s\n", before); - selectedCall->_peer_number = g_strconcat(before, no, NULL); - g_free(before); + gchar *old = selectedCall->_peer_number; + DEBUG("TO: %s\n", old); + selectedCall->_peer_number = g_strconcat(old, no, NULL); + g_free(old); if (selectedCall->_state == CALL_STATE_DIALING) selectedCall->_peer_info = g_strconcat("\"\" <", - selectedCall->_peer_number, ">", NULL); + selectedCall->_peer_number, ">", NULL); - calltree_update_call(current_calls, selectedCall, NULL); + calltree_update_call(current_calls_tab, selectedCall); } break; case CALL_STATE_RINGING: @@ -854,33 +843,33 @@ edit_paste(void * foo UNUSED) case CALL_STATE_HOLD: { // Create a new call to hold the new text selectedCall = sflphone_new_call(); - g_free(selectedCall->_peer_number); - selectedCall->_peer_number = g_strconcat(selectedCall->_peer_number, - no, NULL); + gchar *old = selectedCall->_peer_number; + selectedCall->_peer_number = g_strconcat(old, no, NULL); + g_free(old); DEBUG("TO: %s", selectedCall->_peer_number); g_free(selectedCall->_peer_info); selectedCall->_peer_info = g_strconcat("\"\" <", - selectedCall->_peer_number, ">", NULL); + selectedCall->_peer_number, ">", NULL); - calltree_update_call(current_calls, selectedCall, NULL); + calltree_update_call(current_calls_tab, selectedCall); } break; case CALL_STATE_CURRENT: case CALL_STATE_RECORD: default: { - for(unsigned i = 0; i < strlen(no); i++) { + for (unsigned i = 0; i < strlen(no); i++) { gchar * oneNo = g_strndup(&no[i], 1); DEBUG("<%s>", oneNo); dbus_play_dtmf(oneNo); - gchar * temp = g_strconcat(selectedCall->_peer_number, oneNo, - NULL); + gchar * temp = g_strconcat(selectedCall->_peer_number, + oneNo, NULL); g_free(selectedCall->_peer_info); selectedCall->_peer_info = get_peer_info(temp, selectedCall->_peer_name); g_free(temp); g_free(oneNo); - calltree_update_call(current_calls, selectedCall, NULL); + calltree_update_call(current_calls_tab, selectedCall); } } break; @@ -888,18 +877,15 @@ edit_paste(void * foo UNUSED) } else { // There is no current call, create one selectedCall = sflphone_new_call(); - gchar * before = selectedCall->_peer_number; - gchar *new_peer_number = g_strconcat(selectedCall->_peer_number, no, - NULL); - g_free(selectedCall->_peer_number); - selectedCall->_peer_number = new_peer_number; - g_free(before); + gchar * old = selectedCall->_peer_number; + selectedCall->_peer_number = g_strconcat(old, no, NULL); + g_free(old); DEBUG("UIManager: TO: %s", selectedCall->_peer_number); g_free(selectedCall->_peer_info); selectedCall->_peer_info = g_strconcat("\"\" <", - selectedCall->_peer_number, ">", NULL); - calltree_update_call(current_calls, selectedCall, NULL); + selectedCall->_peer_number, ">", NULL); + calltree_update_call(current_calls_tab, selectedCall); } g_free(no); @@ -908,11 +894,7 @@ edit_paste(void * foo UNUSED) static void clear_history(void) { - if (conferencelist_get_size(history) != 0) - conferencelist_clean_history(); - - if (calllist_get_size(history) != 0) - calllist_clean_history(); + calllist_clean_history(); } /** @@ -939,74 +921,106 @@ call_mailbox_cb(void) const gchar * const account_id = g_strdup(current->accountID); callable_obj_t *mailbox_call = create_new_call(CALL, CALL_STATE_DIALING, - "", account_id, - _("Voicemail"), to); + "", account_id, + _("Voicemail"), to); DEBUG("TO : %s" , mailbox_call->_peer_number); - calllist_add_call(current_calls, mailbox_call); - calltree_add_call(current_calls, mailbox_call, NULL); + calllist_add_call(current_calls_tab, mailbox_call); + calltree_add_call(current_calls_tab, mailbox_call, NULL); update_actions(); sflphone_place_call(mailbox_call); - calltree_display(current_calls); + calltree_display(current_calls_tab); } static void toggle_history_cb(GtkToggleAction *action, gpointer user_data UNUSED) { if (gtk_toggle_action_get_active(action)) - calltree_display(history); + calltree_display(history_tab); else - calltree_display(current_calls); + calltree_display(current_calls_tab); } static void toggle_addressbook_cb(GtkToggleAction *action, gpointer user_data UNUSED) { if (gtk_toggle_action_get_active(action)) - calltree_display(contacts); + calltree_display(contacts_tab); else - calltree_display(current_calls); + calltree_display(current_calls_tab); } static const GtkActionEntry menu_entries[] = { - // Call Menu { "Call", NULL, N_("Call"), NULL, NULL, NULL}, - { "NewCall", GTK_STOCK_DIAL, N_("_New call"), "<control>N", - N_("Place a new call"), G_CALLBACK(call_new_call) }, - { "PickUp", GTK_STOCK_PICKUP, N_("_Pick up"), NULL, - N_("Answer the call"), G_CALLBACK(call_pick_up) }, - { "HangUp", GTK_STOCK_HANGUP, N_("_Hang up"), "<control>S", - N_("Finish the call"), G_CALLBACK(call_hang_up) }, - { "OnHold", GTK_STOCK_ONHOLD, N_("O_n hold"), "<control>P", - N_("Place the call on hold"), G_CALLBACK(call_hold) }, - { "OffHold", GTK_STOCK_OFFHOLD, N_("O_ff hold"), "<control>P", - N_("Place the call off hold"), G_CALLBACK(call_hold) }, - { "InstantMessaging", GTK_STOCK_IM, N_("Send _message"), "<control>M", - N_("Send message"), G_CALLBACK(call_im) }, - { "AccountAssistant", NULL, N_("Configuration _Assistant"), NULL, - N_("Run the configuration assistant"), G_CALLBACK(call_configuration_assistant) }, - { "Voicemail", "mail-read", N_("Voicemail"), NULL, - N_("Call your voicemail"), G_CALLBACK(call_mailbox_cb) }, - { "Close", GTK_STOCK_CLOSE, N_("_Close"), "<control>W", - N_("Minimize to system tray"), G_CALLBACK(call_minimize) }, - { "Quit", GTK_STOCK_CLOSE, N_("_Quit"), "<control>Q", - N_("Quit the program"), G_CALLBACK(call_quit) }, - { "StartPlaybackRecord", GTK_STOCK_MEDIA_PLAY, N_("_Playback record"), NULL, - N_("Playback recorded file"), G_CALLBACK(start_playback_record_cb) }, - { "StopPlaybackRecord", GTK_STOCK_MEDIA_PAUSE, N_("_Stop playback"), NULL, - N_("Stop recorded file playback"), G_CALLBACK(stop_playback_record_cb) }, + { + "NewCall", GTK_STOCK_DIAL, N_("_New call"), "<control>N", + N_("Place a new call"), G_CALLBACK(call_new_call) + }, + { + "PickUp", GTK_STOCK_PICKUP, N_("_Pick up"), NULL, + N_("Answer the call"), G_CALLBACK(call_pick_up) + }, + { + "HangUp", GTK_STOCK_HANGUP, N_("_Hang up"), "<control>S", + N_("Finish the call"), G_CALLBACK(call_hang_up) + }, + { + "OnHold", GTK_STOCK_ONHOLD, N_("O_n hold"), "<control>P", + N_("Place the call on hold"), G_CALLBACK(call_hold) + }, + { + "OffHold", GTK_STOCK_OFFHOLD, N_("O_ff hold"), "<control>P", + N_("Place the call off hold"), G_CALLBACK(call_hold) + }, + { + "InstantMessaging", GTK_STOCK_IM, N_("Send _message"), "<control>M", + N_("Send message"), G_CALLBACK(call_im) + }, + { + "AccountAssistant", NULL, N_("Configuration _Assistant"), NULL, + N_("Run the configuration assistant"), G_CALLBACK(call_configuration_assistant) + }, + { + "Voicemail", "mail-read", N_("Voicemail"), NULL, + N_("Call your voicemail"), G_CALLBACK(call_mailbox_cb) + }, + { + "Close", GTK_STOCK_CLOSE, N_("_Close"), "<control>W", + N_("Minimize to system tray"), G_CALLBACK(call_minimize) + }, + { + "Quit", GTK_STOCK_CLOSE, N_("_Quit"), "<control>Q", + N_("Quit the program"), G_CALLBACK(call_quit) + }, + { + "StartPlaybackRecord", GTK_STOCK_MEDIA_PLAY, N_("_Playback record"), NULL, + N_("Playback recorded file"), G_CALLBACK(start_playback_record_cb) + }, + { + "StopPlaybackRecord", GTK_STOCK_MEDIA_PAUSE, N_("_Stop playback"), NULL, + N_("Stop recorded file playback"), G_CALLBACK(stop_playback_record_cb) + }, // Edit Menu { "Edit", NULL, N_("_Edit"), NULL, NULL, NULL }, - { "Copy", GTK_STOCK_COPY, N_("_Copy"), "<control>C", - N_("Copy the selection"), G_CALLBACK(edit_copy) }, - { "Paste", GTK_STOCK_PASTE, N_("_Paste"), "<control>V", - N_("Paste the clipboard"), G_CALLBACK(edit_paste) }, - { "ClearHistory", GTK_STOCK_CLEAR, N_("Clear _history"), NULL, - N_("Clear the call history"), G_CALLBACK(clear_history) }, - { "Accounts", NULL, N_("_Accounts"), NULL, - N_("Edit your accounts"), G_CALLBACK(edit_accounts) }, - { "Preferences", GTK_STOCK_PREFERENCES, N_("_Preferences"), NULL, + { + "Copy", GTK_STOCK_COPY, N_("_Copy"), "<control>C", + N_("Copy the selection"), G_CALLBACK(edit_copy) + }, + { + "Paste", GTK_STOCK_PASTE, N_("_Paste"), "<control>V", + N_("Paste the clipboard"), G_CALLBACK(edit_paste) + }, + { + "ClearHistory", GTK_STOCK_CLEAR, N_("Clear _history"), NULL, + N_("Clear the call history"), G_CALLBACK(clear_history) + }, + { + "Accounts", NULL, N_("_Accounts"), NULL, + N_("Edit your accounts"), G_CALLBACK(edit_accounts) + }, + { + "Preferences", GTK_STOCK_PREFERENCES, N_("_Preferences"), NULL, N_("Change your preferences"), G_CALLBACK(edit_preferences) }, @@ -1019,11 +1033,9 @@ static const GtkActionEntry menu_entries[] = { N_("Open the manual"), G_CALLBACK(help_contents_cb) }, { "About", GTK_STOCK_ABOUT, NULL, NULL, N_("About this application"), G_CALLBACK(help_about) } - }; static const GtkToggleActionEntry toggle_menu_entries[] = { - { "Transfer", GTK_STOCK_TRANSFER, N_("_Transfer"), "<control>T", N_("Transfer the call"), NULL, TRUE }, { "Record", GTK_STOCK_MEDIA_RECORD, N_("_Record"), "<control>R", N_("Record the current conversation"), NULL, TRUE }, { "Toolbar", NULL, N_("_Show toolbar"), "<control>T", N_("Show the toolbar"), NULL, TRUE }, @@ -1044,13 +1056,16 @@ GtkUIManager *uimanager_new(void) gchar *path = g_build_filename(SFLPHONE_UIDIR_UNINSTALLED, "./ui.xml", NULL); guint manager_id; GError *error = NULL; - if (g_file_test(path, G_FILE_TEST_EXISTS)) { + + if (g_file_test(path, G_FILE_TEST_EXISTS)) manager_id = gtk_ui_manager_add_ui_from_file(ui_manager, path, &error); - } else { + else { g_free(path); path = g_build_filename(SFLPHONE_UIDIR, "./ui.xml", NULL); + if (!g_file_test(path, G_FILE_TEST_EXISTS)) goto fail; + manager_id = gtk_ui_manager_add_ui_from_file(ui_manager, path, &error); } @@ -1062,13 +1077,13 @@ GtkUIManager *uimanager_new(void) if (addrbook) { // These actions must be loaded dynamically and is not specified in the xml description gtk_ui_manager_add_ui(ui_manager, manager_id, "/ViewMenu", - "Addressbook", - "Addressbook", - GTK_UI_MANAGER_MENUITEM, FALSE); + "Addressbook", + "Addressbook", + GTK_UI_MANAGER_MENUITEM, FALSE); gtk_ui_manager_add_ui(ui_manager, manager_id, "/ToolbarActions", - "AddressbookToolbar", - "Addressbook", - GTK_UI_MANAGER_TOOLITEM, FALSE); + "AddressbookToolbar", + "Addressbook", + GTK_UI_MANAGER_TOOLITEM, FALSE); } GtkActionGroup *action_group = gtk_action_group_new("SFLphoneWindowActions"); @@ -1082,11 +1097,11 @@ GtkUIManager *uimanager_new(void) return ui_manager; fail: + if (error) g_error_free(error); g_free(path); - g_free(ui_manager); return NULL; } @@ -1103,12 +1118,12 @@ add_registered_accounts_to_menu(GtkWidget *menu) gtk_menu_shell_append(GTK_MENU_SHELL(menu), separator); gtk_widget_show(separator); - for(unsigned i = 0; i != account_list_get_size(); i++) { + for (unsigned i = 0; i != account_list_get_size(); i++) { account_t *acc = account_list_get_nth(i); // Display only the registered accounts if (g_strcasecmp(account_state_name(acc->state), account_state_name( - ACCOUNT_STATE_REGISTERED)) == 0) { + ACCOUNT_STATE_REGISTERED)) == 0) { gchar *alias = g_strconcat(g_hash_table_lookup(acc->properties, ACCOUNT_ALIAS), " - ", g_hash_table_lookup(acc->properties, ACCOUNT_TYPE), @@ -1125,8 +1140,8 @@ add_registered_accounts_to_menu(GtkWidget *menu) } g_signal_connect(G_OBJECT(menu_items), "activate", - G_CALLBACK(switch_account), - NULL); + G_CALLBACK(switch_account), + NULL); gtk_widget_show(menu_items); } } @@ -1135,6 +1150,7 @@ add_registered_accounts_to_menu(GtkWidget *menu) static void menu_popup_wrapper(GtkWidget *menu, GtkWidget *my_widget, GdkEventButton *event) { gtk_menu_attach_to_widget(GTK_MENU(menu), my_widget, NULL); + if (event) gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL, event->button, event->time); @@ -1154,11 +1170,11 @@ show_popup_menu(GtkWidget *my_widget, GdkEventButton *event) gboolean hangup_or_hold_conf = FALSE; callable_obj_t * selectedCall = NULL; - conference_obj_t * selectedConf; + conference_obj_t * selectedConf = NULL; - if (calltab_get_selected_type(current_calls) == A_CALL) { + if (calltab_get_selected_type(current_calls_tab) == A_CALL) { DEBUG("UIManager: Menus: Selected a call"); - selectedCall = calltab_get_selected_call(current_calls); + selectedCall = calltab_get_selected_call(current_calls_tab); if (selectedCall) { copy = TRUE; @@ -1199,11 +1215,11 @@ show_popup_menu(GtkWidget *my_widget, GdkEventButton *event) } } else { DEBUG("UIManager: Menus: selected a conf"); - selectedConf = calltab_get_selected_conf(active_calltree); + selectedConf = calltab_get_selected_conf(active_calltree_tab); if (selectedConf) { switch (selectedConf->_state) { - case CONFERENCE_STATE_ACTIVE_ATACHED: + case CONFERENCE_STATE_ACTIVE_ATTACHED: case CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD: hangup_or_hold_conf = TRUE; break; @@ -1220,16 +1236,15 @@ show_popup_menu(GtkWidget *my_widget, GdkEventButton *event) break; } } - } GtkWidget *menu = gtk_menu_new(); - if (calltab_get_selected_type(current_calls) == A_CALL) { + if (calltab_get_selected_type(current_calls_tab) == A_CALL) { DEBUG("UIManager: Build call menu"); if (copy) { GtkWidget *menu_items = gtk_image_menu_item_new_from_stock(GTK_STOCK_COPY, - get_accel_group()); + get_accel_group()); gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items); g_signal_connect(G_OBJECT(menu_items), "activate", G_CALLBACK(edit_copy), @@ -1238,10 +1253,10 @@ show_popup_menu(GtkWidget *my_widget, GdkEventButton *event) } GtkWidget *paste = gtk_image_menu_item_new_from_stock(GTK_STOCK_PASTE, - get_accel_group()); + get_accel_group()); gtk_menu_shell_append(GTK_MENU_SHELL(menu), paste); g_signal_connect(G_OBJECT(paste), "activate", G_CALLBACK(edit_paste), - NULL); + NULL); gtk_widget_show(paste); if (pickup || hangup || hold) { @@ -1256,8 +1271,8 @@ show_popup_menu(GtkWidget *my_widget, GdkEventButton *event) gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_items), image); gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items); g_signal_connect(G_OBJECT(menu_items), "activate", - G_CALLBACK(call_pick_up), - NULL); + G_CALLBACK(call_pick_up), + NULL); gtk_widget_show(menu_items); } @@ -1267,8 +1282,8 @@ show_popup_menu(GtkWidget *my_widget, GdkEventButton *event) gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_items), image); gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items); g_signal_connect(G_OBJECT(menu_items), "activate", - G_CALLBACK(call_hang_up), - NULL); + G_CALLBACK(call_hang_up), + NULL); gtk_widget_show(menu_items); } @@ -1278,20 +1293,20 @@ show_popup_menu(GtkWidget *my_widget, GdkEventButton *event) gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menu_items), (selectedCall->_state == CALL_STATE_HOLD)); g_signal_connect(G_OBJECT(menu_items), "activate", - G_CALLBACK(call_hold), - NULL); + G_CALLBACK(call_hold), + NULL); gtk_widget_show(menu_items); } if (record) { GtkWidget *menu_items = gtk_image_menu_item_new_with_mnemonic(_("_Record")); GtkWidget *image = gtk_image_new_from_stock(GTK_STOCK_MEDIA_RECORD, - GTK_ICON_SIZE_MENU); + GTK_ICON_SIZE_MENU); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_items), image); gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items); g_signal_connect(G_OBJECT(menu_items), "activate", - G_CALLBACK(call_record), - NULL); + G_CALLBACK(call_record), + NULL); gtk_widget_show(menu_items); } @@ -1312,8 +1327,8 @@ show_popup_menu(GtkWidget *my_widget, GdkEventButton *event) gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_items), image); gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items); g_signal_connect(G_OBJECT(menu_items), "activate", - G_CALLBACK(call_im), - NULL); + G_CALLBACK(call_im), + NULL); gtk_widget_show(menu_items); } } @@ -1327,8 +1342,8 @@ show_popup_menu(GtkWidget *my_widget, GdkEventButton *event) gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_items), image); gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items); g_signal_connect(G_OBJECT(menu_items), "activate", - G_CALLBACK(conference_hang_up), - NULL); + G_CALLBACK(conference_hang_up), + NULL); gtk_widget_show(menu_items); menu_items = gtk_check_menu_item_new_with_mnemonic(_("On _Hold")); @@ -1336,8 +1351,8 @@ show_popup_menu(GtkWidget *my_widget, GdkEventButton *event) gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menu_items), (selectedConf->_state == CONFERENCE_STATE_HOLD ? TRUE : FALSE)); g_signal_connect(G_OBJECT(menu_items), "activate", - G_CALLBACK(conference_hold), - NULL); + G_CALLBACK(conference_hold), + NULL); gtk_widget_show(menu_items); } } @@ -1351,17 +1366,15 @@ show_popup_menu(GtkWidget *my_widget, GdkEventButton *event) void show_popup_menu_history(GtkWidget *my_widget, GdkEventButton *event) { - DEBUG("UIManager: Show popup menu history"); - gboolean pickup = FALSE; - gboolean remove = FALSE; + gboolean add_remove_button = FALSE; gboolean edit = FALSE; gboolean accounts = FALSE; - callable_obj_t * selectedCall = calltab_get_selected_call(history); + callable_obj_t * selectedCall = calltab_get_selected_call(history_tab); if (selectedCall) { - remove = TRUE; + add_remove_button = TRUE; pickup = TRUE; edit = TRUE; accounts = TRUE; @@ -1384,15 +1397,15 @@ show_popup_menu_history(GtkWidget *my_widget, GdkEventButton *event) if (edit) { GtkWidget *menu_items = gtk_image_menu_item_new_from_stock(GTK_STOCK_EDIT, - get_accel_group()); + get_accel_group()); gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items); g_signal_connect(G_OBJECT(menu_items), "activate", G_CALLBACK(edit_number_cb), selectedCall); gtk_widget_show(menu_items); } - if (remove) { + if (add_remove_button) { GtkWidget *menu_items = gtk_image_menu_item_new_from_stock(GTK_STOCK_DELETE, - get_accel_group()); + get_accel_group()); gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_items); g_signal_connect(G_OBJECT(menu_items), "activate", G_CALLBACK(remove_from_history), NULL); gtk_widget_show(menu_items); @@ -1408,8 +1421,7 @@ show_popup_menu_history(GtkWidget *my_widget, GdkEventButton *event) void show_popup_menu_contacts(GtkWidget *my_widget, GdkEventButton *event) { - callable_obj_t * selectedCall = calltab_get_selected_call(contacts); - + callable_obj_t * selectedCall = calltab_get_selected_call(contacts_tab); GtkWidget *menu = gtk_menu_new(); @@ -1422,7 +1434,7 @@ show_popup_menu_contacts(GtkWidget *my_widget, GdkEventButton *event) gtk_widget_show(new_call); GtkWidget *edit = gtk_image_menu_item_new_from_stock(GTK_STOCK_EDIT, - get_accel_group()); + get_accel_group()); gtk_menu_shell_append(GTK_MENU_SHELL(menu), edit); g_signal_connect(edit, "activate", G_CALLBACK(edit_number_cb), selectedCall); gtk_widget_show(edit); @@ -1442,13 +1454,13 @@ ok_cb(GtkWidget *widget UNUSED, gpointer userdata) // Create the new call callable_obj_t *modified_call = create_new_call(CALL, CALL_STATE_DIALING, "", original->_accountID, - original->_peer_name, new_number); + original->_peer_name, new_number); // Update the internal data structure and the GUI - calllist_add_call(current_calls, modified_call); - calltree_add_call(current_calls, modified_call, NULL); + calllist_add_call(current_calls_tab, modified_call); + calltree_add_call(current_calls_tab, modified_call, NULL); sflphone_place_call(modified_call); - calltree_display(current_calls); + calltree_display(current_calls_tab); // Close the contextual menu gtk_widget_destroy(edit_dialog_); @@ -1472,7 +1484,7 @@ show_edit_number(callable_obj_t *call) g_signal_connect(G_OBJECT(edit_dialog_), "delete-event", G_CALLBACK(on_delete), NULL); - GtkWidget *hbox = gtk_hbox_new(FALSE, 0); + GtkWidget *hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(edit_dialog_))), hbox, TRUE, TRUE, 0); // Set the number to be edited @@ -1489,7 +1501,7 @@ show_edit_number(callable_obj_t *call) // Set a custom image for the button GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file_at_scale(ICONS_DIR "/outgoing.svg", 32, 32, - TRUE, NULL); + TRUE, NULL); GtkWidget *image = gtk_image_new_from_pixbuf(pixbuf); GtkWidget *ok = gtk_button_new(); gtk_button_set_image(GTK_BUTTON(ok), image); @@ -1506,11 +1518,14 @@ create_waiting_icon() { GtkWidget * waiting_icon = gtk_image_menu_item_new_with_label(""); struct stat st; + if (!stat(ICONS_DIR "/wait-on.gif", &st)) gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(waiting_icon), - gtk_image_new_from_animation(gdk_pixbuf_animation_new_from_file( - ICONS_DIR "/wait-on.gif", NULL))); - gtk_menu_item_set_right_justified(GTK_MENU_ITEM(waiting_icon), TRUE); + gtk_image_new_from_animation(gdk_pixbuf_animation_new_from_file( + ICONS_DIR "/wait-on.gif", NULL))); + + /* Deprecated: + * gtk_menu_item_set_right_justified(GTK_MENU_ITEM(waiting_icon), TRUE); */ return waiting_icon; } @@ -1548,38 +1563,39 @@ create_toolbar_actions(GtkUIManager *ui_manager) toolbar_ = gtk_ui_manager_get_widget(ui_manager, "/ToolbarActions"); holdToolbar_ = gtk_ui_manager_get_widget(ui_manager, - "/ToolbarActions/OnHoldToolbar"); + "/ToolbarActions/OnHoldToolbar"); offHoldToolbar_ = gtk_ui_manager_get_widget(ui_manager, - "/ToolbarActions/OffHoldToolbar"); + "/ToolbarActions/OffHoldToolbar"); transferToolbar_ = gtk_ui_manager_get_widget(ui_manager, - "/ToolbarActions/TransferToolbar"); + "/ToolbarActions/TransferToolbar"); voicemailAction_ = gtk_ui_manager_get_action(ui_manager, - "/ToolbarActions/Voicemail"); + "/ToolbarActions/Voicemail"); voicemailToolbar_ = gtk_ui_manager_get_widget(ui_manager, - "/ToolbarActions/VoicemailToolbar"); + "/ToolbarActions/VoicemailToolbar"); newCallWidget_ = gtk_ui_manager_get_widget(ui_manager, - "/ToolbarActions/NewCallToolbar"); + "/ToolbarActions/NewCallToolbar"); pickUpWidget_ = gtk_ui_manager_get_widget(ui_manager, - "/ToolbarActions/PickUpToolbar"); + "/ToolbarActions/PickUpToolbar"); hangUpWidget_ = gtk_ui_manager_get_widget(ui_manager, - "/ToolbarActions/HangUpToolbar"); + "/ToolbarActions/HangUpToolbar"); recordWidget_ = gtk_ui_manager_get_widget(ui_manager, - "/ToolbarActions/RecordToolbar"); + "/ToolbarActions/RecordToolbar"); imToolbar_ = gtk_ui_manager_get_widget(ui_manager, - "/ToolbarActions/InstantMessagingToolbar"); + "/ToolbarActions/InstantMessagingToolbar"); historyButton_ = gtk_ui_manager_get_widget(ui_manager, - "/ToolbarActions/HistoryToolbar"); + "/ToolbarActions/HistoryToolbar"); playRecordWidget_ = gtk_ui_manager_get_widget(ui_manager, - "/ToolbarActions/StartPlaybackRecordToolbar"); + "/ToolbarActions/StartPlaybackRecordToolbar"); stopRecordWidget_ = gtk_ui_manager_get_widget(ui_manager, - "/ToolbarActions/StopPlaybackRecordToolbar"); + "/ToolbarActions/StopPlaybackRecordToolbar"); + if (addrbook) contactButton_ = gtk_ui_manager_get_widget(ui_manager, "/ToolbarActions/AddressbookToolbar"); // Set the handler ID for the transfer transferButtonConnId_ = g_signal_connect(G_OBJECT(transferToolbar_), "toggled", G_CALLBACK(call_transfer_cb), NULL); recordButtonConnId_ = g_signal_connect(G_OBJECT(recordWidget_), "toggled", G_CALLBACK(call_record), NULL); - active_calltree = current_calls; + active_calltree_tab = current_calls_tab; return toolbar_; } diff --git a/daemon/src/plug-in/test/pluginTest.cpp b/gnome/src/unused.h similarity index 62% rename from daemon/src/plug-in/test/pluginTest.cpp rename to gnome/src/unused.h index 584f151d744b47f8b1883767e0621f10ec7ea02d..24a0ac2e40553a92badabed036fdb285057ee365 100644 --- a/daemon/src/plug-in/test/pluginTest.cpp +++ b/gnome/src/unused.h @@ -1,6 +1,6 @@ /* - * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Savoir-Faire Linux Inc. - * Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com> + * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. + * Author: Tristan Matthews <tristan.matthews@savoirfairelinux.com> * * 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 @@ -28,36 +28,8 @@ * as that of the covered work. */ -#include "plugin.h" +#ifndef UNUSED_H_ -#define MAJOR_VERSION 1 -#define MINOR_VERSION 0 +#define UNUSED __attribute__((__unused__)) -class PluginTest : public Plugin -{ - - public: - PluginTest (const std::string &name) - :Plugin (name) { - } - - virtual int initFunc (PluginInfo **info) { - - (*info)->_plugin = this; - (*info)->_major_version = MAJOR_VERSION; - (*info)->_minor_version = MINOR_VERSION; - (*info)->_name = getPluginName(); - - return 0; - } -}; - -extern "C" Plugin* createPlugin (void) -{ - return new PluginTest ("mytest"); -} - -extern "C" void destroyPlugin (Plugin *p) -{ - delete p; -} +#endif /* UNUSED_H_ */ diff --git a/gnome/src/widget/Makefile.am b/gnome/src/widget/Makefile.am index 7d67024bd31d970a0a517caabb678ef8b795747e..1c84e2fedbb4b13ea4a7279b34f5337ece446e9c 100644 --- a/gnome/src/widget/Makefile.am +++ b/gnome/src/widget/Makefile.am @@ -2,23 +2,13 @@ include ../../globals.mak noinst_LTLIBRARIES = libwidget.la -libwidget_la_SOURCES = \ - gtkscrollbook.c \ - gtkscrollbook.h \ - minidialog.h \ - minidialog.c \ - imwidget.c \ - imwidget.h +libwidget_la_SOURCES = minidialog.h minidialog.c imwidget.c imwidget.h libwidget_la_LDFLAGS = $(DBUSGLIB_LDFLAGS) $(LIBNOTIFY_LDFLAGS) \ - $(GTK_LDFLAGS) $(GLIB_LDFLAGS) $(WEBKIT_LDFLAGS) $(LIBGNOMEUI_LDFLAGS) \ - $(GNOMEDOCUTILS_LDFLAGS) + $(GTK_LDFLAGS) $(GLIB_LDFLAGS) $(WEBKIT_LDFLAGS) libwidget_la_LIBADD = $(DBUSGLIB_LIBS) $(LIBNOTIFY_LIBS) \ - $(GTK_LIBS) $(GLIB_LIBS) $(WEBKIT_LIBS) $(LIBGNOMEUI_LIBS) \ - $(GNOMEDOCUTILS_LIBS) + $(GTK_LIBS) $(GLIB_LIBS) $(WEBKIT_LIBS) libwidget_la_CFLAGS = $(DBUSGLIB_CFLAGS) $(LIBNOTIFY_CFLAGS) \ - $(GTK_CFLAGS) $(GLIB_CFLAGS) $(WEBKIT_CFLAGS) $(LIBEBOOK_CFLAGS) \ - $(LIBEDATASERVER_CFLAGS) $(LIBEDATASERVERUI_CFLAGS) $(LIBGNOMEUI_CFLAGS) \ - $(GNOMEDOCUTILS_CFLAGS) + $(GTK_CFLAGS) $(GLIB_CFLAGS) $(WEBKIT_CFLAGS) diff --git a/gnome/src/widget/gtkscrollbook.c b/gnome/src/widget/gtkscrollbook.c deleted file mode 100644 index 9c118a587011adc2aab4a5985fa0a1c134b871ca..0000000000000000000000000000000000000000 --- a/gnome/src/widget/gtkscrollbook.c +++ /dev/null @@ -1,272 +0,0 @@ -/* - * @file gtkscrollbook.c GTK+ Scrolling notebook widget - * @ingroup pidgin - */ - -/* pidgin - * - * Pidgin is the legal property of its developers, whose names are too numerous - * to list here. Please refer to the COPYRIGHT file distributed with this - * source distribution. - * - * 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA - */ - -#include "gtkscrollbook.h" -#include "sflphone_const.h" - -static void pidgin_scroll_book_init (PidginScrollBook *scroll_book); -static void pidgin_scroll_book_class_init (PidginScrollBookClass *klass); -static void pidgin_scroll_book_forall (GtkContainer *c, - gboolean include_internals, - GtkCallback callback, - gpointer user_data); - -GType -pidgin_scroll_book_get_type (void) -{ - static GType scroll_book_type = 0; - - if (!scroll_book_type) { - static const GTypeInfo scroll_book_info = { - sizeof (PidginScrollBookClass), - NULL, /* base_init */ - NULL, /* base_finalize */ - (GClassInitFunc) pidgin_scroll_book_class_init, - NULL, /* class_finalize */ - NULL, /* class_data */ - sizeof (PidginScrollBook), - 0, - (GInstanceInitFunc) pidgin_scroll_book_init, - NULL /* value_table */ - }; - - scroll_book_type = g_type_register_static (GTK_TYPE_VBOX, - "PidginScrollBook", - &scroll_book_info, - 0); - } - - return scroll_book_type; -} - -static gboolean -scroll_left_cb (PidginScrollBook *scroll_book) -{ - int index = gtk_notebook_get_current_page (GTK_NOTEBOOK (scroll_book->notebook)); - - if (index > 0) - gtk_notebook_set_current_page (GTK_NOTEBOOK (scroll_book->notebook), index - 1); - - return TRUE; -} - -static gboolean -scroll_right_cb (PidginScrollBook *scroll_book) -{ - int index = gtk_notebook_get_current_page (GTK_NOTEBOOK (scroll_book->notebook)); - int count = gtk_notebook_get_n_pages (GTK_NOTEBOOK (scroll_book->notebook)); - - if (index + 1 < count) - gtk_notebook_set_current_page (GTK_NOTEBOOK (scroll_book->notebook), index + 1); - - return TRUE; -} - -static void -refresh_scroll_box (PidginScrollBook *scroll_book, int index, int count) -{ - gtk_widget_show_all (GTK_WIDGET (scroll_book)); - - if (count < 1) - gtk_widget_hide_all (scroll_book->hbox); - else { - gtk_widget_show_all (scroll_book->hbox); - - if (count == 1) { - gtk_widget_hide (scroll_book->label); - gtk_widget_hide (scroll_book->left_arrow); - gtk_widget_hide (scroll_book->right_arrow); - } - } - - char *label = g_strdup_printf ("<span size='smaller' weight='bold'>(%d/%d)</span>", index+1, count); - gtk_label_set_markup (GTK_LABEL (scroll_book->label), label); - g_free (label); - - gtk_widget_set_sensitive (scroll_book->left_arrow, index != 0); - gtk_widget_set_sensitive (scroll_book->right_arrow, index + 1 != count); -} - - -static void -page_count_change_cb (PidginScrollBook *scroll_book) -{ - int index = gtk_notebook_get_current_page (GTK_NOTEBOOK (scroll_book->notebook)); - int count = gtk_notebook_get_n_pages (GTK_NOTEBOOK (scroll_book->notebook)); - refresh_scroll_box (scroll_book, index, count); -} - -static gboolean -scroll_close_cb (PidginScrollBook *scroll_book) -{ - gtk_widget_destroy (gtk_notebook_get_nth_page (GTK_NOTEBOOK (scroll_book->notebook), gtk_notebook_get_current_page (GTK_NOTEBOOK (scroll_book->notebook)))); - return FALSE; -} - -static void -switch_page_cb (GtkNotebook *notebook UNUSED, GtkNotebookPage *page UNUSED, guint page_num, PidginScrollBook *scroll_book) -{ - int count = gtk_notebook_get_n_pages (GTK_NOTEBOOK (scroll_book->notebook)); - refresh_scroll_box (scroll_book, page_num, count); -} - -static void -pidgin_scroll_book_add (GtkContainer *container, GtkWidget *widget) -{ - PidginScrollBook *scroll_book; - - g_return_if_fail (GTK_IS_WIDGET (widget)); - g_return_if_fail (gtk_widget_get_parent(widget) == NULL); - - scroll_book = PIDGIN_SCROLL_BOOK (container); - scroll_book->children = g_list_append (scroll_book->children, widget); - gtk_widget_show (widget); - gtk_notebook_append_page (GTK_NOTEBOOK (scroll_book->notebook), widget, NULL); - page_count_change_cb (PIDGIN_SCROLL_BOOK (container)); -} - -static void -pidgin_scroll_book_remove (GtkContainer *container, GtkWidget *widget) -{ - g_return_if_fail (GTK_IS_WIDGET (widget)); - - PidginScrollBook *scroll_book = PIDGIN_SCROLL_BOOK (container); - scroll_book->children = g_list_remove (scroll_book->children, widget); - - int page = gtk_notebook_page_num (GTK_NOTEBOOK (PIDGIN_SCROLL_BOOK (container)->notebook), widget); - if (page >= 0) - gtk_notebook_remove_page (GTK_NOTEBOOK (PIDGIN_SCROLL_BOOK (container)->notebook), page); -} - -static void -pidgin_scroll_book_forall (GtkContainer *container, - gboolean include_internals, - GtkCallback callback, - gpointer callback_data) -{ - g_return_if_fail (GTK_IS_CONTAINER (container)); - - PidginScrollBook *scroll_book = PIDGIN_SCROLL_BOOK (container); - - if (include_internals) { - (*callback) (scroll_book->hbox, callback_data); - (*callback) (scroll_book->notebook, callback_data); - } -} - -static void -pidgin_scroll_book_class_init (PidginScrollBookClass *klass) -{ - GtkContainerClass *container_class = (GtkContainerClass*) klass; - - container_class->add = pidgin_scroll_book_add; - container_class->remove = pidgin_scroll_book_remove; - container_class->forall = pidgin_scroll_book_forall; -} - -static gboolean -close_button_left_cb (GtkWidget *widget UNUSED, GdkEventCrossing *event, GtkLabel *label) -{ - static GdkCursor *ptr = NULL; - - if (ptr == NULL) { - ptr = gdk_cursor_new (GDK_LEFT_PTR); - } - - gtk_label_set_markup (label, "×"); - gdk_window_set_cursor (event->window, ptr); - return FALSE; -} - -static gboolean -close_button_entered_cb (GtkWidget *widget UNUSED, GdkEventCrossing *event, GtkLabel *label) -{ - static GdkCursor *hand = NULL; - - if (hand == NULL) { - hand = gdk_cursor_new (GDK_HAND2); - } - - gtk_label_set_markup (label, "<u>×</u>"); - gdk_window_set_cursor (event->window, hand); - return FALSE; -} - -static void -pidgin_scroll_book_init (PidginScrollBook *scroll_book) -{ - GtkWidget *eb; - GtkWidget *close_button; - - scroll_book->hbox = gtk_hbox_new (FALSE, 0); - - /* Close */ - eb = gtk_event_box_new(); - gtk_box_pack_end (GTK_BOX (scroll_book->hbox), eb, FALSE, FALSE, 0); - gtk_event_box_set_visible_window (GTK_EVENT_BOX (eb), FALSE); - gtk_widget_set_events (eb, GDK_ENTER_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK); - close_button = gtk_label_new ("×"); - g_signal_connect (G_OBJECT (eb), "enter-notify-event", G_CALLBACK (close_button_entered_cb), close_button); - g_signal_connect (G_OBJECT (eb), "leave-notify-event", G_CALLBACK (close_button_left_cb), close_button); - gtk_container_add (GTK_CONTAINER (eb), close_button); - g_signal_connect_swapped (G_OBJECT (eb), "button-press-event", G_CALLBACK (scroll_close_cb), scroll_book); - - /* Right arrow */ - eb = gtk_event_box_new(); - gtk_box_pack_end (GTK_BOX (scroll_book->hbox), eb, FALSE, FALSE, 0); - scroll_book->right_arrow = gtk_arrow_new (GTK_ARROW_RIGHT, GTK_SHADOW_NONE); - gtk_container_add (GTK_CONTAINER (eb), scroll_book->right_arrow); - g_signal_connect_swapped (G_OBJECT (eb), "button-press-event", G_CALLBACK (scroll_right_cb), scroll_book); - - /* Count */ - scroll_book->label = gtk_label_new (NULL); - gtk_box_pack_end (GTK_BOX (scroll_book->hbox), scroll_book->label, FALSE, FALSE, 0); - - /* Left arrow */ - eb = gtk_event_box_new(); - gtk_box_pack_end (GTK_BOX (scroll_book->hbox), eb, FALSE, FALSE, 0); - scroll_book->left_arrow = gtk_arrow_new (GTK_ARROW_LEFT, GTK_SHADOW_NONE); - gtk_container_add (GTK_CONTAINER (eb), scroll_book->left_arrow); - g_signal_connect_swapped (G_OBJECT (eb), "button-press-event", G_CALLBACK (scroll_left_cb), scroll_book); - - gtk_box_pack_start (GTK_BOX (scroll_book), scroll_book->hbox, FALSE, FALSE, 0); - - scroll_book->notebook = gtk_notebook_new(); - gtk_notebook_set_show_tabs (GTK_NOTEBOOK (scroll_book->notebook), FALSE); - gtk_notebook_set_show_border (GTK_NOTEBOOK (scroll_book->notebook), FALSE); - - gtk_box_pack_start (GTK_BOX (scroll_book), scroll_book->notebook, TRUE, TRUE, 0); - - g_signal_connect_swapped (G_OBJECT (scroll_book->notebook), "remove", G_CALLBACK (page_count_change_cb), scroll_book); - g_signal_connect (G_OBJECT (scroll_book->notebook), "switch-page", G_CALLBACK (switch_page_cb), scroll_book); - gtk_widget_show_all (scroll_book->notebook); -} - -GtkWidget * -pidgin_scroll_book_new() -{ - return g_object_new (PIDGIN_TYPE_SCROLL_BOOK, NULL); -} diff --git a/gnome/src/widget/gtkscrollbook.h b/gnome/src/widget/gtkscrollbook.h deleted file mode 100644 index a012f7825923bb04a5ccf5a8e39eebfac2729627..0000000000000000000000000000000000000000 --- a/gnome/src/widget/gtkscrollbook.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * @file gtkscrollbook GTK+ Scrolling notebook Widget - * @ingroup pidgin - */ - -/* pidgin - * - * Pidgin is the legal property of its developers, whose names are too numerous - * to list here. Please refer to the COPYRIGHT file distributed with this - * source distribution. - * - * 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA - */ - -#ifndef __PIDGIN_SCROLL_BOOK_H__ -#define __PIDGIN_SCROLL_BOOK_H__ - -#include <gtk/gtk.h> - -G_BEGIN_DECLS - -#define PIDGIN_TYPE_SCROLL_BOOK (pidgin_scroll_book_get_type ()) -#define PIDGIN_SCROLL_BOOK(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), PIDGIN_TYPE_SCROLL_BOOK, PidginScrollBook)) -#define PIDGIN_SCROLL_BOOK_CLASS(vtable) (G_TYPE_CHECK_CLASS_CAST ((vtable), PIDGIN_TYPE_SCROLL_BOOK, PidginScrollBookClass)) -#define PIDGIN_IS_SCROLL_BOOK(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), PIDGIN_TYPE_SCROLL_BOOK)) -#define PIDGIN_IS_SCROLL_BOOK_CLASS(vtable) (G_TYPE_CHECK_CLASS_TYPE ((vtable), PIDGIN_TYPE_SCROLL_BOOK)) -#define PIDGIN_SCROLL_BOOK_GET_CLASS(inst) (G_TYPE_INSTANCE_GET_CLASS ((inst), PIDGIN_TYPE_SCROLL_BOOK, PidginScrollBookClass)) - -typedef struct _PidginScrollBook PidginScrollBook; -typedef struct _PidginScrollBookClass PidginScrollBookClass; - -struct _PidginScrollBook { - GtkVBox parent_instance; - - GtkWidget *notebook; - GtkWidget *hbox; - GtkWidget *label; - GtkWidget *left_arrow; - GtkWidget *right_arrow; - GList *children; - - /* Padding for future expansion */ - void (*_gtk_reserved1) (void); - void (*_gtk_reserved2) (void); - void (*_gtk_reserved3) (void); - -}; - - -struct _PidginScrollBookClass { - GtkContainerClass parent_class; - - /* Padding for future expansion */ - void (*_gtk_reserved0) (void); - void (*_gtk_reserved1) (void); - void (*_gtk_reserved2) (void); - void (*_gtk_reserved3) (void); -}; - - -GType pidgin_scroll_book_get_type (void) G_GNUC_CONST; -GtkWidget *pidgin_scroll_book_new (void); - -G_END_DECLS - -#endif /* __PIDGIN_SCROLL_BOOK_H__ */ diff --git a/gnome/src/widget/imwidget.c b/gnome/src/widget/imwidget.c index fd1087a5a77618355599ed26071d225d83421119..adb83b4473d9da8a702b4cb18347029ff1a5f96c 100644 --- a/gnome/src/widget/imwidget.c +++ b/gnome/src/widget/imwidget.c @@ -27,39 +27,41 @@ * as that of the covered work. */ -#include <imwindow.h> +#include "imwindow.h" +#include "logger.h" #include "imwidget.h" -#include <icons/icon_factory.h> -#include <contacts/calltab.h> -#include <contacts/conferencelist.h> +#include "dbus.h" +#include "unused.h" +#include "icons/icon_factory.h" +#include "contacts/calltab.h" +#include "contacts/conferencelist.h" #include <JavaScriptCore/JavaScript.h> #include <gdk/gdkkeysyms.h> #include <gtk/gtk.h> -#include <assert.h> -#include "sflphone_const.h" #define WEBKIT_DIR "file://" DATA_DIR "/webkit/" static void -on_frame_loading_done (GObject *gobject UNUSED, GParamSpec *pspec UNUSED, gpointer user_data) +on_frame_loading_done(GObject *gobject UNUSED, GParamSpec *pspec UNUSED, gpointer user_data) { - IMWidget *im = IM_WIDGET (user_data); + IMWidget *im = IM_WIDGET(user_data); if (!im->first_message || !im->first_message_from) return; - switch (webkit_web_frame_get_load_status (WEBKIT_WEB_FRAME (im->web_frame))) { + switch (webkit_web_frame_get_load_status(WEBKIT_WEB_FRAME(im->web_frame))) { case WEBKIT_LOAD_FIRST_VISUALLY_NON_EMPTY_LAYOUT: case WEBKIT_LOAD_PROVISIONAL: case WEBKIT_LOAD_COMMITTED: break; case WEBKIT_LOAD_FINISHED: - if (calllist_get_call (current_calls, im->call_id)) - im_widget_add_message (im, im->first_message_from, im->first_message, 0); - if (conferencelist_get (current_calls, im->call_id)) - im_widget_add_message (im, im->first_message_from, im->first_message, 0); + if (calllist_get_call(current_calls_tab, im->call_id)) + im_widget_add_message(im, im->first_message_from, im->first_message, 0); + + if (conferencelist_get(current_calls_tab, im->call_id)) + im_widget_add_message(im, im->first_message_from, im->first_message, 0); g_free(im->first_message); g_free(im->first_message_from); @@ -73,7 +75,7 @@ on_frame_loading_done (GObject *gobject UNUSED, GParamSpec *pspec UNUSED, gpoint } static gchar * -escape_single_quotes (const gchar *message) +escape_single_quotes(const gchar *message) { gchar **ptr_token = g_strsplit(message, "'", 0); gchar *string = g_strjoinv("\\'", ptr_token); @@ -83,14 +85,14 @@ escape_single_quotes (const gchar *message) } static gchar* -im_widget_add_message_time () +im_widget_add_message_time() { time_t now; char str[100]; /* Compute the current time */ - time (&now); - const struct tm* ptr = localtime (&now); + time(&now); + const struct tm* ptr = localtime(&now); /* Get the time of the message. Format: HH:MM::SS */ strftime(str, sizeof(str), "%R", (const struct tm *) ptr); @@ -98,32 +100,32 @@ im_widget_add_message_time () } void -im_widget_add_message (IMWidget *im, const gchar *from, const gchar *message, gint level) +im_widget_add_message(IMWidget *im, const gchar *from, const gchar *message, gint level) { - assert(im); + g_assert(im); /* Compute the date the message was sent */ - gchar *msgtime = im_widget_add_message_time (); + gchar *msgtime = im_widget_add_message_time(); gchar *css_class = (level == MESSAGE_LEVEL_ERROR) ? "error" : ""; - gchar *message_escaped = escape_single_quotes (message); + gchar *message_escaped = escape_single_quotes(message); /* Prepare and execute the Javascript code */ - gchar *script = g_strdup_printf ("add_message('%s', '%s', '%s', '%s');", message_escaped, from, css_class, msgtime); - webkit_web_view_execute_script (WEBKIT_WEB_VIEW (im->web_view), script); + gchar *script = g_strdup_printf("add_message('%s', '%s', '%s', '%s');", message_escaped, from, css_class, msgtime); + webkit_web_view_execute_script(WEBKIT_WEB_VIEW(im->web_view), script); /* Mark it as used */ im->containText = TRUE; /* Cleanup */ - g_free (script); - g_free (message_escaped); - g_free (msgtime); + g_free(script); + g_free(message_escaped); + g_free(msgtime); } static gboolean -web_view_nav_requested_cb ( +web_view_nav_requested_cb( WebKitWebView *web_view UNUSED, WebKitWebFrame *frame UNUSED, WebKitNetworkRequest *request, @@ -131,56 +133,56 @@ web_view_nav_requested_cb ( WebKitWebPolicyDecision *policy_decision, gpointer user_data UNUSED) { - const gchar *uri = webkit_network_request_get_uri (request); + const gchar *uri = webkit_network_request_get_uri(request); /* Always allow files we are serving ourselves. */ - if (!strncmp (uri, WEBKIT_DIR, sizeof (WEBKIT_DIR) - 1)) { - webkit_web_policy_decision_use (policy_decision); + if (!strncmp(uri, WEBKIT_DIR, sizeof(WEBKIT_DIR) - 1)) { + webkit_web_policy_decision_use(policy_decision); } else { /* Running a system command to open the URL in the user's default browser */ - gchar *cmd = g_strdup_printf ("x-www-browser %s", uri); + gchar *cmd = g_strdup_printf("x-www-browser %s", uri); - if (system (cmd) == -1) - ERROR ("InstantMessaging: Error: executing command %s", cmd); + if (system(cmd) == -1) + ERROR("InstantMessaging: Error: executing command %s", cmd); - webkit_web_policy_decision_ignore (policy_decision); - g_free (cmd); + webkit_web_policy_decision_ignore(policy_decision); + g_free(cmd); } return TRUE; } static gboolean -on_Textview_changed (GtkWidget *widget UNUSED, GdkEventKey *event, gpointer user_data) +on_Textview_changed(GtkWidget *widget UNUSED, GdkEventKey *event, gpointer user_data) { GtkTextIter start, end; /* Get all the text in the buffer */ IMWidget *im = user_data; - GtkTextBuffer *buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (im->textarea)); + GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(im->textarea)); /* Catch the keyboard events */ if (event->type == GDK_KEY_PRESS) { switch (event->keyval) { - case GDK_Return: - case GDK_KP_Enter: + case GDK_KEY_Return: + case GDK_KEY_KP_Enter: /* We want to send the message on pressing ENTER */ - if (gtk_text_buffer_get_char_count (buffer) != 0) { + if (gtk_text_buffer_get_char_count(buffer) != 0) { /* Fetch the string text */ - gtk_text_buffer_get_bounds (GTK_TEXT_BUFFER (buffer), &start, &end); - gchar *message = gtk_text_buffer_get_text (buffer, &start, &end, FALSE); + gtk_text_buffer_get_bounds(GTK_TEXT_BUFFER(buffer), &start, &end); + gchar *message = gtk_text_buffer_get_text(buffer, &start, &end, FALSE); /* Display our own message in the chat window */ - im_widget_add_message (im, "Me", message, MESSAGE_LEVEL_NORMAL); + im_widget_add_message(im, "Me", message, MESSAGE_LEVEL_NORMAL); /* Send the message to the peer */ - im_widget_send_message (im->call_id, message); + im_widget_send_message(im->call_id, message); /* Empty the buffer */ - gtk_text_buffer_delete (GTK_TEXT_BUFFER (buffer), &start, &end); + gtk_text_buffer_delete(GTK_TEXT_BUFFER(buffer), &start, &end); } @@ -192,100 +194,104 @@ on_Textview_changed (GtkWidget *widget UNUSED, GdkEventKey *event, gpointer user } void -im_widget_send_message (const gchar *id, const gchar *message) +im_widget_send_message(const gchar *id, const gchar *message) { - callable_obj_t *im_widget_call = calllist_get_call (current_calls, id); - conference_obj_t *im_widget_conf = conferencelist_get (current_calls, id); + callable_obj_t *im_widget_call = calllist_get_call(current_calls_tab, id); + conference_obj_t *im_widget_conf = conferencelist_get(current_calls_tab, id); /* If the call has been hungup, it is not anymore in the current_calls calltab */ - if (!im_widget_call) { - /* So try the history tab */ - im_widget_call = calllist_get_call (history, id); - } + /* So try the history tab */ + if (!im_widget_call) + im_widget_call = calllist_get_call(history_tab, id); - if (im_widget_conf) { - dbus_send_text_message (id, message); - } else if (im_widget_call) { + if (im_widget_conf) + dbus_send_text_message(id, message); + else if (im_widget_call) { if (im_widget_call->_type == CALL && (im_widget_call->_state == CALL_STATE_CURRENT || im_widget_call->_state == CALL_STATE_HOLD || im_widget_call->_state == CALL_STATE_RECORD)) { /* Ship the message through D-Bus */ - dbus_send_text_message (id, message); + dbus_send_text_message(id, message); } else { /* Display an error message */ - im_widget_add_message (IM_WIDGET (im_widget_call->_im_widget), "sflphoned", "Oups, something went wrong! Unable to send text messages outside a call.", MESSAGE_LEVEL_ERROR); + im_widget_add_message(IM_WIDGET(im_widget_call->_im_widget), "sflphoned", "Oups, something went wrong! Unable to send text messages outside a call.", MESSAGE_LEVEL_ERROR); } } } static void -im_widget_class_init (IMWidgetClass *klass UNUSED) +im_widget_class_init(IMWidgetClass *klass UNUSED) { } static void -im_widget_init (IMWidget *im) +im_widget_init(IMWidget *im) { /* A text view to enable users to enter text */ - im->textarea = gtk_text_view_new (); + im->textarea = gtk_text_view_new(); /* The webkit widget to display the message */ im->web_view = webkit_web_view_new(); - GtkWidget *textscrollwin = gtk_scrolled_window_new (NULL, NULL); - GtkWidget *webscrollwin = gtk_scrolled_window_new (NULL, NULL); - im->info_bar = gtk_info_bar_new (); + GtkWidget *textscrollwin = gtk_scrolled_window_new(NULL, NULL); + GtkWidget *webscrollwin = gtk_scrolled_window_new(NULL, NULL); + im->info_bar = gtk_info_bar_new(); /* A bar with the entry text and the button to send the message */ - GtkWidget *hbox = gtk_hbox_new (FALSE, 10); - gtk_text_view_set_editable (GTK_TEXT_VIEW (im->textarea), TRUE); - gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (textscrollwin), GTK_POLICY_NEVER, GTK_POLICY_NEVER); - gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (webscrollwin), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); - gtk_widget_set_size_request (GTK_WIDGET (textscrollwin), -1, 20); - gtk_widget_set_size_request (GTK_WIDGET (im->textarea), -1, 20); - gtk_text_view_set_wrap_mode (GTK_TEXT_VIEW (im->textarea), GTK_WRAP_CHAR); + GtkWidget *box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10); + gtk_text_view_set_editable(GTK_TEXT_VIEW(im->textarea), TRUE); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(textscrollwin), GTK_POLICY_NEVER, GTK_POLICY_NEVER); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(webscrollwin), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); + gtk_widget_set_size_request(GTK_WIDGET(textscrollwin), -1, 20); + gtk_widget_set_size_request(GTK_WIDGET(im->textarea), -1, 20); + gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(im->textarea), GTK_WRAP_CHAR); // gtk_container_set_resize_mode(GTK_CONTAINER(im->textarea), GTK_RESIZE_PARENT); - gtk_container_add (GTK_CONTAINER (textscrollwin), im->textarea); - gtk_container_add (GTK_CONTAINER (webscrollwin), im->web_view); - gtk_container_add (GTK_CONTAINER (hbox), textscrollwin); - gtk_box_pack_start (GTK_BOX (im), im->info_bar, FALSE, FALSE, 2); - gtk_box_pack_start (GTK_BOX (im), webscrollwin, TRUE, TRUE, 5); - gtk_box_pack_end (GTK_BOX (im), hbox, FALSE, FALSE, 2); - g_signal_connect (im->web_view, "navigation-policy-decision-requested", G_CALLBACK (web_view_nav_requested_cb), NULL); - g_signal_connect (im->textarea, "key-press-event", G_CALLBACK (on_Textview_changed), im); + gtk_container_add(GTK_CONTAINER(textscrollwin), im->textarea); + gtk_container_add(GTK_CONTAINER(webscrollwin), im->web_view); + gtk_container_add(GTK_CONTAINER(box), textscrollwin); + gtk_box_pack_start(GTK_BOX(im), im->info_bar, FALSE, FALSE, 2); + gtk_box_pack_start(GTK_BOX(im), webscrollwin, TRUE, TRUE, 5); + gtk_box_pack_end(GTK_BOX(im), box, FALSE, FALSE, 2); + g_signal_connect(im->web_view, "navigation-policy-decision-requested", G_CALLBACK(web_view_nav_requested_cb), NULL); + g_signal_connect(im->textarea, "key-press-event", G_CALLBACK(on_Textview_changed), im); - im->web_frame = webkit_web_view_get_main_frame (WEBKIT_WEB_VIEW (im->web_view)); - im->js_context = webkit_web_frame_get_global_context (im->web_frame); - im->js_global = JSContextGetGlobalObject (im->js_context); - webkit_web_view_load_uri (WEBKIT_WEB_VIEW (im->web_view), "file://" DATA_DIR "/webkit/im/im.html"); + im->web_frame = webkit_web_view_get_main_frame(WEBKIT_WEB_VIEW(im->web_view)); + im->js_context = webkit_web_frame_get_global_context(im->web_frame); + im->js_global = JSContextGetGlobalObject(im->js_context); + webkit_web_view_load_uri(WEBKIT_WEB_VIEW(im->web_view), "file://" DATA_DIR "/webkit/im/im.html"); im->containText = FALSE; - g_signal_connect (G_OBJECT (im->web_frame), "notify", G_CALLBACK (on_frame_loading_done), im); + g_signal_connect(G_OBJECT(im->web_frame), "notify", G_CALLBACK(on_frame_loading_done), im); + /* See + * http://developer.gnome.org/gtk3/stable/GtkVBox.html#GtkVBox.description + */ + gtk_orientable_set_orientation (GTK_ORIENTABLE (im), + GTK_ORIENTATION_VERTICAL); } GType -im_widget_get_type (void) +im_widget_get_type(void) { static GType im_widget_type = 0; if (!im_widget_type) { static const GTypeInfo im_widget_info = { - sizeof (IMWidgetClass), + sizeof(IMWidgetClass), NULL, /* base_init */ NULL, /* base_finalize */ (GClassInitFunc) im_widget_class_init, NULL, /* class_finalize */ NULL, /* class_data */ - sizeof (IMWidget), + sizeof(IMWidget), 0, (GInstanceInitFunc) im_widget_init, NULL /* value_table */ }; - im_widget_type = g_type_register_static ( - GTK_TYPE_VBOX, + im_widget_type = g_type_register_static( + GTK_TYPE_BOX, "IMWidget", &im_widget_info, 0); @@ -296,10 +302,10 @@ im_widget_get_type (void) static GtkWidget* -conf_state_image_widget (conference_state_t state) +conf_state_image_widget(conference_state_t state) { switch (state) { - case CONFERENCE_STATE_ACTIVE_ATACHED: + case CONFERENCE_STATE_ACTIVE_ATTACHED: case CONFERENCE_STATE_ACTIVE_DETACHED: case CONFERENCE_STATE_ACTIVE_ATTACHED_RECORD: case CONFERENCE_STATE_ACTIVE_DETACHED_RECORD: @@ -312,7 +318,7 @@ conf_state_image_widget (conference_state_t state) } static GtkWidget* -call_state_image_widget (call_state_t state) +call_state_image_widget(call_state_t state) { switch (state) { case CALL_STATE_CURRENT: @@ -325,68 +331,69 @@ call_state_image_widget (call_state_t state) } static void -im_widget_infobar (IMWidget *im) +im_widget_infobar(IMWidget *im) { GtkWidget *infobar = im->info_bar; - GtkWidget *content_area = gtk_info_bar_get_content_area (GTK_INFO_BAR (infobar)); + GtkWidget *content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(infobar)); /* Fetch call/conference information */ - callable_obj_t *im_widget_call = calllist_get_call (current_calls, im->call_id); - conference_obj_t *im_widget_conf = conferencelist_get (current_calls, im->call_id); + callable_obj_t *im_widget_call = calllist_get_call(current_calls_tab, im->call_id); + conference_obj_t *im_widget_conf = conferencelist_get(current_calls_tab, im->call_id); /* Create the label widgets with the call information saved in the IM Widget struct */ gchar *msg1; if (im_widget_call) - msg1 = g_strdup_printf ("Calling %s %s", im_widget_call->_peer_number, im_widget_call->_peer_name); + msg1 = g_strdup_printf("Calling %s %s", im_widget_call->_peer_number, im_widget_call->_peer_name); else if (im_widget_conf) - msg1 = g_strdup_printf ("Conferencing"); + msg1 = g_strdup_printf("Conferencing"); else - msg1 = g_strdup (""); + msg1 = g_strdup(""); - GtkWidget *call_label = gtk_label_new (msg1); - g_free (msg1); + GtkWidget *call_label = gtk_label_new(msg1); + g_free(msg1); if (im_widget_call) - im->info_state = call_state_image_widget (im_widget_call->_state); + im->info_state = call_state_image_widget(im_widget_call->_state); if (im_widget_conf) - im->info_state = conf_state_image_widget (im_widget_conf->_state); + im->info_state = conf_state_image_widget(im_widget_conf->_state); - GtkWidget *logoUser = gtk_image_new_from_stock (GTK_STOCK_USER, GTK_ICON_SIZE_LARGE_TOOLBAR); + GtkWidget *logoUser = gtk_image_new_from_stock(GTK_STOCK_USER, GTK_ICON_SIZE_LARGE_TOOLBAR); /* Pack it all */ - gtk_container_add (GTK_CONTAINER (content_area), logoUser); - gtk_container_add (GTK_CONTAINER (content_area), call_label); - gtk_container_add (GTK_CONTAINER (content_area), im->info_state); + gtk_container_add(GTK_CONTAINER(content_area), logoUser); + gtk_container_add(GTK_CONTAINER(content_area), call_label); + gtk_container_add(GTK_CONTAINER(content_area), im->info_state); - gtk_info_bar_set_message_type (GTK_INFO_BAR (infobar), GTK_MESSAGE_INFO); + gtk_info_bar_set_message_type(GTK_INFO_BAR(infobar), GTK_MESSAGE_INFO); - gtk_widget_show (infobar); + gtk_widget_show(infobar); } -GtkWidget *im_widget_display (const gchar *id) +GtkWidget *im_widget_display(const gchar *id) { - IMWidget *imwidget = IM_WIDGET(g_object_new (IM_WIDGET_TYPE, NULL)); + IMWidget *imwidget = IM_WIDGET(g_object_new(IM_WIDGET_TYPE, NULL)); imwidget->call_id = id; - im_widget_infobar (imwidget); - im_window_add (GTK_WIDGET (imwidget)); + im_widget_infobar(imwidget); + im_window_add(imwidget); return GTK_WIDGET(imwidget); } void -im_widget_update_state (IMWidget *im, gboolean active) +im_widget_update_state(IMWidget *im, gboolean active) { if (!im) return; - gtk_widget_set_sensitive (im->info_state, active); + + gtk_widget_set_sensitive(im->info_state, active); if (active) { /* the call is in current state, so sflphone can send text messages */ - gtk_info_bar_set_message_type (GTK_INFO_BAR (im->info_bar), GTK_MESSAGE_INFO); + gtk_info_bar_set_message_type(GTK_INFO_BAR(im->info_bar), GTK_MESSAGE_INFO); } else if (im) { /* the call is over, we can't send text messages anymore */ - gtk_info_bar_set_message_type (GTK_INFO_BAR (im->info_bar), GTK_MESSAGE_WARNING); - gtk_widget_set_tooltip_text (im->info_state, "Call has terminated"); + gtk_info_bar_set_message_type(GTK_INFO_BAR(im->info_bar), GTK_MESSAGE_WARNING); + gtk_widget_set_tooltip_text(im->info_state, "Call has terminated"); } } diff --git a/gnome/src/widget/imwidget.h b/gnome/src/widget/imwidget.h index fd7722927006672df7ba08634f30a9719e7f7588..02226cbc7a511cf5761ff54d1279bf0ea4f559c5 100644 --- a/gnome/src/widget/imwidget.h +++ b/gnome/src/widget/imwidget.h @@ -53,7 +53,7 @@ typedef struct _IMWidget IMWidget; typedef struct _IMWidgetClass IMWidgetClass; struct _IMWidget { - GtkVBox parent_instance; + GtkBox parent_instance; /* Private */ GtkWidget *tab; @@ -71,7 +71,7 @@ struct _IMWidget { }; struct _IMWidgetClass { - GtkContainerClass parent_class; + GtkBoxClass parent_class; }; diff --git a/gnome/src/widget/minidialog.c b/gnome/src/widget/minidialog.c index 82b3385a62d3c963195ef49c27928cc5b5ba45d6..46de0379601c3fa128dbf11716d039d7260b6f31 100644 --- a/gnome/src/widget/minidialog.c +++ b/gnome/src/widget/minidialog.c @@ -24,43 +24,44 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA */ #include <gtk/gtk.h> +#include "unused.h" #include "sflphone_const.h" #include "minidialog.h" #define HIG_BOX_SPACE 6 #define LABEL_WIDTH 200 -static void pidgin_mini_dialog_init (PidginMiniDialog *self); -static void pidgin_mini_dialog_class_init (PidginMiniDialogClass *klass); +static void pidgin_mini_dialog_init(PidginMiniDialog *self); +static void pidgin_mini_dialog_class_init(PidginMiniDialogClass *klass); static gpointer pidgin_mini_dialog_parent_class = NULL; static void -pidgin_mini_dialog_class_intern_init (gpointer klass) +pidgin_mini_dialog_class_intern_init(gpointer klass) { - pidgin_mini_dialog_parent_class = g_type_class_peek_parent (klass); - pidgin_mini_dialog_class_init ( (PidginMiniDialogClass*) klass); + pidgin_mini_dialog_parent_class = g_type_class_peek_parent(klass); + pidgin_mini_dialog_class_init((PidginMiniDialogClass*) klass); } GType -pidgin_mini_dialog_get_type (void) +pidgin_mini_dialog_get_type(void) { static GType g_define_type_id = 0; if (g_define_type_id == 0) { static const GTypeInfo g_define_type_info = { - sizeof (PidginMiniDialogClass), + sizeof(PidginMiniDialogClass), (GBaseInitFunc) NULL, (GBaseFinalizeFunc) NULL, (GClassInitFunc) pidgin_mini_dialog_class_intern_init, (GClassFinalizeFunc) NULL, NULL, /* class_data */ - sizeof (PidginMiniDialog), + sizeof(PidginMiniDialog), 0, /* n_preallocs */ (GInstanceInitFunc) pidgin_mini_dialog_init, NULL, }; - g_define_type_id = g_type_register_static (GTK_TYPE_VBOX, + g_define_type_id = g_type_register_static(GTK_TYPE_BOX, "PidginMiniDialog", &g_define_type_info, 0); } @@ -89,11 +90,11 @@ typedef struct _PidginMiniDialogPrivate { ((PidginMiniDialogPrivate *) ((dialog)->priv)) PidginMiniDialog * -pidgin_mini_dialog_new (const gchar *title, - const gchar *description, - const gchar *icon_name) +pidgin_mini_dialog_new(const gchar *title, + const gchar *description, + const gchar *icon_name) { - PidginMiniDialog *mini_dialog = g_object_new (PIDGIN_TYPE_MINI_DIALOG, + PidginMiniDialog *mini_dialog = g_object_new(PIDGIN_TYPE_MINI_DIALOG, "title", title, "description", description, "icon-name", icon_name, @@ -103,24 +104,24 @@ pidgin_mini_dialog_new (const gchar *title, } void -pidgin_mini_dialog_set_title (PidginMiniDialog *mini_dialog, - const char *title) +pidgin_mini_dialog_set_title(PidginMiniDialog *mini_dialog, + const char *title) { - g_object_set (G_OBJECT (mini_dialog), "title", title, NULL); + g_object_set(G_OBJECT(mini_dialog), "title", title, NULL); } void -pidgin_mini_dialog_set_description (PidginMiniDialog *mini_dialog, - const char *description) +pidgin_mini_dialog_set_description(PidginMiniDialog *mini_dialog, + const char *description) { - g_object_set (G_OBJECT (mini_dialog), "description", description, NULL); + g_object_set(G_OBJECT(mini_dialog), "description", description, NULL); } void -pidgin_mini_dialog_set_icon_name (PidginMiniDialog *mini_dialog, - const char *icon_name) +pidgin_mini_dialog_set_icon_name(PidginMiniDialog *mini_dialog, + const char *icon_name) { - g_object_set (G_OBJECT (mini_dialog), "icon_name", icon_name, NULL); + g_object_set(G_OBJECT(mini_dialog), "icon_name", icon_name, NULL); } struct _mini_dialog_button_clicked_cb_data { @@ -130,221 +131,221 @@ struct _mini_dialog_button_clicked_cb_data { }; guint -pidgin_mini_dialog_get_num_children (PidginMiniDialog *mini_dialog) +pidgin_mini_dialog_get_num_children(PidginMiniDialog *mini_dialog) { return g_list_length(gtk_container_get_children(GTK_CONTAINER(mini_dialog->contents))); } static gboolean -idle_destroy_cb (GtkWidget *mini_dialog) +idle_destroy_cb(GtkWidget *mini_dialog) { - gtk_widget_destroy (mini_dialog); + gtk_widget_destroy(mini_dialog); return FALSE; } static void -mini_dialog_button_clicked_cb (GtkButton *button, - gpointer user_data) +mini_dialog_button_clicked_cb(GtkButton *button, + gpointer user_data) { struct _mini_dialog_button_clicked_cb_data *data = user_data; PidginMiniDialogPrivate *priv = - PIDGIN_MINI_DIALOG_GET_PRIVATE (data->mini_dialog); + PIDGIN_MINI_DIALOG_GET_PRIVATE(data->mini_dialog); /* Set up the destruction callback before calling the clicked callback, * so that if the mini-dialog gets destroyed during the clicked callback * the idle_destroy_cb is correctly removed by _finalize. */ priv->idle_destroy_cb_id = - g_idle_add ( (GSourceFunc) idle_destroy_cb, data->mini_dialog); + g_idle_add((GSourceFunc) idle_destroy_cb, data->mini_dialog); if (data->callback != NULL) - data->callback (data->mini_dialog, button, data->user_data); + data->callback(data->mini_dialog, button, data->user_data); } static void -mini_dialog_button_destroy_cb (GtkButton *button UNUSED, - gpointer user_data) +mini_dialog_button_destroy_cb(GtkButton *button UNUSED, + gpointer user_data) { struct _mini_dialog_button_clicked_cb_data *data = user_data; - g_free (data); + g_free(data); } void -pidgin_mini_dialog_add_button (PidginMiniDialog *self, - const char *text, - PidginMiniDialogCallback clicked_cb, - gpointer user_data) +pidgin_mini_dialog_add_button(PidginMiniDialog *self, + const char *text, + PidginMiniDialogCallback clicked_cb, + gpointer user_data) { - PidginMiniDialogPrivate *priv = PIDGIN_MINI_DIALOG_GET_PRIVATE (self); + PidginMiniDialogPrivate *priv = PIDGIN_MINI_DIALOG_GET_PRIVATE(self); struct _mini_dialog_button_clicked_cb_data *callback_data - = g_new0 (struct _mini_dialog_button_clicked_cb_data, 1); + = g_new0(struct _mini_dialog_button_clicked_cb_data, 1); GtkWidget *button = gtk_button_new(); - GtkWidget *label = gtk_label_new (NULL); + GtkWidget *label = gtk_label_new(NULL); char *button_text = - g_strdup_printf ("<span size=\"smaller\">%s</span>", text); + g_strdup_printf("<span size=\"smaller\">%s</span>", text); - gtk_label_set_markup_with_mnemonic (GTK_LABEL (label), button_text); - g_free (button_text); + gtk_label_set_markup_with_mnemonic(GTK_LABEL(label), button_text); + g_free(button_text); callback_data->mini_dialog = self; callback_data->callback = clicked_cb; callback_data->user_data = user_data; - g_signal_connect (G_OBJECT (button), "clicked", - (GCallback) mini_dialog_button_clicked_cb, callback_data); - g_signal_connect (G_OBJECT (button), "destroy", - (GCallback) mini_dialog_button_destroy_cb, callback_data); + g_signal_connect(G_OBJECT(button), "clicked", + (GCallback) mini_dialog_button_clicked_cb, callback_data); + g_signal_connect(G_OBJECT(button), "destroy", + (GCallback) mini_dialog_button_destroy_cb, callback_data); - gtk_misc_set_alignment (GTK_MISC (label), 0.5, 0.5); - gtk_container_add (GTK_CONTAINER (button), label); + gtk_misc_set_alignment(GTK_MISC(label), 0.5, 0.5); + gtk_container_add(GTK_CONTAINER(button), label); - gtk_box_pack_end (GTK_BOX (priv->buttons), button, FALSE, FALSE, - 0); - gtk_widget_show_all (GTK_WIDGET (button)); + gtk_box_pack_end(GTK_BOX(priv->buttons), button, FALSE, FALSE, + 0); + gtk_widget_show_all(GTK_WIDGET(button)); } static void -pidgin_mini_dialog_get_property (GObject *object, - guint property_id, - GValue *value, - GParamSpec *pspec) +pidgin_mini_dialog_get_property(GObject *object, + guint property_id, + GValue *value, + GParamSpec *pspec) { - PidginMiniDialog *self = PIDGIN_MINI_DIALOG (object); - PidginMiniDialogPrivate *priv = PIDGIN_MINI_DIALOG_GET_PRIVATE (self); + PidginMiniDialog *self = PIDGIN_MINI_DIALOG(object); + PidginMiniDialogPrivate *priv = PIDGIN_MINI_DIALOG_GET_PRIVATE(self); switch (property_id) { case PROP_TITLE: - g_value_set_string (value, gtk_label_get_text (priv->title)); + g_value_set_string(value, gtk_label_get_text(priv->title)); break; case PROP_DESCRIPTION: - g_value_set_string (value, gtk_label_get_text (priv->desc)); + g_value_set_string(value, gtk_label_get_text(priv->desc)); break; case PROP_ICON_NAME: { gchar *icon_name = NULL; GtkIconSize size; - gtk_image_get_stock (priv->icon, &icon_name, &size); - g_value_set_string (value, icon_name); + gtk_image_get_stock(priv->icon, &icon_name, &size); + g_value_set_string(value, icon_name); break; } default: - G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec); } } static void -mini_dialog_set_title (PidginMiniDialog *self, - const char *title) +mini_dialog_set_title(PidginMiniDialog *self, + const char *title) { - PidginMiniDialogPrivate *priv = PIDGIN_MINI_DIALOG_GET_PRIVATE (self); + PidginMiniDialogPrivate *priv = PIDGIN_MINI_DIALOG_GET_PRIVATE(self); - char *title_esc = g_markup_escape_text (title, -1); - char *title_markup = g_strdup_printf ( + char *title_esc = g_markup_escape_text(title, -1); + char *title_markup = g_strdup_printf( "<span weight=\"bold\" size=\"smaller\">%s</span>", title_esc ? title_esc : ""); - gtk_label_set_markup (priv->title, title_markup); + gtk_label_set_markup(priv->title, title_markup); - g_free (title_esc); - g_free (title_markup); + g_free(title_esc); + g_free(title_markup); } static void -mini_dialog_set_description (PidginMiniDialog *self, - const char *description) +mini_dialog_set_description(PidginMiniDialog *self, + const char *description) { - PidginMiniDialogPrivate *priv = PIDGIN_MINI_DIALOG_GET_PRIVATE (self); + PidginMiniDialogPrivate *priv = PIDGIN_MINI_DIALOG_GET_PRIVATE(self); if (description) { - char *desc_esc = g_markup_escape_text (description, -1); - char *desc_markup = g_strdup_printf ( + char *desc_esc = g_markup_escape_text(description, -1); + char *desc_markup = g_strdup_printf( "<span size=\"smaller\">%s</span>", desc_esc); - gtk_label_set_markup (priv->desc, desc_markup); + gtk_label_set_markup(priv->desc, desc_markup); - g_free (desc_esc); - g_free (desc_markup); + g_free(desc_esc); + g_free(desc_markup); - gtk_widget_show (GTK_WIDGET (priv->desc)); - g_object_set (G_OBJECT (priv->desc), "no-show-all", FALSE, NULL); + gtk_widget_show(GTK_WIDGET(priv->desc)); + g_object_set(G_OBJECT(priv->desc), "no-show-all", FALSE, NULL); } else { - gtk_label_set_text (priv->desc, NULL); - gtk_widget_hide (GTK_WIDGET (priv->desc)); + gtk_label_set_text(priv->desc, NULL); + gtk_widget_hide(GTK_WIDGET(priv->desc)); /* make calling show_all() on the minidialog not affect desc * even though it's packed inside it. */ - g_object_set (G_OBJECT (priv->desc), "no-show-all", TRUE, NULL); + g_object_set(G_OBJECT(priv->desc), "no-show-all", TRUE, NULL); } } static void -pidgin_mini_dialog_set_property (GObject *object, - guint property_id, - const GValue *value, - GParamSpec *pspec) +pidgin_mini_dialog_set_property(GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec) { - PidginMiniDialog *self = PIDGIN_MINI_DIALOG (object); - PidginMiniDialogPrivate *priv = PIDGIN_MINI_DIALOG_GET_PRIVATE (self); + PidginMiniDialog *self = PIDGIN_MINI_DIALOG(object); + PidginMiniDialogPrivate *priv = PIDGIN_MINI_DIALOG_GET_PRIVATE(self); switch (property_id) { case PROP_TITLE: - mini_dialog_set_title (self, g_value_get_string (value)); + mini_dialog_set_title(self, g_value_get_string(value)); break; case PROP_DESCRIPTION: - mini_dialog_set_description (self, g_value_get_string (value)); + mini_dialog_set_description(self, g_value_get_string(value)); break; case PROP_ICON_NAME: - gtk_image_set_from_stock (priv->icon, g_value_get_string (value), - GTK_ICON_SIZE_BUTTON); + gtk_image_set_from_stock(priv->icon, g_value_get_string(value), + GTK_ICON_SIZE_BUTTON); break; default: - G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec); } } static void -pidgin_mini_dialog_finalize (GObject *object) +pidgin_mini_dialog_finalize(GObject *object) { - PidginMiniDialog *self = PIDGIN_MINI_DIALOG (object); - PidginMiniDialogPrivate *priv = PIDGIN_MINI_DIALOG_GET_PRIVATE (self); + PidginMiniDialog *self = PIDGIN_MINI_DIALOG(object); + PidginMiniDialogPrivate *priv = PIDGIN_MINI_DIALOG_GET_PRIVATE(self); if (priv->idle_destroy_cb_id) - g_source_remove (priv->idle_destroy_cb_id); + g_source_remove(priv->idle_destroy_cb_id); - g_free (priv); + g_free(priv); self->priv = NULL; - G_OBJECT_CLASS (pidgin_mini_dialog_parent_class)->finalize (object); + G_OBJECT_CLASS(pidgin_mini_dialog_parent_class)->finalize(object); } static void -pidgin_mini_dialog_class_init (PidginMiniDialogClass *klass) +pidgin_mini_dialog_class_init(PidginMiniDialogClass *klass) { - GObjectClass *object_class = G_OBJECT_CLASS (klass); + GObjectClass *object_class = G_OBJECT_CLASS(klass); GParamSpec *param_spec; object_class->get_property = pidgin_mini_dialog_get_property; object_class->set_property = pidgin_mini_dialog_set_property; object_class->finalize = pidgin_mini_dialog_finalize; - param_spec = g_param_spec_string ("title", "title", - "String specifying the mini-dialog's title", NULL, - G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB | - G_PARAM_READWRITE); - g_object_class_install_property (object_class, PROP_TITLE, param_spec); - - param_spec = g_param_spec_string ("description", "description", - "Description text for the mini-dialog, if desired", NULL, - G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB | - G_PARAM_READWRITE); - g_object_class_install_property (object_class, PROP_DESCRIPTION, param_spec); - - param_spec = g_param_spec_string ("icon-name", "icon-name", - "String specifying the Gtk stock name of the dialog's icon", - NULL, - G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB | - G_PARAM_READWRITE); - g_object_class_install_property (object_class, PROP_ICON_NAME, param_spec); + param_spec = g_param_spec_string("title", "title", + "String specifying the mini-dialog's title", NULL, + G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB | + G_PARAM_READWRITE); + g_object_class_install_property(object_class, PROP_TITLE, param_spec); + + param_spec = g_param_spec_string("description", "description", + "Description text for the mini-dialog, if desired", NULL, + G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB | + G_PARAM_READWRITE); + g_object_class_install_property(object_class, PROP_DESCRIPTION, param_spec); + + param_spec = g_param_spec_string("icon-name", "icon-name", + "String specifying the Gtk stock name of the dialog's icon", + NULL, + G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB | + G_PARAM_READWRITE); + g_object_class_install_property(object_class, PROP_ICON_NAME, param_spec); } /* 16 is the width of the icon, due to PIDGIN_ICON_SIZE_TANGO_EXTRA_SMALL */ @@ -355,48 +356,51 @@ pidgin_mini_dialog_class_init (PidginMiniDialogClass *klass) (PIDGIN_PREFS_ROOT "/blist/width") static void -pidgin_mini_dialog_init (PidginMiniDialog *self) +pidgin_mini_dialog_init(PidginMiniDialog *self) { - GtkBox *self_box = GTK_BOX (self); + GtkBox *self_box = GTK_BOX(self); guint label_width = LABEL_WIDTH; - PidginMiniDialogPrivate *priv = g_new0 (PidginMiniDialogPrivate, 1); + PidginMiniDialogPrivate *priv = g_new0(PidginMiniDialogPrivate, 1); self->priv = priv; - gtk_container_set_border_width (GTK_CONTAINER (self), HIG_BOX_SPACE); + gtk_container_set_border_width(GTK_CONTAINER(self), HIG_BOX_SPACE); - priv->title_box = GTK_BOX (gtk_hbox_new (FALSE, HIG_BOX_SPACE)); + priv->title_box = GTK_BOX(gtk_box_new(GTK_ORIENTATION_HORIZONTAL, HIG_BOX_SPACE)); - priv->icon = GTK_IMAGE (gtk_image_new()); - gtk_misc_set_alignment (GTK_MISC (priv->icon), 0, 0); + priv->icon = GTK_IMAGE(gtk_image_new()); + gtk_misc_set_alignment(GTK_MISC(priv->icon), 0, 0); - priv->title = GTK_LABEL (gtk_label_new (NULL)); - gtk_widget_set_size_request (GTK_WIDGET (priv->title), label_width, -1); - gtk_label_set_line_wrap (priv->title, TRUE); - gtk_label_set_selectable (priv->title, TRUE); - gtk_misc_set_alignment (GTK_MISC (priv->title), 0, 0); + priv->title = GTK_LABEL(gtk_label_new(NULL)); + gtk_widget_set_size_request(GTK_WIDGET(priv->title), label_width, -1); + gtk_label_set_line_wrap(priv->title, TRUE); + gtk_label_set_selectable(priv->title, TRUE); + gtk_misc_set_alignment(GTK_MISC(priv->title), 0, 0); - gtk_box_pack_start (priv->title_box, GTK_WIDGET (priv->icon), FALSE, FALSE, 0); - gtk_box_pack_start (priv->title_box, GTK_WIDGET (priv->title), TRUE, TRUE, 0); + gtk_box_pack_start(priv->title_box, GTK_WIDGET(priv->icon), FALSE, FALSE, 0); + gtk_box_pack_start(priv->title_box, GTK_WIDGET(priv->title), TRUE, TRUE, 0); - priv->desc = GTK_LABEL (gtk_label_new (NULL)); - gtk_widget_set_size_request (GTK_WIDGET (priv->desc), label_width, -1); - gtk_label_set_line_wrap (priv->desc, TRUE); - gtk_misc_set_alignment (GTK_MISC (priv->desc), 0, 0); - gtk_label_set_selectable (priv->desc, TRUE); + priv->desc = GTK_LABEL(gtk_label_new(NULL)); + gtk_widget_set_size_request(GTK_WIDGET(priv->desc), label_width, -1); + gtk_label_set_line_wrap(priv->desc, TRUE); + gtk_misc_set_alignment(GTK_MISC(priv->desc), 0, 0); + gtk_label_set_selectable(priv->desc, TRUE); /* make calling show_all() on the minidialog not affect desc even though * it's packed inside it. */ - g_object_set (G_OBJECT (priv->desc), "no-show-all", TRUE, NULL); + g_object_set(G_OBJECT(priv->desc), "no-show-all", TRUE, NULL); - self->contents = GTK_BOX (gtk_vbox_new (FALSE, 0)); + self->contents = GTK_BOX(gtk_box_new(GTK_ORIENTATION_VERTICAL, 0)); - priv->buttons = GTK_BOX (gtk_hbox_new (FALSE, 0)); + priv->buttons = GTK_BOX(gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0)); - gtk_box_pack_start (self_box, GTK_WIDGET (priv->title_box), FALSE, FALSE, 0); - gtk_box_pack_start (self_box, GTK_WIDGET (priv->desc), FALSE, FALSE, 0); - gtk_box_pack_start (self_box, GTK_WIDGET (self->contents), TRUE, TRUE, 0); - gtk_box_pack_start (self_box, GTK_WIDGET (priv->buttons), FALSE, FALSE, 0); + gtk_box_pack_start(self_box, GTK_WIDGET(priv->title_box), FALSE, FALSE, 0); + gtk_box_pack_start(self_box, GTK_WIDGET(priv->desc), FALSE, FALSE, 0); + gtk_box_pack_start(self_box, GTK_WIDGET(self->contents), TRUE, TRUE, 0); + gtk_box_pack_start(self_box, GTK_WIDGET(priv->buttons), FALSE, FALSE, 0); - gtk_widget_show_all (GTK_WIDGET (self)); + gtk_orientable_set_orientation(GTK_ORIENTABLE (self), + GTK_ORIENTATION_VERTICAL); + + gtk_widget_show_all(GTK_WIDGET(self)); } diff --git a/gnome/src/widget/minidialog.h b/gnome/src/widget/minidialog.h index 6f02b83be4a8432dccca4669cc5c3afc18b0c104..673841659e78795a8a8fc832bc9b1765ff080c28 100644 --- a/gnome/src/widget/minidialog.h +++ b/gnome/src/widget/minidialog.h @@ -75,9 +75,9 @@ G_BEGIN_DECLS * </dl> */ typedef struct { - GtkVBox parent; + GtkBox parent; - /** A GtkVBox into which extra widgets for the dialog should be packed. + /** A GtkBox into which extra widgets for the dialog should be packed. */ GtkBox *contents; diff --git a/gnome/tests/Makefile.am b/gnome/tests/Makefile.am index d06467c5aafd7ecd60ee6c704207d771266c5644..fe5a5190ce90d15fd481aff0f6a9bc365c6fb8d1 100644 --- a/gnome/tests/Makefile.am +++ b/gnome/tests/Makefile.am @@ -9,27 +9,42 @@ SFLPHONE_LIBS = $(top_builddir)/src/contacts/libcontacts.la \ ########################################################### -check_global_SOURCES = check_global.c $(top_srcdir)/src/accountlist.c $(top_srcdir)/src/logger.c -check_global_CFLAGS = @CHECK_CFLAGS@ @GTK_CFLAGS@ @DBUSGLIB_CFLAGS@ -check_global_LDADD = $(SFLPHONE_LIBS) @CHECK_LIBS@ @GTK_LIBS@ @DBUSGLIB_LIBS@ +check_global_SOURCES = check_global.c $(top_srcdir)/src/accountlist.c $(top_srcdir)/src/logger.c +check_global_CFLAGS = @CHECK_CFLAGS@ @GTK_CFLAGS@ @GLIB_CFLAGS@ @DBUSGLIB_CFLAGS@ @GCONF_CFLAGS@ +check_global_LDADD = $(SFLPHONE_LIBS) @CHECK_LIBS@ @GLIB_LIBS@ @GTK_LIBS@ @DBUSGLIB_LIBS@ @GCONF_LIBS@ ########################################################### -check_contacts_SOURCES = check_contacts.c -check_contacts_CFLAGS = @CHECK_CFLAGS@ @GTK_CFLAGS@ -check_contacts_LDADD = $(SFLPHONE_LIBS) @CHECK_LIBS@ +check_contacts_SOURCES = check_contacts.c +check_contacts_CFLAGS = @CHECK_CFLAGS@ @GTK_CFLAGS@ +check_contacts_LDADD = $(SFLPHONE_LIBS) @CHECK_LIBS@ ########################################################### -check_config_SOURCES = check_config.c -check_config_CFLAGS = @CHECK_CFLAGS@ @GTK_CFLAGS@ -check_config_LDADD = $(SFLPHONE_LIBS) @CHECK_LIBS@ +check_config_SOURCES = check_config.c +check_config_CFLAGS = @CHECK_CFLAGS@ @GTK_CFLAGS@ +check_config_LDADD = $(SFLPHONE_LIBS) @CHECK_LIBS@ ########################################################### -check_dbus_SOURCES = check_dbus.c $(top_srcdir)/src/logger.c $(top_srcdir)/src/accountlist.c $(top_srcdir)/src/actions.c $(top_srcdir)/src/codeclist.c $(top_srcdir)/src/dialpad.c $(top_srcdir)/src/mainwindow.c $(top_srcdir)/src/reqaccount.c $(top_srcdir)/src/sflnotify.c $(top_srcdir)/src/sliders.c $(top_srcdir)/src/statusicon.c $(top_srcdir)/src/callable_obj.c $(top_srcdir)/src/eel-gconf-extensions.c $(top_srcdir)/src/uimanager.c $(top_srcdir)/src/conference_obj.c $(top_srcdir)/src/shortcuts.c $(top_srcdir)/src/imwindow.c - -check_dbus_CFLAGS = @CHECK_CFLAGS@ @GTK_CFLAGS@ @DBUSGLIB_CFLAGS@ @WEBKIT_CFLAGS@ @LIBGNOMEUI_CFLAGS@ -check_dbus_LDADD = $(SFLPHONE_LIBS) @CHECK_LIBS@ $(top_builddir)/src/widget/libwidget.la $(top_builddir)/src/icons/libicons.la +check_dbus_SOURCES = check_dbus.c $(top_srcdir)/src/logger.c \ + $(top_srcdir)/src/accountlist.c \ + $(top_srcdir)/src/actions.c \ + $(top_srcdir)/src/codeclist.c \ + $(top_srcdir)/src/dialpad.c \ + $(top_srcdir)/src/mainwindow.c \ + $(top_srcdir)/src/reqaccount.c \ + $(top_srcdir)/src/sflnotify.c \ + $(top_srcdir)/src/sliders.c \ + $(top_srcdir)/src/statusicon.c \ + $(top_srcdir)/src/callable_obj.c \ + $(top_srcdir)/src/eel-gconf-extensions.c \ + $(top_srcdir)/src/uimanager.c \ + $(top_srcdir)/src/conference_obj.c \ + $(top_srcdir)/src/shortcuts.c \ + $(top_srcdir)/src/imwindow.c + +check_dbus_CFLAGS = @CHECK_CFLAGS@ @GTK_CFLAGS@ @DBUSGLIB_CFLAGS@ @GCONF_CFLAGS@ @WEBKIT_CFLAGS@ +check_dbus_LDADD = $(SFLPHONE_LIBS) @CHECK_LIBS@ @GCONF_LIBS@ $(top_builddir)/src/widget/libwidget.la $(top_builddir)/src/icons/libicons.la ########################################################### diff --git a/gnome/tests/check_config.c b/gnome/tests/check_config.c index 69686c713234b48083f56d9dec5b21b282d21516..dc330c0e4b9407041aa2586f88383715505e8233 100644 --- a/gnome/tests/check_config.c +++ b/gnome/tests/check_config.c @@ -32,21 +32,21 @@ #include <stdlib.h> Suite * -config_suite (void) +config_suite(void) { - Suite *s = suite_create ("Config"); + Suite *s = suite_create("Config"); - return s; + return s; } int -main (void) +main(void) { - int number_failed; - Suite *s = config_suite (); - SRunner *sr = srunner_create (s); - srunner_run_all (sr, CK_NORMAL); - number_failed = srunner_ntests_failed (sr); - srunner_free (sr); - return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; + int number_failed; + Suite *s = config_suite(); + SRunner *sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; } diff --git a/gnome/tests/check_contacts.c b/gnome/tests/check_contacts.c index 5d23e2c0b5e88cbabcb271cb43aa13bfd0341547..e5c17ea45b231374906a9c5aa9fb9b2673913ed2 100644 --- a/gnome/tests/check_contacts.c +++ b/gnome/tests/check_contacts.c @@ -31,31 +31,31 @@ #include "../src/contacts/addressbook.h" -START_TEST (test_eds) +START_TEST(test_eds) { } END_TEST Suite * -contacts_suite (void) +contacts_suite(void) { Suite *s = suite_create("Contacts"); TCase *tc_cases = tcase_create("EDS"); - tcase_add_test (tc_cases, test_eds); - suite_add_tcase (s, tc_cases); + tcase_add_test(tc_cases, test_eds); + suite_add_tcase(s, tc_cases); return s; } int -main (void) +main(void) { int number_failed; - Suite *s = contacts_suite (); - SRunner *sr = srunner_create (s); - srunner_run_all (sr, CK_NORMAL); - number_failed = srunner_ntests_failed (sr); - srunner_free (sr); - return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; + Suite *s = contacts_suite(); + SRunner *sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; } diff --git a/gnome/tests/check_dbus.c b/gnome/tests/check_dbus.c index 6755286edeb9bd6c7731c52c40eef8116aa83288..a8d96a0503b8d7df584e97b472d56703d111a368 100644 --- a/gnome/tests/check_dbus.c +++ b/gnome/tests/check_dbus.c @@ -31,33 +31,33 @@ #include "../src/dbus/dbus.h" -START_TEST (test_dbus_connect) +START_TEST(test_dbus_connect) { GError *error = NULL; - fail_unless (dbus_connect (&error) == TRUE, "dbus_connect () returns FALSE"); + fail_unless(dbus_connect(&error) == TRUE, "dbus_connect () returns FALSE"); } END_TEST Suite * -dbus_suite (void) +dbus_suite(void) { - Suite *s = suite_create ("D-Bus"); + Suite *s = suite_create("D-Bus"); - TCase *tc_cases = tcase_create ("D-BUS connection"); - tcase_add_test (tc_cases, test_dbus_connect); - suite_add_tcase (s, tc_cases); + TCase *tc_cases = tcase_create("D-BUS connection"); + tcase_add_test(tc_cases, test_dbus_connect); + suite_add_tcase(s, tc_cases); - return s; + return s; } int -main (void) +main(void) { - int number_failed; - Suite *s = dbus_suite (); - SRunner *sr = srunner_create (s); - srunner_run_all (sr, CK_NORMAL); - number_failed = srunner_ntests_failed (sr); - srunner_free (sr); - return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; + int number_failed; + Suite *s = dbus_suite(); + SRunner *sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; } diff --git a/gnome/tests/check_global.c b/gnome/tests/check_global.c index 1986d029041316ea69ee3a453202f749e6820a87..aa3f1bb1569f92f3a7ab1cec9b8e6c0d7219a7ca 100644 --- a/gnome/tests/check_global.c +++ b/gnome/tests/check_global.c @@ -30,131 +30,127 @@ #include <check.h> #include <stdlib.h> #include <gtk/gtk.h> +#include <glib.h> #include "../src/accountlist.h" #include "../src/sflphone_const.h" -account_t* create_test_account (gchar *alias) +account_t* create_test_account(gchar *alias) { account_t *test; - gchar *id; - + srand(time(NULL)); - - test = g_new0 (account_t, 1); - id = g_new0(gchar, 30); - g_sprintf(id, "%s-%d", alias, rand()); - test->accountID = g_strdup (id); + + test = g_new0(account_t, 1); + test->accountID = g_strdup_printf("%s-%d", alias, rand()); test->state = ACCOUNT_STATE_REGISTERED; test->properties = g_hash_table_new(NULL, g_str_equal); - + // Populate the properties - g_hash_table_replace (test->properties, ACCOUNT_ENABLED, "1"); - g_hash_table_replace (test->properties, ACCOUNT_ALIAS, alias); - g_hash_table_replace (test->properties, ACCOUNT_TYPE, "SIP"); - g_hash_table_replace (test->properties, ACCOUNT_HOSTNAME, "sflphone.org"); - g_hash_table_replace (test->properties, ACCOUNT_USERNAME, "1260"); - g_hash_table_replace (test->properties, ACCOUNT_PASSWORD, "NIPAgmLo"); - g_hash_table_replace (test->properties, ACCOUNT_MAILBOX, ""); - g_hash_table_replace (test->properties, ACCOUNT_SIP_STUN_SERVER, ""); - g_hash_table_replace (test->properties, ACCOUNT_SIP_STUN_ENABLED, "0"); + g_hash_table_replace(test->properties, ACCOUNT_ENABLED, "1"); + g_hash_table_replace(test->properties, ACCOUNT_ALIAS, alias); + g_hash_table_replace(test->properties, ACCOUNT_TYPE, "SIP"); + g_hash_table_replace(test->properties, ACCOUNT_HOSTNAME, "sflphone.org"); + g_hash_table_replace(test->properties, ACCOUNT_USERNAME, "1260"); + g_hash_table_replace(test->properties, ACCOUNT_PASSWORD, "NIPAgmLo"); + g_hash_table_replace(test->properties, ACCOUNT_MAILBOX, ""); + g_hash_table_replace(test->properties, ACCOUNT_SIP_STUN_SERVER, ""); + g_hash_table_replace(test->properties, ACCOUNT_SIP_STUN_ENABLED, "0"); return test; - } -START_TEST (test_add_account) +START_TEST(test_add_account) { - account_t *test = create_test_account ("test"); + account_t *test = create_test_account("test"); - account_list_init (); - account_list_add (test); - fail_unless (account_list_get_registered_accounts () == 1, "ERROR"); + account_list_init(); + account_list_add(test); + fail_unless(account_list_get_registered_accounts() == 1, "ERROR"); } END_TEST -START_TEST (test_ordered_list) +START_TEST(test_ordered_list) { - gchar *list; - account_t *test = create_test_account ("test"); - - list = g_new0(gchar, 30); - g_sprintf(list, "%s/%s/", test->accountID, test->accountID); - account_list_init (); - account_list_add (test); - account_list_add (test); - fail_unless (g_strcasecmp (account_list_get_ordered_list (), list) == 0, "ERROR - BAD ACCOUNT LIST SERIALIZING"); + account_t *test = create_test_account("test"); + + gchar *list = g_strdup_printf("%s/%s/", test->accountID, test->accountID); + account_list_init(); + account_list_add(test); + account_list_add(test); + fail_unless(g_strcasecmp(account_list_get_ordered_list(), list) == 0, "ERROR - BAD ACCOUNT LIST SERIALIZING"); + g_free(list); } END_TEST -START_TEST (test_get_by_id) +START_TEST(test_get_by_id) { - account_t *test = create_test_account ("test"); + account_t *test = create_test_account("test"); account_t *tmp; - account_list_init (); - account_list_add (test); - tmp = account_list_get_by_id (test->accountID); - fail_unless (g_strcasecmp (tmp->accountID, test->accountID) == 0, "ERROR - ACCOUNTLIST_GET_BY_ID"); + account_list_init(); + account_list_add(test); + tmp = account_list_get_by_id(test->accountID); + fail_unless(g_strcasecmp(tmp->accountID, test->accountID) == 0, "ERROR - ACCOUNTLIST_GET_BY_ID"); } END_TEST -START_TEST (test_get_current_account) +START_TEST(test_get_current_account) { - account_t *test = create_test_account ("test"); - account_t *test2 = create_test_account ("test2"); + account_t *test = create_test_account("test"); + account_t *test2 = create_test_account("test2"); account_t *current; - account_list_init (); - account_list_add (test); - account_list_add (test2); - current = account_list_get_current (); - fail_unless (current != NULL, "ERROR - current account NULL"); + account_list_init(); + account_list_add(test); + account_list_add(test2); + current = account_list_get_current(); + fail_unless(current != NULL, "ERROR - current account NULL"); + // The current account must be the first we add - if (current) - { - fail_unless (g_strcasecmp (g_hash_table_lookup(current->properties, ACCOUNT_ALIAS) , - g_hash_table_lookup(test->properties, ACCOUNT_ALIAS)) == 0, - "ERROR - BAD CURRENT ACCOUNT"); + if (current) { + fail_unless(g_strcasecmp(g_hash_table_lookup(current->properties, ACCOUNT_ALIAS) , + g_hash_table_lookup(test->properties, ACCOUNT_ALIAS)) == 0, + "ERROR - BAD CURRENT ACCOUNT"); } // Then we try to change the current account - account_list_set_current (test2); - current = account_list_get_current (); - fail_unless (current != NULL, "ERROR - current account NULL"); + account_list_set_current(test2); + current = account_list_get_current(); + fail_unless(current != NULL, "ERROR - current account NULL"); + // The current account must be the first we add - if (current) - { - fail_unless (g_strcasecmp (g_hash_table_lookup(current->properties, ACCOUNT_ALIAS) , - g_hash_table_lookup(test2->properties, ACCOUNT_ALIAS)) == 0, + if (current) { + fail_unless(g_strcasecmp(g_hash_table_lookup(current->properties, ACCOUNT_ALIAS) , + g_hash_table_lookup(test2->properties, ACCOUNT_ALIAS)) == 0, "ERROR - BAD CURRENT ACCOUNT"); } } END_TEST Suite * -global_suite (void) +global_suite(void) { - Suite *s = suite_create ("Global"); + Suite *s = suite_create("Global"); - TCase *tc_cases = tcase_create ("Accounts"); - tcase_add_test (tc_cases, test_add_account); - tcase_add_test (tc_cases, test_ordered_list); - tcase_add_test (tc_cases, test_get_by_id); - tcase_add_test (tc_cases, test_get_current_account); - suite_add_tcase (s, tc_cases); + TCase *tc_cases = tcase_create("Accounts"); + tcase_add_test(tc_cases, test_add_account); + tcase_add_test(tc_cases, test_ordered_list); + tcase_add_test(tc_cases, test_get_by_id); + tcase_add_test(tc_cases, test_get_current_account); + suite_add_tcase(s, tc_cases); - return s; + return s; } int -main (void) +main(void) { - int number_failed; - Suite *s = global_suite (); - SRunner *sr = srunner_create (s); - srunner_run_all (sr, CK_NORMAL); - number_failed = srunner_ntests_failed (sr); - srunner_free (sr); - return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; + int number_failed; + Suite *s = global_suite(); + SRunner *sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; } diff --git a/kde/CMakeLists.txt b/kde/CMakeLists.txt index 2b0d6b0a6dde7c0609f95f4863d873b1aa25eb7a..30f36bf1dae0a93c8181e8b12468615689cf232c 100755 --- a/kde/CMakeLists.txt +++ b/kde/CMakeLists.txt @@ -30,3 +30,12 @@ add_subdirectory(doc) add_subdirectory(man) add_subdirectory(po) add_subdirectory(plasma) + +# make dist target, see: +# https://agateau.wordpress.com/2009/08/09/cmake-and-make-dist-the-simple-version/ +set(PROJECT_VERSION "1.0.0") +set(ARCHIVE_NAME ${CMAKE_PROJECT_NAME}-${PROJECT_VERSION}) + add_custom_target(dist + COMMAND git archive --prefix=${ARCHIVE_NAME}/ HEAD + | gzip > ${CMAKE_BINARY_DIR}/${ARCHIVE_NAME}.tar.gz + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) diff --git a/plugins/.gitignore b/plugins/.gitignore index 998031e94ace72b8c33d7b6121bc6ca0695f5568..2e55b18e4baa7ea3d7a1e4ecc8480d49679eefc0 100644 --- a/plugins/.gitignore +++ b/plugins/.gitignore @@ -3,6 +3,7 @@ .settings/* active autom4te.cache/* +compile config.guess config.* configure @@ -16,4 +17,3 @@ sflphone.desktop sflphone.desktop.* stamp-h.in stamp-h1 - diff --git a/plugins/addressbook/evolution/addressbook.h b/plugins/addressbook/evolution/addressbook.h index f268760cf741c648968d6e315802a1fcede4048c..68ac7bb666edf3679ddf236eef0bc46a1002185c 100644 --- a/plugins/addressbook/evolution/addressbook.h +++ b/plugins/addressbook/evolution/addressbook.h @@ -103,7 +103,7 @@ gboolean addressbook_is_active(); /** * Perform a search in addressbook */ -void addressbook_search (void (*search_cb)(GList *, gpointer), GtkEntry *, AddressBook_Config *); +void addressbook_search(void (*search_cb)(GList *, gpointer), GtkEntry *, AddressBook_Config *); /** * Get a list of addressbook book diff --git a/plugins/addressbook/evolution/eds.c b/plugins/addressbook/evolution/eds.c index ca036ea4d4023dd73379aee9aaaefcbafc48c5f8..b1171fb4307d22d9c09ced1942bc23ad16fc6c62 100644 --- a/plugins/addressbook/evolution/eds.c +++ b/plugins/addressbook/evolution/eds.c @@ -41,7 +41,6 @@ #include <string.h> #include <pango/pango.h> #include "eds.h" -//#include <addressbook-config.h> #include <libedataserver/e-source.h> #include "config.h" diff --git a/plugins/addressbook/evolution/eds.h b/plugins/addressbook/evolution/eds.h index 362b6539597f23fcb18de548d33c1614b471dc66..0ce1783831d585eca4bef8bc2422771fe67d39ce 100644 --- a/plugins/addressbook/evolution/eds.h +++ b/plugins/addressbook/evolution/eds.h @@ -51,32 +51,32 @@ G_BEGIN_DECLS * Template callback function for the asynchronous search */ typedef void -(* SearchAsyncHandler) (GList *hits, gpointer user_data); +(* SearchAsyncHandler)(GList *hits, gpointer user_data); /** * Initialize the address book. * Connection to evolution data server */ void -init_eds (); +init_eds(); /** * Fill list of addressbooks */ void -fill_books_data (void); +fill_books_data(void); /** * Asynchronous query to EDS using get contact method. */ void -search_async_by_contacts (const char *query, int max_results, SearchAsyncHandler handler, gpointer user_data); +search_async_by_contacts(const char *query, int max_results, SearchAsyncHandler handler, gpointer user_data); GSList* -get_books (void); +get_books(void); book_data_t * -books_get_book_data_by_uid (gchar *uid); +books_get_book_data_by_uid(gchar *uid); /** * Public way to know if we can perform a search @@ -100,10 +100,10 @@ addressbook_get_books_data(); * Set the current address book */ void -set_current_addressbook (const gchar *name); +set_current_addressbook(const gchar *name); void -set_current_addressbook_test (EBookQueryTest test); +set_current_addressbook_test(EBookQueryTest test); GSList * get_books_data(); diff --git a/plugins/configure.ac b/plugins/configure.ac index 4b10f7332ffca98dad23b5c3c491c6f2925f50c1..7c0cd8b9ad0822a17ee058e4761063330154f33a 100644 --- a/plugins/configure.ac +++ b/plugins/configure.ac @@ -1,4 +1,4 @@ -AC_INIT([sflphone],[1.0.0],[sflphoneteam@savoirfairelinux.com],[sflphone-plugins]) +AC_INIT([sflphone],[1.0.1],[sflphoneteam@savoirfairelinux.com],[sflphone-plugins]) AC_CONFIG_HEADERS([config.h]) AM_INIT_AUTOMAKE @@ -15,21 +15,26 @@ AC_ARG_WITH(debug, [with_debug=${withval}], [with_debug=no] ) -if test "x$with_debug" = "xfull" -o "x$with_debug" = "xyes"; then - CFLAGS="-g -O0 -DDEBUG -Wall -Wextra" -else - CFLAGS="$CFLAGS -Wall -Wextra" -fi AC_PROG_CC_C99 +dnl For target specific flags +AM_PROG_CC_C_O AC_PROG_INSTALL AC_HEADER_STDC LT_INIT +MIGRATION_FLAGS="-DGDK_DISABLE_DEPRECATED -DGTK_DISABLE_DEPRECATED -DGTK_DISABLE_SINGLE_INCLUDES" +if test "x$with_debug" = "xfull" -o "x$with_debug" = "xyes"; then + CFLAGS="-g -O0 -DDEBUG -Wall -Wextra $MIGRATION_FLAGS" +else + CFLAGS="$CFLAGS -g -Wall -Wextra -Wshadow $MIGRATION_FLAGS" +fi + + dnl GCONF utilities AM_GCONF_SOURCE_2 -PKG_CHECK_MODULES(GTK, gtk+-2.0 > 2.2) +PKG_CHECK_MODULES(GTK, gtk+-3.0) PKG_CHECK_MODULES(GLIB, glib-2.0 >= 2.2) PKG_CHECK_MODULES(LIBEBOOK, libebook-1.2 >= 1.4) PKG_CHECK_MODULES([LIBEDATASERVER], [libedataserver-1.2 >= 2.32], diff --git a/tools/build-system/launch-build-machine-2.sh b/tools/build-system/launch-build-machine-2.sh index 7834cfc113712310beef0a061690f89fcb774a44..7020d26b10d71b5fb74c47c694b7755a505176bc 100755 --- a/tools/build-system/launch-build-machine-2.sh +++ b/tools/build-system/launch-build-machine-2.sh @@ -22,7 +22,7 @@ DO_LOGGING=1 DO_UPLOAD=1 SNAPSHOT_TAG=`date +%Y%m%d` TAG_NAME_PREFIX= -VERSION_NUMBER="1.0.0" +VERSION_NUMBER="1.0.1" LAUNCHPAD_PACKAGES=( "sflphone-client-gnome" "sflphone-common" "sflphone-plugins") @@ -118,8 +118,8 @@ if [ ${IS_KDE_CLIENT} ]; then TAG_NAME_PREFIX="kde." LAUNCHPAD_PACKAGES=( "sflphone-client-kde" ) fi -CURRENT_RELEASE_TAG_NAME=`git tag -l "${TAG_NAME_PREFIX}[0-9]\.[0-9]\.[0-9]*\.*" | tail -n 1` -PREVIOUS_RELEASE_TAG_NAME=`git tag -l "${TAG_NAME_PREFIX}[0-9]\.[0-9]\.[0-9]*\.*" | tail -n 2 | sed -n '1p;1q'` +CURRENT_RELEASE_TAG_NAME=$(git for-each-ref refs/tags --sort=-authordate --format='%(refname)' --count=1 | cut -d'/' -f3) +PREVIOUS_RELEASE_TAG_NAME=$(git for-each-ref refs/tags --sort=-authordate --format='%(refname)' --count=2 | cut -d'/' -f3 | tail -n1) CURRENT_RELEASE_COMMIT_HASH=`git show --pretty=format:"%H" -s ${CURRENT_RELEASE_TAG_NAME} | tail -n 1` PREVIOUS_RELEASE_COMMIT_HASH=`git show --pretty=format:"%H" -s ${PREVIOUS_RELEASE_TAG_NAME} | tail -n 1` CURRENT_COMMIT=`git show --pretty=format:"%H" -s | tail -n 1` @@ -131,8 +131,8 @@ if [ ${IS_KDE_CLIENT} ]; then PREVIOUS_VERSION=${PREVIOUS_RELEASE_TAG_NAME%.*} PREVIOUS_VERSION=${PREVIOUS_VERSION#*.} else - CURRENT_RELEASE_VERSION=${CURRENT_RELEASE_TAG_NAME%.*} - PREVIOUS_VERSION=${PREVIOUS_RELEASE_TAG_NAME%.*} + CURRENT_RELEASE_VERSION=${CURRENT_RELEASE_TAG_NAME} + PREVIOUS_VERSION=${PREVIOUS_RELEASE_TAG_NAME} fi cd ${LAUNCHPAD_DIR} @@ -143,11 +143,7 @@ SOFTWARE_VERSION="" LAUNCHPAD_CONF_PREFIX="" if [ ${IS_RELEASE} ]; then - VERSION_APPEND="" - if [ "${CURRENT_RELEASE_TYPE}" != "stable" ] ; then - VERSION_APPEND="~${CURRENT_RELEASE_TYPE}" - fi - SOFTWARE_VERSION="${CURRENT_RELEASE_VERSION}${VERSION_APPEND}" + SOFTWARE_VERSION="${CURRENT_RELEASE_VERSION}" COMMIT_HASH_BEGIN="${PREVIOUS_RELEASE_COMMIT_HASH}" LAUNCHPAD_CONF_PREFIX="sflphone" else @@ -232,7 +228,6 @@ END LOCAL_VERSION="${SOFTWARE_VERSION}~ppa${VERSION_INDEX}~${LAUNCHPAD_DISTRIBUTION}" - cp ${DEBIAN_DIR}/control.${LAUNCHPAD_DISTRIBUTION} ${DEBIAN_DIR}/control cp ${DEBIAN_DIR}/changelog.generic ${DEBIAN_DIR}/changelog sed -i "s/SYSTEM/${LAUNCHPAD_DISTRIBUTION}/g" ${DEBIAN_DIR}/changelog diff --git a/tools/build-system/launchpad/dput.conf b/tools/build-system/launchpad/dput.conf index be2e975652ae0404475c11dde4941300c1ce3a3f..ad0545a8ab988d416a9cbde3c7c27f20d05c7b7a 100644 --- a/tools/build-system/launchpad/dput.conf +++ b/tools/build-system/launchpad/dput.conf @@ -1,41 +1,41 @@ -[sflphone-lucid] +[sflphone-natty] fqdn = ppa.launchpad.net method = ftp -incoming = ~savoirfairelinux/ubuntu/lucid +incoming = ~savoirfairelinux/ubuntu/natty login = anonymous allow_unsigned_uploads = 0 -[sflphone-maverick] +[sflphone-oneiric] fqdn = ppa.launchpad.net method = ftp -incoming = ~savoirfairelinux/ubuntu/maverick +incoming = ~savoirfairelinux/ubuntu/oneiric login = anonymous allow_unsigned_uploads = 0 -[sflphone-natty] +[sflphone-precise] fqdn = ppa.launchpad.net method = ftp -incoming = ~savoirfairelinux/ubuntu/natty +incoming = ~savoirfairelinux/ubuntu/precise login = anonymous allow_unsigned_uploads = 0 -[sflphone-nightly-lucid] +[sflphone-nightly-natty] fqdn = ppa.launchpad.net method = ftp -incoming = ~savoirfairelinux/sflphone-nightly/ubuntu/lucid +incoming = ~savoirfairelinux/sflphone-nightly/ubuntu/natty login = anonymous allow_unsigned_uploads = 0 -[sflphone-nightly-maverick] +[sflphone-nightly-oneiric] fqdn = ppa.launchpad.net method = ftp -incoming = ~savoirfairelinux/sflphone-nightly/ubuntu/maverick +incoming = ~savoirfairelinux/sflphone-nightly/ubuntu/oneiric login = anonymous allow_unsigned_uploads = 0 -[sflphone-nightly-natty] +[sflphone-nightly-precise] fqdn = ppa.launchpad.net method = ftp -incoming = ~savoirfairelinux/sflphone-nightly/ubuntu/natty +incoming = ~savoirfairelinux/sflphone-nightly/ubuntu/precise login = anonymous allow_unsigned_uploads = 0 diff --git a/tools/build-system/launchpad/sflphone-client-gnome/debian/changelog b/tools/build-system/launchpad/sflphone-client-gnome/debian/changelog index 8021fb0d7d0b35eb2d8330c906baee884e297e43..f85fb80ecde0ef76455b02a998fad3fdda139376 100644 --- a/tools/build-system/launchpad/sflphone-client-gnome/debian/changelog +++ b/tools/build-system/launchpad/sflphone-client-gnome/debian/changelog @@ -1,3 +1,1096 @@ +sflphone-client-gnome (1.0.0-rc20110930~ppa1~SYSTEM) SYSTEM; urgency=low + + ** SNAPSHOT 1.0.0-rc20110930~ppa1~SYSTEM ** + + * update kde .gitignore + * Fix bug in volume widget + * More polishing for release + * Bump version to 1.0.0 + * [#7023] Add the ability to load an abstract contact backend in the + library to resolve more data, polish code + * [#7021] More cleanup for release + * Cleanup + * [#7021] Refactor KDE client dbus handling, add a missing call in + daemon and port the DataEngine to the new API + * Remove some annoying debug + * merge language scripts + * remove obsolete 'VERSION' files + * update install instructions + * Add missing translations to gnome + * language update + * Revert "Don't reference count DBus clients, exit core immediately + when one of them request it" + * Don't reference count DBus clients, exit core immediately when one + of them request it + * [7021] Add contact abstraction support + * [#7121] Polishing library (over). Indentation, spacing and naming + are now consistent + * codecs: link to libccrtp, don't use logger + * Fix a daemon bug + * [#7038] Fix adding contact + * * #7037 : stop audio stream after all calls have been hanged up + * [#7025] Add full support for bookmark + * SFLPhone KDE do not destroy history anymore + * Fix config skeleton + * Close the daemon once and for all, no more automatic respawning + * Fix "unregistered account" bug (I hope so) + * Close SFLPhone at the right place, it still respawn, I don't know + why + * Remove dead code + * Fix regressions introduced in the last commit + * Dead code elimination 1/3 + * Fix bug, add "add contact" option, fix warning + * * #7019: Fix IAX codec negociation + * Remove or comment unnecessary/unhelpful debug output + * Fix "same as local" account setting, fix IP2IP LED color + * Add support for some more advanced config options and add missing + config dialog icons + * Fix crash with noise suppressor + * Alternative can now be selected from the call view context menu + * Add drag and drop support, initial context menu and fix 3 bugs in + the account dialog + * Add basic history drag and drop support + * Complete contact support is back + * * #6991 : fix IAX problems + * Fix IAX accounts being disabled by default + * Revert "deb: forge -g flags for pjsip" + * * #5884: Disable debug code in pjsip + * echo suppressor : more assertions + * Don't let the daemon think crypto is enabled when it's not + * Simplify ToneList + * Some progress on contact support + * Remove unused getRegistrationCount() + * remove annoying debug + * revert SIP bit of e27e5c39bad27bae28f574eb2cba7717e8956229 + * Simplify CallManager::placeCallFirstAccount + * Fix crash on hold + * * #6905 : SIP refactor + * gnome client: be sure key exchange is set correctly + * Move code into createSipTransport + * Fix account registration on start + * ManagerImpl::registerAccounts(): simplify + * * #5884: don't mess with pjsip threads in echo suppressor + * * #6905 : simplify udp/stun/tls pjsip transport creation + * Restore and improve support for Call history + * fix launchpad build + * SIPVoIPLink: simplify / refactor + * Fix libwidget linking + * SIP: simplify + * IM : simplify + * gnome: remove some debug + * AudioRtpFactory::stop() cannot fail + * * #6905: simplify SIP code + * pjlib: fix build without SSLv2, fix warnings + * Port history to the new syntax + * Test a dock widget based implementation for contact and history + * Disable SSLv2 support from pjsip and sflphone + * deb: forge -g flags for pjsip + * Fix deb packaging to get debug symbols + * remove debug + * pjproject: update to last stable release (1.10) + * Require gtk >= 2.20 and glib >= 2.24 + * tlsadvanceddialog: simplify + * * #6902 : fix errors spotted by -DGSEAL_ENABLE + * Update daemon dbus XML and port KDE config backend from dbus to + local + * Remove unused but set variables + * * #6929 : fix IM widget, cleanup + * Unconditionally enable debug symbols + * Should fix many KDE issues + * * #6886 : hitting backspace on empty number have no side effects + * * #6905 : fix AudioCodecFactory access in optimized builds (-O > 0) + * Remove unsupported and broken jaunty/karmic packages + * * #6902 : avoid using some gtk deprecated functions + * Update dbus introspection files + * * #6904: removed unused contactmanager + * * #6903 : use correct dbus-cxx package name + * * #6902: don't use individual gtk headers + * Fix a segfault when config is not present + * Merge latest (0.9.13) KDE code. This version is not yet ready for + git master, but better than the previous one + * addressbook : simplify + * * #5659 : sflphone-plugins doesn't depend on libedataserverui + * * #5659 : addressbook doesn't use libedataserverui + * gnome client doesn't depend on evolution + * * #5695: addressbook: simplify + * * #5695: addressbook : remove AddrBookHandle from plugin + * * #5695 : addressbook : remove unused stuff in the client + * * #5695 : addressbook : remove unused stuff, use static mutex + * gnome client doesn't use evolution + * gnome: use proper API to set GTK_CAN_FOCUS + * * #6897: removed unused focus state vars/callbacks + * gnome: fix calls to sflphone_fill_codec_list_per_account + * * #6623: gnome: don't leak in mainwindow + * gnome: mainwindow whitespace cleanup + * gnome: actions.c parameter doesn't have to be a double pointer + * * #6895: fix memleaks, cleanup in accountconfigdialog + * * #6893: fixes segfault in client on clean history + * * #6894: fix leaks, cleanup in sflnotify + * daemon: fixed prints in main + * * #6892: simplify, fix leaks in dialpad + * * #6887: audiopreference creates audio layer + * * #6660: use const char * const, not std::string for globally + visible constants + * * #6852: Preferences now solely responsible for audiolayer creation. + * * #6860: refactor uimanager, also fixes #6865 + * * #6853: hangup as soon as all digits have been deleted + * * #6852: alsa: retry if device is busy + * * #6852: audiolayer creation depends only on preference.audioApi + * * #6850: gnome: fix build for gtk < 2.22.0 + * cleanup in iax + * alsa: typo + * pulse: if we can't peek in audio input, we can't drop samples + * * #6849: show error window if codecs are missing, instead of dying + * EchoCancel: unused, remove + * * #6629 : use number of samples as arguments for audio filters + * * #6629 : remove unused Algorithm interface + * * #6629 : use helper to call alsa functions and display error msgs + * Remove unused type + * * #6841: fix some error handling + * * #6629: simplify AlsaLayer::alsa_set_params() + * Get gdk key definition from header + * * #6828: Replace raw key codes by gdk defines + * remove some debug, enhance some other + * mainbuffer: simplify + * * #6561 : fix phantom call after transfer + * Conference Participant set : simplify + * SIPCall: remove unused functions, make invite session public + * * #6229 : remove malloc/free from pulse audio loop + * * #6629 : simplify pulse callbacks + * * #6629 + * Simplify widgets + * * #6629 : keep the correct audio module when frequency changes + * * #6751: fixed erroneous debug msgs + * callable_obj.h: removed unneeded pthread header + * alsalayer: cleanup + * * #6629: Always restart audio driver when changing parameters (ALSA + only) + * gnome GUI: don't block in DBus signal errorAlert() + * * #6629 : simplify AudioLayer creation + * * #6629 : remove unused and unconfigurable frameSize from audiolayer + * * #6629 : remove unused error message from audio layer + * Fix logic error when switching audio API + * Remove unused AudioProcessing class + * AudioRtpRecordHandler::initNoiseSuppress() : use noiseSuppress + directly + * * #6629 : use DC blocker directly in audio layers + * * #6629 : clean AudioLayer + * * #6629 : don't store mainbuffer inside audiolayer + * * #6629 : correct AudioLayer::notifyincomingCall() + * * #6554: cleanup, refactoring in sipvoiplink + * * #6554: cleanup in iaxvoiplink + * * #6554: throw exception in getSIPCall if pointer is NULL + * * #6554: make some methods of sipvoiplink static + * * #6655: cleanup in managerimpl + * * #6554: refactoring, fix memleaks in sipvoiplink + * * #6478: remove throw specs, cleanup in voiplink + * * #6629 : remove unused AudioDevice + * * #6655: removed more dependencies from managerimpl + * * #6744: simplified numbercleaner + * conference : remove one prototype + * * #6743: fix ip2ip + * Don't give glib warnings if icons are not found + * gnome: fixed includes + * Codec.h: removed unused function + * * #6742 : clean dbus & icons + * * #6699: refactor/cleanup accounts + * icons: cleanup + * timer : use second precision, not millisecond + * calltree_update_clock : use correct type, returns something + * * #6737: fixed typo in dbus call + * * #6737: removed tests for removed API + * * #6737: dbus: fixed bug from merge + * * #6737: cleanup in accountlist + * * #6737: cleanup in dbus + * * #6740 : fix history double free + * * #6740 : remove time updating thread from calls + * * #6737 : use c99 for client + * * #6738 : make history loading faster + * sipvoiplink : don't crash on transfers + * fixed typo + * Remove unused file + * Don't build networkmanager.cpp at all if NM is disabled + * _debug* -> _debug + * * #6554 : simplify sipvoiplink + * hudson: added -x to git clean command + * added git clean to hudson script + * audiocodecfactory: cleanup + * * #6718: refactored setTlsSettings into SIPAccount + * * #6718: removed more unused methods + * * #6718: refactored confmanager code into sipaccount + * remove unused functions + * * #6718: confmanager: removed more unused methods + * AudioCodecFactory : cleanup + * #6697 : Turn callableElement struct into union + * * #6718: confmanager: removed more unused methods + * * #6718: confmanager: removed more unused methods + * * #6718: removed unused dbus methods, refactoring + * * #6699: accounts: cleanup/refactoring + * * #6699: refactoring, cleanup in accounts + * * #6699: more account cleanup + * remove unused autoconf variable + * * #6714: fixed hudson script + * make distclean in hudson + * added || exit 1 to run_tests.sh call + * * #6714: fixed make distcheck for sflphone-plugins + * * #6714: fixed make distcheck for gnome client + * * #6714: fixed make distcheck for daemon + * git: #6698 split the main .gitignore file + * gnome: gpointer is already a pointer + * gnome: calltab_init: use calloc instead of malloc + * * #6699: more account cleanup + * * #6699: cleanup account + * * #6554 : more *voiplink cleanup + * * #6558 : more sipvoiplink simplification + * * #6558: saner loadSIPLocalIP prototype + * gnome: #6623 clean calllists + * * #6692: more audiolayer cleanup + * * #6692: cleanup/refactoring in audiolayers + * * #6692: more forward declarations, AudioThread->AlsaThread + * * #6692: audiolayer cleanup + * * #6692: alsalayer cleanup + * * #6558 : remove account creator + * * #6558 : clean sipvoiplink + * * #6554 : cleanup sipvoiplink + * audiortp: cleanup + * * #6657 : fix launchpad builds for good + * * #6675 : send RTP dtmf events only once + * * #6655: more cleanup + * AudioRtpSession::updateSessionMedia() : simplify + * * #6655: more cleanup in managerimpl + * * #6655: removed more code, cleanup + * * #6655: more cleanup, fixed infinite loop + * * #6655: removed more unused files + * * #6655: removed unused mutex + * * #6655 removed more unused code + * * #6655: removed unused methods + * * #6655: cleanup in main + * * #6663: fixed segfault when off hold from transfer + * * #6658: user's active codec selection is respected + * * #6660: static global string should be static const char* const + class member + * * #6659: use g_strcmp0, not strcmp for vals that may be null + * callable_obj: fix double free + * calltree_display_call_info() : simplify + * * #6657: Fix launchpad builds + * Logger::log() : simplify + * AudioRtpSession : privatize members + * * #6655: more constness, cleaned up/simplified methods + * * #6654: call DBus::_init_threading so that dbus-c++ to make it + threadaware + * set default credentials on account creation + * AudioCodecFactory::scanCodecDirectory() : simplify and correct + * * #6623: fixed typos + * * #6623: fixed more leaks + * * #6623: fixed more leaks + * * #6623: fixed more leaks, don't print codec name if null + * * #6623: more leaks fixed in client + * * #6623: fix more leaks, fixed some warnings + * * #6623: fixed leak in history + * updated gitignore + * initialize dbus dispatcher correctly + * Fix tests, hudson doesn't have a dbus daemon running + * remove unused code + * removeCall() : simplify , fix leak + * stopRtpThread() : simplify + * *CurrentCall : simplify + * Fix memleak + * fix serialization of audio api (pulse / alsa) + * account map : simplify + * remove call from callmap before terminating it, avoid use after free + * * #6630 : don't make DBusManager a singleton + * call: return confID by value + * add back history code deleted by error + * history : reverse logic + * simplify history serialization and remove some debug + * remove annoying debug + * * #6464 : replace cerr with _error + * * #6464: replace cout with logger macros + * replace printf() with logger macros + * update .gitignore + * remove unused function + * update eclipse projects + * uimanager_new() : simplify + * rename directories + * celt: simplify a bit + * Fix CELT configure.ac test + * * #6612 : template speex codecs + * * #6623: refactored conference obj + * * #6623: refactored callable object, removed leaks + * * #6623: more cleanup, fix leaks, make global vars static and rename + them + * * #6623: calltree: fixed memleaks, simplified code. + * audiolayer: init pointer members + * manager: catch exception on invalid hangup + * * #6623: don't leak on calls to create_new_call + * * #6611 : clarify codecs prototypes + * ringtones : .au and .ul files are both ulaw + * * #6611 : make sure samplerate converters are called correctly + * ManagerImpl::switchAudioManager() : simplify + * * #6623: fixed more leaks + * * #6623: fixed more leaks + * * #6623: fixed more leaks + * * #6623: fixed leak, line-endings in imwidget + * * #6627: zero-initialize pointers if they're going to be deleted + * * #6628: don't leak calls on exceptions + * Revert "audiortp: call join after calling stop on RtpThread" + * sflphone-client: more constness + * audiortp: call join after calling stop on RtpThread + * * #6625: return 0 on successful completion + * * #6624: fix segfault on servercallfailure + * * #6621: Fixed double free, unlock mutex in ManagerImpl::terminate + * * #6220: remove audio stream when peer hangs up + * * #6596: AudioSymmetricSession shouldn't self-delete + * resampler: grow internal buffers dynamically + * merge up and down sampling => resampling + * Leave test directory unchanged when running make check + * audio algorithms : remove unused prototype + * ringtone: detect codec from file extension + * *AudioFile : simplify + * * #6596: create local SDP on the stack, not the heap + * * #6596: don't call Ost::Thread::terminate from dtor + * audiofile: cleanup (samplerate -> unsigned) + * remove unused func + * samplerateconverter: cleanup + * RingBuffer::Put() : remove unused return value + * MainBuffer::putData() : remove unused return argument + * audiolayer::putMain() : remove unused func + * AudioLayer::putUrgent() : remove unused return value + * * #6618: delete any remaining ringbuffers in destructor + * RingBuffer::availForPut() : remove + * * #6617: return from main rather than calling exit + * MainBuffer::availForPut(): remove + * RingBuffer: simplify + * alsa : remove write only variable + * fix memcpy declaration + * bcopy(src, dst) -> memcpy(dst, src) + * RingBuffer::Get() : remove constant volume argument + * return a copy of the call ID, not just a reference. + * MainBuffer::getDataById() : remove volume argument (always 100) + * MainBuffer::getData() : remove constant volume argument + * RingBuffer::Put() : remove constant volume argument + * MainBuffer::putData() : remove constant (=100) volume argument + * audiolayer: remove constant _defaultvolume + * AudioRtpRecordHandler / AudioRtpSession : simplify + * mainbuffer: fix test + * iaxvoiplink : simplify + * sip registration callback: fix a dbus crash + * MainBuffer: simplify + * AudioRtpFactory: return cached type of rtp session. The rtp session + can have disappeared if the call was put on hold + * AudioRtpFactory: remove unused setters + * Fix launchpad builds + * * #6611 : remove unused bandwidth codec information + * * #6611: AudioCodec: remove useless/unused setters + * make sure buffer string is initialized correctly + * * #6596: declare certain destructors virtual + * audiolayer : cleanup + * Simplify doc build rules + * * #6270: don't build dbus-api doc with make, should require make all + * configure.ac: cleanup + * Remove copy of dbus-c++ from libs/ + * * #6596: stop clock thread when peer hangs up + * removed unused Fmtp.h + * * #6595: more logical initialization order + * * #6600 : fix account creation + * * #6601 : fix configure.ac tests + * remove unused variable + * Don't mix stack and heap based allocations + * Fix copyright (2009, 2008, 2009 -> 2008, 2009) + * Fix warnings found by clang + * * #6595: fix initialization order for AudioRTP + * * #6592: removed typedef std::string CallID + * * #6586: implement local g_slist_free_full for older glib versions + * * #6579: fix memory leaks in client (there's a lot left) + * ShortcutPreferences::setShortcuts() : simplify + * Fix merge + * * #6548: remove call to non thread-safe strerror() + * AudioRtpFactory: each instance is associated to exactly one SipCall + * create_audiocodecs_configuration() : make static + * * #6269 : refactor AudioRtpSession + * Fix AudioSymmetricRtpSession.h inclusion guard (cherry picked from + commit c3081dce1cc1370d6d3558a4c4ef5cfac0d21caf) + * * #6269: Rename AudioRtpSession to AudioSymmetricRtpSession + * * #6574: Don't exit when connection to pulseaudio server fails + * accountconfigdialog.h : remove some stuff from header + * * #6560: fix configuration test + * Fix warning in test + * * #6560: don't hide password entry in security tab + * * #6560: set initial password for SIP accounts + * * #6506: remove useless pointer indirection + * * 6560: password is now specific to IAX accounts + * * #6560 : actually use, store, restore, transmit SIP credentials + * * #6560: YamlEmitter: serialize sequences + * YamlEmitterException: typo + * ManagerImpl::computeMd5HashFromCredential() : simplify, fix memleak + * * #6561: invite_session_state_changed_cb() : simplify + * * #6561: More useful debug in VoIPLink::removeCall + * * #6561 : fix ghost call reappearing in GUI after transfer + * while -> for (make the code smaller) + * * #6558 : Account::loadConfig() : move IAX code to IAXAccount + * IAXVoIPLink::getAccountPtr : simplify + * * #6554 : access the SIPVoIPLink directly, not per account + * SIPVoIPLink is instanciated only once and is not associated to a + single account + * yamlnode: use const references when possible (still some left to do) + * Account::_accountID: constify + * VoIPLink: simplify, remove unused method + * hudson test : no need to call run_tests.sh anymore + * Remove AccountID type and AccountNULL define + * Make check runs the test (no need to call run_tests.sh manually + anymore) + * gnome GUI: Fix tests + * Revert "Move registration information from SIPAccount to + SIPVoIPLink" + * * #6392: pluginmanagertest: fix warnings reported by valgrind + * * #6547 : remove unused exceptions + * * #6547: CallManagerException: use runtime exceptions + * * #6547: InstantMessageException: use runtime exceptions + * * #6547: do not throw exceptions if some settings are not present in + config file + * * #6547: YamlParserException: use runtime exceptions + * * #6547: VoipLinkException: use runtime exceptions + * * #6547: YamlEmitterException: use runtime exceptions + * * #6547: DTMFException: use runtime exceptions + * * #6547: AudioFile: use runtime exceptions + * * 6547: AudioZRtpSession: remove impossible error case + * * #6547 : AudioRtpSession: remove impossible error case + * * #6547: AudioZrtp: use runtime exceptions + * * #6408 : send authenticationUsername to GUI + * * #6408 : store/restore authenticationUsername from config file + * SIPAccount: simplify + * Move registration information from SIPAccount to SIPVoIPLink + * SIPAccount::getAccountDetails : simplify + * * #6540: yaml parser: simplify + * sdp.cpp : fix a warning + * * #6540: yaml parser : remove std::string typedefs + * * #6540: Simplify yaml unserialization + * * #6540 : add a Conf::ScalarNode constructor for booleans + * setAccountDetails(): simplify + * * #6408: store authentication username in daemon + * * #6408: Be able to set the authentication username in the GUI + * * #6507 : do not crash if the program is not sflphoned + * Fix tests + * macroify SIPAccount::unserialize() + * Move all .cpp files from sflphoned target to libsflphone.la, except + main.c + * main() : simplify, return positive error codes + * * #6507 : find codecs dir in build directory + * * #6392: Sdp: move clean functions to destructor + * AlsaLayer::adjustVolume() : simplify + * alsalayer : reduce indentation + * malloc/free -> new/delete + * malloc/free -> new[]/delete[] + * malloc/free -> new/delete + * AudioSrtpSession: simplify base64 encoding + * * #6392: Initialize std::string from pj_str_t correctly + * * #6392: AudioRtpSession: Initialize remote port + * Audio settings : Initialize _echoCancelTailLength and + _echoCancelDelay(0) + * Initialize variable + * YamlParserException : fix use of stack variable after it has been + deallocated + * * #6392: fix memory leak in history + * * #6392 AudioCodec : fix memory leak + * * #6392 : fix memory leak in sip account + * * #6408: clean up sipaccount (cosmetics mostly) + * sipaccount.cpp serialize() : reduce number of lines + * * #6392: invalid memory access + * * #6392 : fix invalid memory access + * * #6479: merged useful code from MimeParameters into Codec interface + * * #6462: fixed hangup on IP2IP call + * added run_daemon.sh script + * test: remove unused variable + * Remove functions only used by a failing test (cherry picked from + commit fcf718cb75de7f1882dc61c07bb8d300dfa10f85) + * * #6360 : make client tests build (cherry picked from commit + 028b2835f040e51ab8ab979b32732b07b8798fce) + * * #6360 : fix warnings in check_global test (cherry picked from + commit 9e2bd6a7496dd64f6f48595e385760019aab1193) + * * 6360: updated API calls in tests, but they're not building yet + (cherry picked from commit 548f6f0f919b43772a3e9c667e5e292791281795) + * Fixed include in tests (cherry picked from commit + aeadc7525c1e31f936670ac8b02f0bcf387c38a8) + * Remove unused variables and functions + * IAX: fix warnings (cherry picked from commit + fd7a113a11cac2cd9a7c36929e88ad28195c4c35) + * Remove unused DEBUG define which interferes with logger.h (cherry + picked from commit b2f72b91d0f43cb1dd94d138882a8caa9c841c24) + * * #6392: no need to check for account NULLity since it is + dereferenced above + * * #6392: fix a memory leak, replace by stack allocation + * * #6392: remove a variable assignement which confuses cppcheck + * process_conference_participant_from_serialized() : remove unused + function + * * #6392: s/free/g_free/ + * * #6392: fix a memory leak in abookfactory_load_module() + * * #6392: remove generate_call_id() used only once + * * #6392: fix memory leak (opendir() without closedir()) + * * #6392: AudioRecorder(): ensures mbuffer is set + * Remove SFLPHONED_VERSION from global.h, use autoconf PACKAGE_VERSION + * #6298: Cleanup + * #6331: Fix deleting ringtone file after call have been answered + * * #6330: merged user_cfg into headers + * #6298: Fix conference recording file update at conference end + * #6298: Fix record file name serialization for conference + * * #6295: cleanup of codec hierarchy + * #6298: Fix gtk warnings + * * #6300: added script to run tests + * #6109: Add recording playback for conference + * * #6300: tests do not require an installed sflphone + * * #6295: re-removed clone methods + * #6109: Fix gtk_critical warnings for incoming calls + * #6109: Fix GTK_CRITICAL warning + * #6109: Fix icons when history is not activated + * #6109: Fix warnings + * #6109: Implement stop recorded file playback signal + * Revert "* #6295: removed unused clone method" + * * #6295: removed unused clone method + * * #6296: removed non existant file from Makefile.am + * #6109: Stop fileplayback for outgoing call + * #6109: Implement stop recording playback button + * Fix binding names errors in dbus introspection file + * #6109: Implement playback recorded file callback in client + * #6109: Store recorded file path on client side + * #6109: Add dbus methods for call recording playback + * * #6290: remove unused classes from utilspp + * * #6288: cleanup sdp + * * #6288: fix exception usage + * * #6288: simplify SdpException + * * #6288: cleanup in sdp.cpp/h + * #6109: Only display playback button if record file is set and valid + * * 6290: updated configure.ac to remove functor Makefile + * * #6290, #6289: removed unused classes from utilspp, fixed make + check + * #6109: Add button for history playback of recorded file + * * #6289: removed unused observer class + * * #6282: forward declare sdpMedia in sdp.h + * * #6281: renamed setCallAudioLocal->setCallMediaLocal + * #6183: Handle conference with more tahn two calls + * #6183: Fix history icons when calling back a conference from history + * #6183: Fix icons inconsistencies in history for conference hang up + * #6183: Fix toolbar actions when selecting a conference in history + * #6183: Fix conference serialization + * #6268: Serialize only calls + * * #6269: removed useless type testing + * ignore some files in test/ + * * #6268: Remove dead class AudioSymmetricRtpSession + * #6251: Do not had history calls in calllist when loading history + file + * #6251: Fix insertion in history map in before saving history file in + daemon + * #6251: Fix history unit tests + * #6251: Order the list before serailization, get rid of the hashtable + in history + * #6251: Implement history serialization using a list wether than a + map + * * #6253: remove external audioport from header, make all members + private + * * #6253: don't store external local audio port (used for NAT) in + Call + * #6251: Add start_time timestamp in history serialization + * #6251: Fix call insertion in conference items + * #6233: Fix serialized account list terminated with a ";" character + * #6238: Fix draggable history calls into current calls + * #6233: Fix toolbar updates + * #6233: Fix history + * * #6235: remove pyc files from git tree + * #6233: Handle cases when one or manuy calls are unreachable in + createConfFomrParticipantList + * #6233: Handle wrong numbers in createConferenceFromParticipantList + * #6231: Fix drag-n-drop issue + * * #6173 : move sippxml in tools + * #6231: Fix merging issue + * #6183: Implement conference unserialize + * * #6212: remove extraneous flags from globals.mak + * #6183: Unserialize conference data in conference + * #6183: Add account information in request for conference call from + history + * #5755: Add -ldl to liker in sflphone-client-gnome + * #5755: Fix fedora 15 compilation issue + * #6183: Serialize conference participant phone number and account + * #6183: Add conference timestamp in serialization + * * #6186: don't include global.h, just logger.h + * #6183: Fix saving history to file + * #6183: Fix removing call from calllist + * * #6184: remove pointers to Manager from AudioRtpSessions + * #6183: Calling calltree_add_call explicitely for history + * #6183: Ability to store conference inside history tab queue + * * 6181: remove unused API from sipcall + * #6171: Implment nreCallCreated callback + * #6167: Fix participant list NULL ending + * #6149: First draft of conference creation from history + * #6149: Fix multiple call/conf selection callbacks ... + * #6129: Fix place_call function called twice for pressing enter + action + * #6129: Fix double click action for history + * #6149: Add dbus call for creating conference from history + * #6129: Fix placing call from history and addressbook (still need to + fix icon) + * * #6148: removed unused AudioRtpFactory constructor + * * #6145: remove unused isAudioStarted + * * #6145: remove unused isAudioStarted + * #6129: Add conference into history, fix call/conference selection + * * #6143: don't use getType outside of serialization methods + * * #6132: forward declarations instead of includes + * * #6132: add constness, remove redundant "inline" keywords + * #6129: Add timestamp to conference object to order history entries + * * #6128: remove unused forward declarations from header + * * #6127: make noncopyable class actually noncopyable + * * #6125: don't include AudioRtpFactory in sipcall.h + * #6123: Fix alsa ringback audio file + * #6123: Fix raw audio file loading problem + * #6109: Fix daemon plugin manager unit test + * #6109: Fix history manager unit tests + * #6109: Recording filename in daemon and client for history items + + serialization + * #6109: Refactor AudioFile to play recorded call + * * #6104: AudioCodec moved to sfl namespace + * * #6099: remove active flags from codec classes + * #6095: Add notification-daemon as a runtime dependencies for rpm + packages + * #6095: Fix fedora 15 compilation in MineParameters.h + * #6095: Declare static variable explicitely for client + * #6095: Add logs to build OSC build machine + * * #6098: global variables should have file-scope to avoid name + conflicts + * #6095: Fix compilation error for Fedora 15 + * #6095: Update SFLphone version to 0.9.14 + * #6095: Add specification file in opensusse build service for + sflphone-plugins + * #6073: Fix sflphone-plugins build on launchpad + * #6093: Rename CodecDescriptor for AudioCodecFactory + * * #6089: fix warnings in make check + * * #6086: renamed codecs methods to audio_codecs + * * #6085: renamed codec related dbus calls to audio_codec + * #6065: Remove g_print from client, use DEBUG instead + * #6065: Add actions name for addressbook + * * #6085: renamed codecs* widgets/functions audiocodecs* + * #6065: Fix Addressbook runtime warnings + * #6065: Replace Codecs tab for Audio in account preference dialog + * #6065: Fix "transfert" typo + * #6065: Fix addressbook action runtime warning in uimanager + * * #6082: fixes make check by adding libcrypto libs to test + dependencies + * #6073: Rename plugin/addressbook folders for addressbook/evolution + in sflphone-plugins + * #6074: Removed AC_SUBST from configure.ac when using + PKG_CHECK_MODULE + * #6073: Fix sflphone-plugins package build + * #6073: Fix sflphone-common build + * #6065: Fix runtime gtk warning when initializing searchbar without + addressbook + * #6063: Fix mozilla-tellify gitignore + * #6063: Remove stream copy file using ifdef macro + * * #6012: fix make dist for sflphone-common + * #6063: Update .gitignore file + * #6058: Fix base64 encoding related warnings + * #6056: Fix SdpException handling + * #6055: Fix unknown pargma warning for gcc <= 4.5 + * * #5949: test gcc version before disabling unused-but-set warning + * #6054: Fix addressbook plugin compilation warning + * #6048: Fix uimanager static initialization + * #6046: Fix addressbook factory static initialization of member + addrbook + * #5979: Fix implicit function declaration warning + * #6042: Fixed discarding qualifier warnings in client + * #6041: Fix instant messaging unhandled case warning + * #5994: Implement set current addressbook name and search type in + addressbook plugin + * #5994: add rules for launchpad packaging of addressbook plugin + * #5994: Fix addressbook plugin configuration loading + * #6027: Fix addressbook enabled test from configuration + * #6027: No need of gnomedoc related macros in addressbook plugin + * #6027: Add NEWS file required for build + * #6027: Add addressbook plugin autogen.sh script + * #6027: Remove plugins from client + * #6027: Add sflphone-plugins folder at project's root level + * #5994: Move addressbook folder from contacts to plugin folder + * * #6011: removed unused Makefiles + * * #6010: remove unused headers + * * #5952: fix "string constant to char*" warnings + * * #6009 fixed warnings + * * #6003: finished cleanup of account classes + * * #6003, #6004: cleanup of account classes, defaultAccount no longer + global + * * #6000: fix memory leak of args object + * * #5998: removed using namespace std from networkmanager + * * #5998: removed "using namespace std" from ZrtpSessionCallback + * * #5998: removed using namespacestd from AudioZrtpSession.h + * * #5998: remove "using namespace std" from auriorecord.h and + MimeParameters.h + * * #5998: remove using namespace std in main + * * #5998: removed "using namespace std" from logger + * * #5949: test gcc version before disabling unused-but-set warning + * #5994: Installation of addressbook plugin + * #5979: Implement codec full addressbook search from plugin + * #5979: Implement addressbook factory and plugin + * * #5981: unused webwidget removed + * #5966: Account config synchronization fix (for stun) + * #5954: Handle media name exception + * #5954: Fix audio codec name display in client + * #5954: Clean up getSessionMedia methods + * * #5957: getRecordingSmplRate returns a value + * #5954: Clean up getCurrentCodec methods + * * #5950: remove "converting to non-pointer type 'int' from NULL" + warnings + * #5915: Full gain control version + * * #5949: remove more unused variable warnings + * * #5949: remove unused/unused-but-set variable warnings + * * #5949: show_preferences_dialog returns a success value + * * #5946: cleanup of include directives, undefined function + * * #5515: comment out SSLv2 calls in pjsip + * #5915: Implement different slope for attack tme and release time for + gain control + * #5915: use only one input signal for gain control (removed output + buffer) + * #5921: Fix no audio after holding a conference + * #5916: Add gaincontrol files + * #5916: Implement FFMPEG/CCRTP video streaming prototype + * #5903: Fix call transfer during a conference + * #5915: implement rms detector, first order averager, limiter for + gain control + * #5914: Fix call transfer when no notification request is required + * #5899: Fix conference right-click segfault + * #5884: temporary fix segfault in pjsip memory pool + * #5883: Fix compilation issues on maverick and lucid + * #5755: Fix fedora 15 compilation without patching ccrtp + * [#5855] Make echo canceller optional + * #5855: Fix echo suppression activation/deactivation + * #5855: Implement pjsip echo canceller + * #5814: Speex initialization function uses samples, not bytes + * #5814: Test using more unbalanced signals + * #5814: Fix buffer size for long echo length or long echo delay + * #5814: Adjust level for echo cancellation at runtime + * #5814: Process noise reduction before echo cancelling + * #5814: Implement speex post echo canceller processing + * #5814: Dump echo cancel file to disk + * #5814: Add parameters for echo cancel + * #5809: Add configuration parameters + * #5809: Implement speex echo canceller in audio rtp session + * #5814: Code cleanup + * #5814: Fix conf creation with several incomming ringing calls + * #5814: Fix conf creation segfault when dragging a call on hold on a + ringing call + * #5809: Added unit test for echo cancellation and implemented + "process" virtual method + * #5709: Add always recording option in configuration + * #5709: Add always recording option in audio conference panel + * #5709: Add core functionnality for always recording (missing config + options) + * #5769: Fix conference participant handling (detach/attach) and hold + actions + * #5747: Fix recording icons and state for conference when adding new + participant + * #5769: Code cleanup + * #5769: Fix hangup unsent calls + * #5769: Fix remove/add additional participant to conference + * 5769: Several fixes concerning confererence handling + * #5769: Fix compilation error + * [#5769] Fix audio streams binding in main buffer + * #5769: Removed access to audio mixer from audio layer + * #5765: Fix audio crash for illformated wavefiles + * #5765: Add maximum iteration for finding fmt and data "chunck" + * #5589: Fix compilation of libnotify under + * #5757: Fix abort signal when receiving INFO + * #5747: Add usersDetached.svg + * #5747: Handle offhold action for recording conference + * #5747: Fix off hold action for conferences + * #5747: Implement update conference in record action in calltree + * #5747: Add new icons for recording conferences + * #5747: Add recording state for conferences + * [#5738] Remove getAudioDriver call from manager (replace by + _audiodriver var) + * [#5738] Refactor mutex protecting audiolayer + * [#5737] Fix HD conference recording + * [#5730] Fix start audio session after changing sampling rate + * [#5714] Fix enter keyboard event for addressbbok and history + * [5695] Fix addressbook combo box update when no addressbook selected + * [#5695] Fix addressbook initialization and search bar update + * [#5695] Add mutex for books_data in addressbook to protect async + calls + * [#5695] Get back addressbook open from uri + * [#5695] Fix absolute addressbook URI for local addressbooks + * [#5695] Implement libebook 3.0 interface + * [#5571] Better logic for hangup (for case where call have not been + sent yet) + * [#5571] Update error handling in voip links + * [#5571] Fix compile time warnings + * [#5696] Fix installation dependencies for Natty + * [#5669] Add mention that sflphone.org is for testing only + * [#5693] Add natty in teh dput.conf file + * [#5690] Remove not useful logs + * [#5670] Use dynamic payload type for rtp dtmf + * [#5668] Clean up sflphone configuration logging + * [#5668] Fix hook checkbox configuration update + * [#5666] Fix unit tests + * [#5666] Manage event subscription + * [#5666] Emit bye request when subscription is terminated + * [#5666] Bye request should be sent after event subscription + notification is done on transfer + * [#5666] Make reinvite method static (to be called in pjsip + callbacks) + * [#5666] Hangup Call in manager for AccountNULL and IP2IP + * [#5589] Use PKG_CHECK_MODULE for every client's dependencies + * [#5623] Enlarge initial size of pjsip memory pool for calls (16k) + * [#5564] Fix audio recording resampling for g722 + * [#5571] Move attribute handling for onhold/offhold actions in SDP + session + * [#5571] Codec negotiation refactored and unittested + * [#5571] Implement tests + * [#5571] Implement pjsip negociator + * [#5571] Fix unit tests + * [#5571] Add Fmtp.h to repository + * [#5571] Integrate mime types and codec factory + * [#5571] Handle exception when SDP negotiation fails + * [#5570] Add sflphoned-sample.yml in repository + * [#5564]: Implement stereo to mono mixing for rigntone + * [#5342] Update audio stream initialization + * [#5514] Restore test ni historytest suite + * [#5514] Fix + * [#5514] Disable test_create_history_path + * [#5514] use pulseaudio in sample config file + * [#5514] Fix test: load history from file + * [#5514] Do not use X + * [#5513] Make unit tests compile successfully + * [#3947] Enable unit tests in Jenkins + * [#5454] Fix build system to handle new version number + * [#5454] Update languages from launchpad + * [#5454] Add --without-celt in OpenSuse build service + * [#5454] Change version number + * [#5331] Added first SDP session tests + * [#5273] Update nightly build version tags to conform dpkg rules + * [#5211] Refactor send register method for iaxvoiplink and + sipvoiplink + * [#3950] Remove call being transfered from calltree + * [#5211] Use appropriate memory pool for transport selector + * [#5211] Fix strict aliasing rules warning in pjsip + * [#5211] Bring back pjsip shutting down sleep to 1000 ms + * [#5211] Fix registration callback segfault when closing the + application + * [#5211] Use the dialog memory pool for Route header in INVITE + request + * [#5211] Add temporary memory pool for findLocalAddressFromUri and + findLocalPortFromUri + * [#5211] Use individual memory pool for dtmfs + * [#5211] SipVoipLink refactoring + * [#3950] Attended transfer for conference calls + * [#5284] Fix DNS resolution for Route with specified port number + * [#5284] Some code cleanup + * [#3947] Fix typo in hudson script + * [#5284] Added sip route to REGISTER, INVITE, BYE request, plus DNS + resolution + * [#5266] Use RTP dtmf as default + * [#5284] Added pjsip_process_route_set after setting routes in regc + structure + * [#5286] Fix parsing error due to long configuration file (removed + max event) + * [#5286] Fix false test in configuration emmiter + * [#5286] Code cleanup + * [#5286] Updated exception handling in configuration system + * [#4969] Fix put SRTP call on hold + * [#3950] Add debug messages + * [#3950] Ability to perform an attended transfer + * [#5276] Fix initialization problem in g722 + * [#3950] Add replace header in SIPVoIPLink::transferWithReplaces + method + * [#3950] Implemented attended method in SIPVoIPLink + * [#3950] Cleanup transaction request received callback + * [#3950] Implement dummy attended transfer in gnome-client + * [#5249] Fix audio samplerate update algorithm for g722 + * [#5249] Fix uninitialized variable used in conditional jumps + * [#5249] Fix conditional jump error in audiolayer (uninitialized + value) + * [#5267] Use autoconf 2.65 as a requirement (instead of 2.67) + * [#5267] Restore manual pjsip configuration and compilation + * [#5267] Autodetect celt version (0.9.1, 0.7.1) + * [#5267] Fix deprecated macros in gnome client configure.ac + * [#5267] Update configuration for libcelt-dev + * [#5267] Fix build autoconf and automake + * [#5227] Deactivate automatic call to astyle after compilation + * [#5242] Hangup every calls before leaving + * [#5237] Will now nightly-build for natty, Karmic deprecated + * [#5229] Use inner class for rtp thread instead of inheritance + * [#5211] Move mainbuffer unbind call in rtp final method + * [#5211] Initialize sip call memory pool using 16 kb + * [#5211] Use call memory pool in session reinvite + * [#5211] Add debug messages + * [#5211] Use and internal pool for calls + * [#5211] Reduce pjsip memory pool usage for stateless error messages + * [#5211] Refactor call deletion + * [#5212] + * [#5208] Refactor codec management for accounts + * [#5168] Remove printf from codec's encode & decode method + * [#5168] Fix celt compilation on launchpad + * [#5168] Fix sflphoned compilation warnings in audiocodec.h + * [#[#5168] Must keep the g722 specific RTP rate to avoid incoming + packet timeout + * [#5168] Fix static/dynamic payload rtp session update + * [#5168] Throw SIPVoipLink Error if codec not instantiated in new + outgoing call + * [#5168] Fix dynamic/static codec payload type ambiguity + * [#5169] Fix doubled IP2IP profile when no config file + * [#4867] Add gtkinfobar in configuration panel + * [#4867] Disable input/output/ringtone selection when using default + alsa plugin + * [#4952] Patches for possible buffer overflows + * [$4885] Fix schemas problem + * [#4885] sflphone-client-gnome.schemas not present during build + * [#4885] Add gconf shemas directories in opensuse build system + * [#4885] Add file/folder ownership for opensuse-factory build system + * [#4906] Fix opensuse-factory build + * [#4885] Update name dependency for libedataserver + * [#4885] Fix non-void function without return in dbus-c++ + * [#4895] Update language translation + * [#4896] Update session timestamp when updating media + * [#4896] Reapply RTP hack for G722 payload type + * [#4896] Update recording sampling rate when updating codec + * [#4897] Save codecs in config for each configuration changes + * [#4895] Do not save config when sflphone quit + * [#4885] Update date for copyright + * [#4885] Deactivate siptest that require more than one sipp instance + * [#4879] Remove inmcoming call notification from IAX + * [#4885] Some cleanup + * [#4874] Add setCancel immediate/deffered for ost::Thread + * [#4879] Fix incoming call notification + * [#4878] Set keyboard focus on searchbar when selecting addressbook + * [#4874] Fixed compilation warning + * [#4874] Fixed compilation warning in sipvoiplink + * [#4874] Fix compile time warning in RTP record handler + * [#4874] Fix conditional jump in SDP + * [#4874] Fix conditional jump based on uninitialized value + * [#4874] Store call id within rtp thread context + * [#4874] Fixed conditional jump based on uninitialised value in + conference + * [#4871] Fix default account fetching + * [#4870] Delete RTP session when Refusing an incoming call + * Restore IP to IP call + * [#4857] Fix audio codec negotiation problem + * [#3947] Adjust ressources allocated to compilation + * [#3947] Disable unit tests in Hudson + * [#4305] Free mutex only when really quiting SFLphone + * [#4859] Update copyright to 2011 in every source file + * [#3218] Character '.' stripped by the caller engine + * [#4854] Fix typos, desktop entry + * [#4847] Apply RTP modification to ZRTP session + * [#4852] Update Karmic and Lucid dependencies + * [#4852] Add Libedataserver and libedataserverui as gnome client + dependencies + * [#4852] Add authentication mechanism for EDS + * [#4851] Fix segfault when closing pulseaudio layer too rapidly + * [#4808] Some otehr cleanup + * [#4808] Made some cleanup + * [#4808] Added mutex in rtp session for codecs and noise process + * [#4847] Update audio processing when updating RTP media + * [#4842] Add support for linking with gold/ld --no-add-needed + * [#4808] Make update g722 related static/dynamic payload logic + * [#4827] Upper limit on the number of contacts to import from EDS is + hard-coded to 500 + * [#4808] Fix put call on/off hold + * [#4808] Implement early RTP start for incoming calls + * [#4808] Audio stream is no longer start within RTP session. + * [#4808] Removed coupling between audio layer and and RTP session + * [#4702] Start audio rtp session as soon as it is created + * [#4702] Init timestamp to 0 + * #4702: Send RTP packets immediately, no need of outgoing queue + * [#4784] Update dbus-c++ version from gitorious + * [#4702] Update RTP timeouts + * [#4702] Lengthen RTP timeouts + * [PATCH] Fixed compatibility with old libtool versions. + * [PATCH] Accept older libebook (Maemo 5 has 1.4.2) + * [PATCH] Fixed double-free error in preferences dialog + * [PATCH] Fixed building of sflphone-common on Maemo5 + * [PATCH] Improved Gnome client initialization error handling. 1. It + no longer segfaults when sflphoned isn't available. 2. User is + provided with GUI error dialog. + * [PATCH] Improved autogen.sh scripts 1. They do not require bash + anymore 2. Added workaround for Debian bug #565663 3. Replaced + manual autotools invocations with single autoreconf call 4. Non-zero + return status on failure + * Revert "[#4468] libtool <= 2.2 doesn't have LT_INIT macro so + AC_PROG_LIBTOOL should be used instead." + * Revert "[#4468] Libebook 1.4 is sufficient" + * Revert "[#4468] Apply big path on dbus communication system" + * [#4468] Apply big path on dbus communication system + * [#4468] Libebook 1.4 is sufficient + * [#4468] libtool <= 2.2 doesn't have LT_INIT macro so AC_PROG_LIBTOOL + should be used instead. + * [#4639] Fix determining default addressbook if this property is not + set in gconf + * [#4639] Fix memory leaks in Addressbook + * [#4637] Fix opening default addressbook at sflphone init + * [#4622] Free yaml events while parsing configuration file + * [#4623] Fix conditional jumps based on uninitialized variable + * [#4622] Fix leaks in yaml serialization engine + * [#4616] Fix addressbook warnings + * [#4514] Adjust RTP timestamp + * #4527: Rename Karmic libyaml and Celt package in debian control file + * #4495: Rework addressbook opening loop + * [#4524] Increment RTP count when sending data + * [#4524] DO NOT start RTP session twice + * [#4367] Use PKG_CHECK_MODULE for celt + * [#4367] Fedora package celt as celt (not libcelt) + * [#4367] Astyling + * [#4367] Update .po files + * [#4367] Fix segfault in gensin + * [#4354] Make celt a direct dependency on launchpad opensuse build + service + * [#4367] Make celt a required package, option --without-celt valid + * [#4367] Fix zrtp timestamping error + * [#4367] Fix audio zrtp timing + * [#4367] Dispatch ZRTP packets + * [#4367] Fix segfault when unloading account map + * [#4367] Fix zrtp session + * [#4367] Implement on packet receive + * [#4367] use symetric audio rtp session, not dual + * [#4367] Reduce packet receive/sent timeout + * [#4367] Reduce RTP timeouts + * [#4367] Move speaker data receive + * [#4367] Move speaker data receive + * [#4367] Move receive speaker data method + * [#4367] Remove debug in rtp session + * [#4367] Fix g722 codec clock rate + * [#4367] Fix noise suppression initialization + * [#4367] Fix segfault in RTP mic fadein method + * [#4367] Refactor mic data encoding in rtp session + * [#4367] Implement RTP main loop + * [#4367] Fix compilation problem + * [#4367] Fix AudioRtpclass using TRTPSessionBase + * [#4367] Fix AudioRtpSession putDtmfEvent shadowing + * [#4367] Fix AudioRtpSession putDtmfEvent shadowing + * [#4367] Refactor RTP session (phase 2) + * [#4367] Refactor RTP session (phase 1) + * [#4367] Remove Redeclaration of SymetricAudioRtpSession in + rtpfactory + * [#4265] Add continue statement in for loop for invalid addressbook + * [#4261] Makes addressbook initialization more robust + * [#4257] Add maverick in build system + * [#4233] Add sdp related unit tests + * [#4233] Add condition and signal in two incoming call test + * [#4243] Fix segfault in AudioSrtpSession + * [#4243] Fix memory leak in AudioSrtpSession + * [#4243] Make audio srtp optional in for incoming call + * [#4243] Add boolean variable to make sure remote crypto context + initialized only once + * [#4243] Add documentation to AudioSrtpSession + * [#4243] Use 80 bits authentication tags by default + * [#4243] Init audio srtp remote crypto context in + call_on_media_update + * [#4243] Move SDP negotiastion in mod_on_rx_request + * [#4243] Implement initLocalCryptoInfo to be called at different + momment + * [#4243] Init init local crypto context in when initializing audiortp + * [#4243] Change key length according to sdes negociation + * [#4243] Associate callid to accountid for incoming calls + * [#4242] Fix no SDES keys in IP2IP calls + * [#4242] Fix no SDES keys in IP2IP calls + * [#4233] Test for call on/off hold + * [#4233] Add two incoming call test + * [#4233] + * [#4233] Add 2 outgoing simultaneous call unit tests + + -- Julien Bonjean <julien.bonjean@savoirfairelinux.com> Fri, 30 Sep 2011 13:44:57 -0400 + sflphone-client-gnome (0.9.7~rc1~ppa1~SYSTEM) SYSTEM; urgency=low ** 0.9.7~rc1~ppa1~SYSTEM ** diff --git a/tools/build-system/launchpad/sflphone-client-gnome/debian/control.karmic b/tools/build-system/launchpad/sflphone-client-gnome/debian/control similarity index 69% rename from tools/build-system/launchpad/sflphone-client-gnome/debian/control.karmic rename to tools/build-system/launchpad/sflphone-client-gnome/debian/control index 0b15d3effcde27a0adc3808c40f0be23a9606b4f..fefd939e490decf14e5cbf8567f4f8cfd211d34a 100644 --- a/tools/build-system/launchpad/sflphone-client-gnome/debian/control.karmic +++ b/tools/build-system/launchpad/sflphone-client-gnome/debian/control @@ -2,13 +2,13 @@ Source: sflphone-client-gnome Maintainer: SavoirFaireLinux Inc <julien.bonjean@savoirfairelinux.com> Section: gnome Priority: optional -Build-Depends: debhelper, libgcc1, autoconf, automake, libtool, libgtk2.0-dev, libdbus-glib-1-dev, libnotify-dev, check, liblog4c-dev, libgnomeui-dev, gnome-doc-utils, rarian-compat, libwebkit-dev +Build-Depends: debhelper, libgcc1, autoconf, automake, libtool, libgtk-3-dev, libdbus-glib-1-dev, libnotify-dev, check, liblog4c-dev, gnome-doc-utils, rarian-compat, libwebkitgtk-3.0-dev Standards-Version: 3.7.3 Package: sflphone-client-gnome Priority: optional Architecture: any -Depends: sflphone-common (=${source:Version}), libdbus-glib-1-2, libgtk2.0-0, libc6, libglib2.0-0, libdbus-glib-1-2, libnotify1, librsvg2-common, liblog4c3, libgnomeui-0, libwebkit-1.0-2 +Depends: sflphone-common (=${source:Version}), ${shlibs:Depends}, ${misc:Depends} Replaces: sflphone Conflicts: sflphone Homepage: http://www.sflphone.org diff --git a/tools/build-system/launchpad/sflphone-client-gnome/debian/control.jaunty b/tools/build-system/launchpad/sflphone-client-gnome/debian/control.jaunty deleted file mode 100644 index c72878afda415cff757f8bb6da1167c5d431544f..0000000000000000000000000000000000000000 --- a/tools/build-system/launchpad/sflphone-client-gnome/debian/control.jaunty +++ /dev/null @@ -1,20 +0,0 @@ -Source: sflphone-client-gnome -Maintainer: SavoirFaireLinux Inc <julien.bonjean@savoirfairelinux.com> -Section: gnome -Priority: optional -Build-Depends: debhelper, libgcc1, autoconf, automake, libtool, libgtk2.0-dev, libdbus-glib-1-dev, libnotify-dev, libebook1.2-dev, check, liblog4c-dev, libgnomeui-dev, gnome-doc-utils, rarian-compat -Standards-Version: 3.7.3 - -Package: sflphone-client-gnome -Priority: optional -Architecture: any -Depends: sflphone-common (=${source:Version}), libdbus-glib-1-2, libgtk2.0-0, libc6, libglib2.0-0, libdbus-glib-1-2, libnotify1, librsvg2-common, liblog4c3, libebook1.2-9, libgnomeui-0 -Replaces: sflphone -Conflicts: sflphone -Homepage: http://www.sflphone.org -Description: GNOME client for SFLphone - Provide a GNOME client for SFLphone. - SFLphone is meant to be a robust enterprise-class desktop phone. - SFLphone is released under the GNU General Public License. - SFLphone is being developed by the global community, and maintained by - Savoir-faire Linux, a Montreal, Quebec, Canada-based Linux consulting company. diff --git a/tools/build-system/launchpad/sflphone-client-gnome/debian/control.lucid b/tools/build-system/launchpad/sflphone-client-gnome/debian/control.lucid deleted file mode 100644 index 0b15d3effcde27a0adc3808c40f0be23a9606b4f..0000000000000000000000000000000000000000 --- a/tools/build-system/launchpad/sflphone-client-gnome/debian/control.lucid +++ /dev/null @@ -1,20 +0,0 @@ -Source: sflphone-client-gnome -Maintainer: SavoirFaireLinux Inc <julien.bonjean@savoirfairelinux.com> -Section: gnome -Priority: optional -Build-Depends: debhelper, libgcc1, autoconf, automake, libtool, libgtk2.0-dev, libdbus-glib-1-dev, libnotify-dev, check, liblog4c-dev, libgnomeui-dev, gnome-doc-utils, rarian-compat, libwebkit-dev -Standards-Version: 3.7.3 - -Package: sflphone-client-gnome -Priority: optional -Architecture: any -Depends: sflphone-common (=${source:Version}), libdbus-glib-1-2, libgtk2.0-0, libc6, libglib2.0-0, libdbus-glib-1-2, libnotify1, librsvg2-common, liblog4c3, libgnomeui-0, libwebkit-1.0-2 -Replaces: sflphone -Conflicts: sflphone -Homepage: http://www.sflphone.org -Description: GNOME client for SFLphone - Provide a GNOME client for SFLphone. - SFLphone is meant to be a robust enterprise-class desktop phone. - SFLphone is released under the GNU General Public License. - SFLphone is being developed by the global community, and maintained by - Savoir-faire Linux, a Montreal, Quebec, Canada-based Linux consulting company. diff --git a/tools/build-system/launchpad/sflphone-client-gnome/debian/control.maverick b/tools/build-system/launchpad/sflphone-client-gnome/debian/control.maverick deleted file mode 100644 index 0b15d3effcde27a0adc3808c40f0be23a9606b4f..0000000000000000000000000000000000000000 --- a/tools/build-system/launchpad/sflphone-client-gnome/debian/control.maverick +++ /dev/null @@ -1,20 +0,0 @@ -Source: sflphone-client-gnome -Maintainer: SavoirFaireLinux Inc <julien.bonjean@savoirfairelinux.com> -Section: gnome -Priority: optional -Build-Depends: debhelper, libgcc1, autoconf, automake, libtool, libgtk2.0-dev, libdbus-glib-1-dev, libnotify-dev, check, liblog4c-dev, libgnomeui-dev, gnome-doc-utils, rarian-compat, libwebkit-dev -Standards-Version: 3.7.3 - -Package: sflphone-client-gnome -Priority: optional -Architecture: any -Depends: sflphone-common (=${source:Version}), libdbus-glib-1-2, libgtk2.0-0, libc6, libglib2.0-0, libdbus-glib-1-2, libnotify1, librsvg2-common, liblog4c3, libgnomeui-0, libwebkit-1.0-2 -Replaces: sflphone -Conflicts: sflphone -Homepage: http://www.sflphone.org -Description: GNOME client for SFLphone - Provide a GNOME client for SFLphone. - SFLphone is meant to be a robust enterprise-class desktop phone. - SFLphone is released under the GNU General Public License. - SFLphone is being developed by the global community, and maintained by - Savoir-faire Linux, a Montreal, Quebec, Canada-based Linux consulting company. diff --git a/tools/build-system/launchpad/sflphone-client-gnome/debian/control.natty b/tools/build-system/launchpad/sflphone-client-gnome/debian/control.natty deleted file mode 100644 index efc74416d2f682f854194a19a707a9e671500458..0000000000000000000000000000000000000000 --- a/tools/build-system/launchpad/sflphone-client-gnome/debian/control.natty +++ /dev/null @@ -1,20 +0,0 @@ -Source: sflphone-client-gnome -Maintainer: SavoirFaireLinux Inc <julien.bonjean@savoirfairelinux.com> -Section: gnome -Priority: optional -Build-Depends: debhelper, libgcc1, autoconf, automake, libtool, libgtk2.0-dev, libdbus-glib-1-dev, libnotify-dev, libebook1.2-dev, check, liblog4c-dev, libgnomeui-dev, gnome-doc-utils, rarian-compat, libwebkitgtk-dev -Standards-Version: 3.7.3 - -Package: sflphone-client-gnome -Priority: optional -Architecture: any -Depends: sflphone-common (=${source:Version}), libdbus-glib-1-2, libgtk2.0-0, libc6, libglib2.0-0, libnotify1, librsvg2-common, liblog4c3, libgnomeui-0, libwebkitgtk-1.0-0 -Replaces: sflphone -Conflicts: sflphone -Homepage: http://www.sflphone.org -Description: GNOME client for SFLphone - Provide a GNOME client for SFLphone. - SFLphone is meant to be a robust enterprise-class desktop phone. - SFLphone is released under the GNU General Public License. - SFLphone is being developed by the global community, and maintained by - Savoir-faire Linux, a Montreal, Quebec, Canada-based Linux consulting company. diff --git a/tools/build-system/launchpad/sflphone-client-gnome/debian/rules b/tools/build-system/launchpad/sflphone-client-gnome/debian/rules index 3ff2428272f3b35249ff95daa41673cc04a559b7..61b69aa3260e5b8e621b31df6ea3710e9db9e377 100755 --- a/tools/build-system/launchpad/sflphone-client-gnome/debian/rules +++ b/tools/build-system/launchpad/sflphone-client-gnome/debian/rules @@ -101,7 +101,7 @@ binary-common: # dh_perl dh_makeshlibs dh_installdeb -# dh_shlibdeps + dh_shlibdeps dh_gencontrol dh_md5sums dh_builddeb diff --git a/tools/build-system/launchpad/sflphone-client-kde/debian/changelog b/tools/build-system/launchpad/sflphone-client-kde/debian/changelog index d59275102a6fe917817c2192bb7f50b4875c64d1..a368c43102ab944f554a06dfb2c3c09994594a27 100644 --- a/tools/build-system/launchpad/sflphone-client-kde/debian/changelog +++ b/tools/build-system/launchpad/sflphone-client-kde/debian/changelog @@ -1,4 +1,1825 @@ -sflphone-client-kde (0.9.6-SYSVER) SYSTEM; urgency=low +sflphone-client-kde (1.0.0-rc20110930~ppa1~SYSTEM) SYSTEM; urgency=low + + ** SNAPSHOT 1.0.0-rc20110930~ppa1~SYSTEM ** + + * update kde .gitignore + * Fix bug in volume widget + * More polishing for release + * Bump version to 1.0.0 + * [#7023] Add the ability to load an abstract contact backend in the + library to resolve more data, polish code + * [#7021] More cleanup for release + * Cleanup + * [#7021] Refactor KDE client dbus handling, add a missing call in + daemon and port the DataEngine to the new API + * Remove some annoying debug + * merge language scripts + * remove obsolete 'VERSION' files + * update install instructions + * Add missing translations to gnome + * language update + * Revert "Don't reference count DBus clients, exit core immediately + when one of them request it" + * Don't reference count DBus clients, exit core immediately when one + of them request it + * [7021] Add contact abstraction support + * [#7121] Polishing library (over). Indentation, spacing and naming + are now consistent + * codecs: link to libccrtp, don't use logger + * Fix a daemon bug + * [#7038] Fix adding contact + * * #7037 : stop audio stream after all calls have been hanged up + * [#7025] Add full support for bookmark + * SFLPhone KDE do not destroy history anymore + * Fix config skeleton + * Close the daemon once and for all, no more automatic respawning + * Fix "unregistered account" bug (I hope so) + * Close SFLPhone at the right place, it still respawn, I don't know + why + * Remove dead code + * Fix regressions introduced in the last commit + * Dead code elimination 1/3 + * Fix bug, add "add contact" option, fix warning + * * #7019: Fix IAX codec negociation + * Remove or comment unnecessary/unhelpful debug output + * Fix "same as local" account setting, fix IP2IP LED color + * Add support for some more advanced config options and add missing + config dialog icons + * Fix crash with noise suppressor + * Alternative can now be selected from the call view context menu + * Add drag and drop support, initial context menu and fix 3 bugs in + the account dialog + * Add basic history drag and drop support + * Complete contact support is back + * * #6991 : fix IAX problems + * Fix IAX accounts being disabled by default + * Revert "deb: forge -g flags for pjsip" + * * #5884: Disable debug code in pjsip + * echo suppressor : more assertions + * Don't let the daemon think crypto is enabled when it's not + * Simplify ToneList + * Some progress on contact support + * Remove unused getRegistrationCount() + * remove annoying debug + * revert SIP bit of e27e5c39bad27bae28f574eb2cba7717e8956229 + * Simplify CallManager::placeCallFirstAccount + * Fix crash on hold + * * #6905 : SIP refactor + * gnome client: be sure key exchange is set correctly + * Move code into createSipTransport + * Fix account registration on start + * ManagerImpl::registerAccounts(): simplify + * * #5884: don't mess with pjsip threads in echo suppressor + * * #6905 : simplify udp/stun/tls pjsip transport creation + * Restore and improve support for Call history + * fix launchpad build + * SIPVoIPLink: simplify / refactor + * Fix libwidget linking + * SIP: simplify + * IM : simplify + * gnome: remove some debug + * AudioRtpFactory::stop() cannot fail + * * #6905: simplify SIP code + * pjlib: fix build without SSLv2, fix warnings + * Port history to the new syntax + * Test a dock widget based implementation for contact and history + * Disable SSLv2 support from pjsip and sflphone + * deb: forge -g flags for pjsip + * Fix deb packaging to get debug symbols + * remove debug + * pjproject: update to last stable release (1.10) + * Require gtk >= 2.20 and glib >= 2.24 + * tlsadvanceddialog: simplify + * * #6902 : fix errors spotted by -DGSEAL_ENABLE + * Update daemon dbus XML and port KDE config backend from dbus to + local + * Remove unused but set variables + * * #6929 : fix IM widget, cleanup + * Unconditionally enable debug symbols + * Should fix many KDE issues + * * #6886 : hitting backspace on empty number have no side effects + * * #6905 : fix AudioCodecFactory access in optimized builds (-O > 0) + * Remove unsupported and broken jaunty/karmic packages + * * #6902 : avoid using some gtk deprecated functions + * Update dbus introspection files + * * #6904: removed unused contactmanager + * * #6903 : use correct dbus-cxx package name + * * #6902: don't use individual gtk headers + * Fix a segfault when config is not present + * Merge latest (0.9.13) KDE code. This version is not yet ready for + git master, but better than the previous one + * addressbook : simplify + * * #5659 : sflphone-plugins doesn't depend on libedataserverui + * * #5659 : addressbook doesn't use libedataserverui + * gnome client doesn't depend on evolution + * * #5695: addressbook: simplify + * * #5695: addressbook : remove AddrBookHandle from plugin + * * #5695 : addressbook : remove unused stuff in the client + * * #5695 : addressbook : remove unused stuff, use static mutex + * gnome client doesn't use evolution + * gnome: use proper API to set GTK_CAN_FOCUS + * * #6897: removed unused focus state vars/callbacks + * gnome: fix calls to sflphone_fill_codec_list_per_account + * * #6623: gnome: don't leak in mainwindow + * gnome: mainwindow whitespace cleanup + * gnome: actions.c parameter doesn't have to be a double pointer + * * #6895: fix memleaks, cleanup in accountconfigdialog + * * #6893: fixes segfault in client on clean history + * * #6894: fix leaks, cleanup in sflnotify + * daemon: fixed prints in main + * * #6892: simplify, fix leaks in dialpad + * * #6887: audiopreference creates audio layer + * * #6660: use const char * const, not std::string for globally + visible constants + * * #6852: Preferences now solely responsible for audiolayer creation. + * * #6860: refactor uimanager, also fixes #6865 + * * #6853: hangup as soon as all digits have been deleted + * * #6852: alsa: retry if device is busy + * * #6852: audiolayer creation depends only on preference.audioApi + * * #6850: gnome: fix build for gtk < 2.22.0 + * cleanup in iax + * alsa: typo + * pulse: if we can't peek in audio input, we can't drop samples + * * #6849: show error window if codecs are missing, instead of dying + * EchoCancel: unused, remove + * * #6629 : use number of samples as arguments for audio filters + * * #6629 : remove unused Algorithm interface + * * #6629 : use helper to call alsa functions and display error msgs + * Remove unused type + * * #6841: fix some error handling + * * #6629: simplify AlsaLayer::alsa_set_params() + * Get gdk key definition from header + * * #6828: Replace raw key codes by gdk defines + * remove some debug, enhance some other + * mainbuffer: simplify + * * #6561 : fix phantom call after transfer + * Conference Participant set : simplify + * SIPCall: remove unused functions, make invite session public + * * #6229 : remove malloc/free from pulse audio loop + * * #6629 : simplify pulse callbacks + * * #6629 + * Simplify widgets + * * #6629 : keep the correct audio module when frequency changes + * * #6751: fixed erroneous debug msgs + * callable_obj.h: removed unneeded pthread header + * alsalayer: cleanup + * * #6629: Always restart audio driver when changing parameters (ALSA + only) + * gnome GUI: don't block in DBus signal errorAlert() + * * #6629 : simplify AudioLayer creation + * * #6629 : remove unused and unconfigurable frameSize from audiolayer + * * #6629 : remove unused error message from audio layer + * Fix logic error when switching audio API + * Remove unused AudioProcessing class + * AudioRtpRecordHandler::initNoiseSuppress() : use noiseSuppress + directly + * * #6629 : use DC blocker directly in audio layers + * * #6629 : clean AudioLayer + * * #6629 : don't store mainbuffer inside audiolayer + * * #6629 : correct AudioLayer::notifyincomingCall() + * * #6554: cleanup, refactoring in sipvoiplink + * * #6554: cleanup in iaxvoiplink + * * #6554: throw exception in getSIPCall if pointer is NULL + * * #6554: make some methods of sipvoiplink static + * * #6655: cleanup in managerimpl + * * #6554: refactoring, fix memleaks in sipvoiplink + * * #6478: remove throw specs, cleanup in voiplink + * * #6629 : remove unused AudioDevice + * * #6655: removed more dependencies from managerimpl + * * #6744: simplified numbercleaner + * conference : remove one prototype + * * #6743: fix ip2ip + * Don't give glib warnings if icons are not found + * gnome: fixed includes + * Codec.h: removed unused function + * * #6742 : clean dbus & icons + * * #6699: refactor/cleanup accounts + * icons: cleanup + * timer : use second precision, not millisecond + * calltree_update_clock : use correct type, returns something + * * #6737: fixed typo in dbus call + * * #6737: removed tests for removed API + * * #6737: dbus: fixed bug from merge + * * #6737: cleanup in accountlist + * * #6737: cleanup in dbus + * * #6740 : fix history double free + * * #6740 : remove time updating thread from calls + * * #6737 : use c99 for client + * * #6738 : make history loading faster + * sipvoiplink : don't crash on transfers + * fixed typo + * Remove unused file + * Don't build networkmanager.cpp at all if NM is disabled + * _debug* -> _debug + * * #6554 : simplify sipvoiplink + * hudson: added -x to git clean command + * added git clean to hudson script + * audiocodecfactory: cleanup + * * #6718: refactored setTlsSettings into SIPAccount + * * #6718: removed more unused methods + * * #6718: refactored confmanager code into sipaccount + * remove unused functions + * * #6718: confmanager: removed more unused methods + * AudioCodecFactory : cleanup + * #6697 : Turn callableElement struct into union + * * #6718: confmanager: removed more unused methods + * * #6718: confmanager: removed more unused methods + * * #6718: removed unused dbus methods, refactoring + * * #6699: accounts: cleanup/refactoring + * * #6699: refactoring, cleanup in accounts + * * #6699: more account cleanup + * remove unused autoconf variable + * * #6714: fixed hudson script + * make distclean in hudson + * added || exit 1 to run_tests.sh call + * * #6714: fixed make distcheck for sflphone-plugins + * * #6714: fixed make distcheck for gnome client + * * #6714: fixed make distcheck for daemon + * git: #6698 split the main .gitignore file + * gnome: gpointer is already a pointer + * gnome: calltab_init: use calloc instead of malloc + * * #6699: more account cleanup + * * #6699: cleanup account + * * #6554 : more *voiplink cleanup + * * #6558 : more sipvoiplink simplification + * * #6558: saner loadSIPLocalIP prototype + * gnome: #6623 clean calllists + * * #6692: more audiolayer cleanup + * * #6692: cleanup/refactoring in audiolayers + * * #6692: more forward declarations, AudioThread->AlsaThread + * * #6692: audiolayer cleanup + * * #6692: alsalayer cleanup + * * #6558 : remove account creator + * * #6558 : clean sipvoiplink + * * #6554 : cleanup sipvoiplink + * audiortp: cleanup + * * #6657 : fix launchpad builds for good + * * #6675 : send RTP dtmf events only once + * * #6655: more cleanup + * AudioRtpSession::updateSessionMedia() : simplify + * * #6655: more cleanup in managerimpl + * * #6655: removed more code, cleanup + * * #6655: more cleanup, fixed infinite loop + * * #6655: removed more unused files + * * #6655: removed unused mutex + * * #6655 removed more unused code + * * #6655: removed unused methods + * * #6655: cleanup in main + * * #6663: fixed segfault when off hold from transfer + * * #6658: user's active codec selection is respected + * * #6660: static global string should be static const char* const + class member + * * #6659: use g_strcmp0, not strcmp for vals that may be null + * callable_obj: fix double free + * calltree_display_call_info() : simplify + * * #6657: Fix launchpad builds + * Logger::log() : simplify + * AudioRtpSession : privatize members + * * #6655: more constness, cleaned up/simplified methods + * * #6654: call DBus::_init_threading so that dbus-c++ to make it + threadaware + * set default credentials on account creation + * AudioCodecFactory::scanCodecDirectory() : simplify and correct + * * #6623: fixed typos + * * #6623: fixed more leaks + * * #6623: fixed more leaks + * * #6623: fixed more leaks, don't print codec name if null + * * #6623: more leaks fixed in client + * * #6623: fix more leaks, fixed some warnings + * * #6623: fixed leak in history + * updated gitignore + * initialize dbus dispatcher correctly + * Fix tests, hudson doesn't have a dbus daemon running + * remove unused code + * removeCall() : simplify , fix leak + * stopRtpThread() : simplify + * *CurrentCall : simplify + * Fix memleak + * fix serialization of audio api (pulse / alsa) + * account map : simplify + * remove call from callmap before terminating it, avoid use after free + * * #6630 : don't make DBusManager a singleton + * call: return confID by value + * add back history code deleted by error + * history : reverse logic + * simplify history serialization and remove some debug + * remove annoying debug + * * #6464 : replace cerr with _error + * * #6464: replace cout with logger macros + * replace printf() with logger macros + * update .gitignore + * remove unused function + * update eclipse projects + * uimanager_new() : simplify + * rename directories + * celt: simplify a bit + * Fix CELT configure.ac test + * * #6612 : template speex codecs + * * #6623: refactored conference obj + * * #6623: refactored callable object, removed leaks + * * #6623: more cleanup, fix leaks, make global vars static and rename + them + * * #6623: calltree: fixed memleaks, simplified code. + * audiolayer: init pointer members + * manager: catch exception on invalid hangup + * * #6623: don't leak on calls to create_new_call + * * #6611 : clarify codecs prototypes + * ringtones : .au and .ul files are both ulaw + * * #6611 : make sure samplerate converters are called correctly + * ManagerImpl::switchAudioManager() : simplify + * * #6623: fixed more leaks + * * #6623: fixed more leaks + * * #6623: fixed more leaks + * * #6623: fixed leak, line-endings in imwidget + * * #6627: zero-initialize pointers if they're going to be deleted + * * #6628: don't leak calls on exceptions + * Revert "audiortp: call join after calling stop on RtpThread" + * sflphone-client: more constness + * audiortp: call join after calling stop on RtpThread + * * #6625: return 0 on successful completion + * * #6624: fix segfault on servercallfailure + * * #6621: Fixed double free, unlock mutex in ManagerImpl::terminate + * * #6220: remove audio stream when peer hangs up + * * #6596: AudioSymmetricSession shouldn't self-delete + * resampler: grow internal buffers dynamically + * merge up and down sampling => resampling + * Leave test directory unchanged when running make check + * audio algorithms : remove unused prototype + * ringtone: detect codec from file extension + * *AudioFile : simplify + * * #6596: create local SDP on the stack, not the heap + * * #6596: don't call Ost::Thread::terminate from dtor + * audiofile: cleanup (samplerate -> unsigned) + * remove unused func + * samplerateconverter: cleanup + * RingBuffer::Put() : remove unused return value + * MainBuffer::putData() : remove unused return argument + * audiolayer::putMain() : remove unused func + * AudioLayer::putUrgent() : remove unused return value + * * #6618: delete any remaining ringbuffers in destructor + * RingBuffer::availForPut() : remove + * * #6617: return from main rather than calling exit + * MainBuffer::availForPut(): remove + * RingBuffer: simplify + * alsa : remove write only variable + * fix memcpy declaration + * bcopy(src, dst) -> memcpy(dst, src) + * RingBuffer::Get() : remove constant volume argument + * return a copy of the call ID, not just a reference. + * MainBuffer::getDataById() : remove volume argument (always 100) + * MainBuffer::getData() : remove constant volume argument + * RingBuffer::Put() : remove constant volume argument + * MainBuffer::putData() : remove constant (=100) volume argument + * audiolayer: remove constant _defaultvolume + * AudioRtpRecordHandler / AudioRtpSession : simplify + * mainbuffer: fix test + * iaxvoiplink : simplify + * sip registration callback: fix a dbus crash + * MainBuffer: simplify + * AudioRtpFactory: return cached type of rtp session. The rtp session + can have disappeared if the call was put on hold + * AudioRtpFactory: remove unused setters + * Fix launchpad builds + * * #6611 : remove unused bandwidth codec information + * * #6611: AudioCodec: remove useless/unused setters + * make sure buffer string is initialized correctly + * * #6596: declare certain destructors virtual + * audiolayer : cleanup + * Simplify doc build rules + * * #6270: don't build dbus-api doc with make, should require make all + * configure.ac: cleanup + * Remove copy of dbus-c++ from libs/ + * * #6596: stop clock thread when peer hangs up + * removed unused Fmtp.h + * * #6595: more logical initialization order + * * #6600 : fix account creation + * * #6601 : fix configure.ac tests + * remove unused variable + * Don't mix stack and heap based allocations + * Fix copyright (2009, 2008, 2009 -> 2008, 2009) + * Fix warnings found by clang + * * #6595: fix initialization order for AudioRTP + * * #6592: removed typedef std::string CallID + * * #6586: implement local g_slist_free_full for older glib versions + * * #6579: fix memory leaks in client (there's a lot left) + * ShortcutPreferences::setShortcuts() : simplify + * Fix merge + * * #6548: remove call to non thread-safe strerror() + * AudioRtpFactory: each instance is associated to exactly one SipCall + * create_audiocodecs_configuration() : make static + * * #6269 : refactor AudioRtpSession + * Fix AudioSymmetricRtpSession.h inclusion guard (cherry picked from + commit c3081dce1cc1370d6d3558a4c4ef5cfac0d21caf) + * * #6269: Rename AudioRtpSession to AudioSymmetricRtpSession + * * #6574: Don't exit when connection to pulseaudio server fails + * accountconfigdialog.h : remove some stuff from header + * * #6560: fix configuration test + * Fix warning in test + * * #6560: don't hide password entry in security tab + * * #6560: set initial password for SIP accounts + * * #6506: remove useless pointer indirection + * * 6560: password is now specific to IAX accounts + * * #6560 : actually use, store, restore, transmit SIP credentials + * * #6560: YamlEmitter: serialize sequences + * YamlEmitterException: typo + * ManagerImpl::computeMd5HashFromCredential() : simplify, fix memleak + * * #6561: invite_session_state_changed_cb() : simplify + * * #6561: More useful debug in VoIPLink::removeCall + * * #6561 : fix ghost call reappearing in GUI after transfer + * while -> for (make the code smaller) + * * #6558 : Account::loadConfig() : move IAX code to IAXAccount + * IAXVoIPLink::getAccountPtr : simplify + * * #6554 : access the SIPVoIPLink directly, not per account + * SIPVoIPLink is instanciated only once and is not associated to a + single account + * yamlnode: use const references when possible (still some left to do) + * Account::_accountID: constify + * VoIPLink: simplify, remove unused method + * hudson test : no need to call run_tests.sh anymore + * Remove AccountID type and AccountNULL define + * Make check runs the test (no need to call run_tests.sh manually + anymore) + * gnome GUI: Fix tests + * Revert "Move registration information from SIPAccount to + SIPVoIPLink" + * * #6392: pluginmanagertest: fix warnings reported by valgrind + * * #6547 : remove unused exceptions + * * #6547: CallManagerException: use runtime exceptions + * * #6547: InstantMessageException: use runtime exceptions + * * #6547: do not throw exceptions if some settings are not present in + config file + * * #6547: YamlParserException: use runtime exceptions + * * #6547: VoipLinkException: use runtime exceptions + * * #6547: YamlEmitterException: use runtime exceptions + * * #6547: DTMFException: use runtime exceptions + * * #6547: AudioFile: use runtime exceptions + * * 6547: AudioZRtpSession: remove impossible error case + * * #6547 : AudioRtpSession: remove impossible error case + * * #6547: AudioZrtp: use runtime exceptions + * * #6408 : send authenticationUsername to GUI + * * #6408 : store/restore authenticationUsername from config file + * SIPAccount: simplify + * Move registration information from SIPAccount to SIPVoIPLink + * SIPAccount::getAccountDetails : simplify + * * #6540: yaml parser: simplify + * sdp.cpp : fix a warning + * * #6540: yaml parser : remove std::string typedefs + * * #6540: Simplify yaml unserialization + * * #6540 : add a Conf::ScalarNode constructor for booleans + * setAccountDetails(): simplify + * * #6408: store authentication username in daemon + * * #6408: Be able to set the authentication username in the GUI + * * #6507 : do not crash if the program is not sflphoned + * Fix tests + * macroify SIPAccount::unserialize() + * Move all .cpp files from sflphoned target to libsflphone.la, except + main.c + * main() : simplify, return positive error codes + * * #6507 : find codecs dir in build directory + * * #6392: Sdp: move clean functions to destructor + * AlsaLayer::adjustVolume() : simplify + * alsalayer : reduce indentation + * malloc/free -> new/delete + * malloc/free -> new[]/delete[] + * malloc/free -> new/delete + * AudioSrtpSession: simplify base64 encoding + * * #6392: Initialize std::string from pj_str_t correctly + * * #6392: AudioRtpSession: Initialize remote port + * Audio settings : Initialize _echoCancelTailLength and + _echoCancelDelay(0) + * Initialize variable + * YamlParserException : fix use of stack variable after it has been + deallocated + * * #6392: fix memory leak in history + * * #6392 AudioCodec : fix memory leak + * * #6392 : fix memory leak in sip account + * * #6408: clean up sipaccount (cosmetics mostly) + * sipaccount.cpp serialize() : reduce number of lines + * * #6392: invalid memory access + * * #6392 : fix invalid memory access + * * #6479: merged useful code from MimeParameters into Codec interface + * * #6462: fixed hangup on IP2IP call + * added run_daemon.sh script + * test: remove unused variable + * Remove functions only used by a failing test (cherry picked from + commit fcf718cb75de7f1882dc61c07bb8d300dfa10f85) + * * #6360 : make client tests build (cherry picked from commit + 028b2835f040e51ab8ab979b32732b07b8798fce) + * * #6360 : fix warnings in check_global test (cherry picked from + commit 9e2bd6a7496dd64f6f48595e385760019aab1193) + * * 6360: updated API calls in tests, but they're not building yet + (cherry picked from commit 548f6f0f919b43772a3e9c667e5e292791281795) + * Fixed include in tests (cherry picked from commit + aeadc7525c1e31f936670ac8b02f0bcf387c38a8) + * Remove unused variables and functions + * IAX: fix warnings (cherry picked from commit + fd7a113a11cac2cd9a7c36929e88ad28195c4c35) + * Remove unused DEBUG define which interferes with logger.h (cherry + picked from commit b2f72b91d0f43cb1dd94d138882a8caa9c841c24) + * * #6392: no need to check for account NULLity since it is + dereferenced above + * * #6392: fix a memory leak, replace by stack allocation + * * #6392: remove a variable assignement which confuses cppcheck + * process_conference_participant_from_serialized() : remove unused + function + * * #6392: s/free/g_free/ + * * #6392: fix a memory leak in abookfactory_load_module() + * * #6392: remove generate_call_id() used only once + * * #6392: fix memory leak (opendir() without closedir()) + * * #6392: AudioRecorder(): ensures mbuffer is set + * Remove SFLPHONED_VERSION from global.h, use autoconf PACKAGE_VERSION + * #6298: Cleanup + * #6331: Fix deleting ringtone file after call have been answered + * * #6330: merged user_cfg into headers + * #6298: Fix conference recording file update at conference end + * #6298: Fix record file name serialization for conference + * * #6295: cleanup of codec hierarchy + * #6298: Fix gtk warnings + * * #6300: added script to run tests + * #6109: Add recording playback for conference + * * #6300: tests do not require an installed sflphone + * * #6295: re-removed clone methods + * #6109: Fix gtk_critical warnings for incoming calls + * #6109: Fix GTK_CRITICAL warning + * #6109: Fix icons when history is not activated + * #6109: Fix warnings + * #6109: Implement stop recorded file playback signal + * Revert "* #6295: removed unused clone method" + * * #6295: removed unused clone method + * * #6296: removed non existant file from Makefile.am + * #6109: Stop fileplayback for outgoing call + * #6109: Implement stop recording playback button + * Fix binding names errors in dbus introspection file + * #6109: Implement playback recorded file callback in client + * #6109: Store recorded file path on client side + * #6109: Add dbus methods for call recording playback + * * #6290: remove unused classes from utilspp + * * #6288: cleanup sdp + * * #6288: fix exception usage + * * #6288: simplify SdpException + * * #6288: cleanup in sdp.cpp/h + * #6109: Only display playback button if record file is set and valid + * * 6290: updated configure.ac to remove functor Makefile + * * #6290, #6289: removed unused classes from utilspp, fixed make + check + * #6109: Add button for history playback of recorded file + * * #6289: removed unused observer class + * * #6282: forward declare sdpMedia in sdp.h + * * #6281: renamed setCallAudioLocal->setCallMediaLocal + * #6183: Handle conference with more tahn two calls + * #6183: Fix history icons when calling back a conference from history + * #6183: Fix icons inconsistencies in history for conference hang up + * #6183: Fix toolbar actions when selecting a conference in history + * #6183: Fix conference serialization + * #6268: Serialize only calls + * * #6269: removed useless type testing + * ignore some files in test/ + * * #6268: Remove dead class AudioSymmetricRtpSession + * #6251: Do not had history calls in calllist when loading history + file + * #6251: Fix insertion in history map in before saving history file in + daemon + * #6251: Fix history unit tests + * #6251: Order the list before serailization, get rid of the hashtable + in history + * #6251: Implement history serialization using a list wether than a + map + * * #6253: remove external audioport from header, make all members + private + * * #6253: don't store external local audio port (used for NAT) in + Call + * #6251: Add start_time timestamp in history serialization + * #6251: Fix call insertion in conference items + * #6233: Fix serialized account list terminated with a ";" character + * #6238: Fix draggable history calls into current calls + * #6233: Fix toolbar updates + * #6233: Fix history + * * #6235: remove pyc files from git tree + * #6233: Handle cases when one or manuy calls are unreachable in + createConfFomrParticipantList + * #6233: Handle wrong numbers in createConferenceFromParticipantList + * #6231: Fix drag-n-drop issue + * * #6173 : move sippxml in tools + * #6231: Fix merging issue + * #6183: Implement conference unserialize + * * #6212: remove extraneous flags from globals.mak + * #6183: Unserialize conference data in conference + * #6183: Add account information in request for conference call from + history + * #5755: Add -ldl to liker in sflphone-client-gnome + * #5755: Fix fedora 15 compilation issue + * #6183: Serialize conference participant phone number and account + * #6183: Add conference timestamp in serialization + * * #6186: don't include global.h, just logger.h + * #6183: Fix saving history to file + * #6183: Fix removing call from calllist + * * #6184: remove pointers to Manager from AudioRtpSessions + * #6183: Calling calltree_add_call explicitely for history + * #6183: Ability to store conference inside history tab queue + * * 6181: remove unused API from sipcall + * #6171: Implment nreCallCreated callback + * #6167: Fix participant list NULL ending + * #6149: First draft of conference creation from history + * #6149: Fix multiple call/conf selection callbacks ... + * #6129: Fix place_call function called twice for pressing enter + action + * #6129: Fix double click action for history + * #6149: Add dbus call for creating conference from history + * #6129: Fix placing call from history and addressbook (still need to + fix icon) + * * #6148: removed unused AudioRtpFactory constructor + * * #6145: remove unused isAudioStarted + * * #6145: remove unused isAudioStarted + * #6129: Add conference into history, fix call/conference selection + * * #6143: don't use getType outside of serialization methods + * * #6132: forward declarations instead of includes + * * #6132: add constness, remove redundant "inline" keywords + * #6129: Add timestamp to conference object to order history entries + * * #6128: remove unused forward declarations from header + * * #6127: make noncopyable class actually noncopyable + * * #6125: don't include AudioRtpFactory in sipcall.h + * #6123: Fix alsa ringback audio file + * #6123: Fix raw audio file loading problem + * #6109: Fix daemon plugin manager unit test + * #6109: Fix history manager unit tests + * #6109: Recording filename in daemon and client for history items + + serialization + * #6109: Refactor AudioFile to play recorded call + * * #6104: AudioCodec moved to sfl namespace + * * #6099: remove active flags from codec classes + * #6095: Add notification-daemon as a runtime dependencies for rpm + packages + * #6095: Fix fedora 15 compilation in MineParameters.h + * #6095: Declare static variable explicitely for client + * #6095: Add logs to build OSC build machine + * * #6098: global variables should have file-scope to avoid name + conflicts + * #6095: Fix compilation error for Fedora 15 + * #6095: Update SFLphone version to 0.9.14 + * #6095: Add specification file in opensusse build service for + sflphone-plugins + * #6073: Fix sflphone-plugins build on launchpad + * #6093: Rename CodecDescriptor for AudioCodecFactory + * * #6089: fix warnings in make check + * * #6086: renamed codecs methods to audio_codecs + * * #6085: renamed codec related dbus calls to audio_codec + * #6065: Remove g_print from client, use DEBUG instead + * #6065: Add actions name for addressbook + * * #6085: renamed codecs* widgets/functions audiocodecs* + * #6065: Fix Addressbook runtime warnings + * #6065: Replace Codecs tab for Audio in account preference dialog + * #6065: Fix "transfert" typo + * #6065: Fix addressbook action runtime warning in uimanager + * * #6082: fixes make check by adding libcrypto libs to test + dependencies + * #6073: Rename plugin/addressbook folders for addressbook/evolution + in sflphone-plugins + * #6074: Removed AC_SUBST from configure.ac when using + PKG_CHECK_MODULE + * #6073: Fix sflphone-plugins package build + * #6073: Fix sflphone-common build + * #6065: Fix runtime gtk warning when initializing searchbar without + addressbook + * #6063: Fix mozilla-tellify gitignore + * #6063: Remove stream copy file using ifdef macro + * * #6012: fix make dist for sflphone-common + * #6063: Update .gitignore file + * #6058: Fix base64 encoding related warnings + * #6056: Fix SdpException handling + * #6055: Fix unknown pargma warning for gcc <= 4.5 + * * #5949: test gcc version before disabling unused-but-set warning + * #6054: Fix addressbook plugin compilation warning + * #6048: Fix uimanager static initialization + * #6046: Fix addressbook factory static initialization of member + addrbook + * #5979: Fix implicit function declaration warning + * #6042: Fixed discarding qualifier warnings in client + * #6041: Fix instant messaging unhandled case warning + * #5994: Implement set current addressbook name and search type in + addressbook plugin + * #5994: add rules for launchpad packaging of addressbook plugin + * #5994: Fix addressbook plugin configuration loading + * #6027: Fix addressbook enabled test from configuration + * #6027: No need of gnomedoc related macros in addressbook plugin + * #6027: Add NEWS file required for build + * #6027: Add addressbook plugin autogen.sh script + * #6027: Remove plugins from client + * #6027: Add sflphone-plugins folder at project's root level + * #5994: Move addressbook folder from contacts to plugin folder + * * #6011: removed unused Makefiles + * * #6010: remove unused headers + * * #5952: fix "string constant to char*" warnings + * * #6009 fixed warnings + * * #6003: finished cleanup of account classes + * * #6003, #6004: cleanup of account classes, defaultAccount no longer + global + * * #6000: fix memory leak of args object + * * #5998: removed using namespace std from networkmanager + * * #5998: removed "using namespace std" from ZrtpSessionCallback + * * #5998: removed using namespacestd from AudioZrtpSession.h + * * #5998: remove "using namespace std" from auriorecord.h and + MimeParameters.h + * * #5998: remove using namespace std in main + * * #5998: removed "using namespace std" from logger + * * #5949: test gcc version before disabling unused-but-set warning + * #5994: Installation of addressbook plugin + * #5979: Implement codec full addressbook search from plugin + * #5979: Implement addressbook factory and plugin + * * #5981: unused webwidget removed + * #5966: Account config synchronization fix (for stun) + * #5954: Handle media name exception + * #5954: Fix audio codec name display in client + * #5954: Clean up getSessionMedia methods + * * #5957: getRecordingSmplRate returns a value + * #5954: Clean up getCurrentCodec methods + * * #5950: remove "converting to non-pointer type 'int' from NULL" + warnings + * #5915: Full gain control version + * * #5949: remove more unused variable warnings + * * #5949: remove unused/unused-but-set variable warnings + * * #5949: show_preferences_dialog returns a success value + * * #5946: cleanup of include directives, undefined function + * * #5515: comment out SSLv2 calls in pjsip + * #5915: Implement different slope for attack tme and release time for + gain control + * #5915: use only one input signal for gain control (removed output + buffer) + * #5921: Fix no audio after holding a conference + * #5916: Add gaincontrol files + * #5916: Implement FFMPEG/CCRTP video streaming prototype + * #5903: Fix call transfer during a conference + * #5915: implement rms detector, first order averager, limiter for + gain control + * #5914: Fix call transfer when no notification request is required + * #5899: Fix conference right-click segfault + * #5884: temporary fix segfault in pjsip memory pool + * #5883: Fix compilation issues on maverick and lucid + * #5755: Fix fedora 15 compilation without patching ccrtp + * [#5855] Make echo canceller optional + * #5855: Fix echo suppression activation/deactivation + * #5855: Implement pjsip echo canceller + * #5814: Speex initialization function uses samples, not bytes + * #5814: Test using more unbalanced signals + * #5814: Fix buffer size for long echo length or long echo delay + * #5814: Adjust level for echo cancellation at runtime + * #5814: Process noise reduction before echo cancelling + * #5814: Implement speex post echo canceller processing + * #5814: Dump echo cancel file to disk + * #5814: Add parameters for echo cancel + * #5809: Add configuration parameters + * #5809: Implement speex echo canceller in audio rtp session + * #5814: Code cleanup + * #5814: Fix conf creation with several incomming ringing calls + * #5814: Fix conf creation segfault when dragging a call on hold on a + ringing call + * #5809: Added unit test for echo cancellation and implemented + "process" virtual method + * #5709: Add always recording option in configuration + * #5709: Add always recording option in audio conference panel + * #5709: Add core functionnality for always recording (missing config + options) + * #5769: Fix conference participant handling (detach/attach) and hold + actions + * #5747: Fix recording icons and state for conference when adding new + participant + * #5769: Code cleanup + * #5769: Fix hangup unsent calls + * #5769: Fix remove/add additional participant to conference + * 5769: Several fixes concerning confererence handling + * #5769: Fix compilation error + * [#5769] Fix audio streams binding in main buffer + * #5769: Removed access to audio mixer from audio layer + * #5765: Fix audio crash for illformated wavefiles + * #5765: Add maximum iteration for finding fmt and data "chunck" + * #5589: Fix compilation of libnotify under + * #5757: Fix abort signal when receiving INFO + * #5747: Add usersDetached.svg + * #5747: Handle offhold action for recording conference + * #5747: Fix off hold action for conferences + * #5747: Implement update conference in record action in calltree + * #5747: Add new icons for recording conferences + * #5747: Add recording state for conferences + * [#5738] Remove getAudioDriver call from manager (replace by + _audiodriver var) + * [#5738] Refactor mutex protecting audiolayer + * [#5737] Fix HD conference recording + * [#5730] Fix start audio session after changing sampling rate + * [#5714] Fix enter keyboard event for addressbbok and history + * [5695] Fix addressbook combo box update when no addressbook selected + * [#5695] Fix addressbook initialization and search bar update + * [#5695] Add mutex for books_data in addressbook to protect async + calls + * [#5695] Get back addressbook open from uri + * [#5695] Fix absolute addressbook URI for local addressbooks + * [#5695] Implement libebook 3.0 interface + * [#5571] Better logic for hangup (for case where call have not been + sent yet) + * [#5571] Update error handling in voip links + * [#5571] Fix compile time warnings + * [#5696] Fix installation dependencies for Natty + * [#5669] Add mention that sflphone.org is for testing only + * [#5693] Add natty in teh dput.conf file + * [#5690] Remove not useful logs + * [#5670] Use dynamic payload type for rtp dtmf + * [#5668] Clean up sflphone configuration logging + * [#5668] Fix hook checkbox configuration update + * [#5666] Fix unit tests + * [#5666] Manage event subscription + * [#5666] Emit bye request when subscription is terminated + * [#5666] Bye request should be sent after event subscription + notification is done on transfer + * [#5666] Make reinvite method static (to be called in pjsip + callbacks) + * [#5666] Hangup Call in manager for AccountNULL and IP2IP + * [#5589] Use PKG_CHECK_MODULE for every client's dependencies + * [#5623] Enlarge initial size of pjsip memory pool for calls (16k) + * [#5564] Fix audio recording resampling for g722 + * [#5571] Move attribute handling for onhold/offhold actions in SDP + session + * [#5571] Codec negotiation refactored and unittested + * [#5571] Implement tests + * [#5571] Implement pjsip negociator + * [#5571] Fix unit tests + * [#5571] Add Fmtp.h to repository + * [#5571] Integrate mime types and codec factory + * [#5571] Handle exception when SDP negotiation fails + * [#5570] Add sflphoned-sample.yml in repository + * [#5564]: Implement stereo to mono mixing for rigntone + * [#5342] Update audio stream initialization + * [#5514] Restore test ni historytest suite + * [#5514] Fix + * [#5514] Disable test_create_history_path + * [#5514] use pulseaudio in sample config file + * [#5514] Fix test: load history from file + * [#5514] Do not use X + * [#5513] Make unit tests compile successfully + * [#3947] Enable unit tests in Jenkins + * [#5454] Fix build system to handle new version number + * [#5454] Update languages from launchpad + * [#5454] Add --without-celt in OpenSuse build service + * [#5454] Change version number + * [#5331] Added first SDP session tests + * [#5273] Update nightly build version tags to conform dpkg rules + * [#5211] Refactor send register method for iaxvoiplink and + sipvoiplink + * [#3950] Remove call being transfered from calltree + * [#5211] Use appropriate memory pool for transport selector + * [#5211] Fix strict aliasing rules warning in pjsip + * [#5211] Bring back pjsip shutting down sleep to 1000 ms + * [#5211] Fix registration callback segfault when closing the + application + * [#5211] Use the dialog memory pool for Route header in INVITE + request + * [#5211] Add temporary memory pool for findLocalAddressFromUri and + findLocalPortFromUri + * [#5211] Use individual memory pool for dtmfs + * [#5211] SipVoipLink refactoring + * [#3950] Attended transfer for conference calls + * [#5284] Fix DNS resolution for Route with specified port number + * [#5284] Some code cleanup + * [#3947] Fix typo in hudson script + * [#5284] Added sip route to REGISTER, INVITE, BYE request, plus DNS + resolution + * [#5266] Use RTP dtmf as default + * [#5284] Added pjsip_process_route_set after setting routes in regc + structure + * [#5286] Fix parsing error due to long configuration file (removed + max event) + * [#5286] Fix false test in configuration emmiter + * [#5286] Code cleanup + * [#5286] Updated exception handling in configuration system + * [#4969] Fix put SRTP call on hold + * [#3950] Add debug messages + * [#3950] Ability to perform an attended transfer + * [#5276] Fix initialization problem in g722 + * [#3950] Add replace header in SIPVoIPLink::transferWithReplaces + method + * [#3950] Implemented attended method in SIPVoIPLink + * [#3950] Cleanup transaction request received callback + * [#3950] Implement dummy attended transfer in gnome-client + * [#5249] Fix audio samplerate update algorithm for g722 + * [#5249] Fix uninitialized variable used in conditional jumps + * [#5249] Fix conditional jump error in audiolayer (uninitialized + value) + * [#5267] Use autoconf 2.65 as a requirement (instead of 2.67) + * [#5267] Restore manual pjsip configuration and compilation + * [#5267] Autodetect celt version (0.9.1, 0.7.1) + * [#5267] Fix deprecated macros in gnome client configure.ac + * [#5267] Update configuration for libcelt-dev + * [#5267] Fix build autoconf and automake + * [#5227] Deactivate automatic call to astyle after compilation + * [#5242] Hangup every calls before leaving + * [#5237] Will now nightly-build for natty, Karmic deprecated + * [#5229] Use inner class for rtp thread instead of inheritance + * [#5211] Move mainbuffer unbind call in rtp final method + * [#5211] Initialize sip call memory pool using 16 kb + * [#5211] Use call memory pool in session reinvite + * [#5211] Add debug messages + * [#5211] Use and internal pool for calls + * [#5211] Reduce pjsip memory pool usage for stateless error messages + * [#5211] Refactor call deletion + * [#5212] + * [#5208] Refactor codec management for accounts + * [#5168] Remove printf from codec's encode & decode method + * [#5168] Fix celt compilation on launchpad + * [#5168] Fix sflphoned compilation warnings in audiocodec.h + * [#[#5168] Must keep the g722 specific RTP rate to avoid incoming + packet timeout + * [#5168] Fix static/dynamic payload rtp session update + * [#5168] Throw SIPVoipLink Error if codec not instantiated in new + outgoing call + * [#5168] Fix dynamic/static codec payload type ambiguity + * [#5169] Fix doubled IP2IP profile when no config file + * [#4867] Add gtkinfobar in configuration panel + * [#4867] Disable input/output/ringtone selection when using default + alsa plugin + * [#4952] Patches for possible buffer overflows + * [$4885] Fix schemas problem + * [#4885] sflphone-client-gnome.schemas not present during build + * [#4885] Add gconf shemas directories in opensuse build system + * [#4885] Add file/folder ownership for opensuse-factory build system + * [#4906] Fix opensuse-factory build + * [#4885] Update name dependency for libedataserver + * [#4885] Fix non-void function without return in dbus-c++ + * [#4895] Update language translation + * [#4896] Update session timestamp when updating media + * [#4896] Reapply RTP hack for G722 payload type + * [#4896] Update recording sampling rate when updating codec + * [#4897] Save codecs in config for each configuration changes + * [#4895] Do not save config when sflphone quit + * [#4885] Update date for copyright + * [#4885] Deactivate siptest that require more than one sipp instance + * [#4879] Remove inmcoming call notification from IAX + * [#4885] Some cleanup + * [#4874] Add setCancel immediate/deffered for ost::Thread + * [#4879] Fix incoming call notification + * [#4878] Set keyboard focus on searchbar when selecting addressbook + * [#4874] Fixed compilation warning + * [#4874] Fixed compilation warning in sipvoiplink + * [#4874] Fix compile time warning in RTP record handler + * [#4874] Fix conditional jump in SDP + * [#4874] Fix conditional jump based on uninitialized value + * [#4874] Store call id within rtp thread context + * [#4874] Fixed conditional jump based on uninitialised value in + conference + * [#4871] Fix default account fetching + * [#4870] Delete RTP session when Refusing an incoming call + * Restore IP to IP call + * [#4857] Fix audio codec negotiation problem + * [#3947] Adjust ressources allocated to compilation + * [#3947] Disable unit tests in Hudson + * [#4305] Free mutex only when really quiting SFLphone + * [#4859] Update copyright to 2011 in every source file + * [#3218] Character '.' stripped by the caller engine + * [#4854] Fix typos, desktop entry + * [#4847] Apply RTP modification to ZRTP session + * [#4852] Update Karmic and Lucid dependencies + * [#4852] Add Libedataserver and libedataserverui as gnome client + dependencies + * [#4852] Add authentication mechanism for EDS + * [#4851] Fix segfault when closing pulseaudio layer too rapidly + * [#4808] Some otehr cleanup + * [#4808] Made some cleanup + * [#4808] Added mutex in rtp session for codecs and noise process + * [#4847] Update audio processing when updating RTP media + * [#4842] Add support for linking with gold/ld --no-add-needed + * [#4808] Make update g722 related static/dynamic payload logic + * [#4827] Upper limit on the number of contacts to import from EDS is + hard-coded to 500 + * [#4808] Fix put call on/off hold + * [#4808] Implement early RTP start for incoming calls + * [#4808] Audio stream is no longer start within RTP session. + * [#4808] Removed coupling between audio layer and and RTP session + * [#4702] Start audio rtp session as soon as it is created + * [#4702] Init timestamp to 0 + * #4702: Send RTP packets immediately, no need of outgoing queue + * [#4784] Update dbus-c++ version from gitorious + * [#4702] Update RTP timeouts + * [#4702] Lengthen RTP timeouts + * [PATCH] Fixed compatibility with old libtool versions. + * [PATCH] Accept older libebook (Maemo 5 has 1.4.2) + * [PATCH] Fixed double-free error in preferences dialog + * [PATCH] Fixed building of sflphone-common on Maemo5 + * [PATCH] Improved Gnome client initialization error handling. 1. It + no longer segfaults when sflphoned isn't available. 2. User is + provided with GUI error dialog. + * [PATCH] Improved autogen.sh scripts 1. They do not require bash + anymore 2. Added workaround for Debian bug #565663 3. Replaced + manual autotools invocations with single autoreconf call 4. Non-zero + return status on failure + * Revert "[#4468] libtool <= 2.2 doesn't have LT_INIT macro so + AC_PROG_LIBTOOL should be used instead." + * Revert "[#4468] Libebook 1.4 is sufficient" + * Revert "[#4468] Apply big path on dbus communication system" + * [#4468] Apply big path on dbus communication system + * [#4468] Libebook 1.4 is sufficient + * [#4468] libtool <= 2.2 doesn't have LT_INIT macro so AC_PROG_LIBTOOL + should be used instead. + * [#4639] Fix determining default addressbook if this property is not + set in gconf + * [#4639] Fix memory leaks in Addressbook + * [#4637] Fix opening default addressbook at sflphone init + * [#4622] Free yaml events while parsing configuration file + * [#4623] Fix conditional jumps based on uninitialized variable + * [#4622] Fix leaks in yaml serialization engine + * [#4616] Fix addressbook warnings + * [#4514] Adjust RTP timestamp + * #4527: Rename Karmic libyaml and Celt package in debian control file + * #4495: Rework addressbook opening loop + * [#4524] Increment RTP count when sending data + * [#4524] DO NOT start RTP session twice + * [#4367] Use PKG_CHECK_MODULE for celt + * [#4367] Fedora package celt as celt (not libcelt) + * [#4367] Astyling + * [#4367] Update .po files + * [#4367] Fix segfault in gensin + * [#4354] Make celt a direct dependency on launchpad opensuse build + service + * [#4367] Make celt a required package, option --without-celt valid + * [#4367] Fix zrtp timestamping error + * [#4367] Fix audio zrtp timing + * [#4367] Dispatch ZRTP packets + * [#4367] Fix segfault when unloading account map + * [#4367] Fix zrtp session + * [#4367] Implement on packet receive + * [#4367] use symetric audio rtp session, not dual + * [#4367] Reduce packet receive/sent timeout + * [#4367] Reduce RTP timeouts + * [#4367] Move speaker data receive + * [#4367] Move speaker data receive + * [#4367] Move receive speaker data method + * [#4367] Remove debug in rtp session + * [#4367] Fix g722 codec clock rate + * [#4367] Fix noise suppression initialization + * [#4367] Fix segfault in RTP mic fadein method + * [#4367] Refactor mic data encoding in rtp session + * [#4367] Implement RTP main loop + * [#4367] Fix compilation problem + * [#4367] Fix AudioRtpclass using TRTPSessionBase + * [#4367] Fix AudioRtpSession putDtmfEvent shadowing + * [#4367] Fix AudioRtpSession putDtmfEvent shadowing + * [#4367] Refactor RTP session (phase 2) + * [#4367] Refactor RTP session (phase 1) + * [#4367] Remove Redeclaration of SymetricAudioRtpSession in + rtpfactory + * [#4265] Add continue statement in for loop for invalid addressbook + * [#4261] Makes addressbook initialization more robust + * [#4257] Add maverick in build system + * [#4233] Add sdp related unit tests + * [#4233] Add condition and signal in two incoming call test + * [#4243] Fix segfault in AudioSrtpSession + * [#4243] Fix memory leak in AudioSrtpSession + * [#4243] Make audio srtp optional in for incoming call + * [#4243] Add boolean variable to make sure remote crypto context + initialized only once + * [#4243] Add documentation to AudioSrtpSession + * [#4243] Use 80 bits authentication tags by default + * [#4243] Init audio srtp remote crypto context in + call_on_media_update + * [#4243] Move SDP negotiastion in mod_on_rx_request + * [#4243] Implement initLocalCryptoInfo to be called at different + momment + * [#4243] Init init local crypto context in when initializing audiortp + * [#4243] Change key length according to sdes negociation + * [#4243] Associate callid to accountid for incoming calls + * [#4242] Fix no SDES keys in IP2IP calls + * [#4242] Fix no SDES keys in IP2IP calls + * [#4233] Test for call on/off hold + * [#4233] Add two incoming call test + * [#4233] + * [#4233] Add 2 outgoing simultaneous call unit tests + + -- Julien Bonjean <julien.bonjean@savoirfairelinux.com> Fri, 30 Sep 2011 13:51:04 -0400 + +sflphone-client-kde (0.9.7~rc1~ppa1~SYSTEM) SYSTEM; urgency=low + + ** 0.9.7~rc1~ppa1~SYSTEM ** + + * [#2462] Set explicitly the transport on incoming call too + * [#2462] fix typo + * [#2462] Use different address for SDP and call IP + * [#2462] Use published address in SIP-SDP + * [#2181] Fixed changelog files + * [#2181] Updated spec file + * [#2402] Fix pointer to int conversion warning (atoi) + * [#2402] Remove daemon warnings, make indent + * [#2459] Make sure the stream is opened when the call is answered + * [#2402] Add conference related picture in documentation + * [#2443] Not much ... + * [#2399] Fix dialing display problem + * [#2450] Fix incoming call already in conference crash + * [#2399] Display peer name on the first line and peer number on the + second + * [#2450] Handle 403 FORBIDDEN when refused + * [#2447] Bind offHold/onHold actions to button in gtk client + * [#2447] Bind hangup action to button for conference + * [#2447] Add conference action in gtk client's ToolBar + * [#2381] Disable the password hashing in config file + * [#2402] Cleanup + * [#2366] Set callback to null when deleting Pulseaudio streams + * [#1313] Fix main buffer unit test + * [#1313] Fix audio layer unit test + * [#2315] Hide pw in security tab, display when editing, sync with + basic tab + * [#1313] UnitTest change AudioRtpSession for AudioSymetricRtpSession + instance + * [#2402] Code cleanup + * [#2444] Add debug to catch occasional crash when loading client's + config + * [#2444] Add debug info to catch occasional crash when loading config + dialog + * [#2402] Restore Call menu translations + * [#2403] Use the published address if checked in GUI + * [#2442] Add protection test in sdp + * [#1841] Reapply pjsip patch concerning DNS SRV resolution + * [#2384] Tags incoming call as direct SIP call, if applicable + * [#2402] Change the monkey face + * [#2315] Enable user to display password in clear text + * [#2434] Force optimization level at 2 + * [#2284] Fix dbus_get_all_ip_interface compilation warnings + * [#2431] Popup main window on incoming if applicable + * [$2402] Fix simple warnings + * [#2402] Fix implicit variable init order in LibraryManagerException + * [#2402] Fixing implicit variable initialization warnings in + AudioRtpSession + * [#2402] Revert atoi change, fixing codec list doubled entries + * [#2402] Fix gpointer to gint conversion + * [#2402] Fix pointer casting to integer different size warning in + codec list + * [#2402] Fix warning discarting qualifiers from pointer target + * [#2402] Fix gtk tree view assignement from incompatible type warning + * [#1669] Fix audio recording folder utf-8 non compatibility issue + * [#2414] Clean up debugs + * [#2414] Use transport set in iptoip Account and update it frm + preference + * [#2348] Use macro N_() to mark ui.xml strings as translatable + * [#2414] Rename getSipAddress/setSipAddress functions + * [#2407] Fix volume controls display + * [#2407] Fixes dialpad + * [#2383] Set ip to ip config when clicking apply button + * [#2404] Update call-to script - Maxime Chambreuil + * [#2405] Client handles unknown call in current state as well + * [#2383] Add DBUS signal to send IPtoIP local address and port as + string + * [#2383] Add Ip to IP config change apply call back + * Clonflict + * [#2402] Code cleanup + * [#2383] Do the same for IPtoIP (init localn ip with first in the + list) + * [#2383] Use first interface in the list if local addresss is not + defined + * [#2403] Clean up unuseful addresses/ports + * [#2403] Use the IP profile SIP port as global SIP port + * [#2383] Fix dbus_get_all_ip_interface warnings + * [#2383] Take into account sameAsLocal when loading published address + * [#2383] Tsake into account sameAsLocal option when saving published + address + * [#2383] Update local ip address in ip to ip config + * [#2383] Save ip 2 ip local port in config + * [#2406] Update toolbar at startup + * [#2284] Remove redefinition warnings + speex warnings + * [#2383] Fix security table in account config + * [#2383] Save ip 2 ip network interface parameters in config + * [#2403] Restore sip transport selector + * [#2383] Fix filling the Localt IP Address on account creation + * [#2383] Fix Gtk-Critical when checking STUN + * [#2383] Fix reopening account configuration display issue + * [#2383] Load IPtoIP local address and port in preference iptoiptab + * [#2383] Add LocalAddress and Localport in Preference IpToIp tab + * [#2403] Use the address and port associated to the account as often + as possible + * [#1753] Removed pjsip generated files + * [#1753] Removed remaining milenage lib references + * [#2383] Add _publishedSameasLocal variable in sipaccount + * [#2383] Add PUBLISHED_SAMEAS_LOCAL variable in config + * [#2383] Fix stun set active or not when opening config + * [#2181] Added RPM 64bits dbus patch + * [#2402] Code indentation + * [#2313] Force $(HOME).cache directory creation at startup + * [#2383] Separate network interface and published address in account + config + * [#2400] Change dbus service installation path to libdir + * [#2382] Move TLS related published address options in security tab + * [#2382] Indent accountconfigdialog.c + * [#2181] Install libdbus-c++ in $pkglib instead of $lib + * [#1753] Remove ILBC code and disable it by default in the configure + * [#1753] Remove milenage directory + * [#2382] Fix switching interaface instabilities + * [#2396] Save local ip in account creation wizard + * [#2284] Remove warning on hold + * [#2387] Fixes history searching and filtering + * [#1215] Add samplerate display in the GUI + * [#1663] Voicemail icon reflects voice messages + * [#2395] Fix account registration ( specifically with callcentric) + * [#2386] Strip "sip:" on incoming call, fixing history call back + * [#2181] Updated spec files + * [#1215] Display codec name in calltree instead of status bar + * [#2390] Move back nbCalls and stopStream higher in refuseCall + * [#2392] Fix ringtone during call in IAX + * [#2391] Stop audio streams when there is 0 calls only + * [#2391] Add debug when call state is not valid + * [#2390] Clear returns in IAXvoipLink::sendAudioFromMic() method + * [#2380] Fixing IncomingCallNotification not regular + * [#2339] Query conference at client startup + * [#2339] Working conference querying at startup + * [#2339] Add conference in call tree + * [#2339] Primitives to query conferences at client startup + * [#2320] Add account selection in history + * [#2355] Temporary solution: do not delete pointer when removing + account + * [#2380] Change algorithm in AudioRtp to trigger an + IncomingCallNotification + * [#2274] Comment sdebug in MainBuffer flush method + * [#2274] Add flushMain() in ManagerImpl::addStream + * [#2274] Add getBufferID() method in ring buffer + * [#2274] Fix warning, comment debug in ringbuffer's flush method + * [#2274] Use AudioLayer flushMain() and flushUrgent() in ALSA + * [#2274] Clean up unused variable warning + * [#2274] Protect minbudffer pointer on flushing + * [#2274] Fix playATone method which writing empty buffer in urgent + ringbuffer + * [#2274] Use audio layer flushUrgent and flushMain in createStreams + * [#2274] Use flush audio calls from audiolayer + * [#2274] Flush when peer answered call + * [#2375] Flush main buffer in iax when answering a call + * [#2274] Parse displayname using c++ string method + * [#2375] Flush main buffer when off holding calls + * [#2375] Flush main buffer mon RTP startup + * [#2376] Use now Pulseaudio module-cork-music-on-phone + * Updated OSC packaging + + -- Julien Bonjean <julien.bonjean@savoirfairelinux.com> Fri, 20 Nov 2009 14:00:02 -0500 + +sflphone-client-kde (0.9.7~beta~ppa1~SYSTEM) SYSTEM; urgency=low + + ** 0.9.7~beta~ppa1~SYSTEM ** + + * [#1933] Cleanup debug + * [#1933] Clean up debug + * Fix mic + * [#1933] Set the IAx format earlier + * [#1933] Move IAX sendAudioFromMic outside if (call) statement + * [#1933] Fix startstream when offhold in iax and add debug concerning + codec neg. + * [#2371] sflphone_notify_voice_mail: minor gettext message formatting + cleanup + * [#2371] select_account_cb: properly gettextize status message + * [#2371] show_account_list_config_dialog: properly gettextize status + message + * INSTALL: Minor tidyup of core install guide + * Add /sflphone-client-gnome/src/icons/Makefile to .gitignore + * [#2181] Updated OpenSUSE files (tmp) + * [#1933] Add debug for codec negociation for iax + * [#1933] Get rid of getMicAvail and getMicData in audiolayer (not + used anymore) + * [#1933] Add "audio codec not determined" error in IAX + * [#1933] Test flush data + * [#1933] Do not need to start audio stream in iax anymore + * [#1933] Protecting pointer + * [#2284] Remove more compilation/execution warnings + * [#2284] Cleanup debug in client, use DEBUG instead of g_print + * [#2284] Clean up uimanager + * [#2370] Remove warnings + * [#2366] Clean up other debug + * [#2366] Clean up debug + * [#2366] Call pa_xfree explicitely in writeToSpeaker + * [#2284] Remove address book warnings + * [#2365] Fixes bad cast + * [#2352] Fix continuous ringing when peer hangup and call not yet + answered + * [#2181] Added version support + * [#2181] Fixed some minor issues + * [#2360] Moved MainBuffer from AudioLayer to ManagerImpl + * [#2352] Makes getMainBuffer() everywhere + * [#2352] Use 50 sec latency on pulseaudio stream creation + * [#2352] Add alsa debug + * [#2359] Update repository documentation + * [#2354] Move pulseaudio disconnectAudioStream after stopping main + loop + * [#2352] Adjust nb byte copied in pulseaudio according to + writeableSize + * [#2352] Specify pulseaudio tlength parameters using pa_usec_to_bytes + * [#2322] Convert italian translation to UTF-8 + * [#2357] Fixes window size + * [#2357] Display only actionnable tool item + * [#2333] Update streams parameters + * [#2347] Use GNOME user settings for Menu and Toolbar appareance + * [#2349] Load/Save properly audio params + * [#2322] Update translations from Launchpad + * [#2181] Added Francois Marier script + * [#2350] Remove non-valid test + * [#2181] Updated launchpad packaging + * [#2333] Fix Pulseaudio Capture + * [#2333] Use pulseaudio ADJUST_LATENCY flag and ALSA RT-SCHEDULING + * [#2333] Pulseaudio Interpolate timing + * [#2333] Change (again) Pulseaudio settings to fit logiteck usb hdw + requirement + * [#2333] Adjust pulseaudio fragment size to 4096 (max sflphone's + frames per buffer) + * [#2284] Remove recurrent compilation warning (g++ linker problem) + * [#2333] Safer Audiostream parameters + * [#2333] Fix alsa playback to reduce underrun + * [#2333] Better audiostream parameters + * [#2181] Updated version management + * [#2333] Exclusive test in playback loop + * [#2181] Updated build system + * [#2333] Less underrun with these value + * [#2333] Update playback audiostream parameters + * [#2333] Lengthen the audio buffer reduce number of underrun in + pulseaudio + * [#2333] Add ALSA recovery functions for underrun (begin) + * [#2333] Add pa_stream_trigger in pulse audio underrun callabck + * [#2048] Reduce prebuffering in pulseaudio (which affect incomming + calls' plbck) + * [#2316] Do not display any icons to the right on the history tab + * [#2333] Comment pa_stream_trigger in pulseaudio underrun + * [#2333] Modify pulseaudio streams parameters + * [#2318] Fix transfer tool button double signal + * [#2181] Updated + * [#2333] Fix ALSA ringtone + * [#2333] Flush all main buffer before starting audio + * [#2333] Open/Close Alsa thread between calls while there is no audio + * [#2333] Add debug message and test condition on starting playback + and capture + * [#2181] Fixed gnome client makefile + * [#2181] Updated + * [#2308] Remove getTelephoneTone debug + * [#2308] Change plughw for default in ALSA + * [#2308] Oups, forgot to change function name in audiolayertest.cpp + * [#2308] Cleanup in pulseaudio code (debug, function name) + * [#2308] Fix pulseaudio stream closing assertion failure + * [#2308] Moved pulseaudio mainloop locking from AudioStream + disconnect stream + * [2308] Fix latency at the beginning of a call, when playing DTMF and + wehn starting tone + * [#2181] Updated karmic + * [#2317] [#2319] Fix address book toggle button contextual behaviour + * [#2308] Stop stream when refusing a call + * [#2308] Stop pulseaudio stream when peer hungup + * [#2308] Fix tone and ringtone + * [#2312] Display the STUN entry widget when opening the tab + * [#2308] Implement two different callbacks for capture/playback in + pulseaudio + * [#2309] Open/close pulseaudio connections in startStream/stopStream + * [2308] Leave pulseaudio stream running, do not cork/uncork them + anymore + * [#2295] Set gtk file chooser to None if nothing is set in + configuration + * [#1976] Add codec and conference documentation + * [#2209] Fix recording in regard of resamling + * [#2297] Update .gitignore + * [#2297] Update translation files + * [#2297] Add reference to our coding standards + * [#2297] Remove old docbook code + * [#2296] Reinit tls account settings after modification + * [#2253] Add DcBlocker class to remove capture's dc offset + * [#2034] Fixes for TLS transport to initialize + * [#2284] Add silent build rule + client clean warnings + * [#2274] Fix unserialize history items in cilent at startup + * [#2274] Complete display name parsing and displaying + * [#2274] Parse the Display Name in sip INVITE message + * [#2050] Fix capture volume control in ALSA + * [#1970] Volume controls disable when using pulseaudio + * [#1970] Disable volume controls when using pulseaudio + * [#2277] Fix direct ip2ip ZRTP enabling/disabling in ip2ip + preferences + * [#2181] Added launchpad debian files + * [#2181] Added spec files for OSC + * [#2274] Set display name for "Contact" sip header as the hostname + * [#2181] Fixed daemon issues + * [#2181] Fixed gnome client issues + * [#1976] Remove warnings - need to fix the transfer + * [#2006] Add init is_rec variable in ManagerImpl + * [#2006] Update codec display on call selection + * [#2006] Restore double click actions in history and contact calltree + (GTK) + * [#2176] use XDG_CACHE_HOME when initializing sfl.zid file + * [#1976] Fix calltree switching from history + * [#2209] (Re)Fix cache for zid + * [#2209] Clean up debug messages + * [#2209] Clean debug messages + * [#2209] Fix trasnfering a call during a conference + * [#2209] Speex decode must return the number of bytes + * [#2209] Change frameSize speex 32kHz + * [#2209] Fix speex codec framesize + * [#2209] Reinit converterSamplingRate in RTP sessions + * [#2209] Change speex ultra wide band framesize + * [#1747] Add pixmap data + * [#2252] Fix Receiving a server error 488 crashes the callee + * [#2209] Fix iax low rate packate sending + * [#2209] Clean up debug messages + * [#2209] Add resampling changes for IAX + * [#2209] Clean up resampling code + * [#2209] Fix latency introduced by pulseaudio + * [#2209] Fix initialization of mainbuffer's internal sampling rate + * [#2176] Fix upsampling buffer size in audiolayer + * [#2209] Add dynamic converter sampling rate in audiortp sessions + * [#1747] Fixes runtime warnings + * [#1747] Remove from repo + * [#1747] register our icons to be used as stock icons + * [#2209] Fix number of byte in alsa's write to speaker + * [#2209] Fix putting non-resampled data in RTP's mainbuffer + * [#2209] Add alsa resampler + * [#2209] Add a samplerate converter in PulseLayer + * [#2209] Add mainbuffer's internal sampling rate and flushall method + * [#2176] Add mainbuffer stateInfo debug method + * [#2209] Resampling is optimal using SRC_LINEAR not SRC_FASTEST + * [#2176] Remove debug recordings + * [#2176] Fix Holding a conference participant on new calls + * [#2224] Add confID in callable object + * [#2176] Fix putting onhold a call participating to a conference when + pressing new call + * [#2176] Reset auidio buffers when adding streams (rtp, audiolayer) + * [#1976] Use xml to describe toolbars - Add a naviguation toolbar + * [#2176] Remove conference default_id in joinParticipant + * [#2176] Display error message in alsa's snd_pcm_avail_update call + * [#2176] Alsa mic avail data debug + * [#2176] Add some debug message for mic loss problem + * [#2176] Flush mic ring buffer when offholding a call + * [#2176] Reset ringbuffers' readpointer when adding main participant + * [#2176] Fix getAvailData algorithm + * [#2176] Reset ringbuffer's readpointer when adding a new participant + to a conference + * [#1744] Regex object renamed to Pattern. Previous attempt at + providing + * [#2176] Fix detach main participant problem when adding new one + * [#1976] Use right domain to translate + * [#1976] Add xml menu description + * [#2176] Store a list of confernece participant in client + * [#2176] Fix add participant, joinparticipant methods + * [#2181] Do not install dbus-c++ headers + add return value + * [#2176] Fix minor call handling instabilities + * [#2174] Fix incoming IP call contact address + * [#2211] Add test to protect NULL pointer + * [#1163] Add Advanced account configuration section + * [#2176] Add some usefull comments and debugging info + * [#2176] Add conditions to display security icons in conference + * [#2176] Fix detaching one participant while keeping communication to + others + * [#2176] Reenable userActive.svg in call tree + * [#2176] Make user active blue (not red) + * [#2176] Fix user active picture + * [#2176] Fix "hidden" merge conflict in sipvoiplink + * [#2176] Remove iax audio stream on peer hungup + * [#2174] Multiple UDP transports functional (TESTED with 2 accounts + and 3 calls) + * [#2176] Fix fix audio stream binding in iax + * [#2174] Create a default UDP transport + use tp selector for dialogs + also + * [#2176] Register iax audio stream in mainbuffer + * [#2176] Fix getAudioCodecName in IAXvoipLink + * [#2176] Fix iax account init + * [#2176] Handle multiple account using the same sip transport + * [#2165] Add .png files + * [#2176] Small fixes concerning dtmf + * [#2176] Fix make uninstall in codecs + * [#2174] remove stund makefile generation + * [#2176] Add conference lock + * [#2174] Add transport selector for multiple accounts + * [#2176] Change userActive picture from red to blue + * [#2176] Fix security pixbuff in calltree + * [#2176] Replace sfl.zid in .cache/sflphone instead of .sflphone + * [#2176] Fix add call description + * [#2176] Remove detach button from toolbar + * [#2176] Fix calltree call description state and state code in + conferences + * [#2176] Fix pulse audio double free + * [#2176] Fix conference selection + * [#2174] Clean up - remove stun settings in client network + configuration panel + * [#2174] Remove voviva stun code + * [#2174] Rsolve STUN with pjsip - DO NOT WORK + * [#2165] Add user svg + * [#2165] Debugging sip call failed + * [#929] Link against uuid if installed + * Oops + * Fixed bugs related to libsexy (with GTK < 2.16) + * [#929] Remove uuid-dev dependency in the core + * [#2165] Debugging no negociated codecs at communicatio start + * [#2165] Fix calltree bug (gtktreestore instead of gtkliststore) + * [#2165] Fix several merge problems + * Updated opensuse packaging script + * [#1163] Add missing figures + * [#1163] Update INSTALL file + * [#2165] Fix IAX + * [#2165] Add recordabe interface + * [#2165] Finish recording refactoring for call (not for conference) + * [#2165] Enable speaker recording for two different calls + simultanously + * [#2165] Implement call recording using the Recordable interface + * [#2165] Add get and set to AudioLayer's audio recorder + * [#2165] Add class recordable from which inherit call and conference + * [#2006] Fix G722 and Speex 8khz codec conferencing + * [#2006] add recording of audio buffers + * [#1163] Add general settings section + * [#1163] Fixes makefile error + * [#2006] Fix some minor issues + * [#2006] Drag a conference call on another conference call + (difference conferences) + * [#2006] Fix dragging a conference on itself + * [#1744] Integrating some of the needed regular expression patterns + in order + * COmplete call features + * [#1744] Added support for named subgroup in the Regex object. Also, + new + * [#1744] Adds thread safety features, compile() and setPattern() + methods to the Regex class. + * [#1744] Fix inconsistency in the finditer method from the last + commit. + * [#1744] Added regex pattern object built on top of libpcre. To be + used + * [#1744] Initial commit towards implementing RFC4568. Unimplemented + in the + * [#2157] Hide "security" and "advanced" tabs for IAX under account + * [#1163] Add call features section + * [#2006] Add joinConference capabilities + * [#2006] Add dbus joinConference signal + * [#2006] Drag a conference call onto a conference to add it + * [#1163] Add addressbook section + * [#2006] Drag a conference call onto a single call to create a + conference + * [#2006] Expand rows automatically + * [#2006] Add minimal multiple conference handling + * [#2006] Add atached/detached conference icons + * [#2006] Add function processRemainingParticipant + * [#2006] Deep refactoring, fix hangup bug + * [#1163] Update documentation - Accounts part + * [#1976] Integrate user doc to gnome client build system + * [#2122] Remove double inclusion in dbus-c++/src/Makefile.am + * Remove pjproject version number + * [#2006] Fix peerHungup + * [#1976] Make Yelp accessible from the GNOME client (need to install + the sflphone.xml first) + * [#2006] Fix multiconferencing hangup + * [#2006] Fix hangup calls in a conference + * [#2150] Make IAx2 reappear + * [#2006] Fix detach participant on multiple call + * [#2006] Can remove rining call from a conference + * [#2006] Reinit confID when removing a participant + * [#2006] Remove get isCurrentCAll in hangup/peerhungup (SipVoipLink) + * [#2006] Fix refuse call + * [#2006] Fix answerring incoming call + * [#2006] Refactor conference's participant list + * [#2101] Re-integrate test compilation in main build system + * [#2101] Make the test directory compile + * [#2136] Restore history functionality + * [#2006] Fix binding main participant to himself + * [#2006] Fix add current/incoming/onHold participant to an existing + conference + * [#2006] Fix add incoming calls to an already created conference + * [#2006] Fix remove stream + * [#2006] Fix detachParticipant/removeParticipant switchCall ids + * [#2006] Fix adding a call in conference having state "CURRENT" + * [#2006] Remove/add main participant from conferences + * [#2006] Hold/unHold conference + * [#2006] Detach a partcipant from drag n drop + * [#2006] Hangup a conference + * [#2006] Add hold/unhold conference dbus messages + * [#2034] gtk-ui fix under the "basic" tab. + * [#2006] Fix dragging calls on conference calls + * [#2006] Fix detach participant from a conference + * [#2034] Added default message is status bar under the account config + dialog + * [#2112] Fix a crashed caused when a non-md5 password was sent to + pjsip. + * [#2006] Detach participant by ID + * [#2006] Fix addParticipant method in managerImpl to handle + incoming/answered calls + * [#2006] Add addParticipant method in managerimpl and related dbus + messages + * [#2111] Added the ability to configure zrtp on sip.sflphone.org from + * [#2106] Fixed problem in the account assistant under gtk-ui. Also, + assistant.c + * [#2006] Fix dragging a conference call on another conference call + (same conference) + * [#1904] Small UI fix. Assistant was moved from "Call" to "Edit" + menu. + * [#1904] Fix a wrong label under gtk-ui. + * [#2034] Renaming and source code splitting. + * [#2034] Status bar added to account window to better reflect the + registration + * [#2006] Make calltree_remove_call recursive (for GtkTreeStore) + * [#1110] Small gtk-UI fix in the account window (alignment). + * [#2006] Fix remove conference, display children which are still + active + * [#2006] Recursive function call in calltree_update_call + * [#2006] Add multilayered capabilities to calltree (GtkTreeStore) + * [#2006] Implement remove conference in calltree + * [#2034] Now useless as Direct Ip calls settings moved under + Preferences. + * [#2034] Edit/add buttons were set insensitive all the time under + gtk-ui. + * [#1887] Information about the state of the current SIP call is + displayed + * [#2006] Add call tree remove callback + * [#2006] Fix create_conference function + * [#2006] Update conference_added_cb to add new conference to the list + * [#812] Added new tab under GTK-ui Preferences. Moving Direct Ip + Calls from + * [#2121] Disable temporarily test compilation + * [#2006] Fix conferencelist to handle conference_obj_t instead of + gchar + * [#2006] Add conference_obj structure + * [#2121] Update version + * [#2006] Fix conference selection + * [#2101] Use the new source tree to fetch the right object files + * [#2006] Add conference in calltree + * [#2006] Add Dbus signal conference added/removed/changed + * [#2006] Add getConferenceDetails call on dbus + * [#1904] Registration expire now appears as a spin box under gtk-ui. + * [#812] Fixing a segmentation fault caused by a non-existing account + ID + * [#2006] Add getConfList method over dbus + * [#2006] Add a conferencelist data structure in client-gnome + * [#812] Defaults value are now sent if a non-existing account is + requested + * [#2006] Add sflphone action sflphone_join_participant + * [#2006] Fix buffer read pointer problem deletion + * [pjsip] Attempt at fixing via header incompatibility with + Freeswitch. + * [#1797] forget something + * [#2006] Add call new state conferencing in deamon + * [#2006] Remove addParticipant method for conference, use + joinParticipant only + * [#1163] Update INSTALL documentation + * [#812] Msec/sec values were not taken into account. + * [#1797] Make pjproject-1.4 compile + * [#2006] Add Detach participant method + * [#2006] Dragndrop fully functional with INCOMING and HOLD call + * [#1797] Add pjproject-1.4 + * [#1797] Remove pjproject-1.0.3 + * [#2006] Get call state in conference related function + * [#2006] Add joinParticipant (conference) method in ManagerImpl + * [#2006] Add joinConference DBUS message + * [#2006] Store the previously selected call_id on dragndrop + * [#2006] Fix GValue pointer unref in selection callback + * [#2006] Store dragged call_id + * [#2006] Update drag_data_received_cb callback to manipulate CallIDs + * [#2006] Add dragndrop signals + * [#2006] Set calltree reordable + * [#812] Adds the ability to create a TLS listener in case the user + requests + * [#812] Adds the ability to configure local/published address from + * [#1883] Move switchCall in onHoldCall function + * [#812] Deals with the published address/port problem when + integrating TLS. + * [#1883] Switch call id in managerimpl when peerHungUp + * [#1883] Switch call id before hangup + * [#1883] Add usefull and permanent debug info for conference + cretion/deletion + * [#812] Fix various segmentation faults related to Direct IP kind of + calls. + * [#1883] Fix deletion of std::map elements using iterators + * [#2014] Add libzrtpcpp build dependency + * [#1883] Still some for loop test ambiguity (while loop instead) + * [#1883] Fix for loop initial test ambiguity (use while loop instead) + * [#1883] We must discard data in urgent ring buffer if data is get in + mainbuf + * [#1883] Fix availForGet same id for ringbuffer and readpointer + * [#812] Match "sips" as a Direct IP Call when the user enter a sip + uri + * [#812] Fix segmentation fault related to SIP URI creation. + * [#812] Towards integrating multiple tls listeners at the same time. + This + * [#1883] Add debug messages in conference and fix mainbufferTest + * [#812] gkt-ui fix. Private key must be fed as a filename and not as- + is. + * [#812] TLS integration within sipvoiplink and pjsip. Also, + configure.ac + * [#1883] Fix Alsa/Pulse mallocation + * [#1883] Fix data corruption in AudioRtp's micData buffer + * [#812] Full dbus integration for all the tls related options under + gtk-ui. + * [#1883] Fix memory leaks in audiortp session + * [#1883] Fix mem leaks in audio rtp + * [#812] Fix setAccountDetails where TLS_ENABLE was set to the value + * [#812] Small gtk-ui fix. + * [#811][#812] Small gtk-ui fix. + * [#812] Introduced a mechanism for configuration files that makes + possible + * [#812] New dbus bindings added. Also, configuration compliance was + enforced + * [#1881] Remove default buffer from MainBuffer (update unit-tests) + * [#1881] Add ring buffer read pointer tests + * [#1883] Fix issues in ringbuffer reader pointers + * [#2034] Implementing a new configuration dialogue for TLS transport + settings + * [#1883] Add some usefull debug and safety checks + * [#2028] Notify the client with libnotify when the zrtp negotiation + failed. + * [#811] Harmless no to throw an exception, an makes the application + less + * [#2028] A minidialog is showed to the user under sflphone-client- + gnome + * Removed useless file. + * Ignoring Makefile in src/widget + * [#2027] Fix segmentation fault when showMessage callback is called + after + * [#2026] keyExchange was set to ZRTP instead of "1" + * [#2024] Fix the wrong summary at the end of the assistant. + * [#1883] Fix mnagerimpl conference map insertion + * [#1883] Add Mutexes in MainBuffer + * [#811] Gtk ui was not presenting the right information about zrtp + for + * [#2023] security icons were not installed in sflphone-client-gnome. + * [#2021] Fix a mistake in the readme from sflphone-common that gives + wrong + * [#811] The current SRTP mode was not properly displayed for the + IP2IP + * [#1743] Re-implementation of the "automatically remove error dialogs + [...]" + * [#2017] [#2019] Fix the inability to dial a number and place a + registered + * [#811] Final re-integration of ZRTP support in the main branch from + 0.9.6 + * [#1883] Fix map insertion methods + * [#811] Combo box now is now set to the active key exchange method + * [#811] ZRTP options now configurable back again from the Gtk UI. + IP2IP + * Updated hostname for git clone + * [#1883] Add minimal functionalities to create a conference + * [#811] re-integration of all the methods and signals on dbus. + ManagerImpl + * [#811] Got out of a precarious position were nothing would compile. + * [#1976] Build documentation squeleton with docbook + * [#1883] Add sflphone-client "addParticipant" button for conference + * [#1994] Better organize the source directory structure. New + subdirectories + * [#1883] Add a simple Conference class + * [#1882] Use static audio buffer in Pulse and ALSA layer (instead of + malloc) + * [#811] First commit toward re-integration and refactoring of ZRTP + * [#1882] Flush RTP ring buffer before entering mainloop + * [#1882] Fixed MainBuffer::UnBinCallID() in case there is no + ringbuffer + * [#1882] Test (and fixe) high level conference and mixing + functionalities + * [#1772] Apply patch to compile on fedora (sent by Marcin + Zajączkowski <mszpak@wp.pl>) + * [#1882] Update Bind, unBind call_id in MainBuffer + * [#1959] This adds the ability to store password as an MD5 Hash in + the + * [#1538] Fixes rules compilation + * [#1930][#1931] Fixed a mistake (again) related to index and + credential count + * [#1753] Remove ILBC from pjproject - Hacks in pjsip + * [#1930][#1931] Credential was not selected properly using realm + * [#1882] Finilize multiple reading pointer in RingBuffer + * [#1538] Remove configure from autogen.sh to respect debian upstream + authors policy + * [#1773] Remove generated files from repo + * [#1791] Use XDG_CACHE_HOME to save pid file + * [#1791] Fixes path to save history + * [#1791] Fix debian installation scripts + * [#1930][#1931] Settings are now taken into account in the server. + * [#1882] Add ringbuffer default ring buffer pointer in methods + involving mStart + * [#1882] Add default ringbuffer pointer + * [#1882] Add RingBuffer multiple read pointer basic functionnalities + * [#1882] Fix MainBuffer flushData unit test + * [#1930][#1931] Ability to save and retreive the configuration from + * [#1882] Added Multiple CallID mapping to MainBuffer + * [#1791] Not much + * [#1791] If XDG env variables are not null but empty, use default + ones + * [#1791] Make XDG_CONFIG_HOME writable + * [#1930][#1931] Partial commit. Not working yet. Cannot delete + account + * [#1881] Fixed alsa capture latency problem + * [#1881] Fixed Alsa capture temporarily + * [#1930] [#1931] Partial unbroken commit providing the ability to + * [#1881] MainBuffer implemented in AudioLayer/AudioRTP + * [#1881] Add discard and flush unit-tests + * [#1881] Add discard and flush functionnalites to MainRingBuffer + * [#1881] Add availForGet in MainBuffer + * [#1881] Add availForPut function to MainBuffer + * [#1880] Remove AudioRTP* pointer from SipVoIP (reapered while + merging master) + * [#1881] Add a map between call id and coresponding ring buffer + * [#1855] Refresh pot file and upload on Launchpad + * [#1881] MainBuffe now robust to false ids on getData and putData + * [#1881] Fix big big big memory leak + * [#1881] Add getData and putData to mainBuffer + * [#1881] Unit-test basic ring buffer functionnaities + * [#1881] Add class MainBuffer and basic buffer creation unit-tests + * [#1880] Fix call transfer (step2) issues + * [#1880] Moved AudioRtp* pointer from SIPVoIPLink to SIPCall class + * [#1791] Add postinst script to keep user data when migrating + config/history file + * [#1797] Make pjsip compile + * [#1777] Code indentation + * [#1791] Use XDG_DATA_HOME and XDG_CONFIG_HOME for sflphonedrc and + history + unit tests + * [#1746] Useless space does not appear anymore when volume sliders + and + * [#1643] GtkCheckMenuItem is used instead of icons for elements in + the + * [#1110] [#1668] STUN parameters are now located in the preferences, + under + + -- Julien Bonjean <julien.bonjean@savoirfairelinux.com> Fri, 06 Nov 2009 11:23:15 -0500 + +sflphone-client-kde (0.9.6-SYSTEM) SYSTEM; urgency=low ** 0.9.6 ** @@ -63,9 +1884,9 @@ sflphone-client-kde (0.9.6-SYSVER) SYSTEM; urgency=low * [#1425] Put actions in SFLPhone window class instead of ui view, made a separate toolbar for screens. - -- SFLphone Automatic Build System <team@sflphone.org> Mon, 27 Jul 2009 09:53:37 -0400 + -- SFLphone Automatic Build System <team@sflphone.org> Mon, 27 Jul 2009 09:53:00 -0400 -sflphone-client-kde (0.9.6~rc2-SYSVER) SYSTEM; urgency=low +sflphone-client-kde (0.9.6~rc2-SYSTEM) SYSTEM; urgency=low ** 0.9.6~rc2 ** @@ -118,9 +1939,9 @@ sflphone-client-kde (0.9.6~rc2-SYSVER) SYSTEM; urgency=low * common po files * [#1753] Remove ILBC from pjproject - -- SFLphone Automatic Build System <team@sflphone.org> Fri, 17 Jul 2009 19:13:11 -0400 + -- SFLphone Automatic Build System <team@sflphone.org> Fri, 17 Jul 2009 19:12:44 -0400 -sflphone-client-kde (0.9.6~rc1-SYSVER) SYSTEM; urgency=low +sflphone-client-kde (0.9.6~rc1-SYSTEM) SYSTEM; urgency=low ** 0.9.6~rc1 ** @@ -226,9 +2047,9 @@ sflphone-client-kde (0.9.6~rc1-SYSVER) SYSTEM; urgency=low * [#1317] Changed tag convention * [#1317] Cleaned git-dch - -- SFLphone Automatic Build System <team@sflphone.org> Fri, 10 Jul 2009 15:50:55 -0400 + -- SFLphone Automatic Build System <team@sflphone.org> Fri, 10 Jul 2009 15:49:56 -0400 -sflphone-client-kde (0.9.6~beta-SYSVER) SYSTEM; urgency=low +sflphone-client-kde (0.9.6~beta-SYSTEM) SYSTEM; urgency=low ** 0.9.6~beta ** @@ -521,9 +2342,9 @@ sflphone-client-kde (0.9.6~beta-SYSVER) SYSTEM; urgency=low * Config Dialog almost finished. * Base of QT client - -- SFLphone Automatic Build System <team@sflphone.org> Tue, 23 Jun 2009 11:15:26 -0400 + -- SFLphone Automatic Build System <team@sflphone.org> Tue, 23 Jun 2009 11:12:06 -0400 -sflphone-client-kde (0.9.5-SYSVER) SYSTEM; urgency=low +sflphone-client-kde (0.9.5-SYSTEM) SYSTEM; urgency=low ** 0.9.5 release ** @@ -552,9 +2373,9 @@ sflphone-client-kde (0.9.5-SYSVER) SYSTEM; urgency=low * [#1406] add liblog4c-dev in build-depends * [#1409] Restore .desktop icon - -- SFLphone Automatic Build System <team@sflphone.org> Mon, 25 May 2009 11:34:48 -0400 + -- SFLphone Automatic Build System <team@sflphone.org> Mon, 25 May 2009 11:34:40 -0400 -sflphone-client-kde (0.9.5-SYSVER~rc2) SYSTEM; urgency=low +sflphone-client-kde (0.9.5-SYSTEM~rc2) SYSTEM; urgency=low ** 0.9.5 rc2 ** @@ -606,7 +2427,7 @@ sflphone-client-kde (0.9.5-SYSVER~rc2) SYSTEM; urgency=low * Bug #1405: Fix strings as requested. * Bug #1404: Fix strings in preferences panel. - -- SFLphone Automatic Build System <team@sflphone.org> Tue, 19 May 2009 12:08:18 -0400 + -- SFLphone Automatic Build System <team@sflphone.org> Tue, 19 May 2009 12:08:03 -0400 sflphone-client-kde (0.9.5-0ubuntu1~rc1) SYSTEM; urgency=low @@ -635,7 +2456,7 @@ sflphone-client-kde (0.9.5-0ubuntu1~rc1) SYSTEM; urgency=low [ Sflphone Project ] - -- Sflphone Project <sflphone@mtl.savoirfairelinux.net> Tue, 05 May 2009 19:16:13 -0400 + -- Sflphone Project <sflphone@mtl.savoirfairelinux.net> Tue, 05 May 2009 19:16:09 -0400 sflphone-client-kde (0.9.5-0ubuntu1~beta) SYSTEM; urgency=low @@ -857,7 +2678,7 @@ sflphone-client-kde (0.9.5-0ubuntu1~beta) SYSTEM; urgency=low [ Sflphone Project ] - -- Sflphone Project <sflphone@mtl.savoirfairelinux.net> Mon, 27 Apr 2009 17:00:03 -0400 + -- Sflphone Project <sflphone@mtl.savoirfairelinux.net> Mon, 27 Apr 2009 16:57:00 -0400 sflphone-client-kde (0.9.4-0ubuntu2) SYSTEM; urgency=low diff --git a/tools/build-system/launchpad/sflphone-client-kde/debian/control.lucid b/tools/build-system/launchpad/sflphone-client-kde/debian/control.lucid index a4e6a266195dad90c9132c41a8373ea5bf84ae16..183ca4e831341b6778830669d3cfc0a5c017f4b3 100644 --- a/tools/build-system/launchpad/sflphone-client-kde/debian/control.lucid +++ b/tools/build-system/launchpad/sflphone-client-kde/debian/control.lucid @@ -8,7 +8,7 @@ Standards-Version: 3.7.3 Package: sflphone-client-kde Priority: optional Architecture: i386 -Depends: sflphone-common (>=${source:Version}), libcommoncpp2-1.6-0, kdepimlibs5, libqt4-dbus, libqt4-svg, libqtgui4 +Depends: sflphone-common (>=${source:Version}), ${shlibs:Depends}, ${misc:Depends} Replaces: sflphone Conflicts: sflphone Homepage: http://www.sflphone.org diff --git a/tools/build-system/launchpad/sflphone-client-kde/debian/control.jaunty b/tools/build-system/launchpad/sflphone-client-kde/debian/control.natty similarity index 86% rename from tools/build-system/launchpad/sflphone-client-kde/debian/control.jaunty rename to tools/build-system/launchpad/sflphone-client-kde/debian/control.natty index a4e6a266195dad90c9132c41a8373ea5bf84ae16..183ca4e831341b6778830669d3cfc0a5c017f4b3 100644 --- a/tools/build-system/launchpad/sflphone-client-kde/debian/control.jaunty +++ b/tools/build-system/launchpad/sflphone-client-kde/debian/control.natty @@ -8,7 +8,7 @@ Standards-Version: 3.7.3 Package: sflphone-client-kde Priority: optional Architecture: i386 -Depends: sflphone-common (>=${source:Version}), libcommoncpp2-1.6-0, kdepimlibs5, libqt4-dbus, libqt4-svg, libqtgui4 +Depends: sflphone-common (>=${source:Version}), ${shlibs:Depends}, ${misc:Depends} Replaces: sflphone Conflicts: sflphone Homepage: http://www.sflphone.org diff --git a/tools/build-system/launchpad/sflphone-client-kde/debian/control.karmic b/tools/build-system/launchpad/sflphone-client-kde/debian/control.oneiric similarity index 86% rename from tools/build-system/launchpad/sflphone-client-kde/debian/control.karmic rename to tools/build-system/launchpad/sflphone-client-kde/debian/control.oneiric index a4e6a266195dad90c9132c41a8373ea5bf84ae16..183ca4e831341b6778830669d3cfc0a5c017f4b3 100644 --- a/tools/build-system/launchpad/sflphone-client-kde/debian/control.karmic +++ b/tools/build-system/launchpad/sflphone-client-kde/debian/control.oneiric @@ -8,7 +8,7 @@ Standards-Version: 3.7.3 Package: sflphone-client-kde Priority: optional Architecture: i386 -Depends: sflphone-common (>=${source:Version}), libcommoncpp2-1.6-0, kdepimlibs5, libqt4-dbus, libqt4-svg, libqtgui4 +Depends: sflphone-common (>=${source:Version}), ${shlibs:Depends}, ${misc:Depends} Replaces: sflphone Conflicts: sflphone Homepage: http://www.sflphone.org diff --git a/tools/build-system/launchpad/sflphone-common/debian/changelog b/tools/build-system/launchpad/sflphone-common/debian/changelog index 7d5b2fb58422eb4d0d07c06f97e5c612bb380a7e..a7e89561170a9223419ad57bcf7afd545cd223e1 100644 --- a/tools/build-system/launchpad/sflphone-common/debian/changelog +++ b/tools/build-system/launchpad/sflphone-common/debian/changelog @@ -1,3 +1,1096 @@ +sflphone-common (1.0.0-rc20110930~ppa1~SYSTEM) SYSTEM; urgency=low + + ** SNAPSHOT 1.0.0-rc20110930~ppa1~SYSTEM ** + + * update kde .gitignore + * Fix bug in volume widget + * More polishing for release + * Bump version to 1.0.0 + * [#7023] Add the ability to load an abstract contact backend in the + library to resolve more data, polish code + * [#7021] More cleanup for release + * Cleanup + * [#7021] Refactor KDE client dbus handling, add a missing call in + daemon and port the DataEngine to the new API + * Remove some annoying debug + * merge language scripts + * remove obsolete 'VERSION' files + * update install instructions + * Add missing translations to gnome + * language update + * Revert "Don't reference count DBus clients, exit core immediately + when one of them request it" + * Don't reference count DBus clients, exit core immediately when one + of them request it + * [7021] Add contact abstraction support + * [#7121] Polishing library (over). Indentation, spacing and naming + are now consistent + * codecs: link to libccrtp, don't use logger + * Fix a daemon bug + * [#7038] Fix adding contact + * * #7037 : stop audio stream after all calls have been hanged up + * [#7025] Add full support for bookmark + * SFLPhone KDE do not destroy history anymore + * Fix config skeleton + * Close the daemon once and for all, no more automatic respawning + * Fix "unregistered account" bug (I hope so) + * Close SFLPhone at the right place, it still respawn, I don't know + why + * Remove dead code + * Fix regressions introduced in the last commit + * Dead code elimination 1/3 + * Fix bug, add "add contact" option, fix warning + * * #7019: Fix IAX codec negociation + * Remove or comment unnecessary/unhelpful debug output + * Fix "same as local" account setting, fix IP2IP LED color + * Add support for some more advanced config options and add missing + config dialog icons + * Fix crash with noise suppressor + * Alternative can now be selected from the call view context menu + * Add drag and drop support, initial context menu and fix 3 bugs in + the account dialog + * Add basic history drag and drop support + * Complete contact support is back + * * #6991 : fix IAX problems + * Fix IAX accounts being disabled by default + * Revert "deb: forge -g flags for pjsip" + * * #5884: Disable debug code in pjsip + * echo suppressor : more assertions + * Don't let the daemon think crypto is enabled when it's not + * Simplify ToneList + * Some progress on contact support + * Remove unused getRegistrationCount() + * remove annoying debug + * revert SIP bit of e27e5c39bad27bae28f574eb2cba7717e8956229 + * Simplify CallManager::placeCallFirstAccount + * Fix crash on hold + * * #6905 : SIP refactor + * gnome client: be sure key exchange is set correctly + * Move code into createSipTransport + * Fix account registration on start + * ManagerImpl::registerAccounts(): simplify + * * #5884: don't mess with pjsip threads in echo suppressor + * * #6905 : simplify udp/stun/tls pjsip transport creation + * Restore and improve support for Call history + * fix launchpad build + * SIPVoIPLink: simplify / refactor + * Fix libwidget linking + * SIP: simplify + * IM : simplify + * gnome: remove some debug + * AudioRtpFactory::stop() cannot fail + * * #6905: simplify SIP code + * pjlib: fix build without SSLv2, fix warnings + * Port history to the new syntax + * Test a dock widget based implementation for contact and history + * Disable SSLv2 support from pjsip and sflphone + * deb: forge -g flags for pjsip + * Fix deb packaging to get debug symbols + * remove debug + * pjproject: update to last stable release (1.10) + * Require gtk >= 2.20 and glib >= 2.24 + * tlsadvanceddialog: simplify + * * #6902 : fix errors spotted by -DGSEAL_ENABLE + * Update daemon dbus XML and port KDE config backend from dbus to + local + * Remove unused but set variables + * * #6929 : fix IM widget, cleanup + * Unconditionally enable debug symbols + * Should fix many KDE issues + * * #6886 : hitting backspace on empty number have no side effects + * * #6905 : fix AudioCodecFactory access in optimized builds (-O > 0) + * Remove unsupported and broken jaunty/karmic packages + * * #6902 : avoid using some gtk deprecated functions + * Update dbus introspection files + * * #6904: removed unused contactmanager + * * #6903 : use correct dbus-cxx package name + * * #6902: don't use individual gtk headers + * Fix a segfault when config is not present + * Merge latest (0.9.13) KDE code. This version is not yet ready for + git master, but better than the previous one + * addressbook : simplify + * * #5659 : sflphone-plugins doesn't depend on libedataserverui + * * #5659 : addressbook doesn't use libedataserverui + * gnome client doesn't depend on evolution + * * #5695: addressbook: simplify + * * #5695: addressbook : remove AddrBookHandle from plugin + * * #5695 : addressbook : remove unused stuff in the client + * * #5695 : addressbook : remove unused stuff, use static mutex + * gnome client doesn't use evolution + * gnome: use proper API to set GTK_CAN_FOCUS + * * #6897: removed unused focus state vars/callbacks + * gnome: fix calls to sflphone_fill_codec_list_per_account + * * #6623: gnome: don't leak in mainwindow + * gnome: mainwindow whitespace cleanup + * gnome: actions.c parameter doesn't have to be a double pointer + * * #6895: fix memleaks, cleanup in accountconfigdialog + * * #6893: fixes segfault in client on clean history + * * #6894: fix leaks, cleanup in sflnotify + * daemon: fixed prints in main + * * #6892: simplify, fix leaks in dialpad + * * #6887: audiopreference creates audio layer + * * #6660: use const char * const, not std::string for globally + visible constants + * * #6852: Preferences now solely responsible for audiolayer creation. + * * #6860: refactor uimanager, also fixes #6865 + * * #6853: hangup as soon as all digits have been deleted + * * #6852: alsa: retry if device is busy + * * #6852: audiolayer creation depends only on preference.audioApi + * * #6850: gnome: fix build for gtk < 2.22.0 + * cleanup in iax + * alsa: typo + * pulse: if we can't peek in audio input, we can't drop samples + * * #6849: show error window if codecs are missing, instead of dying + * EchoCancel: unused, remove + * * #6629 : use number of samples as arguments for audio filters + * * #6629 : remove unused Algorithm interface + * * #6629 : use helper to call alsa functions and display error msgs + * Remove unused type + * * #6841: fix some error handling + * * #6629: simplify AlsaLayer::alsa_set_params() + * Get gdk key definition from header + * * #6828: Replace raw key codes by gdk defines + * remove some debug, enhance some other + * mainbuffer: simplify + * * #6561 : fix phantom call after transfer + * Conference Participant set : simplify + * SIPCall: remove unused functions, make invite session public + * * #6229 : remove malloc/free from pulse audio loop + * * #6629 : simplify pulse callbacks + * * #6629 + * Simplify widgets + * * #6629 : keep the correct audio module when frequency changes + * * #6751: fixed erroneous debug msgs + * callable_obj.h: removed unneeded pthread header + * alsalayer: cleanup + * * #6629: Always restart audio driver when changing parameters (ALSA + only) + * gnome GUI: don't block in DBus signal errorAlert() + * * #6629 : simplify AudioLayer creation + * * #6629 : remove unused and unconfigurable frameSize from audiolayer + * * #6629 : remove unused error message from audio layer + * Fix logic error when switching audio API + * Remove unused AudioProcessing class + * AudioRtpRecordHandler::initNoiseSuppress() : use noiseSuppress + directly + * * #6629 : use DC blocker directly in audio layers + * * #6629 : clean AudioLayer + * * #6629 : don't store mainbuffer inside audiolayer + * * #6629 : correct AudioLayer::notifyincomingCall() + * * #6554: cleanup, refactoring in sipvoiplink + * * #6554: cleanup in iaxvoiplink + * * #6554: throw exception in getSIPCall if pointer is NULL + * * #6554: make some methods of sipvoiplink static + * * #6655: cleanup in managerimpl + * * #6554: refactoring, fix memleaks in sipvoiplink + * * #6478: remove throw specs, cleanup in voiplink + * * #6629 : remove unused AudioDevice + * * #6655: removed more dependencies from managerimpl + * * #6744: simplified numbercleaner + * conference : remove one prototype + * * #6743: fix ip2ip + * Don't give glib warnings if icons are not found + * gnome: fixed includes + * Codec.h: removed unused function + * * #6742 : clean dbus & icons + * * #6699: refactor/cleanup accounts + * icons: cleanup + * timer : use second precision, not millisecond + * calltree_update_clock : use correct type, returns something + * * #6737: fixed typo in dbus call + * * #6737: removed tests for removed API + * * #6737: dbus: fixed bug from merge + * * #6737: cleanup in accountlist + * * #6737: cleanup in dbus + * * #6740 : fix history double free + * * #6740 : remove time updating thread from calls + * * #6737 : use c99 for client + * * #6738 : make history loading faster + * sipvoiplink : don't crash on transfers + * fixed typo + * Remove unused file + * Don't build networkmanager.cpp at all if NM is disabled + * _debug* -> _debug + * * #6554 : simplify sipvoiplink + * hudson: added -x to git clean command + * added git clean to hudson script + * audiocodecfactory: cleanup + * * #6718: refactored setTlsSettings into SIPAccount + * * #6718: removed more unused methods + * * #6718: refactored confmanager code into sipaccount + * remove unused functions + * * #6718: confmanager: removed more unused methods + * AudioCodecFactory : cleanup + * #6697 : Turn callableElement struct into union + * * #6718: confmanager: removed more unused methods + * * #6718: confmanager: removed more unused methods + * * #6718: removed unused dbus methods, refactoring + * * #6699: accounts: cleanup/refactoring + * * #6699: refactoring, cleanup in accounts + * * #6699: more account cleanup + * remove unused autoconf variable + * * #6714: fixed hudson script + * make distclean in hudson + * added || exit 1 to run_tests.sh call + * * #6714: fixed make distcheck for sflphone-plugins + * * #6714: fixed make distcheck for gnome client + * * #6714: fixed make distcheck for daemon + * git: #6698 split the main .gitignore file + * gnome: gpointer is already a pointer + * gnome: calltab_init: use calloc instead of malloc + * * #6699: more account cleanup + * * #6699: cleanup account + * * #6554 : more *voiplink cleanup + * * #6558 : more sipvoiplink simplification + * * #6558: saner loadSIPLocalIP prototype + * gnome: #6623 clean calllists + * * #6692: more audiolayer cleanup + * * #6692: cleanup/refactoring in audiolayers + * * #6692: more forward declarations, AudioThread->AlsaThread + * * #6692: audiolayer cleanup + * * #6692: alsalayer cleanup + * * #6558 : remove account creator + * * #6558 : clean sipvoiplink + * * #6554 : cleanup sipvoiplink + * audiortp: cleanup + * * #6657 : fix launchpad builds for good + * * #6675 : send RTP dtmf events only once + * * #6655: more cleanup + * AudioRtpSession::updateSessionMedia() : simplify + * * #6655: more cleanup in managerimpl + * * #6655: removed more code, cleanup + * * #6655: more cleanup, fixed infinite loop + * * #6655: removed more unused files + * * #6655: removed unused mutex + * * #6655 removed more unused code + * * #6655: removed unused methods + * * #6655: cleanup in main + * * #6663: fixed segfault when off hold from transfer + * * #6658: user's active codec selection is respected + * * #6660: static global string should be static const char* const + class member + * * #6659: use g_strcmp0, not strcmp for vals that may be null + * callable_obj: fix double free + * calltree_display_call_info() : simplify + * * #6657: Fix launchpad builds + * Logger::log() : simplify + * AudioRtpSession : privatize members + * * #6655: more constness, cleaned up/simplified methods + * * #6654: call DBus::_init_threading so that dbus-c++ to make it + threadaware + * set default credentials on account creation + * AudioCodecFactory::scanCodecDirectory() : simplify and correct + * * #6623: fixed typos + * * #6623: fixed more leaks + * * #6623: fixed more leaks + * * #6623: fixed more leaks, don't print codec name if null + * * #6623: more leaks fixed in client + * * #6623: fix more leaks, fixed some warnings + * * #6623: fixed leak in history + * updated gitignore + * initialize dbus dispatcher correctly + * Fix tests, hudson doesn't have a dbus daemon running + * remove unused code + * removeCall() : simplify , fix leak + * stopRtpThread() : simplify + * *CurrentCall : simplify + * Fix memleak + * fix serialization of audio api (pulse / alsa) + * account map : simplify + * remove call from callmap before terminating it, avoid use after free + * * #6630 : don't make DBusManager a singleton + * call: return confID by value + * add back history code deleted by error + * history : reverse logic + * simplify history serialization and remove some debug + * remove annoying debug + * * #6464 : replace cerr with _error + * * #6464: replace cout with logger macros + * replace printf() with logger macros + * update .gitignore + * remove unused function + * update eclipse projects + * uimanager_new() : simplify + * rename directories + * celt: simplify a bit + * Fix CELT configure.ac test + * * #6612 : template speex codecs + * * #6623: refactored conference obj + * * #6623: refactored callable object, removed leaks + * * #6623: more cleanup, fix leaks, make global vars static and rename + them + * * #6623: calltree: fixed memleaks, simplified code. + * audiolayer: init pointer members + * manager: catch exception on invalid hangup + * * #6623: don't leak on calls to create_new_call + * * #6611 : clarify codecs prototypes + * ringtones : .au and .ul files are both ulaw + * * #6611 : make sure samplerate converters are called correctly + * ManagerImpl::switchAudioManager() : simplify + * * #6623: fixed more leaks + * * #6623: fixed more leaks + * * #6623: fixed more leaks + * * #6623: fixed leak, line-endings in imwidget + * * #6627: zero-initialize pointers if they're going to be deleted + * * #6628: don't leak calls on exceptions + * Revert "audiortp: call join after calling stop on RtpThread" + * sflphone-client: more constness + * audiortp: call join after calling stop on RtpThread + * * #6625: return 0 on successful completion + * * #6624: fix segfault on servercallfailure + * * #6621: Fixed double free, unlock mutex in ManagerImpl::terminate + * * #6220: remove audio stream when peer hangs up + * * #6596: AudioSymmetricSession shouldn't self-delete + * resampler: grow internal buffers dynamically + * merge up and down sampling => resampling + * Leave test directory unchanged when running make check + * audio algorithms : remove unused prototype + * ringtone: detect codec from file extension + * *AudioFile : simplify + * * #6596: create local SDP on the stack, not the heap + * * #6596: don't call Ost::Thread::terminate from dtor + * audiofile: cleanup (samplerate -> unsigned) + * remove unused func + * samplerateconverter: cleanup + * RingBuffer::Put() : remove unused return value + * MainBuffer::putData() : remove unused return argument + * audiolayer::putMain() : remove unused func + * AudioLayer::putUrgent() : remove unused return value + * * #6618: delete any remaining ringbuffers in destructor + * RingBuffer::availForPut() : remove + * * #6617: return from main rather than calling exit + * MainBuffer::availForPut(): remove + * RingBuffer: simplify + * alsa : remove write only variable + * fix memcpy declaration + * bcopy(src, dst) -> memcpy(dst, src) + * RingBuffer::Get() : remove constant volume argument + * return a copy of the call ID, not just a reference. + * MainBuffer::getDataById() : remove volume argument (always 100) + * MainBuffer::getData() : remove constant volume argument + * RingBuffer::Put() : remove constant volume argument + * MainBuffer::putData() : remove constant (=100) volume argument + * audiolayer: remove constant _defaultvolume + * AudioRtpRecordHandler / AudioRtpSession : simplify + * mainbuffer: fix test + * iaxvoiplink : simplify + * sip registration callback: fix a dbus crash + * MainBuffer: simplify + * AudioRtpFactory: return cached type of rtp session. The rtp session + can have disappeared if the call was put on hold + * AudioRtpFactory: remove unused setters + * Fix launchpad builds + * * #6611 : remove unused bandwidth codec information + * * #6611: AudioCodec: remove useless/unused setters + * make sure buffer string is initialized correctly + * * #6596: declare certain destructors virtual + * audiolayer : cleanup + * Simplify doc build rules + * * #6270: don't build dbus-api doc with make, should require make all + * configure.ac: cleanup + * Remove copy of dbus-c++ from libs/ + * * #6596: stop clock thread when peer hangs up + * removed unused Fmtp.h + * * #6595: more logical initialization order + * * #6600 : fix account creation + * * #6601 : fix configure.ac tests + * remove unused variable + * Don't mix stack and heap based allocations + * Fix copyright (2009, 2008, 2009 -> 2008, 2009) + * Fix warnings found by clang + * * #6595: fix initialization order for AudioRTP + * * #6592: removed typedef std::string CallID + * * #6586: implement local g_slist_free_full for older glib versions + * * #6579: fix memory leaks in client (there's a lot left) + * ShortcutPreferences::setShortcuts() : simplify + * Fix merge + * * #6548: remove call to non thread-safe strerror() + * AudioRtpFactory: each instance is associated to exactly one SipCall + * create_audiocodecs_configuration() : make static + * * #6269 : refactor AudioRtpSession + * Fix AudioSymmetricRtpSession.h inclusion guard (cherry picked from + commit c3081dce1cc1370d6d3558a4c4ef5cfac0d21caf) + * * #6269: Rename AudioRtpSession to AudioSymmetricRtpSession + * * #6574: Don't exit when connection to pulseaudio server fails + * accountconfigdialog.h : remove some stuff from header + * * #6560: fix configuration test + * Fix warning in test + * * #6560: don't hide password entry in security tab + * * #6560: set initial password for SIP accounts + * * #6506: remove useless pointer indirection + * * 6560: password is now specific to IAX accounts + * * #6560 : actually use, store, restore, transmit SIP credentials + * * #6560: YamlEmitter: serialize sequences + * YamlEmitterException: typo + * ManagerImpl::computeMd5HashFromCredential() : simplify, fix memleak + * * #6561: invite_session_state_changed_cb() : simplify + * * #6561: More useful debug in VoIPLink::removeCall + * * #6561 : fix ghost call reappearing in GUI after transfer + * while -> for (make the code smaller) + * * #6558 : Account::loadConfig() : move IAX code to IAXAccount + * IAXVoIPLink::getAccountPtr : simplify + * * #6554 : access the SIPVoIPLink directly, not per account + * SIPVoIPLink is instanciated only once and is not associated to a + single account + * yamlnode: use const references when possible (still some left to do) + * Account::_accountID: constify + * VoIPLink: simplify, remove unused method + * hudson test : no need to call run_tests.sh anymore + * Remove AccountID type and AccountNULL define + * Make check runs the test (no need to call run_tests.sh manually + anymore) + * gnome GUI: Fix tests + * Revert "Move registration information from SIPAccount to + SIPVoIPLink" + * * #6392: pluginmanagertest: fix warnings reported by valgrind + * * #6547 : remove unused exceptions + * * #6547: CallManagerException: use runtime exceptions + * * #6547: InstantMessageException: use runtime exceptions + * * #6547: do not throw exceptions if some settings are not present in + config file + * * #6547: YamlParserException: use runtime exceptions + * * #6547: VoipLinkException: use runtime exceptions + * * #6547: YamlEmitterException: use runtime exceptions + * * #6547: DTMFException: use runtime exceptions + * * #6547: AudioFile: use runtime exceptions + * * 6547: AudioZRtpSession: remove impossible error case + * * #6547 : AudioRtpSession: remove impossible error case + * * #6547: AudioZrtp: use runtime exceptions + * * #6408 : send authenticationUsername to GUI + * * #6408 : store/restore authenticationUsername from config file + * SIPAccount: simplify + * Move registration information from SIPAccount to SIPVoIPLink + * SIPAccount::getAccountDetails : simplify + * * #6540: yaml parser: simplify + * sdp.cpp : fix a warning + * * #6540: yaml parser : remove std::string typedefs + * * #6540: Simplify yaml unserialization + * * #6540 : add a Conf::ScalarNode constructor for booleans + * setAccountDetails(): simplify + * * #6408: store authentication username in daemon + * * #6408: Be able to set the authentication username in the GUI + * * #6507 : do not crash if the program is not sflphoned + * Fix tests + * macroify SIPAccount::unserialize() + * Move all .cpp files from sflphoned target to libsflphone.la, except + main.c + * main() : simplify, return positive error codes + * * #6507 : find codecs dir in build directory + * * #6392: Sdp: move clean functions to destructor + * AlsaLayer::adjustVolume() : simplify + * alsalayer : reduce indentation + * malloc/free -> new/delete + * malloc/free -> new[]/delete[] + * malloc/free -> new/delete + * AudioSrtpSession: simplify base64 encoding + * * #6392: Initialize std::string from pj_str_t correctly + * * #6392: AudioRtpSession: Initialize remote port + * Audio settings : Initialize _echoCancelTailLength and + _echoCancelDelay(0) + * Initialize variable + * YamlParserException : fix use of stack variable after it has been + deallocated + * * #6392: fix memory leak in history + * * #6392 AudioCodec : fix memory leak + * * #6392 : fix memory leak in sip account + * * #6408: clean up sipaccount (cosmetics mostly) + * sipaccount.cpp serialize() : reduce number of lines + * * #6392: invalid memory access + * * #6392 : fix invalid memory access + * * #6479: merged useful code from MimeParameters into Codec interface + * * #6462: fixed hangup on IP2IP call + * added run_daemon.sh script + * test: remove unused variable + * Remove functions only used by a failing test (cherry picked from + commit fcf718cb75de7f1882dc61c07bb8d300dfa10f85) + * * #6360 : make client tests build (cherry picked from commit + 028b2835f040e51ab8ab979b32732b07b8798fce) + * * #6360 : fix warnings in check_global test (cherry picked from + commit 9e2bd6a7496dd64f6f48595e385760019aab1193) + * * 6360: updated API calls in tests, but they're not building yet + (cherry picked from commit 548f6f0f919b43772a3e9c667e5e292791281795) + * Fixed include in tests (cherry picked from commit + aeadc7525c1e31f936670ac8b02f0bcf387c38a8) + * Remove unused variables and functions + * IAX: fix warnings (cherry picked from commit + fd7a113a11cac2cd9a7c36929e88ad28195c4c35) + * Remove unused DEBUG define which interferes with logger.h (cherry + picked from commit b2f72b91d0f43cb1dd94d138882a8caa9c841c24) + * * #6392: no need to check for account NULLity since it is + dereferenced above + * * #6392: fix a memory leak, replace by stack allocation + * * #6392: remove a variable assignement which confuses cppcheck + * process_conference_participant_from_serialized() : remove unused + function + * * #6392: s/free/g_free/ + * * #6392: fix a memory leak in abookfactory_load_module() + * * #6392: remove generate_call_id() used only once + * * #6392: fix memory leak (opendir() without closedir()) + * * #6392: AudioRecorder(): ensures mbuffer is set + * Remove SFLPHONED_VERSION from global.h, use autoconf PACKAGE_VERSION + * #6298: Cleanup + * #6331: Fix deleting ringtone file after call have been answered + * * #6330: merged user_cfg into headers + * #6298: Fix conference recording file update at conference end + * #6298: Fix record file name serialization for conference + * * #6295: cleanup of codec hierarchy + * #6298: Fix gtk warnings + * * #6300: added script to run tests + * #6109: Add recording playback for conference + * * #6300: tests do not require an installed sflphone + * * #6295: re-removed clone methods + * #6109: Fix gtk_critical warnings for incoming calls + * #6109: Fix GTK_CRITICAL warning + * #6109: Fix icons when history is not activated + * #6109: Fix warnings + * #6109: Implement stop recorded file playback signal + * Revert "* #6295: removed unused clone method" + * * #6295: removed unused clone method + * * #6296: removed non existant file from Makefile.am + * #6109: Stop fileplayback for outgoing call + * #6109: Implement stop recording playback button + * Fix binding names errors in dbus introspection file + * #6109: Implement playback recorded file callback in client + * #6109: Store recorded file path on client side + * #6109: Add dbus methods for call recording playback + * * #6290: remove unused classes from utilspp + * * #6288: cleanup sdp + * * #6288: fix exception usage + * * #6288: simplify SdpException + * * #6288: cleanup in sdp.cpp/h + * #6109: Only display playback button if record file is set and valid + * * 6290: updated configure.ac to remove functor Makefile + * * #6290, #6289: removed unused classes from utilspp, fixed make + check + * #6109: Add button for history playback of recorded file + * * #6289: removed unused observer class + * * #6282: forward declare sdpMedia in sdp.h + * * #6281: renamed setCallAudioLocal->setCallMediaLocal + * #6183: Handle conference with more tahn two calls + * #6183: Fix history icons when calling back a conference from history + * #6183: Fix icons inconsistencies in history for conference hang up + * #6183: Fix toolbar actions when selecting a conference in history + * #6183: Fix conference serialization + * #6268: Serialize only calls + * * #6269: removed useless type testing + * ignore some files in test/ + * * #6268: Remove dead class AudioSymmetricRtpSession + * #6251: Do not had history calls in calllist when loading history + file + * #6251: Fix insertion in history map in before saving history file in + daemon + * #6251: Fix history unit tests + * #6251: Order the list before serailization, get rid of the hashtable + in history + * #6251: Implement history serialization using a list wether than a + map + * * #6253: remove external audioport from header, make all members + private + * * #6253: don't store external local audio port (used for NAT) in + Call + * #6251: Add start_time timestamp in history serialization + * #6251: Fix call insertion in conference items + * #6233: Fix serialized account list terminated with a ";" character + * #6238: Fix draggable history calls into current calls + * #6233: Fix toolbar updates + * #6233: Fix history + * * #6235: remove pyc files from git tree + * #6233: Handle cases when one or manuy calls are unreachable in + createConfFomrParticipantList + * #6233: Handle wrong numbers in createConferenceFromParticipantList + * #6231: Fix drag-n-drop issue + * * #6173 : move sippxml in tools + * #6231: Fix merging issue + * #6183: Implement conference unserialize + * * #6212: remove extraneous flags from globals.mak + * #6183: Unserialize conference data in conference + * #6183: Add account information in request for conference call from + history + * #5755: Add -ldl to liker in sflphone-client-gnome + * #5755: Fix fedora 15 compilation issue + * #6183: Serialize conference participant phone number and account + * #6183: Add conference timestamp in serialization + * * #6186: don't include global.h, just logger.h + * #6183: Fix saving history to file + * #6183: Fix removing call from calllist + * * #6184: remove pointers to Manager from AudioRtpSessions + * #6183: Calling calltree_add_call explicitely for history + * #6183: Ability to store conference inside history tab queue + * * 6181: remove unused API from sipcall + * #6171: Implment nreCallCreated callback + * #6167: Fix participant list NULL ending + * #6149: First draft of conference creation from history + * #6149: Fix multiple call/conf selection callbacks ... + * #6129: Fix place_call function called twice for pressing enter + action + * #6129: Fix double click action for history + * #6149: Add dbus call for creating conference from history + * #6129: Fix placing call from history and addressbook (still need to + fix icon) + * * #6148: removed unused AudioRtpFactory constructor + * * #6145: remove unused isAudioStarted + * * #6145: remove unused isAudioStarted + * #6129: Add conference into history, fix call/conference selection + * * #6143: don't use getType outside of serialization methods + * * #6132: forward declarations instead of includes + * * #6132: add constness, remove redundant "inline" keywords + * #6129: Add timestamp to conference object to order history entries + * * #6128: remove unused forward declarations from header + * * #6127: make noncopyable class actually noncopyable + * * #6125: don't include AudioRtpFactory in sipcall.h + * #6123: Fix alsa ringback audio file + * #6123: Fix raw audio file loading problem + * #6109: Fix daemon plugin manager unit test + * #6109: Fix history manager unit tests + * #6109: Recording filename in daemon and client for history items + + serialization + * #6109: Refactor AudioFile to play recorded call + * * #6104: AudioCodec moved to sfl namespace + * * #6099: remove active flags from codec classes + * #6095: Add notification-daemon as a runtime dependencies for rpm + packages + * #6095: Fix fedora 15 compilation in MineParameters.h + * #6095: Declare static variable explicitely for client + * #6095: Add logs to build OSC build machine + * * #6098: global variables should have file-scope to avoid name + conflicts + * #6095: Fix compilation error for Fedora 15 + * #6095: Update SFLphone version to 0.9.14 + * #6095: Add specification file in opensusse build service for + sflphone-plugins + * #6073: Fix sflphone-plugins build on launchpad + * #6093: Rename CodecDescriptor for AudioCodecFactory + * * #6089: fix warnings in make check + * * #6086: renamed codecs methods to audio_codecs + * * #6085: renamed codec related dbus calls to audio_codec + * #6065: Remove g_print from client, use DEBUG instead + * #6065: Add actions name for addressbook + * * #6085: renamed codecs* widgets/functions audiocodecs* + * #6065: Fix Addressbook runtime warnings + * #6065: Replace Codecs tab for Audio in account preference dialog + * #6065: Fix "transfert" typo + * #6065: Fix addressbook action runtime warning in uimanager + * * #6082: fixes make check by adding libcrypto libs to test + dependencies + * #6073: Rename plugin/addressbook folders for addressbook/evolution + in sflphone-plugins + * #6074: Removed AC_SUBST from configure.ac when using + PKG_CHECK_MODULE + * #6073: Fix sflphone-plugins package build + * #6073: Fix sflphone-common build + * #6065: Fix runtime gtk warning when initializing searchbar without + addressbook + * #6063: Fix mozilla-tellify gitignore + * #6063: Remove stream copy file using ifdef macro + * * #6012: fix make dist for sflphone-common + * #6063: Update .gitignore file + * #6058: Fix base64 encoding related warnings + * #6056: Fix SdpException handling + * #6055: Fix unknown pargma warning for gcc <= 4.5 + * * #5949: test gcc version before disabling unused-but-set warning + * #6054: Fix addressbook plugin compilation warning + * #6048: Fix uimanager static initialization + * #6046: Fix addressbook factory static initialization of member + addrbook + * #5979: Fix implicit function declaration warning + * #6042: Fixed discarding qualifier warnings in client + * #6041: Fix instant messaging unhandled case warning + * #5994: Implement set current addressbook name and search type in + addressbook plugin + * #5994: add rules for launchpad packaging of addressbook plugin + * #5994: Fix addressbook plugin configuration loading + * #6027: Fix addressbook enabled test from configuration + * #6027: No need of gnomedoc related macros in addressbook plugin + * #6027: Add NEWS file required for build + * #6027: Add addressbook plugin autogen.sh script + * #6027: Remove plugins from client + * #6027: Add sflphone-plugins folder at project's root level + * #5994: Move addressbook folder from contacts to plugin folder + * * #6011: removed unused Makefiles + * * #6010: remove unused headers + * * #5952: fix "string constant to char*" warnings + * * #6009 fixed warnings + * * #6003: finished cleanup of account classes + * * #6003, #6004: cleanup of account classes, defaultAccount no longer + global + * * #6000: fix memory leak of args object + * * #5998: removed using namespace std from networkmanager + * * #5998: removed "using namespace std" from ZrtpSessionCallback + * * #5998: removed using namespacestd from AudioZrtpSession.h + * * #5998: remove "using namespace std" from auriorecord.h and + MimeParameters.h + * * #5998: remove using namespace std in main + * * #5998: removed "using namespace std" from logger + * * #5949: test gcc version before disabling unused-but-set warning + * #5994: Installation of addressbook plugin + * #5979: Implement codec full addressbook search from plugin + * #5979: Implement addressbook factory and plugin + * * #5981: unused webwidget removed + * #5966: Account config synchronization fix (for stun) + * #5954: Handle media name exception + * #5954: Fix audio codec name display in client + * #5954: Clean up getSessionMedia methods + * * #5957: getRecordingSmplRate returns a value + * #5954: Clean up getCurrentCodec methods + * * #5950: remove "converting to non-pointer type 'int' from NULL" + warnings + * #5915: Full gain control version + * * #5949: remove more unused variable warnings + * * #5949: remove unused/unused-but-set variable warnings + * * #5949: show_preferences_dialog returns a success value + * * #5946: cleanup of include directives, undefined function + * * #5515: comment out SSLv2 calls in pjsip + * #5915: Implement different slope for attack tme and release time for + gain control + * #5915: use only one input signal for gain control (removed output + buffer) + * #5921: Fix no audio after holding a conference + * #5916: Add gaincontrol files + * #5916: Implement FFMPEG/CCRTP video streaming prototype + * #5903: Fix call transfer during a conference + * #5915: implement rms detector, first order averager, limiter for + gain control + * #5914: Fix call transfer when no notification request is required + * #5899: Fix conference right-click segfault + * #5884: temporary fix segfault in pjsip memory pool + * #5883: Fix compilation issues on maverick and lucid + * #5755: Fix fedora 15 compilation without patching ccrtp + * [#5855] Make echo canceller optional + * #5855: Fix echo suppression activation/deactivation + * #5855: Implement pjsip echo canceller + * #5814: Speex initialization function uses samples, not bytes + * #5814: Test using more unbalanced signals + * #5814: Fix buffer size for long echo length or long echo delay + * #5814: Adjust level for echo cancellation at runtime + * #5814: Process noise reduction before echo cancelling + * #5814: Implement speex post echo canceller processing + * #5814: Dump echo cancel file to disk + * #5814: Add parameters for echo cancel + * #5809: Add configuration parameters + * #5809: Implement speex echo canceller in audio rtp session + * #5814: Code cleanup + * #5814: Fix conf creation with several incomming ringing calls + * #5814: Fix conf creation segfault when dragging a call on hold on a + ringing call + * #5809: Added unit test for echo cancellation and implemented + "process" virtual method + * #5709: Add always recording option in configuration + * #5709: Add always recording option in audio conference panel + * #5709: Add core functionnality for always recording (missing config + options) + * #5769: Fix conference participant handling (detach/attach) and hold + actions + * #5747: Fix recording icons and state for conference when adding new + participant + * #5769: Code cleanup + * #5769: Fix hangup unsent calls + * #5769: Fix remove/add additional participant to conference + * 5769: Several fixes concerning confererence handling + * #5769: Fix compilation error + * [#5769] Fix audio streams binding in main buffer + * #5769: Removed access to audio mixer from audio layer + * #5765: Fix audio crash for illformated wavefiles + * #5765: Add maximum iteration for finding fmt and data "chunck" + * #5589: Fix compilation of libnotify under + * #5757: Fix abort signal when receiving INFO + * #5747: Add usersDetached.svg + * #5747: Handle offhold action for recording conference + * #5747: Fix off hold action for conferences + * #5747: Implement update conference in record action in calltree + * #5747: Add new icons for recording conferences + * #5747: Add recording state for conferences + * [#5738] Remove getAudioDriver call from manager (replace by + _audiodriver var) + * [#5738] Refactor mutex protecting audiolayer + * [#5737] Fix HD conference recording + * [#5730] Fix start audio session after changing sampling rate + * [#5714] Fix enter keyboard event for addressbbok and history + * [5695] Fix addressbook combo box update when no addressbook selected + * [#5695] Fix addressbook initialization and search bar update + * [#5695] Add mutex for books_data in addressbook to protect async + calls + * [#5695] Get back addressbook open from uri + * [#5695] Fix absolute addressbook URI for local addressbooks + * [#5695] Implement libebook 3.0 interface + * [#5571] Better logic for hangup (for case where call have not been + sent yet) + * [#5571] Update error handling in voip links + * [#5571] Fix compile time warnings + * [#5696] Fix installation dependencies for Natty + * [#5669] Add mention that sflphone.org is for testing only + * [#5693] Add natty in teh dput.conf file + * [#5690] Remove not useful logs + * [#5670] Use dynamic payload type for rtp dtmf + * [#5668] Clean up sflphone configuration logging + * [#5668] Fix hook checkbox configuration update + * [#5666] Fix unit tests + * [#5666] Manage event subscription + * [#5666] Emit bye request when subscription is terminated + * [#5666] Bye request should be sent after event subscription + notification is done on transfer + * [#5666] Make reinvite method static (to be called in pjsip + callbacks) + * [#5666] Hangup Call in manager for AccountNULL and IP2IP + * [#5589] Use PKG_CHECK_MODULE for every client's dependencies + * [#5623] Enlarge initial size of pjsip memory pool for calls (16k) + * [#5564] Fix audio recording resampling for g722 + * [#5571] Move attribute handling for onhold/offhold actions in SDP + session + * [#5571] Codec negotiation refactored and unittested + * [#5571] Implement tests + * [#5571] Implement pjsip negociator + * [#5571] Fix unit tests + * [#5571] Add Fmtp.h to repository + * [#5571] Integrate mime types and codec factory + * [#5571] Handle exception when SDP negotiation fails + * [#5570] Add sflphoned-sample.yml in repository + * [#5564]: Implement stereo to mono mixing for rigntone + * [#5342] Update audio stream initialization + * [#5514] Restore test ni historytest suite + * [#5514] Fix + * [#5514] Disable test_create_history_path + * [#5514] use pulseaudio in sample config file + * [#5514] Fix test: load history from file + * [#5514] Do not use X + * [#5513] Make unit tests compile successfully + * [#3947] Enable unit tests in Jenkins + * [#5454] Fix build system to handle new version number + * [#5454] Update languages from launchpad + * [#5454] Add --without-celt in OpenSuse build service + * [#5454] Change version number + * [#5331] Added first SDP session tests + * [#5273] Update nightly build version tags to conform dpkg rules + * [#5211] Refactor send register method for iaxvoiplink and + sipvoiplink + * [#3950] Remove call being transfered from calltree + * [#5211] Use appropriate memory pool for transport selector + * [#5211] Fix strict aliasing rules warning in pjsip + * [#5211] Bring back pjsip shutting down sleep to 1000 ms + * [#5211] Fix registration callback segfault when closing the + application + * [#5211] Use the dialog memory pool for Route header in INVITE + request + * [#5211] Add temporary memory pool for findLocalAddressFromUri and + findLocalPortFromUri + * [#5211] Use individual memory pool for dtmfs + * [#5211] SipVoipLink refactoring + * [#3950] Attended transfer for conference calls + * [#5284] Fix DNS resolution for Route with specified port number + * [#5284] Some code cleanup + * [#3947] Fix typo in hudson script + * [#5284] Added sip route to REGISTER, INVITE, BYE request, plus DNS + resolution + * [#5266] Use RTP dtmf as default + * [#5284] Added pjsip_process_route_set after setting routes in regc + structure + * [#5286] Fix parsing error due to long configuration file (removed + max event) + * [#5286] Fix false test in configuration emmiter + * [#5286] Code cleanup + * [#5286] Updated exception handling in configuration system + * [#4969] Fix put SRTP call on hold + * [#3950] Add debug messages + * [#3950] Ability to perform an attended transfer + * [#5276] Fix initialization problem in g722 + * [#3950] Add replace header in SIPVoIPLink::transferWithReplaces + method + * [#3950] Implemented attended method in SIPVoIPLink + * [#3950] Cleanup transaction request received callback + * [#3950] Implement dummy attended transfer in gnome-client + * [#5249] Fix audio samplerate update algorithm for g722 + * [#5249] Fix uninitialized variable used in conditional jumps + * [#5249] Fix conditional jump error in audiolayer (uninitialized + value) + * [#5267] Use autoconf 2.65 as a requirement (instead of 2.67) + * [#5267] Restore manual pjsip configuration and compilation + * [#5267] Autodetect celt version (0.9.1, 0.7.1) + * [#5267] Fix deprecated macros in gnome client configure.ac + * [#5267] Update configuration for libcelt-dev + * [#5267] Fix build autoconf and automake + * [#5227] Deactivate automatic call to astyle after compilation + * [#5242] Hangup every calls before leaving + * [#5237] Will now nightly-build for natty, Karmic deprecated + * [#5229] Use inner class for rtp thread instead of inheritance + * [#5211] Move mainbuffer unbind call in rtp final method + * [#5211] Initialize sip call memory pool using 16 kb + * [#5211] Use call memory pool in session reinvite + * [#5211] Add debug messages + * [#5211] Use and internal pool for calls + * [#5211] Reduce pjsip memory pool usage for stateless error messages + * [#5211] Refactor call deletion + * [#5212] + * [#5208] Refactor codec management for accounts + * [#5168] Remove printf from codec's encode & decode method + * [#5168] Fix celt compilation on launchpad + * [#5168] Fix sflphoned compilation warnings in audiocodec.h + * [#[#5168] Must keep the g722 specific RTP rate to avoid incoming + packet timeout + * [#5168] Fix static/dynamic payload rtp session update + * [#5168] Throw SIPVoipLink Error if codec not instantiated in new + outgoing call + * [#5168] Fix dynamic/static codec payload type ambiguity + * [#5169] Fix doubled IP2IP profile when no config file + * [#4867] Add gtkinfobar in configuration panel + * [#4867] Disable input/output/ringtone selection when using default + alsa plugin + * [#4952] Patches for possible buffer overflows + * [$4885] Fix schemas problem + * [#4885] sflphone-client-gnome.schemas not present during build + * [#4885] Add gconf shemas directories in opensuse build system + * [#4885] Add file/folder ownership for opensuse-factory build system + * [#4906] Fix opensuse-factory build + * [#4885] Update name dependency for libedataserver + * [#4885] Fix non-void function without return in dbus-c++ + * [#4895] Update language translation + * [#4896] Update session timestamp when updating media + * [#4896] Reapply RTP hack for G722 payload type + * [#4896] Update recording sampling rate when updating codec + * [#4897] Save codecs in config for each configuration changes + * [#4895] Do not save config when sflphone quit + * [#4885] Update date for copyright + * [#4885] Deactivate siptest that require more than one sipp instance + * [#4879] Remove inmcoming call notification from IAX + * [#4885] Some cleanup + * [#4874] Add setCancel immediate/deffered for ost::Thread + * [#4879] Fix incoming call notification + * [#4878] Set keyboard focus on searchbar when selecting addressbook + * [#4874] Fixed compilation warning + * [#4874] Fixed compilation warning in sipvoiplink + * [#4874] Fix compile time warning in RTP record handler + * [#4874] Fix conditional jump in SDP + * [#4874] Fix conditional jump based on uninitialized value + * [#4874] Store call id within rtp thread context + * [#4874] Fixed conditional jump based on uninitialised value in + conference + * [#4871] Fix default account fetching + * [#4870] Delete RTP session when Refusing an incoming call + * Restore IP to IP call + * [#4857] Fix audio codec negotiation problem + * [#3947] Adjust ressources allocated to compilation + * [#3947] Disable unit tests in Hudson + * [#4305] Free mutex only when really quiting SFLphone + * [#4859] Update copyright to 2011 in every source file + * [#3218] Character '.' stripped by the caller engine + * [#4854] Fix typos, desktop entry + * [#4847] Apply RTP modification to ZRTP session + * [#4852] Update Karmic and Lucid dependencies + * [#4852] Add Libedataserver and libedataserverui as gnome client + dependencies + * [#4852] Add authentication mechanism for EDS + * [#4851] Fix segfault when closing pulseaudio layer too rapidly + * [#4808] Some otehr cleanup + * [#4808] Made some cleanup + * [#4808] Added mutex in rtp session for codecs and noise process + * [#4847] Update audio processing when updating RTP media + * [#4842] Add support for linking with gold/ld --no-add-needed + * [#4808] Make update g722 related static/dynamic payload logic + * [#4827] Upper limit on the number of contacts to import from EDS is + hard-coded to 500 + * [#4808] Fix put call on/off hold + * [#4808] Implement early RTP start for incoming calls + * [#4808] Audio stream is no longer start within RTP session. + * [#4808] Removed coupling between audio layer and and RTP session + * [#4702] Start audio rtp session as soon as it is created + * [#4702] Init timestamp to 0 + * #4702: Send RTP packets immediately, no need of outgoing queue + * [#4784] Update dbus-c++ version from gitorious + * [#4702] Update RTP timeouts + * [#4702] Lengthen RTP timeouts + * [PATCH] Fixed compatibility with old libtool versions. + * [PATCH] Accept older libebook (Maemo 5 has 1.4.2) + * [PATCH] Fixed double-free error in preferences dialog + * [PATCH] Fixed building of sflphone-common on Maemo5 + * [PATCH] Improved Gnome client initialization error handling. 1. It + no longer segfaults when sflphoned isn't available. 2. User is + provided with GUI error dialog. + * [PATCH] Improved autogen.sh scripts 1. They do not require bash + anymore 2. Added workaround for Debian bug #565663 3. Replaced + manual autotools invocations with single autoreconf call 4. Non-zero + return status on failure + * Revert "[#4468] libtool <= 2.2 doesn't have LT_INIT macro so + AC_PROG_LIBTOOL should be used instead." + * Revert "[#4468] Libebook 1.4 is sufficient" + * Revert "[#4468] Apply big path on dbus communication system" + * [#4468] Apply big path on dbus communication system + * [#4468] Libebook 1.4 is sufficient + * [#4468] libtool <= 2.2 doesn't have LT_INIT macro so AC_PROG_LIBTOOL + should be used instead. + * [#4639] Fix determining default addressbook if this property is not + set in gconf + * [#4639] Fix memory leaks in Addressbook + * [#4637] Fix opening default addressbook at sflphone init + * [#4622] Free yaml events while parsing configuration file + * [#4623] Fix conditional jumps based on uninitialized variable + * [#4622] Fix leaks in yaml serialization engine + * [#4616] Fix addressbook warnings + * [#4514] Adjust RTP timestamp + * #4527: Rename Karmic libyaml and Celt package in debian control file + * #4495: Rework addressbook opening loop + * [#4524] Increment RTP count when sending data + * [#4524] DO NOT start RTP session twice + * [#4367] Use PKG_CHECK_MODULE for celt + * [#4367] Fedora package celt as celt (not libcelt) + * [#4367] Astyling + * [#4367] Update .po files + * [#4367] Fix segfault in gensin + * [#4354] Make celt a direct dependency on launchpad opensuse build + service + * [#4367] Make celt a required package, option --without-celt valid + * [#4367] Fix zrtp timestamping error + * [#4367] Fix audio zrtp timing + * [#4367] Dispatch ZRTP packets + * [#4367] Fix segfault when unloading account map + * [#4367] Fix zrtp session + * [#4367] Implement on packet receive + * [#4367] use symetric audio rtp session, not dual + * [#4367] Reduce packet receive/sent timeout + * [#4367] Reduce RTP timeouts + * [#4367] Move speaker data receive + * [#4367] Move speaker data receive + * [#4367] Move receive speaker data method + * [#4367] Remove debug in rtp session + * [#4367] Fix g722 codec clock rate + * [#4367] Fix noise suppression initialization + * [#4367] Fix segfault in RTP mic fadein method + * [#4367] Refactor mic data encoding in rtp session + * [#4367] Implement RTP main loop + * [#4367] Fix compilation problem + * [#4367] Fix AudioRtpclass using TRTPSessionBase + * [#4367] Fix AudioRtpSession putDtmfEvent shadowing + * [#4367] Fix AudioRtpSession putDtmfEvent shadowing + * [#4367] Refactor RTP session (phase 2) + * [#4367] Refactor RTP session (phase 1) + * [#4367] Remove Redeclaration of SymetricAudioRtpSession in + rtpfactory + * [#4265] Add continue statement in for loop for invalid addressbook + * [#4261] Makes addressbook initialization more robust + * [#4257] Add maverick in build system + * [#4233] Add sdp related unit tests + * [#4233] Add condition and signal in two incoming call test + * [#4243] Fix segfault in AudioSrtpSession + * [#4243] Fix memory leak in AudioSrtpSession + * [#4243] Make audio srtp optional in for incoming call + * [#4243] Add boolean variable to make sure remote crypto context + initialized only once + * [#4243] Add documentation to AudioSrtpSession + * [#4243] Use 80 bits authentication tags by default + * [#4243] Init audio srtp remote crypto context in + call_on_media_update + * [#4243] Move SDP negotiastion in mod_on_rx_request + * [#4243] Implement initLocalCryptoInfo to be called at different + momment + * [#4243] Init init local crypto context in when initializing audiortp + * [#4243] Change key length according to sdes negociation + * [#4243] Associate callid to accountid for incoming calls + * [#4242] Fix no SDES keys in IP2IP calls + * [#4242] Fix no SDES keys in IP2IP calls + * [#4233] Test for call on/off hold + * [#4233] Add two incoming call test + * [#4233] + * [#4233] Add 2 outgoing simultaneous call unit tests + + -- Julien Bonjean <julien.bonjean@savoirfairelinux.com> Fri, 30 Sep 2011 13:51:04 -0400 + sflphone-common (0.9.7~rc1~ppa1~SYSTEM) SYSTEM; urgency=low ** 0.9.7~rc1~ppa1~SYSTEM ** diff --git a/tools/build-system/launchpad/sflphone-common/debian/control.maverick b/tools/build-system/launchpad/sflphone-common/debian/control similarity index 59% rename from tools/build-system/launchpad/sflphone-common/debian/control.maverick rename to tools/build-system/launchpad/sflphone-common/debian/control index dd3502656744b3c164fedfb2bfade0de3abba46a..9947a25304953cc3d760d35a198c27e05bfd7b33 100644 --- a/tools/build-system/launchpad/sflphone-common/debian/control.maverick +++ b/tools/build-system/launchpad/sflphone-common/debian/control @@ -2,13 +2,13 @@ Source: sflphone-common Maintainer: SavoirFaireLinux Inc <julien.bonjean@savoirfairelinux.com> Section: gnome Priority: optional -Build-Depends: debhelper (>= 7.0.50), libgcc1 , autoconf, automake, libpulse-dev, libsamplerate0-dev, libcommoncpp2-dev, libccrtp-dev, libgsm1-dev, libspeex-dev, libtool, libdbus-1-dev, libasound2-dev, libspeexdsp-dev, uuid-dev, libexpat1-dev, libzrtpcpp-dev, libssl-dev, libpcre3-dev, libyaml-dev, libcelt-dev, libdbus-c++-dev +Build-Depends: debhelper (>= 7.0.50), libgcc1, autoconf, automake, libpulse-dev, libsamplerate0-dev, libcommoncpp2-dev, libccrtp-dev, libgsm1-dev, libspeex-dev, libtool, libdbus-1-dev, libasound2-dev, libspeexdsp-dev, uuid-dev, libexpat1-dev, libzrtpcpp-dev, libssl-dev, libpcre3-dev, libyaml-dev, libcelt-dev, libdbus-c++-dev Standards-Version: 3.7.3 Package: sflphone-common Priority: optional Architecture: any -Depends: libsamplerate0, libexpat1 , libc6, libccgnu2-1.7-0, libgsm1, libspeex1, libdbus-1-3, libasound2, libpulse0, libccrtp1-1.7-0, libspeexdsp1, libzrtpcpp-1.4-0, libssl0.9.8, libpcre3, libyaml-0-2, libcelt0-0, libdbus-c++-1-0 +Depends: ${shlibs:Depends}, ${misc:Depends} Replaces: sflphone Conflicts: sflphone Homepage: http://www.sflphone.org diff --git a/tools/build-system/launchpad/sflphone-common/debian/control.lucid b/tools/build-system/launchpad/sflphone-common/debian/control.lucid deleted file mode 100644 index 4916f16c2783e05bff17f1bf28597cbd1f5a0614..0000000000000000000000000000000000000000 --- a/tools/build-system/launchpad/sflphone-common/debian/control.lucid +++ /dev/null @@ -1,28 +0,0 @@ -Source: sflphone-common -Maintainer: SavoirFaireLinux Inc <julien.bonjean@savoirfairelinux.com> -Section: gnome -Priority: optional -Build-Depends: debhelper (>= 7.0.50), libgcc1 , autoconf, automake, libpulse-dev, libsamplerate0-dev, libcommoncpp2-dev, libccrtp-dev, libgsm1-dev, libspeex-dev, libtool, libdbus-1-dev, libasound2-dev, libspeexdsp-dev, uuid-dev, libexpat1-dev, libzrtpcpp-dev, libssl-dev, libpcre3-dev, libyaml-dev, libcelt-dev, libdbus-c++-dev -Standards-Version: 3.7.3 - -Package: sflphone-common -Priority: optional -Architecture: any -Depends: libsamplerate0, libexpat1 , libc6, libccgnu2-1.7-0, libgsm1, libspeex1, libdbus-1-3, libasound2, libpulse0, libccrtp1-1.7-0, libspeexdsp1, libzrtpcpp-1.4-0, libssl0.9.8, libpcre3, libyaml-0-2, libcelt0-0, libdbus-c++, libdbus-c++-1-0 -Replaces: sflphone -Conflicts: sflphone -Homepage: http://www.sflphone.org -Description: SIP and IAX2 compatible softphone - Core - SFLphone is meant to be a robust enterprise-class desktop phone. - SFLphone is released under the GNU General Public License. - SFLphone is being developed by the global community, and maintained by - Savoir-faire Linux, a Montreal, Quebec, Canada-based Linux consulting company. - -Package: sflphone-common-dbg -Architecture: any -Section: debug -Priority: extra -Depends: - sflphone-common (= ${binary:Version}), - ${misc:Depends} -Description: debugging symbols for sflphone-common diff --git a/tools/build-system/launchpad/sflphone-common/debian/control.natty b/tools/build-system/launchpad/sflphone-common/debian/control.natty deleted file mode 100644 index e5dd650ae5f8918812f8b033b0dba9aa7410c325..0000000000000000000000000000000000000000 --- a/tools/build-system/launchpad/sflphone-common/debian/control.natty +++ /dev/null @@ -1,28 +0,0 @@ -Source: sflphone-common -Maintainer: SavoirFaireLinux Inc <julien.bonjean@savoirfairelinux.com> -Section: gnome -Priority: optional -Build-Depends: debhelper (>= 7.0.50), libgcc1 , autoconf, automake, libpulse-dev, libsamplerate0-dev, libcommoncpp2-dev, libccrtp-dev, libgsm1-dev, libspeex-dev, libtool, libdbus-1-dev, libasound2-dev, libspeexdsp-dev, uuid-dev, libexpat1-dev, libzrtpcpp-dev, libssl-dev, libpcre3-dev, libyaml-dev, libcelt-dev, libdbus-c++-dev -Standards-Version: 3.7.3 - -Package: sflphone-common -Priority: optional -Architecture: any -Depends: libsamplerate0, libexpat1 , libc6, libccgnu2-1.7-0, libgsm1, libspeex1, libdbus-1-3, libasound2, libpulse0, libccrtp1-1.7-0, libspeexdsp1, libzrtpcpp-1.4-0, libssl0.9.8, libpcre3, libyaml-0-2, libcelt0-0, libdbus-c++-1-0 -Replaces: sflphone -Conflicts: sflphone -Homepage: http://www.sflphone.org -Description: SIP and IAX2 compatible softphone - Core - SFLphone is meant to be a robust enterprise-class desktop phone. - SFLphone is released under the GNU General Public License. - SFLphone is being developed by the global community, and maintained by - Savoir-faire Linux, a Montreal, Quebec, Canada-based Linux consulting company. - -Package: sflphone-common-dbg -Architecture: any -Section: debug -Priority: extra -Depends: - sflphone-common (= ${binary:Version}), - ${misc:Depends} -Description: debugging symbols for sflphone-common diff --git a/tools/build-system/launchpad/sflphone-common/debian/rules b/tools/build-system/launchpad/sflphone-common/debian/rules index 544cbacabf3838a49db1960763673bbbbd609f07..d3f7a238f2362a647d883f62027e6f4a9f9c6580 100755 --- a/tools/build-system/launchpad/sflphone-common/debian/rules +++ b/tools/build-system/launchpad/sflphone-common/debian/rules @@ -77,6 +77,7 @@ binary-common: dh_fixperms dh_makeshlibs dh_installdeb + dh_shlibdeps dh_gencontrol dh_md5sums dh_builddeb diff --git a/tools/build-system/launchpad/sflphone-plugins/debian/changelog b/tools/build-system/launchpad/sflphone-plugins/debian/changelog index ba72a339ab5e3e6e06c9f0c1623a159441bb89a4..0a5d85585dc16fb5f82ed3fa0e623d6a86ab2eb4 100644 --- a/tools/build-system/launchpad/sflphone-plugins/debian/changelog +++ b/tools/build-system/launchpad/sflphone-plugins/debian/changelog @@ -1,3 +1,1096 @@ +sflphone-plugins (1.0.0-rc20110930~ppa1~SYSTEM) SYSTEM; urgency=low + + ** SNAPSHOT 1.0.0-rc20110930~ppa1~SYSTEM ** + + * update kde .gitignore + * Fix bug in volume widget + * More polishing for release + * Bump version to 1.0.0 + * [#7023] Add the ability to load an abstract contact backend in the + library to resolve more data, polish code + * [#7021] More cleanup for release + * Cleanup + * [#7021] Refactor KDE client dbus handling, add a missing call in + daemon and port the DataEngine to the new API + * Remove some annoying debug + * merge language scripts + * remove obsolete 'VERSION' files + * update install instructions + * Add missing translations to gnome + * language update + * Revert "Don't reference count DBus clients, exit core immediately + when one of them request it" + * Don't reference count DBus clients, exit core immediately when one + of them request it + * [7021] Add contact abstraction support + * [#7121] Polishing library (over). Indentation, spacing and naming + are now consistent + * codecs: link to libccrtp, don't use logger + * Fix a daemon bug + * [#7038] Fix adding contact + * * #7037 : stop audio stream after all calls have been hanged up + * [#7025] Add full support for bookmark + * SFLPhone KDE do not destroy history anymore + * Fix config skeleton + * Close the daemon once and for all, no more automatic respawning + * Fix "unregistered account" bug (I hope so) + * Close SFLPhone at the right place, it still respawn, I don't know + why + * Remove dead code + * Fix regressions introduced in the last commit + * Dead code elimination 1/3 + * Fix bug, add "add contact" option, fix warning + * * #7019: Fix IAX codec negociation + * Remove or comment unnecessary/unhelpful debug output + * Fix "same as local" account setting, fix IP2IP LED color + * Add support for some more advanced config options and add missing + config dialog icons + * Fix crash with noise suppressor + * Alternative can now be selected from the call view context menu + * Add drag and drop support, initial context menu and fix 3 bugs in + the account dialog + * Add basic history drag and drop support + * Complete contact support is back + * * #6991 : fix IAX problems + * Fix IAX accounts being disabled by default + * Revert "deb: forge -g flags for pjsip" + * * #5884: Disable debug code in pjsip + * echo suppressor : more assertions + * Don't let the daemon think crypto is enabled when it's not + * Simplify ToneList + * Some progress on contact support + * Remove unused getRegistrationCount() + * remove annoying debug + * revert SIP bit of e27e5c39bad27bae28f574eb2cba7717e8956229 + * Simplify CallManager::placeCallFirstAccount + * Fix crash on hold + * * #6905 : SIP refactor + * gnome client: be sure key exchange is set correctly + * Move code into createSipTransport + * Fix account registration on start + * ManagerImpl::registerAccounts(): simplify + * * #5884: don't mess with pjsip threads in echo suppressor + * * #6905 : simplify udp/stun/tls pjsip transport creation + * Restore and improve support for Call history + * fix launchpad build + * SIPVoIPLink: simplify / refactor + * Fix libwidget linking + * SIP: simplify + * IM : simplify + * gnome: remove some debug + * AudioRtpFactory::stop() cannot fail + * * #6905: simplify SIP code + * pjlib: fix build without SSLv2, fix warnings + * Port history to the new syntax + * Test a dock widget based implementation for contact and history + * Disable SSLv2 support from pjsip and sflphone + * deb: forge -g flags for pjsip + * Fix deb packaging to get debug symbols + * remove debug + * pjproject: update to last stable release (1.10) + * Require gtk >= 2.20 and glib >= 2.24 + * tlsadvanceddialog: simplify + * * #6902 : fix errors spotted by -DGSEAL_ENABLE + * Update daemon dbus XML and port KDE config backend from dbus to + local + * Remove unused but set variables + * * #6929 : fix IM widget, cleanup + * Unconditionally enable debug symbols + * Should fix many KDE issues + * * #6886 : hitting backspace on empty number have no side effects + * * #6905 : fix AudioCodecFactory access in optimized builds (-O > 0) + * Remove unsupported and broken jaunty/karmic packages + * * #6902 : avoid using some gtk deprecated functions + * Update dbus introspection files + * * #6904: removed unused contactmanager + * * #6903 : use correct dbus-cxx package name + * * #6902: don't use individual gtk headers + * Fix a segfault when config is not present + * Merge latest (0.9.13) KDE code. This version is not yet ready for + git master, but better than the previous one + * addressbook : simplify + * * #5659 : sflphone-plugins doesn't depend on libedataserverui + * * #5659 : addressbook doesn't use libedataserverui + * gnome client doesn't depend on evolution + * * #5695: addressbook: simplify + * * #5695: addressbook : remove AddrBookHandle from plugin + * * #5695 : addressbook : remove unused stuff in the client + * * #5695 : addressbook : remove unused stuff, use static mutex + * gnome client doesn't use evolution + * gnome: use proper API to set GTK_CAN_FOCUS + * * #6897: removed unused focus state vars/callbacks + * gnome: fix calls to sflphone_fill_codec_list_per_account + * * #6623: gnome: don't leak in mainwindow + * gnome: mainwindow whitespace cleanup + * gnome: actions.c parameter doesn't have to be a double pointer + * * #6895: fix memleaks, cleanup in accountconfigdialog + * * #6893: fixes segfault in client on clean history + * * #6894: fix leaks, cleanup in sflnotify + * daemon: fixed prints in main + * * #6892: simplify, fix leaks in dialpad + * * #6887: audiopreference creates audio layer + * * #6660: use const char * const, not std::string for globally + visible constants + * * #6852: Preferences now solely responsible for audiolayer creation. + * * #6860: refactor uimanager, also fixes #6865 + * * #6853: hangup as soon as all digits have been deleted + * * #6852: alsa: retry if device is busy + * * #6852: audiolayer creation depends only on preference.audioApi + * * #6850: gnome: fix build for gtk < 2.22.0 + * cleanup in iax + * alsa: typo + * pulse: if we can't peek in audio input, we can't drop samples + * * #6849: show error window if codecs are missing, instead of dying + * EchoCancel: unused, remove + * * #6629 : use number of samples as arguments for audio filters + * * #6629 : remove unused Algorithm interface + * * #6629 : use helper to call alsa functions and display error msgs + * Remove unused type + * * #6841: fix some error handling + * * #6629: simplify AlsaLayer::alsa_set_params() + * Get gdk key definition from header + * * #6828: Replace raw key codes by gdk defines + * remove some debug, enhance some other + * mainbuffer: simplify + * * #6561 : fix phantom call after transfer + * Conference Participant set : simplify + * SIPCall: remove unused functions, make invite session public + * * #6229 : remove malloc/free from pulse audio loop + * * #6629 : simplify pulse callbacks + * * #6629 + * Simplify widgets + * * #6629 : keep the correct audio module when frequency changes + * * #6751: fixed erroneous debug msgs + * callable_obj.h: removed unneeded pthread header + * alsalayer: cleanup + * * #6629: Always restart audio driver when changing parameters (ALSA + only) + * gnome GUI: don't block in DBus signal errorAlert() + * * #6629 : simplify AudioLayer creation + * * #6629 : remove unused and unconfigurable frameSize from audiolayer + * * #6629 : remove unused error message from audio layer + * Fix logic error when switching audio API + * Remove unused AudioProcessing class + * AudioRtpRecordHandler::initNoiseSuppress() : use noiseSuppress + directly + * * #6629 : use DC blocker directly in audio layers + * * #6629 : clean AudioLayer + * * #6629 : don't store mainbuffer inside audiolayer + * * #6629 : correct AudioLayer::notifyincomingCall() + * * #6554: cleanup, refactoring in sipvoiplink + * * #6554: cleanup in iaxvoiplink + * * #6554: throw exception in getSIPCall if pointer is NULL + * * #6554: make some methods of sipvoiplink static + * * #6655: cleanup in managerimpl + * * #6554: refactoring, fix memleaks in sipvoiplink + * * #6478: remove throw specs, cleanup in voiplink + * * #6629 : remove unused AudioDevice + * * #6655: removed more dependencies from managerimpl + * * #6744: simplified numbercleaner + * conference : remove one prototype + * * #6743: fix ip2ip + * Don't give glib warnings if icons are not found + * gnome: fixed includes + * Codec.h: removed unused function + * * #6742 : clean dbus & icons + * * #6699: refactor/cleanup accounts + * icons: cleanup + * timer : use second precision, not millisecond + * calltree_update_clock : use correct type, returns something + * * #6737: fixed typo in dbus call + * * #6737: removed tests for removed API + * * #6737: dbus: fixed bug from merge + * * #6737: cleanup in accountlist + * * #6737: cleanup in dbus + * * #6740 : fix history double free + * * #6740 : remove time updating thread from calls + * * #6737 : use c99 for client + * * #6738 : make history loading faster + * sipvoiplink : don't crash on transfers + * fixed typo + * Remove unused file + * Don't build networkmanager.cpp at all if NM is disabled + * _debug* -> _debug + * * #6554 : simplify sipvoiplink + * hudson: added -x to git clean command + * added git clean to hudson script + * audiocodecfactory: cleanup + * * #6718: refactored setTlsSettings into SIPAccount + * * #6718: removed more unused methods + * * #6718: refactored confmanager code into sipaccount + * remove unused functions + * * #6718: confmanager: removed more unused methods + * AudioCodecFactory : cleanup + * #6697 : Turn callableElement struct into union + * * #6718: confmanager: removed more unused methods + * * #6718: confmanager: removed more unused methods + * * #6718: removed unused dbus methods, refactoring + * * #6699: accounts: cleanup/refactoring + * * #6699: refactoring, cleanup in accounts + * * #6699: more account cleanup + * remove unused autoconf variable + * * #6714: fixed hudson script + * make distclean in hudson + * added || exit 1 to run_tests.sh call + * * #6714: fixed make distcheck for sflphone-plugins + * * #6714: fixed make distcheck for gnome client + * * #6714: fixed make distcheck for daemon + * git: #6698 split the main .gitignore file + * gnome: gpointer is already a pointer + * gnome: calltab_init: use calloc instead of malloc + * * #6699: more account cleanup + * * #6699: cleanup account + * * #6554 : more *voiplink cleanup + * * #6558 : more sipvoiplink simplification + * * #6558: saner loadSIPLocalIP prototype + * gnome: #6623 clean calllists + * * #6692: more audiolayer cleanup + * * #6692: cleanup/refactoring in audiolayers + * * #6692: more forward declarations, AudioThread->AlsaThread + * * #6692: audiolayer cleanup + * * #6692: alsalayer cleanup + * * #6558 : remove account creator + * * #6558 : clean sipvoiplink + * * #6554 : cleanup sipvoiplink + * audiortp: cleanup + * * #6657 : fix launchpad builds for good + * * #6675 : send RTP dtmf events only once + * * #6655: more cleanup + * AudioRtpSession::updateSessionMedia() : simplify + * * #6655: more cleanup in managerimpl + * * #6655: removed more code, cleanup + * * #6655: more cleanup, fixed infinite loop + * * #6655: removed more unused files + * * #6655: removed unused mutex + * * #6655 removed more unused code + * * #6655: removed unused methods + * * #6655: cleanup in main + * * #6663: fixed segfault when off hold from transfer + * * #6658: user's active codec selection is respected + * * #6660: static global string should be static const char* const + class member + * * #6659: use g_strcmp0, not strcmp for vals that may be null + * callable_obj: fix double free + * calltree_display_call_info() : simplify + * * #6657: Fix launchpad builds + * Logger::log() : simplify + * AudioRtpSession : privatize members + * * #6655: more constness, cleaned up/simplified methods + * * #6654: call DBus::_init_threading so that dbus-c++ to make it + threadaware + * set default credentials on account creation + * AudioCodecFactory::scanCodecDirectory() : simplify and correct + * * #6623: fixed typos + * * #6623: fixed more leaks + * * #6623: fixed more leaks + * * #6623: fixed more leaks, don't print codec name if null + * * #6623: more leaks fixed in client + * * #6623: fix more leaks, fixed some warnings + * * #6623: fixed leak in history + * updated gitignore + * initialize dbus dispatcher correctly + * Fix tests, hudson doesn't have a dbus daemon running + * remove unused code + * removeCall() : simplify , fix leak + * stopRtpThread() : simplify + * *CurrentCall : simplify + * Fix memleak + * fix serialization of audio api (pulse / alsa) + * account map : simplify + * remove call from callmap before terminating it, avoid use after free + * * #6630 : don't make DBusManager a singleton + * call: return confID by value + * add back history code deleted by error + * history : reverse logic + * simplify history serialization and remove some debug + * remove annoying debug + * * #6464 : replace cerr with _error + * * #6464: replace cout with logger macros + * replace printf() with logger macros + * update .gitignore + * remove unused function + * update eclipse projects + * uimanager_new() : simplify + * rename directories + * celt: simplify a bit + * Fix CELT configure.ac test + * * #6612 : template speex codecs + * * #6623: refactored conference obj + * * #6623: refactored callable object, removed leaks + * * #6623: more cleanup, fix leaks, make global vars static and rename + them + * * #6623: calltree: fixed memleaks, simplified code. + * audiolayer: init pointer members + * manager: catch exception on invalid hangup + * * #6623: don't leak on calls to create_new_call + * * #6611 : clarify codecs prototypes + * ringtones : .au and .ul files are both ulaw + * * #6611 : make sure samplerate converters are called correctly + * ManagerImpl::switchAudioManager() : simplify + * * #6623: fixed more leaks + * * #6623: fixed more leaks + * * #6623: fixed more leaks + * * #6623: fixed leak, line-endings in imwidget + * * #6627: zero-initialize pointers if they're going to be deleted + * * #6628: don't leak calls on exceptions + * Revert "audiortp: call join after calling stop on RtpThread" + * sflphone-client: more constness + * audiortp: call join after calling stop on RtpThread + * * #6625: return 0 on successful completion + * * #6624: fix segfault on servercallfailure + * * #6621: Fixed double free, unlock mutex in ManagerImpl::terminate + * * #6220: remove audio stream when peer hangs up + * * #6596: AudioSymmetricSession shouldn't self-delete + * resampler: grow internal buffers dynamically + * merge up and down sampling => resampling + * Leave test directory unchanged when running make check + * audio algorithms : remove unused prototype + * ringtone: detect codec from file extension + * *AudioFile : simplify + * * #6596: create local SDP on the stack, not the heap + * * #6596: don't call Ost::Thread::terminate from dtor + * audiofile: cleanup (samplerate -> unsigned) + * remove unused func + * samplerateconverter: cleanup + * RingBuffer::Put() : remove unused return value + * MainBuffer::putData() : remove unused return argument + * audiolayer::putMain() : remove unused func + * AudioLayer::putUrgent() : remove unused return value + * * #6618: delete any remaining ringbuffers in destructor + * RingBuffer::availForPut() : remove + * * #6617: return from main rather than calling exit + * MainBuffer::availForPut(): remove + * RingBuffer: simplify + * alsa : remove write only variable + * fix memcpy declaration + * bcopy(src, dst) -> memcpy(dst, src) + * RingBuffer::Get() : remove constant volume argument + * return a copy of the call ID, not just a reference. + * MainBuffer::getDataById() : remove volume argument (always 100) + * MainBuffer::getData() : remove constant volume argument + * RingBuffer::Put() : remove constant volume argument + * MainBuffer::putData() : remove constant (=100) volume argument + * audiolayer: remove constant _defaultvolume + * AudioRtpRecordHandler / AudioRtpSession : simplify + * mainbuffer: fix test + * iaxvoiplink : simplify + * sip registration callback: fix a dbus crash + * MainBuffer: simplify + * AudioRtpFactory: return cached type of rtp session. The rtp session + can have disappeared if the call was put on hold + * AudioRtpFactory: remove unused setters + * Fix launchpad builds + * * #6611 : remove unused bandwidth codec information + * * #6611: AudioCodec: remove useless/unused setters + * make sure buffer string is initialized correctly + * * #6596: declare certain destructors virtual + * audiolayer : cleanup + * Simplify doc build rules + * * #6270: don't build dbus-api doc with make, should require make all + * configure.ac: cleanup + * Remove copy of dbus-c++ from libs/ + * * #6596: stop clock thread when peer hangs up + * removed unused Fmtp.h + * * #6595: more logical initialization order + * * #6600 : fix account creation + * * #6601 : fix configure.ac tests + * remove unused variable + * Don't mix stack and heap based allocations + * Fix copyright (2009, 2008, 2009 -> 2008, 2009) + * Fix warnings found by clang + * * #6595: fix initialization order for AudioRTP + * * #6592: removed typedef std::string CallID + * * #6586: implement local g_slist_free_full for older glib versions + * * #6579: fix memory leaks in client (there's a lot left) + * ShortcutPreferences::setShortcuts() : simplify + * Fix merge + * * #6548: remove call to non thread-safe strerror() + * AudioRtpFactory: each instance is associated to exactly one SipCall + * create_audiocodecs_configuration() : make static + * * #6269 : refactor AudioRtpSession + * Fix AudioSymmetricRtpSession.h inclusion guard (cherry picked from + commit c3081dce1cc1370d6d3558a4c4ef5cfac0d21caf) + * * #6269: Rename AudioRtpSession to AudioSymmetricRtpSession + * * #6574: Don't exit when connection to pulseaudio server fails + * accountconfigdialog.h : remove some stuff from header + * * #6560: fix configuration test + * Fix warning in test + * * #6560: don't hide password entry in security tab + * * #6560: set initial password for SIP accounts + * * #6506: remove useless pointer indirection + * * 6560: password is now specific to IAX accounts + * * #6560 : actually use, store, restore, transmit SIP credentials + * * #6560: YamlEmitter: serialize sequences + * YamlEmitterException: typo + * ManagerImpl::computeMd5HashFromCredential() : simplify, fix memleak + * * #6561: invite_session_state_changed_cb() : simplify + * * #6561: More useful debug in VoIPLink::removeCall + * * #6561 : fix ghost call reappearing in GUI after transfer + * while -> for (make the code smaller) + * * #6558 : Account::loadConfig() : move IAX code to IAXAccount + * IAXVoIPLink::getAccountPtr : simplify + * * #6554 : access the SIPVoIPLink directly, not per account + * SIPVoIPLink is instanciated only once and is not associated to a + single account + * yamlnode: use const references when possible (still some left to do) + * Account::_accountID: constify + * VoIPLink: simplify, remove unused method + * hudson test : no need to call run_tests.sh anymore + * Remove AccountID type and AccountNULL define + * Make check runs the test (no need to call run_tests.sh manually + anymore) + * gnome GUI: Fix tests + * Revert "Move registration information from SIPAccount to + SIPVoIPLink" + * * #6392: pluginmanagertest: fix warnings reported by valgrind + * * #6547 : remove unused exceptions + * * #6547: CallManagerException: use runtime exceptions + * * #6547: InstantMessageException: use runtime exceptions + * * #6547: do not throw exceptions if some settings are not present in + config file + * * #6547: YamlParserException: use runtime exceptions + * * #6547: VoipLinkException: use runtime exceptions + * * #6547: YamlEmitterException: use runtime exceptions + * * #6547: DTMFException: use runtime exceptions + * * #6547: AudioFile: use runtime exceptions + * * 6547: AudioZRtpSession: remove impossible error case + * * #6547 : AudioRtpSession: remove impossible error case + * * #6547: AudioZrtp: use runtime exceptions + * * #6408 : send authenticationUsername to GUI + * * #6408 : store/restore authenticationUsername from config file + * SIPAccount: simplify + * Move registration information from SIPAccount to SIPVoIPLink + * SIPAccount::getAccountDetails : simplify + * * #6540: yaml parser: simplify + * sdp.cpp : fix a warning + * * #6540: yaml parser : remove std::string typedefs + * * #6540: Simplify yaml unserialization + * * #6540 : add a Conf::ScalarNode constructor for booleans + * setAccountDetails(): simplify + * * #6408: store authentication username in daemon + * * #6408: Be able to set the authentication username in the GUI + * * #6507 : do not crash if the program is not sflphoned + * Fix tests + * macroify SIPAccount::unserialize() + * Move all .cpp files from sflphoned target to libsflphone.la, except + main.c + * main() : simplify, return positive error codes + * * #6507 : find codecs dir in build directory + * * #6392: Sdp: move clean functions to destructor + * AlsaLayer::adjustVolume() : simplify + * alsalayer : reduce indentation + * malloc/free -> new/delete + * malloc/free -> new[]/delete[] + * malloc/free -> new/delete + * AudioSrtpSession: simplify base64 encoding + * * #6392: Initialize std::string from pj_str_t correctly + * * #6392: AudioRtpSession: Initialize remote port + * Audio settings : Initialize _echoCancelTailLength and + _echoCancelDelay(0) + * Initialize variable + * YamlParserException : fix use of stack variable after it has been + deallocated + * * #6392: fix memory leak in history + * * #6392 AudioCodec : fix memory leak + * * #6392 : fix memory leak in sip account + * * #6408: clean up sipaccount (cosmetics mostly) + * sipaccount.cpp serialize() : reduce number of lines + * * #6392: invalid memory access + * * #6392 : fix invalid memory access + * * #6479: merged useful code from MimeParameters into Codec interface + * * #6462: fixed hangup on IP2IP call + * added run_daemon.sh script + * test: remove unused variable + * Remove functions only used by a failing test (cherry picked from + commit fcf718cb75de7f1882dc61c07bb8d300dfa10f85) + * * #6360 : make client tests build (cherry picked from commit + 028b2835f040e51ab8ab979b32732b07b8798fce) + * * #6360 : fix warnings in check_global test (cherry picked from + commit 9e2bd6a7496dd64f6f48595e385760019aab1193) + * * 6360: updated API calls in tests, but they're not building yet + (cherry picked from commit 548f6f0f919b43772a3e9c667e5e292791281795) + * Fixed include in tests (cherry picked from commit + aeadc7525c1e31f936670ac8b02f0bcf387c38a8) + * Remove unused variables and functions + * IAX: fix warnings (cherry picked from commit + fd7a113a11cac2cd9a7c36929e88ad28195c4c35) + * Remove unused DEBUG define which interferes with logger.h (cherry + picked from commit b2f72b91d0f43cb1dd94d138882a8caa9c841c24) + * * #6392: no need to check for account NULLity since it is + dereferenced above + * * #6392: fix a memory leak, replace by stack allocation + * * #6392: remove a variable assignement which confuses cppcheck + * process_conference_participant_from_serialized() : remove unused + function + * * #6392: s/free/g_free/ + * * #6392: fix a memory leak in abookfactory_load_module() + * * #6392: remove generate_call_id() used only once + * * #6392: fix memory leak (opendir() without closedir()) + * * #6392: AudioRecorder(): ensures mbuffer is set + * Remove SFLPHONED_VERSION from global.h, use autoconf PACKAGE_VERSION + * #6298: Cleanup + * #6331: Fix deleting ringtone file after call have been answered + * * #6330: merged user_cfg into headers + * #6298: Fix conference recording file update at conference end + * #6298: Fix record file name serialization for conference + * * #6295: cleanup of codec hierarchy + * #6298: Fix gtk warnings + * * #6300: added script to run tests + * #6109: Add recording playback for conference + * * #6300: tests do not require an installed sflphone + * * #6295: re-removed clone methods + * #6109: Fix gtk_critical warnings for incoming calls + * #6109: Fix GTK_CRITICAL warning + * #6109: Fix icons when history is not activated + * #6109: Fix warnings + * #6109: Implement stop recorded file playback signal + * Revert "* #6295: removed unused clone method" + * * #6295: removed unused clone method + * * #6296: removed non existant file from Makefile.am + * #6109: Stop fileplayback for outgoing call + * #6109: Implement stop recording playback button + * Fix binding names errors in dbus introspection file + * #6109: Implement playback recorded file callback in client + * #6109: Store recorded file path on client side + * #6109: Add dbus methods for call recording playback + * * #6290: remove unused classes from utilspp + * * #6288: cleanup sdp + * * #6288: fix exception usage + * * #6288: simplify SdpException + * * #6288: cleanup in sdp.cpp/h + * #6109: Only display playback button if record file is set and valid + * * 6290: updated configure.ac to remove functor Makefile + * * #6290, #6289: removed unused classes from utilspp, fixed make + check + * #6109: Add button for history playback of recorded file + * * #6289: removed unused observer class + * * #6282: forward declare sdpMedia in sdp.h + * * #6281: renamed setCallAudioLocal->setCallMediaLocal + * #6183: Handle conference with more tahn two calls + * #6183: Fix history icons when calling back a conference from history + * #6183: Fix icons inconsistencies in history for conference hang up + * #6183: Fix toolbar actions when selecting a conference in history + * #6183: Fix conference serialization + * #6268: Serialize only calls + * * #6269: removed useless type testing + * ignore some files in test/ + * * #6268: Remove dead class AudioSymmetricRtpSession + * #6251: Do not had history calls in calllist when loading history + file + * #6251: Fix insertion in history map in before saving history file in + daemon + * #6251: Fix history unit tests + * #6251: Order the list before serailization, get rid of the hashtable + in history + * #6251: Implement history serialization using a list wether than a + map + * * #6253: remove external audioport from header, make all members + private + * * #6253: don't store external local audio port (used for NAT) in + Call + * #6251: Add start_time timestamp in history serialization + * #6251: Fix call insertion in conference items + * #6233: Fix serialized account list terminated with a ";" character + * #6238: Fix draggable history calls into current calls + * #6233: Fix toolbar updates + * #6233: Fix history + * * #6235: remove pyc files from git tree + * #6233: Handle cases when one or manuy calls are unreachable in + createConfFomrParticipantList + * #6233: Handle wrong numbers in createConferenceFromParticipantList + * #6231: Fix drag-n-drop issue + * * #6173 : move sippxml in tools + * #6231: Fix merging issue + * #6183: Implement conference unserialize + * * #6212: remove extraneous flags from globals.mak + * #6183: Unserialize conference data in conference + * #6183: Add account information in request for conference call from + history + * #5755: Add -ldl to liker in sflphone-client-gnome + * #5755: Fix fedora 15 compilation issue + * #6183: Serialize conference participant phone number and account + * #6183: Add conference timestamp in serialization + * * #6186: don't include global.h, just logger.h + * #6183: Fix saving history to file + * #6183: Fix removing call from calllist + * * #6184: remove pointers to Manager from AudioRtpSessions + * #6183: Calling calltree_add_call explicitely for history + * #6183: Ability to store conference inside history tab queue + * * 6181: remove unused API from sipcall + * #6171: Implment nreCallCreated callback + * #6167: Fix participant list NULL ending + * #6149: First draft of conference creation from history + * #6149: Fix multiple call/conf selection callbacks ... + * #6129: Fix place_call function called twice for pressing enter + action + * #6129: Fix double click action for history + * #6149: Add dbus call for creating conference from history + * #6129: Fix placing call from history and addressbook (still need to + fix icon) + * * #6148: removed unused AudioRtpFactory constructor + * * #6145: remove unused isAudioStarted + * * #6145: remove unused isAudioStarted + * #6129: Add conference into history, fix call/conference selection + * * #6143: don't use getType outside of serialization methods + * * #6132: forward declarations instead of includes + * * #6132: add constness, remove redundant "inline" keywords + * #6129: Add timestamp to conference object to order history entries + * * #6128: remove unused forward declarations from header + * * #6127: make noncopyable class actually noncopyable + * * #6125: don't include AudioRtpFactory in sipcall.h + * #6123: Fix alsa ringback audio file + * #6123: Fix raw audio file loading problem + * #6109: Fix daemon plugin manager unit test + * #6109: Fix history manager unit tests + * #6109: Recording filename in daemon and client for history items + + serialization + * #6109: Refactor AudioFile to play recorded call + * * #6104: AudioCodec moved to sfl namespace + * * #6099: remove active flags from codec classes + * #6095: Add notification-daemon as a runtime dependencies for rpm + packages + * #6095: Fix fedora 15 compilation in MineParameters.h + * #6095: Declare static variable explicitely for client + * #6095: Add logs to build OSC build machine + * * #6098: global variables should have file-scope to avoid name + conflicts + * #6095: Fix compilation error for Fedora 15 + * #6095: Update SFLphone version to 0.9.14 + * #6095: Add specification file in opensusse build service for + sflphone-plugins + * #6073: Fix sflphone-plugins build on launchpad + * #6093: Rename CodecDescriptor for AudioCodecFactory + * * #6089: fix warnings in make check + * * #6086: renamed codecs methods to audio_codecs + * * #6085: renamed codec related dbus calls to audio_codec + * #6065: Remove g_print from client, use DEBUG instead + * #6065: Add actions name for addressbook + * * #6085: renamed codecs* widgets/functions audiocodecs* + * #6065: Fix Addressbook runtime warnings + * #6065: Replace Codecs tab for Audio in account preference dialog + * #6065: Fix "transfert" typo + * #6065: Fix addressbook action runtime warning in uimanager + * * #6082: fixes make check by adding libcrypto libs to test + dependencies + * #6073: Rename plugin/addressbook folders for addressbook/evolution + in sflphone-plugins + * #6074: Removed AC_SUBST from configure.ac when using + PKG_CHECK_MODULE + * #6073: Fix sflphone-plugins package build + * #6073: Fix sflphone-common build + * #6065: Fix runtime gtk warning when initializing searchbar without + addressbook + * #6063: Fix mozilla-tellify gitignore + * #6063: Remove stream copy file using ifdef macro + * * #6012: fix make dist for sflphone-common + * #6063: Update .gitignore file + * #6058: Fix base64 encoding related warnings + * #6056: Fix SdpException handling + * #6055: Fix unknown pargma warning for gcc <= 4.5 + * * #5949: test gcc version before disabling unused-but-set warning + * #6054: Fix addressbook plugin compilation warning + * #6048: Fix uimanager static initialization + * #6046: Fix addressbook factory static initialization of member + addrbook + * #5979: Fix implicit function declaration warning + * #6042: Fixed discarding qualifier warnings in client + * #6041: Fix instant messaging unhandled case warning + * #5994: Implement set current addressbook name and search type in + addressbook plugin + * #5994: add rules for launchpad packaging of addressbook plugin + * #5994: Fix addressbook plugin configuration loading + * #6027: Fix addressbook enabled test from configuration + * #6027: No need of gnomedoc related macros in addressbook plugin + * #6027: Add NEWS file required for build + * #6027: Add addressbook plugin autogen.sh script + * #6027: Remove plugins from client + * #6027: Add sflphone-plugins folder at project's root level + * #5994: Move addressbook folder from contacts to plugin folder + * * #6011: removed unused Makefiles + * * #6010: remove unused headers + * * #5952: fix "string constant to char*" warnings + * * #6009 fixed warnings + * * #6003: finished cleanup of account classes + * * #6003, #6004: cleanup of account classes, defaultAccount no longer + global + * * #6000: fix memory leak of args object + * * #5998: removed using namespace std from networkmanager + * * #5998: removed "using namespace std" from ZrtpSessionCallback + * * #5998: removed using namespacestd from AudioZrtpSession.h + * * #5998: remove "using namespace std" from auriorecord.h and + MimeParameters.h + * * #5998: remove using namespace std in main + * * #5998: removed "using namespace std" from logger + * * #5949: test gcc version before disabling unused-but-set warning + * #5994: Installation of addressbook plugin + * #5979: Implement codec full addressbook search from plugin + * #5979: Implement addressbook factory and plugin + * * #5981: unused webwidget removed + * #5966: Account config synchronization fix (for stun) + * #5954: Handle media name exception + * #5954: Fix audio codec name display in client + * #5954: Clean up getSessionMedia methods + * * #5957: getRecordingSmplRate returns a value + * #5954: Clean up getCurrentCodec methods + * * #5950: remove "converting to non-pointer type 'int' from NULL" + warnings + * #5915: Full gain control version + * * #5949: remove more unused variable warnings + * * #5949: remove unused/unused-but-set variable warnings + * * #5949: show_preferences_dialog returns a success value + * * #5946: cleanup of include directives, undefined function + * * #5515: comment out SSLv2 calls in pjsip + * #5915: Implement different slope for attack tme and release time for + gain control + * #5915: use only one input signal for gain control (removed output + buffer) + * #5921: Fix no audio after holding a conference + * #5916: Add gaincontrol files + * #5916: Implement FFMPEG/CCRTP video streaming prototype + * #5903: Fix call transfer during a conference + * #5915: implement rms detector, first order averager, limiter for + gain control + * #5914: Fix call transfer when no notification request is required + * #5899: Fix conference right-click segfault + * #5884: temporary fix segfault in pjsip memory pool + * #5883: Fix compilation issues on maverick and lucid + * #5755: Fix fedora 15 compilation without patching ccrtp + * [#5855] Make echo canceller optional + * #5855: Fix echo suppression activation/deactivation + * #5855: Implement pjsip echo canceller + * #5814: Speex initialization function uses samples, not bytes + * #5814: Test using more unbalanced signals + * #5814: Fix buffer size for long echo length or long echo delay + * #5814: Adjust level for echo cancellation at runtime + * #5814: Process noise reduction before echo cancelling + * #5814: Implement speex post echo canceller processing + * #5814: Dump echo cancel file to disk + * #5814: Add parameters for echo cancel + * #5809: Add configuration parameters + * #5809: Implement speex echo canceller in audio rtp session + * #5814: Code cleanup + * #5814: Fix conf creation with several incomming ringing calls + * #5814: Fix conf creation segfault when dragging a call on hold on a + ringing call + * #5809: Added unit test for echo cancellation and implemented + "process" virtual method + * #5709: Add always recording option in configuration + * #5709: Add always recording option in audio conference panel + * #5709: Add core functionnality for always recording (missing config + options) + * #5769: Fix conference participant handling (detach/attach) and hold + actions + * #5747: Fix recording icons and state for conference when adding new + participant + * #5769: Code cleanup + * #5769: Fix hangup unsent calls + * #5769: Fix remove/add additional participant to conference + * 5769: Several fixes concerning confererence handling + * #5769: Fix compilation error + * [#5769] Fix audio streams binding in main buffer + * #5769: Removed access to audio mixer from audio layer + * #5765: Fix audio crash for illformated wavefiles + * #5765: Add maximum iteration for finding fmt and data "chunck" + * #5589: Fix compilation of libnotify under + * #5757: Fix abort signal when receiving INFO + * #5747: Add usersDetached.svg + * #5747: Handle offhold action for recording conference + * #5747: Fix off hold action for conferences + * #5747: Implement update conference in record action in calltree + * #5747: Add new icons for recording conferences + * #5747: Add recording state for conferences + * [#5738] Remove getAudioDriver call from manager (replace by + _audiodriver var) + * [#5738] Refactor mutex protecting audiolayer + * [#5737] Fix HD conference recording + * [#5730] Fix start audio session after changing sampling rate + * [#5714] Fix enter keyboard event for addressbbok and history + * [5695] Fix addressbook combo box update when no addressbook selected + * [#5695] Fix addressbook initialization and search bar update + * [#5695] Add mutex for books_data in addressbook to protect async + calls + * [#5695] Get back addressbook open from uri + * [#5695] Fix absolute addressbook URI for local addressbooks + * [#5695] Implement libebook 3.0 interface + * [#5571] Better logic for hangup (for case where call have not been + sent yet) + * [#5571] Update error handling in voip links + * [#5571] Fix compile time warnings + * [#5696] Fix installation dependencies for Natty + * [#5669] Add mention that sflphone.org is for testing only + * [#5693] Add natty in teh dput.conf file + * [#5690] Remove not useful logs + * [#5670] Use dynamic payload type for rtp dtmf + * [#5668] Clean up sflphone configuration logging + * [#5668] Fix hook checkbox configuration update + * [#5666] Fix unit tests + * [#5666] Manage event subscription + * [#5666] Emit bye request when subscription is terminated + * [#5666] Bye request should be sent after event subscription + notification is done on transfer + * [#5666] Make reinvite method static (to be called in pjsip + callbacks) + * [#5666] Hangup Call in manager for AccountNULL and IP2IP + * [#5589] Use PKG_CHECK_MODULE for every client's dependencies + * [#5623] Enlarge initial size of pjsip memory pool for calls (16k) + * [#5564] Fix audio recording resampling for g722 + * [#5571] Move attribute handling for onhold/offhold actions in SDP + session + * [#5571] Codec negotiation refactored and unittested + * [#5571] Implement tests + * [#5571] Implement pjsip negociator + * [#5571] Fix unit tests + * [#5571] Add Fmtp.h to repository + * [#5571] Integrate mime types and codec factory + * [#5571] Handle exception when SDP negotiation fails + * [#5570] Add sflphoned-sample.yml in repository + * [#5564]: Implement stereo to mono mixing for rigntone + * [#5342] Update audio stream initialization + * [#5514] Restore test ni historytest suite + * [#5514] Fix + * [#5514] Disable test_create_history_path + * [#5514] use pulseaudio in sample config file + * [#5514] Fix test: load history from file + * [#5514] Do not use X + * [#5513] Make unit tests compile successfully + * [#3947] Enable unit tests in Jenkins + * [#5454] Fix build system to handle new version number + * [#5454] Update languages from launchpad + * [#5454] Add --without-celt in OpenSuse build service + * [#5454] Change version number + * [#5331] Added first SDP session tests + * [#5273] Update nightly build version tags to conform dpkg rules + * [#5211] Refactor send register method for iaxvoiplink and + sipvoiplink + * [#3950] Remove call being transfered from calltree + * [#5211] Use appropriate memory pool for transport selector + * [#5211] Fix strict aliasing rules warning in pjsip + * [#5211] Bring back pjsip shutting down sleep to 1000 ms + * [#5211] Fix registration callback segfault when closing the + application + * [#5211] Use the dialog memory pool for Route header in INVITE + request + * [#5211] Add temporary memory pool for findLocalAddressFromUri and + findLocalPortFromUri + * [#5211] Use individual memory pool for dtmfs + * [#5211] SipVoipLink refactoring + * [#3950] Attended transfer for conference calls + * [#5284] Fix DNS resolution for Route with specified port number + * [#5284] Some code cleanup + * [#3947] Fix typo in hudson script + * [#5284] Added sip route to REGISTER, INVITE, BYE request, plus DNS + resolution + * [#5266] Use RTP dtmf as default + * [#5284] Added pjsip_process_route_set after setting routes in regc + structure + * [#5286] Fix parsing error due to long configuration file (removed + max event) + * [#5286] Fix false test in configuration emmiter + * [#5286] Code cleanup + * [#5286] Updated exception handling in configuration system + * [#4969] Fix put SRTP call on hold + * [#3950] Add debug messages + * [#3950] Ability to perform an attended transfer + * [#5276] Fix initialization problem in g722 + * [#3950] Add replace header in SIPVoIPLink::transferWithReplaces + method + * [#3950] Implemented attended method in SIPVoIPLink + * [#3950] Cleanup transaction request received callback + * [#3950] Implement dummy attended transfer in gnome-client + * [#5249] Fix audio samplerate update algorithm for g722 + * [#5249] Fix uninitialized variable used in conditional jumps + * [#5249] Fix conditional jump error in audiolayer (uninitialized + value) + * [#5267] Use autoconf 2.65 as a requirement (instead of 2.67) + * [#5267] Restore manual pjsip configuration and compilation + * [#5267] Autodetect celt version (0.9.1, 0.7.1) + * [#5267] Fix deprecated macros in gnome client configure.ac + * [#5267] Update configuration for libcelt-dev + * [#5267] Fix build autoconf and automake + * [#5227] Deactivate automatic call to astyle after compilation + * [#5242] Hangup every calls before leaving + * [#5237] Will now nightly-build for natty, Karmic deprecated + * [#5229] Use inner class for rtp thread instead of inheritance + * [#5211] Move mainbuffer unbind call in rtp final method + * [#5211] Initialize sip call memory pool using 16 kb + * [#5211] Use call memory pool in session reinvite + * [#5211] Add debug messages + * [#5211] Use and internal pool for calls + * [#5211] Reduce pjsip memory pool usage for stateless error messages + * [#5211] Refactor call deletion + * [#5212] + * [#5208] Refactor codec management for accounts + * [#5168] Remove printf from codec's encode & decode method + * [#5168] Fix celt compilation on launchpad + * [#5168] Fix sflphoned compilation warnings in audiocodec.h + * [#[#5168] Must keep the g722 specific RTP rate to avoid incoming + packet timeout + * [#5168] Fix static/dynamic payload rtp session update + * [#5168] Throw SIPVoipLink Error if codec not instantiated in new + outgoing call + * [#5168] Fix dynamic/static codec payload type ambiguity + * [#5169] Fix doubled IP2IP profile when no config file + * [#4867] Add gtkinfobar in configuration panel + * [#4867] Disable input/output/ringtone selection when using default + alsa plugin + * [#4952] Patches for possible buffer overflows + * [$4885] Fix schemas problem + * [#4885] sflphone-client-gnome.schemas not present during build + * [#4885] Add gconf shemas directories in opensuse build system + * [#4885] Add file/folder ownership for opensuse-factory build system + * [#4906] Fix opensuse-factory build + * [#4885] Update name dependency for libedataserver + * [#4885] Fix non-void function without return in dbus-c++ + * [#4895] Update language translation + * [#4896] Update session timestamp when updating media + * [#4896] Reapply RTP hack for G722 payload type + * [#4896] Update recording sampling rate when updating codec + * [#4897] Save codecs in config for each configuration changes + * [#4895] Do not save config when sflphone quit + * [#4885] Update date for copyright + * [#4885] Deactivate siptest that require more than one sipp instance + * [#4879] Remove inmcoming call notification from IAX + * [#4885] Some cleanup + * [#4874] Add setCancel immediate/deffered for ost::Thread + * [#4879] Fix incoming call notification + * [#4878] Set keyboard focus on searchbar when selecting addressbook + * [#4874] Fixed compilation warning + * [#4874] Fixed compilation warning in sipvoiplink + * [#4874] Fix compile time warning in RTP record handler + * [#4874] Fix conditional jump in SDP + * [#4874] Fix conditional jump based on uninitialized value + * [#4874] Store call id within rtp thread context + * [#4874] Fixed conditional jump based on uninitialised value in + conference + * [#4871] Fix default account fetching + * [#4870] Delete RTP session when Refusing an incoming call + * Restore IP to IP call + * [#4857] Fix audio codec negotiation problem + * [#3947] Adjust ressources allocated to compilation + * [#3947] Disable unit tests in Hudson + * [#4305] Free mutex only when really quiting SFLphone + * [#4859] Update copyright to 2011 in every source file + * [#3218] Character '.' stripped by the caller engine + * [#4854] Fix typos, desktop entry + * [#4847] Apply RTP modification to ZRTP session + * [#4852] Update Karmic and Lucid dependencies + * [#4852] Add Libedataserver and libedataserverui as gnome client + dependencies + * [#4852] Add authentication mechanism for EDS + * [#4851] Fix segfault when closing pulseaudio layer too rapidly + * [#4808] Some otehr cleanup + * [#4808] Made some cleanup + * [#4808] Added mutex in rtp session for codecs and noise process + * [#4847] Update audio processing when updating RTP media + * [#4842] Add support for linking with gold/ld --no-add-needed + * [#4808] Make update g722 related static/dynamic payload logic + * [#4827] Upper limit on the number of contacts to import from EDS is + hard-coded to 500 + * [#4808] Fix put call on/off hold + * [#4808] Implement early RTP start for incoming calls + * [#4808] Audio stream is no longer start within RTP session. + * [#4808] Removed coupling between audio layer and and RTP session + * [#4702] Start audio rtp session as soon as it is created + * [#4702] Init timestamp to 0 + * #4702: Send RTP packets immediately, no need of outgoing queue + * [#4784] Update dbus-c++ version from gitorious + * [#4702] Update RTP timeouts + * [#4702] Lengthen RTP timeouts + * [PATCH] Fixed compatibility with old libtool versions. + * [PATCH] Accept older libebook (Maemo 5 has 1.4.2) + * [PATCH] Fixed double-free error in preferences dialog + * [PATCH] Fixed building of sflphone-common on Maemo5 + * [PATCH] Improved Gnome client initialization error handling. 1. It + no longer segfaults when sflphoned isn't available. 2. User is + provided with GUI error dialog. + * [PATCH] Improved autogen.sh scripts 1. They do not require bash + anymore 2. Added workaround for Debian bug #565663 3. Replaced + manual autotools invocations with single autoreconf call 4. Non-zero + return status on failure + * Revert "[#4468] libtool <= 2.2 doesn't have LT_INIT macro so + AC_PROG_LIBTOOL should be used instead." + * Revert "[#4468] Libebook 1.4 is sufficient" + * Revert "[#4468] Apply big path on dbus communication system" + * [#4468] Apply big path on dbus communication system + * [#4468] Libebook 1.4 is sufficient + * [#4468] libtool <= 2.2 doesn't have LT_INIT macro so AC_PROG_LIBTOOL + should be used instead. + * [#4639] Fix determining default addressbook if this property is not + set in gconf + * [#4639] Fix memory leaks in Addressbook + * [#4637] Fix opening default addressbook at sflphone init + * [#4622] Free yaml events while parsing configuration file + * [#4623] Fix conditional jumps based on uninitialized variable + * [#4622] Fix leaks in yaml serialization engine + * [#4616] Fix addressbook warnings + * [#4514] Adjust RTP timestamp + * #4527: Rename Karmic libyaml and Celt package in debian control file + * #4495: Rework addressbook opening loop + * [#4524] Increment RTP count when sending data + * [#4524] DO NOT start RTP session twice + * [#4367] Use PKG_CHECK_MODULE for celt + * [#4367] Fedora package celt as celt (not libcelt) + * [#4367] Astyling + * [#4367] Update .po files + * [#4367] Fix segfault in gensin + * [#4354] Make celt a direct dependency on launchpad opensuse build + service + * [#4367] Make celt a required package, option --without-celt valid + * [#4367] Fix zrtp timestamping error + * [#4367] Fix audio zrtp timing + * [#4367] Dispatch ZRTP packets + * [#4367] Fix segfault when unloading account map + * [#4367] Fix zrtp session + * [#4367] Implement on packet receive + * [#4367] use symetric audio rtp session, not dual + * [#4367] Reduce packet receive/sent timeout + * [#4367] Reduce RTP timeouts + * [#4367] Move speaker data receive + * [#4367] Move speaker data receive + * [#4367] Move receive speaker data method + * [#4367] Remove debug in rtp session + * [#4367] Fix g722 codec clock rate + * [#4367] Fix noise suppression initialization + * [#4367] Fix segfault in RTP mic fadein method + * [#4367] Refactor mic data encoding in rtp session + * [#4367] Implement RTP main loop + * [#4367] Fix compilation problem + * [#4367] Fix AudioRtpclass using TRTPSessionBase + * [#4367] Fix AudioRtpSession putDtmfEvent shadowing + * [#4367] Fix AudioRtpSession putDtmfEvent shadowing + * [#4367] Refactor RTP session (phase 2) + * [#4367] Refactor RTP session (phase 1) + * [#4367] Remove Redeclaration of SymetricAudioRtpSession in + rtpfactory + * [#4265] Add continue statement in for loop for invalid addressbook + * [#4261] Makes addressbook initialization more robust + * [#4257] Add maverick in build system + * [#4233] Add sdp related unit tests + * [#4233] Add condition and signal in two incoming call test + * [#4243] Fix segfault in AudioSrtpSession + * [#4243] Fix memory leak in AudioSrtpSession + * [#4243] Make audio srtp optional in for incoming call + * [#4243] Add boolean variable to make sure remote crypto context + initialized only once + * [#4243] Add documentation to AudioSrtpSession + * [#4243] Use 80 bits authentication tags by default + * [#4243] Init audio srtp remote crypto context in + call_on_media_update + * [#4243] Move SDP negotiastion in mod_on_rx_request + * [#4243] Implement initLocalCryptoInfo to be called at different + momment + * [#4243] Init init local crypto context in when initializing audiortp + * [#4243] Change key length according to sdes negociation + * [#4243] Associate callid to accountid for incoming calls + * [#4242] Fix no SDES keys in IP2IP calls + * [#4242] Fix no SDES keys in IP2IP calls + * [#4233] Test for call on/off hold + * [#4233] Add two incoming call test + * [#4233] + * [#4233] Add 2 outgoing simultaneous call unit tests + + -- Julien Bonjean <julien.bonjean@savoirfairelinux.com> Fri, 30 Sep 2011 13:57:10 -0400 + sflphone-plugins (0.9.7~rc1~ppa1~SYSTEM) SYSTEM; urgency=low ** 0.9.7~rc1~ppa1~SYSTEM ** diff --git a/tools/build-system/launchpad/sflphone-plugins/debian/control.jaunty b/tools/build-system/launchpad/sflphone-plugins/debian/control similarity index 84% rename from tools/build-system/launchpad/sflphone-plugins/debian/control.jaunty rename to tools/build-system/launchpad/sflphone-plugins/debian/control index b57290e29f69aa359842ac40401a9b8db166e71c..6ff028b1ad68d1412e97bbd34107f8c95ec494b7 100644 --- a/tools/build-system/launchpad/sflphone-plugins/debian/control.jaunty +++ b/tools/build-system/launchpad/sflphone-plugins/debian/control @@ -2,13 +2,13 @@ Source: sflphone-plugins Maintainer: SavoirFaireLinux Inc <julien.bonjean@savoirfairelinux.com> Section: gnome Priority: optional -Build-Depends: debhelper, libgcc1, autoconf, automake, libtool, libgtk2.0-dev, libebook1.2-dev +Build-Depends: debhelper, libgcc1, autoconf, automake, libtool, libgtk-3-dev, libebook1.2-dev, libedataserver1.2-dev Standards-Version: 3.7.3 Package: sflphone-plugins Priority: optional Architecture: any -Depends: sflphone-client-gnome (=${source:Version}), libgtk2.0-0, libc6, libglib2.0-0, libebook1.2-9 +Depends: sflphone-client-gnome (=${source:Version}), ${shlibs:Depends}, ${misc:Depends} Replaces: sflphone Conflicts: sflphone Homepage: http://www.sflphone.org diff --git a/tools/build-system/launchpad/sflphone-plugins/debian/control.karmic b/tools/build-system/launchpad/sflphone-plugins/debian/control.karmic deleted file mode 100644 index fd049f29576ed9b24913d5784b6255a8c1071a8e..0000000000000000000000000000000000000000 --- a/tools/build-system/launchpad/sflphone-plugins/debian/control.karmic +++ /dev/null @@ -1,20 +0,0 @@ -Source: sflphone-plugins -Maintainer: SavoirFaireLinux Inc <julien.bonjean@savoirfairelinux.com> -Section: gnome -Priority: optional -Build-Depends: debhelper, libgcc1, autoconf, automake, libtool, libgtk2.0-dev, libebook1.2-dev, libedataserver1.2-dev -Standards-Version: 3.7.3 - -Package: sflphone-plugins -Priority: optional -Architecture: any -Depends: sflphone-client-gnome (=${source:Version}), libgtk2.0-0, libc6, libglib2.0-0, libebook1.2-9, libedataserver1.2-11 -Replaces: sflphone -Conflicts: sflphone -Homepage: http://www.sflphone.org -Description: Evolution addressbook plugin for SFLphone - Integrate evolution addressbook functionality to SFLphone. - SFLphone is meant to be a robust enterprise-class desktop phone. - SFLphone is released under the GNU General Public License. - SFLphone is being developed by the global community, and maintained by - Savoir-faire Linux, a Montreal, Quebec, Canada-based Linux consulting company. diff --git a/tools/build-system/launchpad/sflphone-plugins/debian/control.lucid b/tools/build-system/launchpad/sflphone-plugins/debian/control.lucid deleted file mode 100644 index fd049f29576ed9b24913d5784b6255a8c1071a8e..0000000000000000000000000000000000000000 --- a/tools/build-system/launchpad/sflphone-plugins/debian/control.lucid +++ /dev/null @@ -1,20 +0,0 @@ -Source: sflphone-plugins -Maintainer: SavoirFaireLinux Inc <julien.bonjean@savoirfairelinux.com> -Section: gnome -Priority: optional -Build-Depends: debhelper, libgcc1, autoconf, automake, libtool, libgtk2.0-dev, libebook1.2-dev, libedataserver1.2-dev -Standards-Version: 3.7.3 - -Package: sflphone-plugins -Priority: optional -Architecture: any -Depends: sflphone-client-gnome (=${source:Version}), libgtk2.0-0, libc6, libglib2.0-0, libebook1.2-9, libedataserver1.2-11 -Replaces: sflphone -Conflicts: sflphone -Homepage: http://www.sflphone.org -Description: Evolution addressbook plugin for SFLphone - Integrate evolution addressbook functionality to SFLphone. - SFLphone is meant to be a robust enterprise-class desktop phone. - SFLphone is released under the GNU General Public License. - SFLphone is being developed by the global community, and maintained by - Savoir-faire Linux, a Montreal, Quebec, Canada-based Linux consulting company. diff --git a/tools/build-system/launchpad/sflphone-plugins/debian/control.maverick b/tools/build-system/launchpad/sflphone-plugins/debian/control.maverick deleted file mode 100644 index 96c1219a84a6d55cba318ebe43629e08f799f188..0000000000000000000000000000000000000000 --- a/tools/build-system/launchpad/sflphone-plugins/debian/control.maverick +++ /dev/null @@ -1,20 +0,0 @@ -Source: sflphone-plugins -Maintainer: SavoirFaireLinux Inc <julien.bonjean@savoirfairelinux.com> -Section: gnome -Priority: optional -Build-Depends: debhelper, libgcc1, autoconf, automake, libtool, libgtk2.0-dev, libebook1.2-dev, libedataserver1.2-dev -Standards-Version: 3.7.3 - -Package: sflphone-plugins -Priority: optional -Architecture: any -Depends: sflphone-client-gnome (=${source:Version}), libgtk2.0-0, libc6, libglib2.0-0, libebook1.2-9, libedataserver1.2-13 -Replaces: sflphone -Conflicts: sflphone -Homepage: http://www.sflphone.org -Description: Evolution addressbook plugin for SFLphone - Integrate evolution addressbook functionality to SFLphone. - SFLphone is meant to be a robust enterprise-class desktop phone. - SFLphone is released under the GNU General Public License. - SFLphone is being developed by the global community, and maintained by - Savoir-faire Linux, a Montreal, Quebec, Canada-based Linux consulting company. diff --git a/tools/build-system/launchpad/sflphone-plugins/debian/control.natty b/tools/build-system/launchpad/sflphone-plugins/debian/control.natty deleted file mode 100644 index b4ab4fe674bd993aad6509e02c46a07f7fd51bbc..0000000000000000000000000000000000000000 --- a/tools/build-system/launchpad/sflphone-plugins/debian/control.natty +++ /dev/null @@ -1,20 +0,0 @@ -Source: sflphone-plugins -Maintainer: SavoirFaireLinux Inc <julien.bonjean@savoirfairelinux.com> -Section: gnome -Priority: optional -Build-Depends: debhelper, libgcc1, autoconf, automake, libtool, libgtk2.0-dev, libebook1.2-dev, libedataserver1.2-dev -Standards-Version: 3.7.3 - -Package: sflphone-plugins -Priority: optional -Architecture: any -Depends: sflphone-client-gnome (=${source:Version}), libgtk2.0-0, libc6, libglib2.0-0, libebook1.2-10, libedataserver1.2-14 -Replaces: sflphone -Conflicts: sflphone -Homepage: http://www.sflphone.org -Description: Evolution addressbook plugin for SFLphone - Integrate evolution addressbook functionality to SFLphone. - SFLphone is meant to be a robust enterprise-class desktop phone. - SFLphone is released under the GNU General Public License. - SFLphone is being developed by the global community, and maintained by - Savoir-faire Linux, a Montreal, Quebec, Canada-based Linux consulting company. diff --git a/tools/build-system/launchpad/sflphone-plugins/debian/rules b/tools/build-system/launchpad/sflphone-plugins/debian/rules index b3eb5eb357cfc207192d6ef9f539a5dcbcb2e274..d18a6e0a7793070eb76f86f630177a23458920b0 100755 --- a/tools/build-system/launchpad/sflphone-plugins/debian/rules +++ b/tools/build-system/launchpad/sflphone-plugins/debian/rules @@ -100,7 +100,7 @@ binary-common: # dh_perl dh_makeshlibs dh_installdeb -# dh_shlibdeps + dh_shlibdeps dh_gencontrol dh_md5sums dh_builddeb diff --git a/tools/build-system/make-telify-package.sh b/tools/build-system/make-telify-package.sh index be3be86bd2f38dd67536029430396a11bf3db668..4f2300786e7e0004f9a806add5a8d406468edcc6 100644 --- a/tools/build-system/make-telify-package.sh +++ b/tools/build-system/make-telify-package.sh @@ -28,7 +28,7 @@ for LAUNCHPAD_DISTRIBUTION in ${LAUNCHPAD_DISTRIBUTIONS[*]} do LOCAL_VERSION="${SOFTWARE_VERSION}~ppa${VERSION_INDEX}~${LAUNCHPAD_DISTRIBUTION}" - cp ${DEBIAN_DIR}/control.${LAUNCHPAD_DISTRIBUTION} ${DEBIAN_DIR}/control + cp ${DEBIAN_DIR}/control ${DEBIAN_DIR}/control cp ${DEBIAN_DIR}/changelog.generic ${DEBIAN_DIR}/changelog sed -i "s/SYSTEM/${LAUNCHPAD_DISTRIBUTION}/g" ${DEBIAN_DIR}/changelog diff --git a/tools/build-system/setenv.sh b/tools/build-system/setenv.sh index ab645c322fa0495150adf38e4949357da077c7ac..1f22c606008aee759ca5656ef7d4340df391155f 100644 --- a/tools/build-system/setenv.sh +++ b/tools/build-system/setenv.sh @@ -22,6 +22,5 @@ export REFERENCE_REPOSITORY="${ROOT_DIR}/sflphone-source-repository" export WORKING_DIR="${ROOT_DIR}/sflphone-build-repository/tools/build-system" export LAUNCHPAD_DIR="${WORKING_DIR}/launchpad" -LAUNCHPAD_DISTRIBUTIONS=( "lucid" "maverick" "natty") +LAUNCHPAD_DISTRIBUTIONS=("natty" "oneiric" "precise") export LAUNCHPAD_DISTRIBUTIONS -