cisstCommon API

cisstCommon provides the base services used by all cisst libraries: class registration, logging (cmnLogger), serialization, and portability macros.

Key classes

class cmnLogger

Class to glue the class register, the output multiplexer and the message level of detail to form the logging entity of cisst.

cmnLogger is defined as a singleton, i.e. there is only one instance of cmnLogger. This unique object maintains the data required for the cisst logging system. The design of the logging system relies on:

  • Human readable messages are associated to a Level of Detail.

  • The messages are sent and filtered based on their level of detail. The macros used to send the messages actually check if the message is to be sent or not before creating them in order to improve performances (see #CMN_LOG_CLASS and CMN_LOG).

  • The messages are sent to a multiplexer owned by cmnLogger. This multiplexer allows to send the message (along with their level of detail) to multiple output streams.

To filter the messages, the user can use:

  • The global log mask defined in cmnLogger. Any message with a level of detail incompatible with overall log mask will be ignored (at minimal execution time cost). This mask is used by #CMN_LOG_CLASS and CMN_LOG. To modify the overall mask, use cmnLogger::SetMask(newMask).

  • Each class relies on its own log mask. This allows to tune the log based on the user’s needs. One can for example allow all the messages (from errors to debug) from a given class and block all the messages from every other class. As for the overall log mask, if a message’s level of detail is incompatible with the class mask, it will be ignored (at minimal execution time cost). This log mask is used only be #CMN_LOG_CLASS. To modify a class log mask, use either the logger with cmnLogger::SetMaskClass(“className”, newMask), cmnLogger::SetMaskClassMatching(“cmn”, newMask), cmnLogger::SetMaskClassAll(newMask) or the class services with object.Services()->SetLogMask(newMask).

  • The output streams masks. Each output stream has its own log mask and will stream only the messages with a compatible level of detail. This allows for example to log everything to a file while printing only the high priority ones to std::cout. To set the level of detail of an output stream, use cmnLogger::AddChannel(newStream, newMask).

See also

cmnClassRegister cmnClassServicesBase cmnLODOutputMultiplexer

Public Types

typedef cmnLODMultiplexerStreambuf<char> StreamBufType

Type used to define the logging level of detail.

Public Static Functions

static cmnLogger *Instance(void)

The log is instantiated as a singleton. To access the unique instantiation, one needs to use this static method. The instantiated log is created at the first call of this method since it is a static variable declared in this method’s scope.

Returns:

A pointer to the logger.

static inline void SetMask(cmnLogMask mask)

Set the global mask used to filter the log messages.

See also

SetMaskInstance

Parameters:

mask – The overall mask used to filter the log.

static inline void CISST_DEPRECATED SetLoD (cmnLogMask mask)
static inline cmnLogMask GetMask(void)

Get the global mask used to filter the log messages.

See also

GetMaskInstance

Returns:

The global mask used to filter the log.

static inline cmnLogMask CISST_DEPRECATED GetLoD (void)
static inline void SetMaskFunction(cmnLogMask mask)

Set the “function” mask used to filter the log messages.

See also

SetMaskFunctionInstance

Parameters:

mask – The function mask used to filter the log.

static inline cmnLogMask GetMaskFunction(void)

Get the function mask used to filter the log messages.

See also

GetMaskInstance

Returns:

The function mask used to filter the log.

static bool SetMaskClass(const std::string &className, cmnLogMask mask)

Specify the log mask for a specific class. See cmnClassRegister::SetLogMaskClass.

Parameters:
  • className – The name of the class

  • mask – The log mask to be applied

Returns:

bool True if the class is registered.

static bool SetMaskClassAll(cmnLogMask mask)

Specify the log mask for all registered classes. See cmnClassRegister::SetLogMaskClassAll.

Parameters:

mask – The log mask to be applied

Returns:

bool True if there is at least one class mask was modified

static bool SetMaskClassMatching(const std::string &stringToMatch, cmnLogMask mask)

Specify the log mask for all classes with a name matching a given string. See cmnClassRegister::SetLogMaskClassMatching.

Parameters:
  • stringToMatch – A string found in class names (e.g. “cmn”)

  • mask – The log mask to be applied

Returns:

bool True if there is at least one class LoD was modified

static inline StreamBufType *GetMultiplexer(void)

Returns the cmnLODMultiplexerStreambuf directly. This allows manipulation of the streambuffer for operations such as adding or deleting channels for the stream..

See also

GetMultiplexerInstance

Returns:

cmnLODMultiplexerStreambuf<char>* The Streambuffer.

static inline void HaltDefaultLog(void)

Disable the default log file “cisstLog.txt”. This method removes the default log from the output list of the multiplexer but doesn’t close the default log file.

static inline void ResumeDefaultLog(cmnLogMask newLoD = CMN_LOG_ALLOW_DEFAULT)

Resume the default log file. By default, the log is enabled (this is the default behavior of the cmnLogger constructor) but this can be halted by using HaltDefaultLog(). Using ResumeDefaultLog() allows to resume the log to “cisstLog.txt” without losing previous logs.

static inline void SetMaskDefaultLog(cmnLogMask newLoD = CMN_LOG_ALLOW_DEFAULT)

Set a new mask for the default log file. This method uses HaltDefaultLog followed by ResumeDefaultLog.

static inline void AddChannel(std::ostream &outputStream, cmnLogMask mask = CMN_LOG_ALLOW_ALL)

Add an output stream to the logger. The level of detail provided is used to filter the messages, i.e. any message with a level of detail higher than the level associated to the output stream will not be streamed.

static inline void AddChannelToStdOut(cmnLogMask mask = CMN_LOG_ALLOW_ERRORS_AND_WARNINGS)

Add std::cout output stream to the logger. Useful when calling from Python, where redirecting sys.stdout to std::cout is nontrivial.

static inline void AddChannelToStdErr(cmnLogMask mask = CMN_LOG_ALLOW_ERRORS_AND_WARNINGS)

Add std::cerr output stream to the logger. Useful when calling from Python, where redirecting sys.stderr to std::cerr is nontrivial.

static inline void RemoveChannel(std::ostream &outputStream)
static const char *ExtractFileName(const char *file)
static inline void Kill(void)

Kill the logger. Set all masks to disable logs and remove all output streams.

static bool SetDefaultLogFileName(const std::string &defaultLogFileName)

Set the name of the default log file. This function must be called before the cmnLogger instance is created.

Returns:

true if the default log file name can be set (i.e., cmnLogger instance not yet created); false otherwise.

static inline std::string GetDefaultLogFileName(void)

Returns name of default log file.

static inline bool IsCreated()

Returns true if cmnLogger instance has been created (i.e., constructor called).

class cmnGenericObject

Base class for high level objects.

See also

cmnClassRegister cmnClassServiceBase

Subclassed by cmnCommandLineOptions, cmnDeSerializer, cmnGenericObjectProxy< _elementType >, cmnLoggerQtWidget, cmnPath, cmnSerializer, mtsComponent, mtsGenericObject, mtsInterface, mtsInterfaceProvidedOrOutput, mtsInterfaceRequiredOrInput, mtsManagerComponentServices, mtsManagerLocal, mtsQtWidgetEvent, mtsQtWidgetFunction, mtsQtWidgetGenericObjectRead, mtsQtWidgetInterfaceRequired, mtsStateTable, mtsWatchdogClient, mtsWatchdogServer, osaSerialPort, osaSocket, osaSocketServer, osaTimeServer, svlImageCodecBase, svlQtWidgetFileOpen, svlQtWidgetFramerate, svlVidCapSrcBase, svlWebObjectBase, svlWebPublisher

Public Functions

inline virtual ~cmnGenericObject(void)

Destructor. Does nothing specific.

virtual const cmnClassServicesBase *Services(void) const = 0

Pure virtual method to access the class services. The derived classes should always declare and implement this method using the macros #CMN_DECLARE_SERVICES, #CMN_DECLARE_SERVICES_INSTANTIATION and #CMN_IMPLEMENT_SERVICES. In NO WAY, a user should redefine/overload this method otherwise.

See also

cmnClassRegister cmnClassServiceBase

Returns:

A pointer on the class services. This points to the unique instance of cmnClassServiceBase for a given class.

bool ReconstructFrom(const cmnGenericObject &other)

Use the placement new with the copy constructor to re-construct this object based on an existing one. This method will call the destructor to free any memory allocated by the previous constructor. It is important to note that the memory allocated for the object itself is not freed/re-allocated and therefore the object’s address remains valid.

\other An object of the same type, if the types (class derived from cmnGenericObject) don’t correspond the method will return false and will not call the destructor and copy constructor.

Returns:

false if the object other is not of the right type.

std::string ToString(void) const

Formatted IO to a string. This method relies on ToStream which should be overloaded for each class.

virtual void ToStream(std::ostream &outputStream) const

The default ToStream method returns the name of the class. This method must be overloaded to provide a useful message.

virtual void ToStreamRaw(std::ostream &outputStream, const char delimiter = ' ', bool headerOnly = false, const std::string &headerPrefix = "") const

Unformatted text output. Delimiter can be used to create CSV data files if the object requires multiple values (e.g. vector, matrix, ). When headerOnly is set to true, the method should create a label for each value (e.g. v1, v2, v3). The prefix can be used to generated a more useful label (e.g. position-v1)

virtual bool FromStreamRaw(std::istream &inputStream, const char delimiter = ' ')

Read from an unformatted text input (e.g., one created by ToStreamRaw). Returns true if successful.

virtual void SerializeRaw(std::ostream &outputStream) const

Serialize the content of the object without any extra information, i.e. no class type nor format version. The “receiver” is supposed to already know what to expect.

virtual void DeSerializeRaw(std::istream &inputStream)

De-serialize the content of the object without any extra information, i.e. no class type nor format version.

virtual cmnLogger::StreamBufType *GetLogMultiplexer(void) const

Get the multiplexer to use for logging. This is used by the macro CMN_LOG_CLASS to determine the log destination. By default, it uses cmnLogger. This method can be overloaded to define a log file/stream per object.

inline virtual size_t ScalarNumber(void) const

Methods for data visualization. Derived classes should override the following methods in order to be properly processed by the data visualizer of the global component manager.

Return a number of data (which can be visualized, i.e., type-casted to double)

inline virtual bool ScalarNumberIsFixed(void) const

Indicates if this object has a fixed number of scalars. This is used for arrays of object in order to optimize random access for a given scalar. When defining an object with a fixed number of scalars, overloading this method to return true allows some optimizations.

inline virtual double Scalar (const size_t CMN_UNUSED(index)) const CISST_THROW(std

Return the index-th (zero-based) value of data typecasted to double. Note that this method will throw an exception of type std::outputStream if the index exceeds the number of scalars.

inline virtual std::string ScalarDescription(const size_t CMN_UNUSED(index), const std::string &CMN_UNUSED(userDescription)) const

Return the name of index-th (zero-based) data typecasted to double. As for the Scalar, this method will throw an exception of type std::out_of_range if the index exceeds the number of scalar.

class cmnPath : public cmnGenericObject

Search path to find a file. This class contains a list of directories used to locate a file.

The directories can be added either at the head or the tail of the list. This class doesn’t check weither the directories in the path actually exist, mostly to allow a portable program (e.g. one program can add both “/usr/local/bin” and “C:\Program Files”).

As a convention, the separator between subdirectories should be a “/” (slash) and the separation between two directories in the path is “;” (semi-colon). For example, “/bin;/usr/bin” will add both “/bin” and “/usr/bin”.

Public Types

enum [anonymous]

Defines how to add a path to the search list.

Values:

enumerator HEAD
enumerator TAIL
enum [anonymous]

Defines the mode to be used for a given file.

Values:

enumerator EXIST
enumerator WRITE
enumerator READ
enumerator EXECUTE
typedef std::list<std::string> ContainerType

Container used to store the directories.

typedef ContainerType::iterator iterator

STL like iterators.

typedef ContainerType::const_iterator const_iterator

Public Functions

cmnPath(void)
cmnPath(const std::string &path)

Create a search path from a string.

inline virtual ~cmnPath(void)

Destructor

void Set(const std::string &path)

Set the path from a string.

void Add(const std::string &path, bool head = HEAD)

Add one or more directories to the path.

bool AddFromEnvironment(const std::string &variableName, bool head = HEAD)

Add one or more directories to the path using an environment variable.

bool AddRelativeToCisstRoot(const std::string &relativePath, bool head = HEAD)

Add path relative to the CISST_ROOT environment variable. This can be useful to find shared libraries. To find data files, use AddRelativeToCisstShare.

bool AddRelativeToCisstShare(const std::string &relativePath, bool head = HEAD)

Add path relative to the shared cisst directory, i.e. CISST_ROOT/share/cisst-<version>.

std::string Find(const std::string &filename, short mode = READ) const

Find the full name for a given file.

Returns:

The full path including the filename or an empty string.

std::string FindWithSubdirectory(const std::string &filename, const std::string &subdirectory, short mode = READ) const

Find the full name for a given file using all directories in path as well as given “sub directory” in each directory. E.g if the path contains /bin and /usr/bin and the sub-directory provided is “Release”, the full search path if /bin/Release, /bin, /usr/bin/Release, /usr/bin. One can also #include <cisstBuildType.h> which defines the string CISST_BUILD_SUFFIX.

Returns:

The full path including the filename or an empty string.

bool Remove(const std::string &directory)

Remove the first occurence of a directory from the search list.

bool Has(const std::string &directory) const

Indicates if a given directory is in the search list.

virtual void ToStream(std::ostream &outputStream) const override

Write the path to a stream.

Public Static Functions

static const std::string &DirectorySeparator(void)

A platform-independent string for separating subdirectory or file name from the parent directory name. It’s equal to “/” on Linux, “\” on Windows, etc.

static std::string GetWorkingDirectory(void)

Get working directory

static bool GetCisstRoot(std::string &result)

Get CISST_ROOT from the environment variable

static bool GetCisstShare(std::string &result)

Get cisst shared directory based on CISST_ROOT from the environment variable

static bool Exists(const std::string &fullPath, short more = READ)

Check if a file exists assuming the path provided is either relative or absolute, this function doesn’t use any search path.

static bool DeleteFile(const std::string &fullPath)

Delete file. This function doesn’t use any search path.

static bool RenameFile(const std::string &fullPathOld, const std::string &fullPathNew)

Rename file. This function doesn’t use any search path.

static inline std::string SharedLibrary(const std::string &name)

Construct the shared library name based on OS prefix and suffix. For example, the return value for “MyLib” would be “libMyLib.so” on most Unix systems and “MyLib.dll” on Windows. Prefix and suffix are based on CMake and saved in cisstConfig.h.

static inline std::string Executable(const std::string &name)

Construct the executable name based on OS suffix. For example, the return value for “MyProgram” would be “MyProgram” on most Unix systems and “MyProgram.exe” on Windows. Suffix is based on CMake and saved in cisstConfig.h.

class cmnCommandLineOptions : public cmnGenericObject

Set command line options and parse command line arguments.

This class should facilitate the development of command line tools requiring arguments. For example, it can be used to parse parameters such as “my_program -v –file path/file.h –iterations 2”.

cmnCommandLineOptions options;
bool verbose;
std::string filename;
int iterations;
std::list<double> someNumbers;
options.AddOptionNoValue("v", "verbose", "more messages");
options.AddOptionOneValue("f", "file", "file name", cmnCommandLineOptions::REQUIRED_OPTION, &filename);
options.AddOptionOneValue("i", "iterations", "number of iterations", cmnCommandLineOptions::REQUIRED_OPTION, &iterations);
options.AddOptionMultipleValues("n", "number", "one or many numbers", cmnCommandLineOptions::REQUIRED_OPTION, &someNumbers);

std::string errorMessage;
if (!options.Parse(argc, argv, errorMessage)) {
    std::cerr << "Error: " << errorMessage << std::endl;
    options.PrintUsage(std::cerr);
    return -1;
}

verbose = options.IsSet("v"); // or IsSet("verbose")

In this example, note that the first option added doesn’t require a value, i.e. the caller should just use the short option (-v) or the long one (&#8212;verbose).

The second and third options are required, i.e. the “Parse” call will return false if one or more required option is not found. Both options are added as “option with one value” which means that the parser expect a value and this option can not be use twice (such as “my_program -i 2 -i 3). The last parameter of “AddOptionOneValue” can be a string, an integer, a double or anything the C++ operator

can stream in using a single argument of the command line.

The “Parse” method takes the argc and argv of the “main” function. It also requires an empty string passed by reference to generate an error message in case the parse fails. If parsing the command line options fails, one can use PrintUsage to display all the valid options.

Subclassed by mtsCommandLineOptions

Public Types

enum RequiredType

Values:

enumerator REQUIRED_OPTION
enumerator OPTIONAL_OPTION
enumerator SQUASH_REQUIRED_OPTION

Public Functions

cmnCommandLineOptions(void)
~cmnCommandLineOptions()
bool AddOptionNoValue(const std::string &shortOption, const std::string &longOption, const std::string &description, RequiredType required = OPTIONAL_OPTION)
template<typename _elementType>
inline bool AddOptionOneValue(const std::string &shortOption, const std::string &longOption, const std::string &description, RequiredType required, _elementType *value)
template<typename _elementType>
inline bool AddOptionMultipleValues(const std::string &shortOption, const std::string &longOption, const std::string &description, RequiredType required, std::list<_elementType> *value)
bool Parse(int argc, const char *argv[], std::string &errorMessage)

Parse using an array of const C strings. This class doesn’t modify any of the parameters so it is a bit safer. This also allows to create unit tests using static arrays of strings without warnings.

bool Parse(int argc, char *argv[], std::string &errorMessage)

Parse using an array of non const C strings. This is the default for most applications using C like main function. Internally it created an array of const char * pointing to the existing arrays and then call the other Parse method.

bool Parse(const std::vector<std::string> &arguments, std::string &errorMessage)
bool Parse(int argc, char *argv[], std::ostream &outputStream)

Parse and display error messages as well as usage if an error is found.

bool Parse(const std::vector<std::string> &arguments, std::ostream &outputStream)
void PrintUsage(std::ostream &outputStream)

Print list of options with description to any C++ ostream. For example, options.PrintUsage(std::cout).

bool IsSet(const std::string &option)

Check if an option has been set. This can be used after Parse to check if an optional value has been set or not. The option name can be either the short or long one.

void PrintParsedArguments(std::string &parsedArguments) const